@phren/cli 0.3.12 → 0.3.14

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 (58) 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-app-server.d.ts +6 -0
  6. package/dist/bridge/codex-app-server.js +3 -1
  7. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  8. package/dist/bridge/codex-hook-trust.js +237 -0
  9. package/dist/bridge/codex-servers.d.ts +25 -1
  10. package/dist/bridge/codex-servers.js +78 -14
  11. package/dist/bridge/command.js +4 -1
  12. package/dist/bridge/dispatch-command.js +9 -3
  13. package/dist/bridge/dispatch-returns.d.ts +8 -0
  14. package/dist/bridge/dispatch-returns.js +21 -6
  15. package/dist/bridge/dispatch.d.ts +25 -1
  16. package/dist/bridge/dispatch.js +35 -6
  17. package/dist/bridge/hand-off-queue.d.ts +74 -0
  18. package/dist/bridge/hand-off-queue.js +235 -0
  19. package/dist/bridge/hand-off.d.ts +12 -4
  20. package/dist/bridge/hand-off.js +27 -7
  21. package/dist/bridge/install.d.ts +8 -1
  22. package/dist/bridge/install.js +60 -7
  23. package/dist/bridge/pane-status.d.ts +12 -0
  24. package/dist/bridge/pane-status.js +50 -1
  25. package/dist/bridge/push.d.ts +6 -0
  26. package/dist/bridge/push.js +21 -0
  27. package/dist/bridge/schedule-launch.d.ts +1 -1
  28. package/dist/bridge/schedule-launch.js +5 -1
  29. package/dist/bridge/schedule-watch.d.ts +15 -1
  30. package/dist/bridge/schedule-watch.js +45 -10
  31. package/dist/bridge/server-launch.js +14 -4
  32. package/dist/bridge/server-overview.d.ts +8 -1
  33. package/dist/bridge/server-overview.js +12 -3
  34. package/dist/bridge/server-pane-routes.d.ts +1 -0
  35. package/dist/bridge/server-pane-routes.js +9 -7
  36. package/dist/bridge/server-routes.d.ts +4 -0
  37. package/dist/bridge/server-routes.js +57 -7
  38. package/dist/bridge/server.js +15 -2
  39. package/dist/bridge/session-activity.d.ts +24 -12
  40. package/dist/bridge/session-activity.js +36 -14
  41. package/dist/bridge/stalls.d.ts +22 -0
  42. package/dist/bridge/stalls.js +57 -0
  43. package/dist/bridge/sudo.d.ts +209 -0
  44. package/dist/bridge/sudo.js +501 -0
  45. package/dist/bridge/terminal-tmux.d.ts +12 -0
  46. package/dist/bridge/terminal-tmux.js +79 -4
  47. package/dist/bridge/transcript-claude.d.ts +4 -0
  48. package/dist/bridge/transcript-claude.js +131 -6
  49. package/dist/bridge/usage.d.ts +17 -0
  50. package/dist/bridge/usage.js +37 -3
  51. package/dist/bridge-hook.mjs +24911 -23487
  52. package/dist/cli-registry.js +7 -1
  53. package/dist/modules/registry.js +8 -8
  54. package/dist/test-global-setup.js +7 -0
  55. package/dist/tools/dispatch.js +17 -2
  56. package/package.json +1 -1
  57. package/starter/global/AGENTS.md +4 -0
  58. package/starter/global/skills/conductor/SKILL.md +34 -2
@@ -1,3 +1,6 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { deliveryIdSchema } from "./prompt-once.js";
3
+ import { terminalPaneFromEnv } from "./terminal.js";
1
4
  import { z } from "zod";
2
5
  import { computerName } from "./computers.js";
3
6
  import { hookRequest } from "./client.js";
@@ -19,8 +22,12 @@ export const handOffSchema = z.object({
19
22
  project: projectName.optional().describe("Project slug this hand-off belongs to, for conductor grant matching."),
20
23
  account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
21
24
  .describe("Claude account id the session must run under (default, or a slug). A session of another account is refused; a row without an account counts as default."),
22
- text: promptText.describe("Prompt to deliver to the existing session, at most 32768 characters."),
25
+ deliveryId: deliveryIdSchema.describe("Stable message id to keep on retries or to check status."),
26
+ status: z.boolean().optional().describe("Read delivery status without sending; requires deliveryId."),
27
+ text: promptText.optional().describe("Prompt to deliver to the existing session, at most 32768 characters."),
23
28
  }).strict().superRefine((value, context) => {
29
+ if (value.status ? !value.deliveryId || value.text !== undefined : !value.text)
30
+ context.addIssue({ code: "custom", message: "A send requires text; a status query requires deliveryId and no text." });
24
31
  if ((value.target === undefined) === (value.session === undefined))
25
32
  context.addIssue({ code: "custom", message: "Provide exactly one of target or session." });
26
33
  });
@@ -51,9 +58,8 @@ async function targetFromOverview(request, session, server, account) {
51
58
  throw new BridgeError(409, `That session runs under account ${found.account}, not ${account}.`, { code: "account_mismatch" });
52
59
  return found;
53
60
  }
54
- /** `deliveryId` names this one message on the receiving Hook, which then types
55
- * it at most once however often it is sent (the Hook's own callers retry;
56
- * the MCP tool does not take one). */
61
+ /** A stable delivery id names a message on the receiving Hook. The Hook
62
+ * queues busy targets and retains outcomes across restarts. */
57
63
  export async function handOff(input, options = {}) {
58
64
  const data = handOffSchema.parse(input);
59
65
  let request;
@@ -83,7 +89,16 @@ export async function handOff(input, options = {}) {
83
89
  if (peer && target.server !== peer.server)
84
90
  throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
85
91
  const grant = await findGrant({ action: "hand_off", project: data.project, computer: data.computer });
86
- const result = await request("/v1/prompt", { target, text: data.text, ...(options.deliveryId ? { deliveryId: options.deliveryId } : {}) });
92
+ let origin;
93
+ if (!data.status && options.notifySender !== false) {
94
+ const here = await terminalPaneFromEnv();
95
+ if (here)
96
+ origin = await findInOverview((route, body) => hookRequest(route, body), found => found.server === here.server && found.pane === here.pane, here.server).then(found => found?.target, () => undefined);
97
+ }
98
+ const originComputer = peer && origin ? await hookRequest("/v1/health").then(health => object(health.computer).name, () => undefined) : undefined;
99
+ const deliveryId = data.deliveryId ?? options.deliveryId ?? randomUUID().replaceAll("-", "");
100
+ const result = await request(data.status ? "/v1/hand-off/status" : "/v1/hand-off", { target, deliveryId,
101
+ ...(!data.status ? { text: data.text, ...(origin ? { origin, ...(typeof originComputer === "string" ? { originComputer } : {}) } : {}) } : {}) });
87
102
  // A bare ok only acknowledges typing. Even an unchanged, busy Codex pane
88
103
  // may have kept the text in its composer instead of submitting a turn.
89
104
  const delivered = result.ok === true && result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true;
@@ -92,8 +107,12 @@ export async function handOff(input, options = {}) {
92
107
  const label = resolved ? resolved.label
93
108
  : await findInOverview(request, found => found.pane === target.pane && found.session === target.session, peer?.server)
94
109
  .then(found => found?.label, () => undefined);
95
- return { ok: delivered, delivered, target,
96
- ...(!delivered && (result.ok === true || result.deliveryUncertain === true) ? { deliveryUncertain: true } : {}),
110
+ const queued = result.queued === true && result.deliveryUncertain !== true;
111
+ return { ok: delivered || queued, delivered, target,
112
+ ...(queued ? { queued: true } : {}),
113
+ ...(typeof result.deliveryId === "string" ? { deliveryId: result.deliveryId } : {}),
114
+ ...(typeof result.state === "string" ? { state: result.state } : {}),
115
+ ...(!delivered && !queued && (result.ok === true || result.deliveryUncertain === true) ? { deliveryUncertain: true } : {}),
97
116
  ...(result.unsubmitted === true ? { unsubmitted: true } : {}),
98
117
  ...(label ? { label } : {}), ...(grant ? { granted: grantLabel(grant) } : {}) };
99
118
  }
@@ -116,6 +135,7 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
116
135
  title: text(tab.title), agent: tab.agent, status: text(tab.agentStatus), role: text(tab.role),
117
136
  branch: text(tab.branch), model: text(tab.model), ...(typeof object(tab.account).id === "string" ? { account: String(object(tab.account).id) } : {}), ...(target.success ? { target: target.data } : {}),
118
137
  ...(typeof tab.backgroundTasks === "number" && tab.backgroundTasks > 0 ? { backgroundTasks: tab.backgroundTasks } : {}),
138
+ ...(tab.stalled === true ? { stalled: true, stallFor: Number(tab.stallFor), stalledSince: String(tab.stalledSince) } : {}),
119
139
  ...(Number.isFinite(changedAt) ? { idleFor: Math.max(0, Math.floor((now - changedAt) / 1000)) } : {}) });
120
140
  }
121
141
  return sessions;
@@ -1,4 +1,5 @@
1
1
  import { type ModuleSnapshot } from "../modules/runtime.js";
2
+ import { type CodexServerEntry } from "./codex-servers.js";
2
3
  export declare const forcedCommand = "command=\"sh ~/.local/share/phren/bridge/dispatch\"";
3
4
  export declare function upgradeKeys(text: string): {
4
5
  text: string;
@@ -40,7 +41,13 @@ export declare function detectGateway(env?: NodeJS.ProcessEnv): Promise<GatewayK
40
41
  export declare function gatewayScript(gateway: GatewayKind, environment: GatewayEnvironment): string;
41
42
  /** The commands that restart the Hook in `domain`, printed when launchd refuses. */
42
43
  export declare function launchCommands(domain: string, plist: string): string[];
43
- export declare function install(version: string, noService?: boolean): Promise<void>;
44
+ /** How long install waits for Codex turns that would stop with the Hook. */
45
+ export declare const CODEX_TURN_WAIT_MS: number;
46
+ /** Codex workers still running inside the Hook's service (started by a Hook
47
+ * from before each server got its own scope) stop with it, mid-turn or not.
48
+ * Say which, and wait up to `waitMs` for the running turns to finish. */
49
+ export declare function waitForCodexWorkers(waitMs?: number, inService?: () => Promise<CodexServerEntry[]>, log?: (line: string) => void, pollMs?: number): Promise<void>;
50
+ export declare function install(version: string, noService?: boolean, force?: boolean): Promise<void>;
44
51
  export declare function uninstall(): Promise<void>;
45
52
  interface SettingsEdit {
46
53
  file: string;
@@ -15,7 +15,10 @@ import { bridgeRoot, object, objects, atomic, socketPath } from "./protocol.js";
15
15
  import { herdrRoot } from "./herdr.js";
16
16
  import { health } from "./transport.js";
17
17
  import { FAST_HOOK_SOURCE, fastHookPath } from "./hook-fast.js";
18
+ import { installAskpass, removeAskpass } from "./sudo.js";
18
19
  import { readStoredVoice, SPEECH_VOICE_ENV, writeSpeechVoice } from "./speech-voice.js";
20
+ import { carryCodexHookTrust } from "./codex-hook-trust.js";
21
+ import { serversInService } from "./codex-servers.js";
19
22
  const exec = promisify(execFile);
20
23
  const label = "com.phren.hook";
21
24
  const unit = "phren-hook.service";
@@ -197,6 +200,30 @@ async function startService() {
197
200
  await exec("systemctl", ["--user", "enable", "--now", unit]);
198
201
  }
199
202
  }
203
+ /** How long install waits for Codex turns that would stop with the Hook. */
204
+ export const CODEX_TURN_WAIT_MS = 10 * 60 * 1000;
205
+ /** Codex workers still running inside the Hook's service (started by a Hook
206
+ * from before each server got its own scope) stop with it, mid-turn or not.
207
+ * Say which, and wait up to `waitMs` for the running turns to finish. */
208
+ export async function waitForCodexWorkers(waitMs = CODEX_TURN_WAIT_MS, inService = () => serversInService(unit), log = console.log, pollMs = 5_000) {
209
+ if (process.platform !== "linux")
210
+ return;
211
+ const describe = (entry) => `${entry.pane}${entry.dispatchId ? ` (dispatch ${entry.dispatchId.slice(0, 8)})` : ""}${entry.activeTurn ? ", turn running" : ", idle"}`;
212
+ let workers = await inService();
213
+ if (!workers.length)
214
+ return;
215
+ log(`${workers.length} Codex worker${workers.length === 1 ? "" : "s"} run inside the Phren Hook's service and will stop when it restarts: ${workers.map(describe).join("; ")}.`
216
+ + " Hooks from this version on start each Codex server in its own scope, so later restarts leave them running.");
217
+ const deadline = Date.now() + waitMs;
218
+ while (workers.some(entry => entry.activeTurn) && Date.now() < deadline) {
219
+ log(`Waiting up to ${Math.ceil((deadline - Date.now()) / 60_000)} min for ${workers.filter(entry => entry.activeTurn).length} running Codex turn(s) to finish. Pass --force to restart now.`);
220
+ await new Promise(resolve => setTimeout(resolve, pollMs));
221
+ workers = await inService();
222
+ }
223
+ const cut = workers.filter(entry => entry.activeTurn);
224
+ if (cut.length)
225
+ log(`Restarting anyway: ${cut.map(describe).join("; ")} will stop mid-turn and return failed.`);
226
+ }
200
227
  async function serviceReady(version) {
201
228
  for (let i = 0; i < 50; i++) {
202
229
  try {
@@ -209,7 +236,7 @@ async function serviceReady(version) {
209
236
  }
210
237
  return false;
211
238
  }
212
- export async function install(version, noService = false) {
239
+ export async function install(version, noService = false, force = false) {
213
240
  if (!["darwin", "linux"].includes(process.platform))
214
241
  throw new Error("Phren Hook supports macOS and Linux.");
215
242
  if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version))
@@ -245,6 +272,7 @@ export async function install(version, noService = false) {
245
272
  root, herdr, store: modules.store, profile: modules.profile, node: process.execPath,
246
273
  bundle: path.join(root, "current/bridge-hook.mjs"), socket: socketPath(), timing: path.join(root, "gateway.json"),
247
274
  }), 0o700);
275
+ await installAskpass(process.execPath, path.join(root, "current/bridge-hook.mjs"));
248
276
  const environmentPath = [path.dirname(process.execPath), path.join(homedir(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
249
277
  const program = path.join(root, "current/bridge-hook.mjs");
250
278
  if (!noService) {
@@ -261,8 +289,10 @@ export async function install(version, noService = false) {
261
289
  else {
262
290
  const folder = path.join(homedir(), ".config/systemd/user");
263
291
  await mkdir(folder, { recursive: true });
264
- await atomic(path.join(folder, unit), `[Unit]\nDescription=Phren Hook\n[Service]\nExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve\nNice=-5\nEnvironment=${systemdQuote("PATH=" + environmentPath)} ${systemdQuote("PHREN_BRIDGE_HOME=" + root)} ${systemdQuote("PHREN_HERDR_HOME=" + herdr)} ${systemdQuote("PHREN_PATH=" + modules.store)} ${systemdQuote("PHREN_PROFILE=" + modules.profile)}\nRestart=on-failure\nRestartSec=3\nUMask=0077\n[Install]\nWantedBy=default.target\n`);
292
+ await atomic(path.join(folder, unit), `[Unit]\nDescription=Phren Hook\n[Service]\nExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve\nNice=-5\nEnvironment=${systemdQuote("PATH=" + environmentPath)} ${systemdQuote("PHREN_BRIDGE_HOME=" + root)} ${systemdQuote("PHREN_HERDR_HOME=" + herdr)} ${systemdQuote("PHREN_PATH=" + modules.store)} ${systemdQuote("PHREN_PROFILE=" + modules.profile)}\nRestart=always\nRestartSec=3\nUMask=0077\n[Install]\nWantedBy=default.target\n`);
265
293
  }
294
+ if (!force)
295
+ await waitForCodexWorkers();
266
296
  await stopService();
267
297
  }
268
298
  await activate(version);
@@ -307,7 +337,9 @@ export async function install(version, noService = false) {
307
337
  }
308
338
  console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
309
339
  }
310
- await atomic(path.join(root, "installed.json"), JSON.stringify({ version, previous: previous?.version === version ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
340
+ await atomic(path.join(root, "installed.json"), JSON.stringify({ version, previous: previous?.version === version ? previous.previous : previous?.version, node: process.execPath, gateway, store: modules.store }, null, 2) + "\n");
341
+ // Last, so a failed install restores hooks.json without leaving trust for entries it no longer has.
342
+ await carryCodexHookTrust(program, codexHooksBefore(hookEdits));
311
343
  console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
312
344
  console.log(`SSH gateway: ${gateway}${gateway === "node" ? " (no socat or nc -U found)" : ""}.`);
313
345
  console.log(`Phren Hook ${version} installed${noService ? " (service not started)" : " and running"}. Run phren bridge doctor.`);
@@ -339,6 +371,7 @@ export async function uninstall() {
339
371
  }
340
372
  await applyAgentHooks(await planAgentHooks(path.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
341
373
  await applyOpencodePlugin(true);
374
+ await removeAskpass();
342
375
  // Preserve journal, settings, uploaded images, rollback version and SSH backups.
343
376
  console.log("Phren Hook stopped and its background service removed. Remove phren-iphone, phren-android and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
344
377
  }
@@ -485,6 +518,8 @@ async function applyAgentHooks(edits) {
485
518
  await atomic(file, after);
486
519
  }
487
520
  }
521
+ /** Codex's hooks.json as it stood before `edits` rewrote it, when they did. */
522
+ const codexHooksBefore = (edits) => edits.find(edit => edit.file === path.join(codexHome(), "hooks.json"))?.before;
488
523
  async function restoreAgentHooks(edits) {
489
524
  for (const { file, before, after } of edits) {
490
525
  // A concurrent user edit always wins over rollback.
@@ -506,16 +541,34 @@ export async function rollback() {
506
541
  // The version now in `current/` decides whether Claude's callbacks run its
507
542
  // forwarder or, from before the forwarder, its bundle.
508
543
  const root = bridgeRoot();
509
- await applyAgentHooks(await planAgentHooks(path.join(root, "current/bridge-hook.mjs"), false, moduleSnapshot(defaultPhrenPath(), undefined, true), await currentHasFastHook(root)));
510
- await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version }) + "\n");
544
+ const program = path.join(root, "current/bridge-hook.mjs");
545
+ const edits = await planAgentHooks(program, false, moduleSnapshot(defaultPhrenPath(), undefined, true), await currentHasFastHook(root));
546
+ await applyAgentHooks(edits);
547
+ await carryCodexHookTrust(program, codexHooksBefore(edits));
548
+ await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version, ...(config.store ? { store: config.store } : {}) }) + "\n");
511
549
  }
512
550
  export async function reconcileModuleHooks(store, profile) {
513
551
  const modules = moduleSnapshot(store, profile);
514
552
  const root = bridgeRoot();
515
553
  // Synced enablement alone never installs a host service or enrolls a key.
516
- if (!await missingFile(readFile(path.join(root, "installed.json"))))
554
+ const installed = await missingFile(readFile(path.join(root, "installed.json"), "utf8"));
555
+ if (!installed)
517
556
  return;
518
- await applyAgentHooks(await planAgentHooks(path.join(root, "current/bridge-hook.mjs"), false, modules, await currentHasFastHook(root)));
557
+ // The Hook serves the store it was installed with. `phren init` or `link`
558
+ // on another store (a scratch store, a test's) must not stop it or rewrite
559
+ // its agent hooks: a test run inside a Hook-launched worker did exactly that.
560
+ const served = (() => { try {
561
+ return object(JSON.parse(installed)).store;
562
+ }
563
+ catch {
564
+ return undefined;
565
+ } })();
566
+ if (typeof served === "string" && path.resolve(served) !== path.resolve(store))
567
+ return;
568
+ const program = path.join(root, "current/bridge-hook.mjs");
569
+ const edits = await planAgentHooks(program, false, modules, await currentHasFastHook(root));
570
+ await applyAgentHooks(edits);
571
+ await carryCodexHookTrust(program, codexHooksBefore(edits));
519
572
  await applyOpencodePlugin(!modules.has("hook"));
520
573
  if (!modules.has("hook"))
521
574
  await stopService();
@@ -33,5 +33,17 @@ export declare function dialogStatus(server: string, pane: string, terminal: str
33
33
  status: string;
34
34
  seq: number;
35
35
  } | undefined>;
36
+ /** A Codex that has not sent its first lifecycle event, read from its
37
+ * screen: blocked on a startup menu (folder trust, hooks to review), working
38
+ * while it shows its interrupt hint (a turn whose hooks did not run), idle
39
+ * once its composer and footer are drawn, else undefined (still starting). */
40
+ export declare function codexStartupStatus(screen: string): "blocked" | "working" | "idle" | undefined;
41
+ /** The status of a hooked agent in `pane` that has sent no lifecycle event
42
+ * yet: Codex's screen read (`codexStartupStatus`) at most once per
43
+ * DIALOG_READ_MS, else undefined. Its first event takes over for good. */
44
+ export declare function startupStatus(server: string, pane: string, terminal: string, agent: string, read: () => Promise<string>): Promise<{
45
+ status: string;
46
+ seq: number;
47
+ } | undefined>;
36
48
  /** For tests. */
37
49
  export declare function resetPaneStatus(): void;
@@ -14,6 +14,11 @@
14
14
  // looks "working" to all of that. While a pane is working its screen is read,
15
15
  // at most once per DIALOG_READ_MS, and a dialog there makes the pane blocked
16
16
  // until the dialog is gone.
17
+ //
18
+ // Codex holds its SessionStart hook until the first turn, so a Codex that has
19
+ // just opened has sent nothing yet and would stay "unknown", which refuses
20
+ // the phone's first message. Until its first event its screen says instead:
21
+ // a menu (folder trust, hooks to review) is blocked, its composer idle.
17
22
  import { readFile } from "node:fs/promises";
18
23
  import { stripTerminal } from "../terminal-text.js";
19
24
  import { bindingPath } from "./agent-hook-stores.js";
@@ -135,5 +140,49 @@ export async function dialogStatus(server, pane, terminal, agent, base, read) {
135
140
  return { status: "blocked", seq: entry.shown.seq };
136
141
  return { status: base.status, seq: Math.max(base.seq, entry.cleared ?? 0) };
137
142
  }
143
+ /** A Codex that has not sent its first lifecycle event, read from its
144
+ * screen: blocked on a startup menu (folder trust, hooks to review), working
145
+ * while it shows its interrupt hint (a turn whose hooks did not run), idle
146
+ * once its composer and footer are drawn, else undefined (still starting). */
147
+ export function codexStartupStatus(screen) {
148
+ const text = stripTerminal(screen);
149
+ if (visibleTerminalChoice(text))
150
+ return "blocked";
151
+ if (/\besc to interrupt\b/i.test(text))
152
+ return "working";
153
+ const lines = text.split(/\r?\n/).map(line => line.trimEnd()).filter(line => line.trim());
154
+ let composer = lines.length - 1;
155
+ while (composer >= 0 && !/^\u203a(?:\s|$)/.test(lines[composer]))
156
+ composer -= 1;
157
+ // The composer sits above a footer or two: "? for shortcuts" (0.158), or
158
+ // just the model line (0.155). A "\u203a" row higher up is an earlier prompt.
159
+ return composer >= 0 && composer >= lines.length - 3 && lines.length - composer > 1 ? "idle" : undefined;
160
+ }
161
+ const startups = new Map();
162
+ /** The status of a hooked agent in `pane` that has sent no lifecycle event
163
+ * yet: Codex's screen read (`codexStartupStatus`) at most once per
164
+ * DIALOG_READ_MS, else undefined. Its first event takes over for good. */
165
+ export async function startupStatus(server, pane, terminal, agent, read) {
166
+ if (agent !== "codex")
167
+ return undefined;
168
+ const id = key(server, pane);
169
+ let entry = startups.get(id);
170
+ if (!entry || entry.terminal !== terminal) {
171
+ entry = { terminal, readAt: 0 };
172
+ startups.delete(id);
173
+ while (startups.size >= 512)
174
+ startups.delete(startups.keys().next().value);
175
+ startups.set(id, entry);
176
+ }
177
+ const now = Date.now();
178
+ if (now - entry.readAt >= DIALOG_READ_MS) {
179
+ entry.readAt = now;
180
+ // A failed read says nothing: the pane keeps what it had.
181
+ const seen = await read().then(codexStartupStatus, () => entry.status?.status);
182
+ if (seen !== entry.status?.status)
183
+ entry.status = seen ? { status: seen, seq: ++sequence } : undefined;
184
+ }
185
+ return entry.status;
186
+ }
138
187
  /** For tests. */
139
- export function resetPaneStatus() { entries.clear(); dialogs.clear(); }
188
+ export function resetPaneStatus() { entries.clear(); dialogs.clear(); startups.clear(); }
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { type RequestKind } from "./approval-summary.js";
3
+ import type { SudoRequestView } from "./sudo.js";
3
4
  /** A phone registered through the phren push relay: the relay knows where to
4
5
  * deliver, and `key` (32 bytes, base64url) encrypts what the notification says
5
6
  * so only the phone reads it. The phone made the key and sent it over SSH. */
@@ -66,6 +67,10 @@ export interface SchedulePushResult {
66
67
  }
67
68
  export declare function scheduleCollapseId(kind: SchedulePushKind, runId: string): string;
68
69
  export declare function approvalPushPayload(value: ApprovalPush, host?: string): Record<string, unknown>;
70
+ /** A sudo request waiting for its password. The command is what the owner
71
+ * approves; the password itself is typed only in the app, never in a
72
+ * notification action. */
73
+ export declare function sudoPushPayload(value: SudoRequestView, host?: string): Record<string, unknown>;
69
74
  export declare function fanoutBlockedPushPayload(value: FanoutBlockedPush): Record<string, unknown>;
70
75
  export declare function schedulePushPayload(value: SchedulePush): Record<string, unknown>;
71
76
  /** What `phren bridge doctor` prints when the Hook has no APNs sender. */
@@ -114,6 +119,7 @@ export declare class ApprovalPushService {
114
119
  /** One phone: the relay when it registered through one, otherwise direct. */
115
120
  private send;
116
121
  notify(value: ApprovalPush): Promise<boolean>;
122
+ notifySudo(value: SudoRequestView): Promise<boolean>;
117
123
  /** A headless worker whose permission the plugin refused. Approval-registered
118
124
  * phones already accept agent alerts; the payload carries the reason so the
119
125
  * notification is actionable on its own. */
@@ -45,6 +45,19 @@ export function approvalPushPayload(value, host) {
45
45
  request, requestKind: value.requestKind ?? (value.question ? "question" : "other") },
46
46
  };
47
47
  }
48
+ /** A sudo request waiting for its password. The command is what the owner
49
+ * approves; the password itself is typed only in the app, never in a
50
+ * notification action. */
51
+ export function sudoPushPayload(value, host) {
52
+ const command = shortApproval(value.command) || "sudo";
53
+ return {
54
+ aps: {
55
+ alert: { title: `sudo on ${value.computer}`, body: command },
56
+ sound: "default", category: "PHREN_SUDO", "interruption-level": "time-sensitive",
57
+ },
58
+ phren: { version: 1, kind: "sudo", id: value.id, ...(host ? { host } : {}), computer: value.computer, command, expiresAt: value.expiresAt },
59
+ };
60
+ }
48
61
  export function fanoutBlockedPushPayload(value) {
49
62
  return {
50
63
  aps: { alert: { title: `${value.label} blocked`, body: value.reason }, sound: "default", category: "PHREN_FANOUT" },
@@ -238,6 +251,14 @@ export class ApprovalPushService {
238
251
  expiration: String(Math.floor(Date.parse(value.expiresAt) / 1000)), collapseId: value.binding,
239
252
  })))).some(Boolean);
240
253
  }
254
+ async notifySudo(value) {
255
+ const devices = this.reachable.filter(device => device.kinds.includes("approval"));
256
+ if (!devices.length)
257
+ return false;
258
+ return (await Promise.all(devices.map(device => this.send(device, sudoPushPayload(value, device.hostID), {
259
+ expiration: String(Math.floor(Date.parse(value.expiresAt) / 1000)), collapseId: `sudo-${value.id}`,
260
+ })))).some(Boolean);
261
+ }
241
262
  /** A headless worker whose permission the plugin refused. Approval-registered
242
263
  * phones already accept agent alerts; the payload carries the reason so the
243
264
  * notification is actionable on its own. */
@@ -11,7 +11,7 @@ export declare function createScheduleLauncher(launchHerdr: HerdrLauncher, store
11
11
  * since an open run blocks its schedule for good.
12
12
  */
13
13
  export declare function resumeScheduleRun(run: ScheduleRun, schedule: Schedule, signal: AbortSignal, watch?: typeof watchHerdrRun): Promise<ScheduleRunOutcome>;
14
- /** The environment a headless run gets: this Hook's, plus the chosen Claude account's config directory. */
14
+ /** The environment a headless run gets: this Hook's, SUDO_ASKPASS, plus the chosen Claude account's config directory. */
15
15
  export declare function headlessEnv(schedule: Schedule, env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
16
16
  export declare function headlessCommand(schedule: Schedule, cwd: string): {
17
17
  file: string;
@@ -3,6 +3,7 @@ import { createWriteStream } from "node:fs";
3
3
  import { mkdir, readFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { finished as streamFinished } from "node:stream/promises";
6
+ import { askpassEnv } from "./sudo.js";
6
7
  import { claudeHome, claudeLaunchEnv } from "./claude-accounts.js";
7
8
  import { fanoutRoot } from "./fanouts.js";
8
9
  import { pretrustFolder } from "./folder-trust.js";
@@ -90,8 +91,11 @@ async function promptWhenReady(server, paneId, text, signal, waitMs = 60_000) {
90
91
  }
91
92
  }
92
93
  }
93
- /** The environment a headless run gets: this Hook's, plus the chosen Claude account's config directory. */
94
+ /** The environment a headless run gets: this Hook's, SUDO_ASKPASS, plus the chosen Claude account's config directory. */
94
95
  export function headlessEnv(schedule, env = process.env) {
96
+ const askpass = askpassEnv();
97
+ if (askpass.SUDO_ASKPASS)
98
+ env = { ...env, ...askpass };
95
99
  if (!schedule.account || schedule.harness !== "claude")
96
100
  return env;
97
101
  const home = claudeHome(schedule.account, env);
@@ -36,7 +36,10 @@ export interface StartupWatchEnv {
36
36
  * `background`: Claude Code background tasks (shells, subagents, monitors) started in
37
37
  * the transcript's tail with no task-notification or TaskStop ending them yet.
38
38
  * `finishedTasks`: when each Claude background task the tail shows finishing
39
- * finished (its first final task-notification's timestamp), one per task. */
39
+ * finished (its first final task-notification's timestamp), one per task.
40
+ * `awaited`: those of the running tasks that are shells or monitors started
41
+ * since the owner's last prompt, other than streams that never end (a log
42
+ * tail, a watcher, a dev server). Sub-agents are left to the child tree. */
40
43
  export interface FinalTurn {
41
44
  completed: boolean;
42
45
  lastAssistant?: string;
@@ -44,9 +47,20 @@ export interface FinalTurn {
44
47
  interrupted?: boolean;
45
48
  background?: number;
46
49
  finishedTasks?: string[];
50
+ awaited?: number;
47
51
  }
48
52
  /** The public text of one assistant row, without reasoning or tool output. */
49
53
  export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
54
+ /** Claude Code background work a transcript line starts or ends, by task id:
55
+ * a backgrounded Bash call, an async subagent or a Monitor start one; a
56
+ * task-notification with a final status, or a TaskStop, ends it. A
57
+ * persistent monitor runs for the whole session and is never waited on.
58
+ * `finished` keeps when each task's first final notification was written.
59
+ * A notification reaching an idle session is written as a queue-operation
60
+ * row, and may stay there with no new turn to deliver it. */
61
+ /** A backgrounded command that runs until killed rather than finishing:
62
+ * following a log, watching files, serving a dev build. Nobody waits on it. */
63
+ export declare const ENDLESS_COMMAND: RegExp;
50
64
  /** The last assistant reply in a transcript and whether its turn finished.
51
65
  * A person's message after the reply opens a new turn, so it clears both. */
52
66
  export declare function finalTurnFromLines(lines: readonly string[], source: ScheduleHarness): FinalTurn;
@@ -100,15 +100,35 @@ function turnInterrupted(raw, source) {
100
100
  * `finished` keeps when each task's first final notification was written.
101
101
  * A notification reaching an idle session is written as a queue-operation
102
102
  * row, and may stay there with no new turn to deliver it. */
103
- function backgroundTasks(raw, running, finished) {
104
- const result = object(raw.toolUseResult);
105
- const started = typeof result.backgroundTaskId === "string" ? result.backgroundTaskId
106
- : result.isAsync === true && typeof result.agentId === "string" ? result.agentId
107
- : typeof result.taskId === "string" && result.persistent !== true && typeof result.timeoutMs === "number" ? result.taskId : undefined;
103
+ /** A backgrounded command that runs until killed rather than finishing:
104
+ * following a log, watching files, serving a dev build. Nobody waits on it. */
105
+ export const ENDLESS_COMMAND = /\btail\s+(?:-[a-zA-Z]*[fF][a-zA-Z]*\b|--follow\b)|\bjournalctl\b[^|;&]*\s(?:-[a-zA-Z]*f[a-zA-Z]*\b|--follow\b)|\blog\s+stream\b|\blogcat\b|\bwatch\s|--watch\b|\binotifywait\b[^|;&]*\s-m\b|\bfswatch\b|\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|serve|preview)\b|\bhttp\.server\b|\bsleep\s+infinity\b/;
106
+ function backgroundTasks(raw, running, finished, tail) {
107
+ const result = object(raw.toolUseResult), blocks = objects(object(raw.message).content);
108
+ if (raw.type === "assistant") {
109
+ for (const block of blocks) {
110
+ const input = object(block.input);
111
+ if (block.type === "tool_use" && typeof block.id === "string" && input.run_in_background === true && typeof input.command === "string")
112
+ tail.commands.set(block.id, input.command.slice(0, 2_000));
113
+ }
114
+ }
115
+ const shell = typeof result.backgroundTaskId === "string" ? result.backgroundTaskId : undefined;
116
+ const monitor = typeof result.taskId === "string" && result.persistent !== true && typeof result.timeoutMs === "number" ? result.taskId : undefined;
117
+ const started = shell ?? (result.isAsync === true && typeof result.agentId === "string" ? result.agentId : monitor);
108
118
  if (started)
109
119
  running.add(started);
110
- if (typeof result.task_id === "string" && typeof result.message === "string" && /\bstopped\b/i.test(result.message))
120
+ if (shell) {
121
+ const call = blocks.find(block => block.type === "tool_result")?.tool_use_id;
122
+ const command = typeof call === "string" ? tail.commands.get(call) : undefined;
123
+ if (!command || !ENDLESS_COMMAND.test(command))
124
+ tail.awaited.add(shell);
125
+ }
126
+ else if (monitor)
127
+ tail.awaited.add(monitor);
128
+ if (typeof result.task_id === "string" && typeof result.message === "string" && /\bstopped\b/i.test(result.message)) {
111
129
  running.delete(result.task_id);
130
+ tail.awaited.delete(result.task_id);
131
+ }
112
132
  const content = object(raw.message).content, attachment = object(raw.attachment);
113
133
  const notices = [typeof content === "string" ? content : "", typeof attachment.prompt === "string" ? attachment.prompt : "",
114
134
  raw.type === "queue-operation" && typeof raw.content === "string" ? raw.content : ""];
@@ -118,6 +138,7 @@ function backgroundTasks(raw, running, finished) {
118
138
  if (!id || !/<status>(?:completed|failed|killed|stopped)<\/status>/.test(block))
119
139
  continue;
120
140
  running.delete(id);
141
+ tail.awaited.delete(id);
121
142
  if (!finished.has(id) && typeof raw.timestamp === "string" && !Number.isNaN(Date.parse(raw.timestamp)))
122
143
  finished.set(id, raw.timestamp);
123
144
  }
@@ -126,7 +147,7 @@ function backgroundTasks(raw, running, finished) {
126
147
  * A person's message after the reply opens a new turn, so it clears both. */
127
148
  export function finalTurnFromLines(lines, source) {
128
149
  let completed = false, lastAssistant, error, interrupted = false;
129
- const running = new Set(), finished = new Map();
150
+ const running = new Set(), finished = new Map(), tail = { commands: new Map(), awaited: new Set() };
130
151
  for (const line of lines) {
131
152
  if (!line.trim())
132
153
  continue;
@@ -138,8 +159,13 @@ export function finalTurnFromLines(lines, source) {
138
159
  continue;
139
160
  }
140
161
  const payload = object(raw.payload);
141
- if (source === "claude")
142
- backgroundTasks(raw, running, finished);
162
+ if (source === "claude") {
163
+ backgroundTasks(raw, running, finished, tail);
164
+ // The owner moving on leaves what earlier turns started behind: a
165
+ // shell still running from then is a leftover, not work in flight.
166
+ if (ownerPrompt(raw))
167
+ tail.awaited.clear();
168
+ }
143
169
  if (turnInterrupted(raw, source)) {
144
170
  interrupted = true;
145
171
  completed = false;
@@ -169,7 +195,16 @@ export function finalTurnFromLines(lines, source) {
169
195
  }
170
196
  return { completed, ...(lastAssistant ? { lastAssistant } : {}), ...(completed && error ? { error } : {}),
171
197
  ...(interrupted ? { interrupted: true } : {}), ...(completed && running.size ? { background: running.size } : {}),
172
- ...(finished.size ? { finishedTasks: [...finished.values()] } : {}) };
198
+ ...(finished.size ? { finishedTasks: [...finished.values()] } : {}), ...(tail.awaited.size ? { awaited: tail.awaited.size } : {}) };
199
+ }
200
+ /** A prompt the owner (or a dispatcher) typed, not a task's notification or
201
+ * a teammate's message waking the session. */
202
+ function ownerPrompt(raw) {
203
+ const content = object(raw.message).content;
204
+ if (raw.type !== "user" || raw.isMeta || typeof content !== "string")
205
+ return false;
206
+ const text = content.trimStart();
207
+ return !text.startsWith("<task-notification>") && !text.startsWith("<teammate-message");
173
208
  }
174
209
  /** The final turn of a conversation, read from the tail of its transcript. */
175
210
  export async function readFinalTurn(source, sessionId) {
@@ -4,9 +4,11 @@ import { fileURLToPath } from "node:url";
4
4
  import { z } from "zod";
5
5
  import { homeDir } from "../home-paths.js";
6
6
  import { agentNames, findPane, isConductorName, paneChatState, paneIdentity, servers, snapshot } from "./herdr.js";
7
- import { agentNotReady, terminalName, terminalProvider } from "./terminal.js";
7
+ import { agentNotReady, terminalKind, terminalName, terminalProvider } from "./terminal.js";
8
+ import { tmuxScroll } from "./terminal-tmux.js";
8
9
  import { intervalFromEnv } from "./limits.js";
9
10
  import { createLaunchWorktree, launchWorktreeSchema } from "./launch-worktree.js";
11
+ import { askpassEnv } from "./sudo.js";
10
12
  import { briefArgs, DISPATCH_ID_ENV, launchBriefSchema, launchesWithBrief, recordBriefArrival, writeLaunchBrief } from "./launch-brief.js";
11
13
  import { prepareServedLaunch, registerServedPane, sendServedBrief } from "./opencode-panes.js";
12
14
  import { groupConductor } from "./conductor-group.js";
@@ -292,7 +294,8 @@ export async function launchSession(server, data, options = {}) {
292
294
  args.push(...served.args);
293
295
  const briefFile = brief && (launchesWithBrief(kind) || structured || served) ? await writeLaunchBrief(brief, Date.now(), label) : undefined;
294
296
  const briefLaunch = brief && briefFile && launchesWithBrief(kind) ? briefArgs(kind, briefFile) : undefined;
295
- const variables = { ...(brief ? { [DISPATCH_ID_ENV]: brief.id } : {}), ...served?.env, ...(home ? claudeLaunchEnv(home) : {}) };
297
+ // sudo -A in the new agent asks the phone for the password (sudo.ts).
298
+ const variables = { ...askpassEnv(), ...(brief ? { [DISPATCH_ID_ENV]: brief.id } : {}), ...served?.env, ...(home ? claudeLaunchEnv(home) : {}) };
296
299
  const env = Object.keys(variables).length ? variables : undefined;
297
300
  if (workspace && !objects(before.workspaces).some(w => w.workspace_id === workspace))
298
301
  throw new BridgeError(409, "The workspace changed.");
@@ -411,12 +414,19 @@ export async function launchSession(server, data, options = {}) {
411
414
  ...(worktree ? { worktree: { path: worktree.path, branch: worktree.branch } } : {}) };
412
415
  }
413
416
  export async function workspaceAction(server, operation, data) {
414
- if (!["focus", "rename", "create", "close"].includes(operation))
417
+ if (!["focus", "rename", "create", "close", "scroll"].includes(operation))
415
418
  throw new BridgeError(400, "Unsupported Herdr action.");
416
- const s = await snapshot(server);
417
419
  const workspace = typeof data.workspaceId === "string" ? data.workspaceId : undefined;
418
420
  const tab = typeof data.tabId === "string" ? data.tabId : undefined;
419
421
  const pane = typeof data.paneId === "string" ? data.paneId : undefined;
422
+ if (operation === "scroll") {
423
+ // Every swipe step lands here, so it skips the snapshot: tmux itself
424
+ // refuses a pane that is gone.
425
+ if (terminalKind(server) !== "tmux")
426
+ throw new BridgeError(400, "Herdr scrolls in the terminal itself.");
427
+ return { ok: true, ...await tmuxScroll(server, pane, z.number().int().min(-200).max(200).parse(data.lines)) };
428
+ }
429
+ const s = await snapshot(server);
420
430
  if (workspace && !objects(s.workspaces).some(w => w.workspace_id === workspace))
421
431
  throw new BridgeError(409, "The workspace changed.");
422
432
  if (tab && !objects(s.tabs).some(t => t.tab_id === tab && (!workspace || t.workspace_id === workspace)))
@@ -17,6 +17,8 @@ import type { WorkspacesReader } from "./server-routes.js";
17
17
  * `{ type: "heartbeat", phren }`. A phone that asks with `resources=1` also
18
18
  * gets `{ type: "resources", resources }` after the first overview, then at
19
19
  * `OVERVIEW_RESOURCES_MS` intervals (an older phone never asks, so never meets it).
20
+ * One that asks with `sudo=1` gets `{ type: "sudo", requests }` after the first
21
+ * overview and whenever the pending sudo requests change.
20
22
  */
21
23
  export declare const OVERVIEW_TICK_MS: number;
22
24
  export declare const OVERVIEW_REFRESH_MS: number;
@@ -28,6 +30,11 @@ export interface OverviewStreamOptions {
28
30
  info: () => Json;
29
31
  /** Renews the approval watch lease `watchApprovals=1` asks for. */
30
32
  renew: (server: string) => void;
33
+ /** Pending sudo requests (`GET /v1/sudo`), for phones that ask with `sudo=1`. */
34
+ sudo?: {
35
+ list(): unknown[];
36
+ subscribe(listener: (requests: unknown[]) => void): () => void;
37
+ };
31
38
  /** This computer's resources (`GET /v1/resources`), for phones that ask. */
32
39
  resources?: () => Promise<unknown>;
33
40
  snapshot?: (server: string, maxAgeMs: number) => Promise<Json>;
@@ -45,7 +52,7 @@ export interface OverviewClient {
45
52
  close(code?: number, reason?: string): void;
46
53
  once(event: "close" | "error", listener: () => void): unknown;
47
54
  }
48
- export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean, withResources?: boolean, typedMux?: boolean) => {
55
+ export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean, withResources?: boolean, typedMux?: boolean, withSudo?: boolean) => {
49
56
  tick: () => Promise<void>;
50
57
  stop: () => void;
51
58
  };