@phren/cli 0.3.16 → 0.3.17

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 (41) hide show
  1. package/dist/bridge/agent-hooks.d.ts +10 -0
  2. package/dist/bridge/agent-hooks.js +49 -10
  3. package/dist/bridge/claude-suggestion.d.ts +8 -0
  4. package/dist/bridge/claude-suggestion.js +71 -0
  5. package/dist/bridge/dispatch-returns.d.ts +6 -3
  6. package/dist/bridge/dispatch-returns.js +29 -17
  7. package/dist/bridge/job-registry.d.ts +144 -0
  8. package/dist/bridge/job-registry.js +247 -0
  9. package/dist/bridge/opencode-permissions.d.ts +17 -0
  10. package/dist/bridge/opencode-permissions.js +96 -0
  11. package/dist/bridge/protocol.d.ts +4 -0
  12. package/dist/bridge/protocol.js +3 -0
  13. package/dist/bridge/resources.d.ts +38 -5
  14. package/dist/bridge/resources.js +110 -19
  15. package/dist/bridge/server-launch.js +8 -0
  16. package/dist/bridge/server-routes.d.ts +1 -1
  17. package/dist/bridge/server-routes.js +8 -6
  18. package/dist/bridge/server-stream.js +11 -2
  19. package/dist/bridge/session-activity.d.ts +13 -0
  20. package/dist/bridge/session-activity.js +27 -2
  21. package/dist/bridge/settings-switch.d.ts +12 -2
  22. package/dist/bridge/settings-switch.js +13 -6
  23. package/dist/bridge/speech.d.ts +6 -4
  24. package/dist/bridge/speech.js +6 -4
  25. package/dist/bridge/terminal-tmux.d.ts +4 -2
  26. package/dist/bridge/terminal-tmux.js +13 -7
  27. package/dist/bridge/transcript-claude.d.ts +9 -1
  28. package/dist/bridge/transcript-claude.js +50 -1
  29. package/dist/bridge/transcript-codex.js +23 -3
  30. package/dist/bridge/transcripts.d.ts +5 -1
  31. package/dist/bridge/transcripts.js +13 -3
  32. package/dist/bridge-hook.mjs +1044 -528
  33. package/dist/computers/command.js +2 -1
  34. package/dist/fanout/opencode-serve.js +3 -2
  35. package/dist/hooks.d.ts +3 -0
  36. package/dist/hooks.js +41 -6
  37. package/dist/init/setup.js +6 -3
  38. package/dist/modules/registry.js +1 -1
  39. package/dist/tools/dispatch.js +3 -2
  40. package/package.json +1 -1
  41. package/plugins/opencode/phren-transcript.js +4 -4
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { homeDir } from "../home-paths.js";
7
7
  import { recentServers, sharedSnapshot } from "./herdr.js";
8
+ import { JobRegistry, jobPgids, paneKey } from "./job-registry.js";
8
9
  import { intervalFromEnv } from "./limits.js";
9
10
  import { objects } from "./protocol.js";
10
11
  const exec = promisify(execFile);
@@ -22,7 +23,8 @@ export const RESOURCES_MAX_AGE_MS = intervalFromEnv("PHREN_RESOURCES_MAX_AGE_MS"
22
23
  /** Below this much free disk, or above twice the cores in load, a computer is stressed. */
23
24
  export const LOW_DISK_BYTES = 10 * 1024 ** 3;
24
25
  const GB = 1024 ** 3;
25
- /** `ps -axo pid=,ppid=,pcpu=,rss=,comm=` paired with the `args=` listing by pid. */
26
+ /** `ps -axo pid=,ppid=,pgid=,pcpu=,rss=,comm=` paired with the `args=` listing by
27
+ * pid. The older five-column stats (no pgid) still parse, with pgid 0. */
26
28
  export function parsePs(stats, args) {
27
29
  const argv = new Map();
28
30
  for (const line of args.split("\n")) {
@@ -32,11 +34,16 @@ export function parsePs(stats, args) {
32
34
  }
33
35
  const rows = [];
34
36
  for (const line of stats.split("\n")) {
35
- const match = /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
37
+ const six = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
38
+ const five = six ? undefined : /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
39
+ const match = six ?? five;
36
40
  if (!match)
37
41
  continue;
38
42
  const pid = Number(match[1]);
39
- rows.push({ pid, ppid: Number(match[2]), cpu: Number(match[3]), rssKB: Number(match[4]), command: match[5].trim(), args: argv.get(pid) ?? match[5].trim() });
43
+ const pgid = six ? Number(match[3]) : 0;
44
+ const command = (six ? match[6] : match[5]).trim();
45
+ rows.push({ pid, ppid: Number(match[2]), pgid, cpu: Number(six ? match[4] : match[3]), rssKB: Number(six ? match[5] : match[4]),
46
+ command, args: argv.get(pid) ?? command });
40
47
  }
41
48
  return rows;
42
49
  }
@@ -79,7 +86,7 @@ export function heavyKind(row) {
79
86
  * On Linux, ps pcpu is a process lifetime average, so these cutoffs can miss
80
87
  * daemons that spike briefly.
81
88
  */
82
- export function heavyProcesses(rows, owners = new Map(), limit = 12) {
89
+ export function heavyProcesses(rows, owners = new Map(), jobs = [], limit = 12) {
83
90
  const byPid = new Map(rows.map(row => [row.pid, row]));
84
91
  const kinds = new Map();
85
92
  for (const row of rows) {
@@ -96,6 +103,9 @@ export function heavyProcesses(rows, owners = new Map(), limit = 12) {
96
103
  kinds.delete(row.pid);
97
104
  }
98
105
  }
106
+ // Registered process groups: their pane names the job even when a detached
107
+ // process has been reparented away from it.
108
+ const jobsByPgid = jobPgids(jobs);
99
109
  const totals = new Map();
100
110
  const busy = new Map();
101
111
  const claim = (row) => {
@@ -107,28 +117,45 @@ export function heavyProcesses(rows, owners = new Map(), limit = 12) {
107
117
  }
108
118
  return undefined;
109
119
  };
120
+ // The pane that owns a process: by the registered process group first, then
121
+ // by following its ancestry to a pane's shell or foreground process.
110
122
  const owner = (row) => {
111
123
  for (let at = row, hops = 0; at && hops < 64; at = byPid.get(at.ppid), hops++) {
112
124
  const pane = owners.get(at.pid);
113
125
  if (pane)
114
126
  return pane;
127
+ const job = jobsByPgid.get(at.pgid);
128
+ if (job?.pane)
129
+ return job.pane;
115
130
  if (at.ppid === at.pid || at.ppid <= 1)
116
131
  break;
117
132
  }
118
- return undefined;
133
+ return jobsByPgid.get(row.pgid)?.pane;
119
134
  };
135
+ const trackedRoots = new Set();
136
+ for (const row of rows) {
137
+ const root = claim(row);
138
+ if (root !== undefined && jobsByPgid.has(row.pgid))
139
+ trackedRoots.add(root);
140
+ }
120
141
  for (const row of rows) {
121
142
  const root = claim(row);
143
+ const tracked = jobsByPgid.has(row.pgid) || (root !== undefined && trackedRoots.has(root));
122
144
  if (root === undefined) {
123
- // Unclaimed work groups by program: twelve swift-frontends at 40% each are one busy job.
145
+ // Unclaimed work groups by program: twelve swift-frontends at 40% each
146
+ // are one busy job. A registered group keeps its own bucket, so two
147
+ // workers' helpers are not merged under one pane.
124
148
  const name = path.basename(row.command).slice(0, 60);
125
- const group = busy.get(name);
149
+ const key = tracked ? `job:${row.pgid}\0${name}` : name;
150
+ const group = busy.get(key);
126
151
  if (!group)
127
- busy.set(name, { kind: "busy", name, pid: row.pid, processes: 1, cpuPercent: row.cpu, memoryBytes: row.rssKB * 1024, top: row.cpu, row });
152
+ busy.set(key, { kind: "busy", name, pid: row.pid, processes: 1, cpuPercent: row.cpu, memoryBytes: row.rssKB * 1024, top: row.cpu, row, ...(tracked ? { tracked: true } : {}) });
128
153
  else {
129
154
  group.processes++;
130
155
  group.cpuPercent += row.cpu;
131
156
  group.memoryBytes += row.rssKB * 1024;
157
+ if (tracked)
158
+ group.tracked = true;
132
159
  if (row.cpu > group.top) {
133
160
  group.top = row.cpu;
134
161
  group.pid = row.pid;
@@ -141,21 +168,24 @@ export function heavyProcesses(rows, owners = new Map(), limit = 12) {
141
168
  if (!total) {
142
169
  const { kind, name } = kinds.get(root);
143
170
  const pane = owner(byPid.get(root));
144
- total = { kind, name, pid: root, processes: 0, cpuPercent: 0, memoryBytes: 0, ...(pane ? { pane } : {}) };
171
+ total = { kind, name, pid: root, processes: 0, cpuPercent: 0, memoryBytes: 0, ...(tracked ? { tracked: true } : {}),
172
+ ...(pane ? { pane } : {}), ...(pane?.agent ? { agent: pane.agent } : {}) };
145
173
  totals.set(root, total);
146
174
  }
147
175
  total.processes++;
148
176
  total.cpuPercent += row.cpu;
149
177
  total.memoryBytes += row.rssKB * 1024;
178
+ if (tracked)
179
+ total.tracked = true;
150
180
  }
151
181
  for (const { top: _top, row, ...group } of busy.values()) {
152
- if (group.cpuPercent < 50)
182
+ if (group.cpuPercent < 50 && !group.tracked)
153
183
  continue;
154
184
  const pane = owner(row);
155
- totals.set(group.pid, { ...group, ...(pane ? { pane } : {}) });
185
+ totals.set(group.pid, { ...group, ...(pane ? { pane } : {}), ...(pane?.agent ? { agent: pane.agent } : {}) });
156
186
  }
157
187
  return [...totals.values()]
158
- .filter(item => item.kind === "busy" || item.cpuPercent >= 10 || item.memoryBytes >= 200 * 1024 ** 2)
188
+ .filter(item => item.kind === "busy" || item.cpuPercent >= 10 || item.memoryBytes >= 200 * 1024 ** 2 || item.tracked)
159
189
  .map(item => ({ ...item, cpuPercent: Math.round(item.cpuPercent * 10) / 10,
160
190
  resourceReason: (item.cpuPercent >= 10 ? "cpu" : item.memoryBytes >= 200 * 1024 ** 2 ? "memory" : "tracked") }))
161
191
  .sort((a, b) => b.cpuPercent - a.cpuPercent || b.memoryBytes - a.memoryBytes)
@@ -239,8 +269,46 @@ async function linuxBattery() {
239
269
  return { percent, charging: status === "Charging" || status === "Full", onAC: online.includes("1") };
240
270
  }
241
271
  async function processTable() {
242
- const [stats, args] = await Promise.all([run("/bin/ps", ["-axo", "pid=,ppid=,pcpu=,rss=,comm="]), run("/bin/ps", ["-axo", "pid=,args="])]);
243
- return parsePs(stats, args);
272
+ const [stats, args, elapsed] = await Promise.all([run("/bin/ps", ["-axo", "pid=,ppid=,pgid=,pcpu=,rss=,comm="]), run("/bin/ps", ["-axo", "pid=,args="]),
273
+ run("/bin/ps", ["-axo", "pid=,etime="]).catch(() => "")]);
274
+ return withStartTimes(parsePs(stats, args), elapsed, Date.now());
275
+ }
276
+ /** Seconds from `ps`'s `etime` (`[[dd-]hh:]mm:ss`), or undefined. */
277
+ export function parseEtime(value) {
278
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(value.trim());
279
+ if (!match)
280
+ return undefined;
281
+ return Number(match[1] ?? 0) * 86_400 + Number(match[2] ?? 0) * 3_600 + Number(match[3]) * 60 + Number(match[4]);
282
+ }
283
+ /** Each row's start time (epoch ms, to about a second) from a `pid=,etime=`
284
+ * listing. The job registry checks a process group's leader by it, so a group
285
+ * id the system reused for another program is never signalled. */
286
+ export function withStartTimes(rows, elapsed, now) {
287
+ const started = new Map();
288
+ for (const line of elapsed.split("\n")) {
289
+ const match = /^\s*(\d+)\s+(\S+)\s*$/.exec(line);
290
+ const seconds = match ? parseEtime(match[2]) : undefined;
291
+ if (match && seconds !== undefined)
292
+ started.set(Number(match[1]), now - seconds * 1000);
293
+ }
294
+ return rows.map(row => started.has(row.pid) ? { ...row, startedAt: started.get(row.pid) } : row);
295
+ }
296
+ /** Every pane of every terminal server this computer knows, or undefined when
297
+ * any server's snapshot could not be read. Cleanup ends a job only when its
298
+ * pane is missing from a complete listing: a pane that merely failed to
299
+ * answer, or sat past a display cap, must never look gone. */
300
+ export async function livePanes() {
301
+ const panes = new Set(), servers = new Set();
302
+ for (const server of await recentServers()) {
303
+ const name = String(server.session);
304
+ const s = await sharedSnapshot(name, RESOURCES_MAX_AGE_MS).catch(() => undefined);
305
+ if (!s)
306
+ return undefined;
307
+ servers.add(name);
308
+ for (const pane of objects(s.panes))
309
+ panes.add(paneKey({ server: name, pane: String(pane.pane_id) }));
310
+ }
311
+ return { panes, servers };
244
312
  }
245
313
  /** Every pid a Herdr or tmux pane holds (its shell and foreground), for naming a job's pane. */
246
314
  export async function paneOwners() {
@@ -272,7 +340,8 @@ export async function collectResources(deps) {
272
340
  const [one, five, fifteen] = loadavg();
273
341
  const cores = cpus().length || 1;
274
342
  const platform = deps.platform;
275
- const [memory, disk, battery, rows] = await Promise.all([
343
+ const registry = deps.jobs ?? new JobRegistry();
344
+ const [memory, disk, battery, rows, registered] = await Promise.all([
276
345
  platform === "darwin" ? darwinMemory()
277
346
  : platform === "linux" ? readFile("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() }))
278
347
  : Promise.resolve({ totalBytes: totalmem() }),
@@ -280,16 +349,20 @@ export async function collectResources(deps) {
280
349
  platform === "darwin" ? run("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => undefined)
281
350
  : platform === "linux" ? linuxBattery() : Promise.resolve(undefined),
282
351
  deps.processes().catch(() => []),
352
+ registry.list().catch(() => []),
283
353
  ]);
284
354
  // Pane pids cost one terminal call per pane: only when there is a job to name.
285
- const preliminary = heavyProcesses(rows);
286
- const owners = preliminary.length ? await deps.owners().catch(() => new Map()) : new Map();
355
+ const preliminary = heavyProcesses(rows, new Map(), registered);
356
+ const owners = preliminary.length || registered.length ? await deps.owners().catch(() => new Map()) : new Map();
357
+ // Resolve registered workers' process groups and pane names from the table,
358
+ // so a detached job keeps the agent that owns it.
359
+ const jobs = owners.size ? await registry.reconcile(rows, owners).catch(() => registered) : registered;
287
360
  const round = (n) => Math.round(n * 100) / 100;
288
361
  const value = {
289
362
  collectedAt: new Date(deps.now()).toISOString(), platform, uptimeSeconds: Math.round(uptime()),
290
363
  cpu: { cores, load1: round(one), load5: round(five), load15: round(fifteen), loadPerCore: round(one / cores) },
291
364
  memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}),
292
- heavy: owners.size ? heavyProcesses(rows, owners) : preliminary,
365
+ heavy: owners.size || jobs.length ? heavyProcesses(rows, owners, jobs) : preliminary,
293
366
  };
294
367
  return { ...value, ...assess(value) };
295
368
  }
@@ -299,9 +372,11 @@ export class ResourceMonitor {
299
372
  cached;
300
373
  pending;
301
374
  deps;
375
+ registry;
302
376
  constructor(deps = {}, maxAgeMs = RESOURCES_MAX_AGE_MS) {
303
377
  this.maxAgeMs = maxAgeMs;
304
- this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable, owners: paneOwners, ...deps };
378
+ this.registry = deps.jobs ?? new JobRegistry();
379
+ this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable, owners: paneOwners, panes: livePanes, ...deps, jobs: this.registry };
305
380
  }
306
381
  async read() {
307
382
  if (this.cached && this.deps.now() - this.cached.at < this.maxAgeMs)
@@ -311,4 +386,20 @@ export class ResourceMonitor {
311
386
  .finally(() => { this.pending = undefined; });
312
387
  return this.pending;
313
388
  }
389
+ /**
390
+ * End only the registered process groups whose owning pane is gone. The
391
+ * registry (job-registry.ts) does the safety checks; a failed pane read ends
392
+ * nothing. Never the Hook's own service, never an owner's session, never an
393
+ * unregistered process.
394
+ */
395
+ async cleanupJobs() {
396
+ const rows = await this.deps.processes().catch(() => []);
397
+ const owners = await this.deps.owners().catch(() => new Map());
398
+ // Gone means absent from a complete listing of every server's panes; the
399
+ // owners map skips panes whose process read failed, so it can't say that.
400
+ const live = await this.deps.panes().catch(() => undefined);
401
+ const report = await this.registry.cleanup(rows, live?.panes ?? new Set(), { owners, panesKnown: live !== undefined, ...(live ? { servers: live.servers } : {}) });
402
+ this.cached = undefined;
403
+ return report;
404
+ }
314
405
  }
@@ -23,6 +23,7 @@ import { optionalHookPeers } from "./peers.js";
23
23
  import { AppServerRpcError } from "./codex-app-server.js";
24
24
  import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
25
25
  import { logger } from "../logger.js";
26
+ import { JobRegistry } from "./job-registry.js";
26
27
  import { atomic, BridgeError, bridgeRoot, id, launchEfforts, objects, PERMISSION_MODES, provider } from "./protocol.js";
27
28
  import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags } from "./settings-switch.js";
28
29
  /** Starting agents in Herdr from the phone: the launch route's harness
@@ -409,6 +410,13 @@ export async function launchSession(server, data, options = {}) {
409
410
  const chat = !sessionId && pane && pane.agent === kind ? await paneChatState(server, pane).catch(() => ({})) : {};
410
411
  const target = sessionId ? { ...binding, session: sessionId }
411
412
  : chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : undefined;
413
+ // Register a dispatched or scheduled worker's job, so the resources report
414
+ // can name its agent and a sweep can end a leftover process group after its
415
+ // pane is gone. The process group is resolved on the next read.
416
+ if (brief && role === "agent") {
417
+ await new JobRegistry().register({ pane: { server, pane: created.paneId, ...(created.workspaceId ? { workspace: created.workspaceId } : {}), agent: kind, label },
418
+ ...(sessionId ? { session: sessionId } : {}), agent: kind, label, command: kind }).catch(() => undefined);
419
+ }
412
420
  return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
413
421
  // The caller types the brief itself unless it went with the launch.
414
422
  ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief } : {}),
@@ -107,7 +107,7 @@ export declare const capabilities: {
107
107
  speech: boolean;
108
108
  speechTimestamps: boolean;
109
109
  speechVoices: boolean;
110
- speechFormats: ("mp3_44100_192" | "pcm_24000" | "pcm_44100")[];
110
+ speechFormats: ("mp3_44100_128" | "mp3_44100_192" | "pcm_24000" | "pcm_44100")[];
111
111
  transcribe: boolean;
112
112
  memoryStore: boolean;
113
113
  promptOnce: boolean;
@@ -27,9 +27,9 @@ import { liveBackground, markBackground, paneRecord, recordTitle } from "./sessi
27
27
  import { paneAccountField, paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
28
28
  import { locateProject } from "./locate.js";
29
29
  import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projects.js";
30
- import { BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
30
+ import { approvalDecisions, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
31
31
  import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
32
- import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, targetTranscriptPath } from "./transcripts.js";
32
+ import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, runningChildAgents, targetTranscriptPath } from "./transcripts.js";
33
33
  import { listUploads, saveUpload, uploadImage } from "./uploads.js";
34
34
  import { currentModel, currentStep } from "./steps.js";
35
35
  import { capacityRoom, usageForCaller } from "./usage.js";
@@ -57,9 +57,7 @@ async function childActivity(source, session) {
57
57
  if (cached && now - cached.at < CHILD_ACTIVITY_CACHE_MS)
58
58
  return cached.result;
59
59
  const result = childAgentTree(source, session).then(tree => {
60
- const running = tree.flatMap(function visit(child) {
61
- return [child, ...child.children.flatMap(visit)];
62
- }).filter(child => child.state === "running");
60
+ const running = runningChildAgents(tree);
63
61
  return { runningChildren: running.length, childProviders: [...new Set(running.map(child => child.provider))].sort() };
64
62
  }).catch(() => ({ runningChildren: 0, childProviders: [] }));
65
63
  childActivityCache.set(key, { at: now, result });
@@ -615,6 +613,10 @@ export function createRouteHandler(ctx) {
615
613
  else if (url.pathname === "/v1/sessions/rename") {
616
614
  result = await renameSession(selectedServer(url), data);
617
615
  }
616
+ else if (url.pathname === "/v1/jobs/cleanup") {
617
+ // Ends only registered worker process groups whose pane is gone.
618
+ result = { ok: true, ...await ctx.resources.cleanupJobs() };
619
+ }
618
620
  else if (url.pathname === "/v1/schedules") {
619
621
  result = await scheduler.statuses();
620
622
  }
@@ -666,7 +668,7 @@ export function createRouteHandler(ctx) {
666
668
  result = { returns: await ctx.returns.take() };
667
669
  }
668
670
  else if (url.pathname === "/v1/dispatch/approve") {
669
- const body = z.object({ id: z.string().uuid(), decision: z.enum(["approve", "deny"]), actionId: z.string().min(1).max(200), origin: originPaneSchema.optional() }).strict().parse(data);
671
+ const body = z.object({ id: z.string().uuid(), decision: z.enum(approvalDecisions), actionId: z.string().min(1).max(200), origin: originPaneSchema.optional() }).strict().parse(data);
670
672
  await ctx.returns.answerApproval(body.id, body.decision, body.actionId, body.origin);
671
673
  result = { ok: true };
672
674
  }
@@ -73,6 +73,7 @@ export function transcriptStreams(ctx) {
73
73
  let busy = false, ready = false, first = true;
74
74
  let awaitingTranscript = false, lastTranscriptLookup = 0;
75
75
  let initialPane;
76
+ let busyAt = 0;
76
77
  const pending = [];
77
78
  const stop = () => { abort.abort(); clearInterval(timer); unwatch?.(); pending.length = 0; };
78
79
  client.once("close", stop);
@@ -176,13 +177,21 @@ export function transcriptStreams(ctx) {
176
177
  : undefined);
177
178
  // Claude's own state comes from its footer, which leads the transcript.
178
179
  const codexServed = target.source === "codex" && !!codexServers.forTarget(target);
179
- const { settings, settingsState } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed)
180
- : { settings: settingsCapabilities(target.source, codexServed), settingsState: undefined };
180
+ const { settings, settingsState, suggestion } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed)
181
+ : { settings: settingsCapabilities(target.source, codexServed), settingsState: undefined, suggestion: undefined };
182
+ // Claude's suggested next prompt, only between turns. The footer
183
+ // read can be a throttle old, so one from before a turn this
184
+ // stream saw start is stale: the turn cleared it.
185
+ const between = ["idle", "done"].includes(String(pane.agent_status)) && !pendingApproval && !servedQuestion;
186
+ if (!between)
187
+ busyAt = Date.now();
188
+ const nextPrompt = between && suggestion && suggestion.readAt > busyAt ? suggestion.text : undefined;
181
189
  const historyHealth = target.source === "codex" ? await threadHealth(target.session, pane.agent_status) : { stalled: false };
182
190
  send(client, { agentStatus: { source: target.source, session: target.session,
183
191
  status: pendingApproval || servedQuestion ? "waiting" : pane.agent_status, pendingApproval, pendingQuestions, terminalPrompt,
184
192
  ...(waiting && agentHooks.passwordPrompt(target) ? { passwordPrompt: true } : {}),
185
193
  compacting: agentHooks.compacting(target),
194
+ ...(nextPrompt ? { suggestion: nextPrompt } : {}),
186
195
  ...(historyHealth.stalled ? { historyStalled: true, historyStalledSince: historyHealth.since } : {}),
187
196
  modules: info.modules, store: info.store, profile: info.profile, generation: info.generation,
188
197
  capabilities: { ...activeCapabilities, asyncQuestions: codexQuestions.availableFor(target),
@@ -36,6 +36,19 @@ export declare const BACKGROUND_STALE_MS: number;
36
36
  * the Stop's count less those `finishedTasks` (FinalTurn's) says finished
37
37
  * after it. Undefined once none are left or the Stop is BACKGROUND_STALE_MS old. */
38
38
  export declare function recordedBackground(record: TurnRecord | undefined, finishedTasks?: readonly string[], now?: number): number | undefined;
39
+ /** The background shells and monitors a turn still awaits, from its transcript
40
+ * final turn. A recorded ended turn bounds `FinalTurn.awaited` by the Stop's
41
+ * count less the tasks that finished since, and by the 2-hour cap; a Stop that
42
+ * named no count leaves the transcript's own awaited shells, and a Stop the
43
+ * Hook never saw falls back to them too. Undefined once none is awaited. A log
44
+ * tail, a watcher or a shell left from an earlier exchange is not awaited, so
45
+ * it never holds a turn open. */
46
+ export declare function awaitedShells(record: TurnRecord | undefined, final: FinalTurn | undefined, now?: number): number | undefined;
47
+ /** The live work a finished turn still waits on: its awaited shells and
48
+ * monitors plus the running children (sub-agents, teammates, workflows,
49
+ * fan-out jobs) the caller counted. Leftover shells are awaited by neither, so
50
+ * they do not hold a session or a dispatched worker open. */
51
+ export declare function liveWork(record: TurnRecord | undefined, final: FinalTurn | undefined, runningChildren?: number, now?: number): number | undefined;
39
52
  /** The background shells and monitors a pane's ended Claude turn is waiting
40
53
  * on (`FinalTurn.awaited`), at most `recordedBackground`. Reads the transcript
41
54
  * (`readFinalTurn`, passed in: schedule-watch imports herdr, which imports
@@ -49,6 +49,32 @@ export function recordedBackground(record, finishedTasks, now = Date.now()) {
49
49
  return undefined;
50
50
  return backgroundLeft(phase.background, phase.at, finishedTasks) || undefined;
51
51
  }
52
+ /** The background shells and monitors a turn still awaits, from its transcript
53
+ * final turn. A recorded ended turn bounds `FinalTurn.awaited` by the Stop's
54
+ * count less the tasks that finished since, and by the 2-hour cap; a Stop that
55
+ * named no count leaves the transcript's own awaited shells, and a Stop the
56
+ * Hook never saw falls back to them too. Undefined once none is awaited. A log
57
+ * tail, a watcher or a shell left from an earlier exchange is not awaited, so
58
+ * it never holds a turn open. */
59
+ export function awaitedShells(record, final, now = Date.now()) {
60
+ const phase = record ? turnPhase(record) : undefined;
61
+ if (phase?.phase === "ended") {
62
+ if (!(now - Date.parse(phase.at) < BACKGROUND_STALE_MS))
63
+ return undefined;
64
+ const recorded = backgroundLeft(phase.background, phase.at, final?.finishedTasks);
65
+ const shells = phase.background !== undefined ? recorded : final?.awaited ?? 0;
66
+ return shells && final?.awaited ? Math.min(shells, final.awaited) : undefined;
67
+ }
68
+ return final?.completed ? final.awaited || undefined : undefined;
69
+ }
70
+ /** The live work a finished turn still waits on: its awaited shells and
71
+ * monitors plus the running children (sub-agents, teammates, workflows,
72
+ * fan-out jobs) the caller counted. Leftover shells are awaited by neither, so
73
+ * they do not hold a session or a dispatched worker open. */
74
+ export function liveWork(record, final, runningChildren = 0, now = Date.now()) {
75
+ const total = (awaitedShells(record, final, now) ?? 0) + runningChildren;
76
+ return total || undefined;
77
+ }
52
78
  /** The background shells and monitors a pane's ended Claude turn is waiting
53
79
  * on (`FinalTurn.awaited`), at most `recordedBackground`. Reads the transcript
54
80
  * (`readFinalTurn`, passed in: schedule-watch imports herdr, which imports
@@ -60,8 +86,7 @@ export async function liveBackground(record, readFinal, now = Date.now()) {
60
86
  if (!record || record.source !== "claude" || !recordedBackground(record, [], now))
61
87
  return undefined;
62
88
  const final = await readFinal("claude", record.session).catch(() => undefined);
63
- const left = recordedBackground(record, final?.finishedTasks, now);
64
- return left && final?.awaited ? Math.min(left, final.awaited) : undefined;
89
+ return awaitedShells(record, final, now);
65
90
  }
66
91
  /**
67
92
  * Marks a tab whose main turn ended but whose background work continues:
@@ -29,7 +29,8 @@ export interface SettingsState {
29
29
  }
30
30
  /** A Claude pane's settings as its footer shows them, read at most once per
31
31
  * `PHREN_DIALOG_THROTTLE_MS` like the dialog check, and whether bypass was
32
- * ever seen in it (which is when full access is offered). */
32
+ * ever seen in it (which is when full access is offered). The same read, with
33
+ * its styles, carries the suggested next prompt in the input box. */
33
34
  export declare class ClaudeSettingsReader {
34
35
  private readonly hooks;
35
36
  private readonly every;
@@ -38,6 +39,10 @@ export declare class ClaudeSettingsReader {
38
39
  read(target: Target, terminal: unknown): Promise<{
39
40
  state?: SettingsState;
40
41
  bypass: boolean;
42
+ suggestion?: {
43
+ text: string;
44
+ readAt: number;
45
+ };
41
46
  }>;
42
47
  }
43
48
  /** One settings transaction per pane owns its terminal input until it ends. */
@@ -47,10 +52,15 @@ export declare class SettingsSwitcher {
47
52
  private active;
48
53
  private readonly reader;
49
54
  constructor(hooks: AgentHooks, wait?: number);
50
- /** A Claude pane's footer-read settings and capabilities for the stream. */
55
+ /** A Claude pane's footer-read settings and capabilities for the stream,
56
+ * with the suggested next prompt its input box shows. */
51
57
  streamSettings(target: Target, terminal: unknown, codexServed: boolean): Promise<{
52
58
  settings?: SettingsCapabilities;
53
59
  settingsState?: SettingsState;
60
+ suggestion?: {
61
+ text: string;
62
+ readAt: number;
63
+ };
54
64
  }>;
55
65
  private key;
56
66
  assertAvailable(target: Target): void;
@@ -1,6 +1,7 @@
1
1
  import { open, stat } from "node:fs/promises";
2
2
  import { z } from "zod";
3
3
  import { visibleTerminalChoice } from "./agent-hooks.js";
4
+ import { claudeSuggestion } from "./claude-suggestion.js";
4
5
  import { codexServers } from "./codex-servers.js";
5
6
  import { validateTarget } from "./herdr.js";
6
7
  import { intervalFromEnv } from "./limits.js";
@@ -64,7 +65,8 @@ export function claudeFooterMode(screen) {
64
65
  }
65
66
  /** A Claude pane's settings as its footer shows them, read at most once per
66
67
  * `PHREN_DIALOG_THROTTLE_MS` like the dialog check, and whether bypass was
67
- * ever seen in it (which is when full access is offered). */
68
+ * ever seen in it (which is when full access is offered). The same read, with
69
+ * its styles, carries the suggested next prompt in the input box. */
68
70
  export class ClaudeSettingsReader {
69
71
  hooks;
70
72
  every;
@@ -83,14 +85,18 @@ export class ClaudeSettingsReader {
83
85
  this.cache.set(key, entry);
84
86
  if (Date.now() - entry.at >= this.every) {
85
87
  entry.at = Date.now();
86
- entry.mode = await this.hooks.paneLines(target).then(claudeFooterMode, () => entry.mode);
88
+ const screen = await this.hooks.paneAnsi(target).catch(() => undefined);
89
+ if (screen !== undefined)
90
+ entry.mode = claudeFooterMode(screen);
91
+ entry.suggestion = screen === undefined ? undefined : claudeSuggestion(screen);
87
92
  if (entry.mode === "bypassPermissions")
88
93
  entry.bypass = true;
89
94
  while (this.cache.size > 64)
90
95
  this.cache.delete(this.cache.keys().next().value);
91
96
  }
92
97
  const phone = entry.mode ? CLAUDE_MODES[entry.mode] : undefined;
93
- return { bypass: entry.bypass, ...(phone ? { state: phone === "plan" ? { plan: true } : { permissionMode: phone, plan: false } } : {}) };
98
+ return { bypass: entry.bypass, ...(phone ? { state: phone === "plan" ? { plan: true } : { permissionMode: phone, plan: false } } : {}),
99
+ ...(entry.suggestion ? { suggestion: { text: entry.suggestion, readAt: entry.at } } : {}) };
94
100
  }
95
101
  }
96
102
  /** Claude's answer to a slash command: the first `<local-command-stdout>` user
@@ -130,14 +136,15 @@ export class SettingsSwitcher {
130
136
  this.wait = wait;
131
137
  this.reader = new ClaudeSettingsReader(hooks);
132
138
  }
133
- /** A Claude pane's footer-read settings and capabilities for the stream. */
139
+ /** A Claude pane's footer-read settings and capabilities for the stream,
140
+ * with the suggested next prompt its input box shows. */
134
141
  async streamSettings(target, terminal, codexServed) {
135
142
  if (target.source !== "claude") {
136
143
  const settings = settingsCapabilities(target.source, codexServed);
137
144
  return settings ? { settings } : {};
138
145
  }
139
- const { state, bypass } = await this.reader.read(target, terminal);
140
- return { settings: settingsCapabilities("claude", false, bypass), ...(state ? { settingsState: state } : {}) };
146
+ const { state, bypass, suggestion } = await this.reader.read(target, terminal);
147
+ return { settings: settingsCapabilities("claude", false, bypass), ...(state ? { settingsState: state } : {}), ...(suggestion ? { suggestion } : {}) };
141
148
  }
142
149
  key(target) { return `${target.server}:${target.pane}`; }
143
150
  assertAvailable(target) {
@@ -11,10 +11,11 @@ export { DEFAULT_SPEECH_MODEL, DEFAULT_SPEECH_VOICE, FALLBACK_SPEECH_MODEL } fro
11
11
  * it queues straight into its audio engine without decoding. */
12
12
  export declare const SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
13
13
  /** ElevenLabs output formats the Hook can serve, best first. Each account
14
- * plan allows some of them (Creator refuses pcm_44100, which is Pro and
15
- * above); the Hook learns which from ElevenLabs' refusal rather than a
16
- * hard-coded plan table. pcm_24000 works on every plan and every phone. */
17
- export declare const SPEECH_FORMATS: readonly ["pcm_44100", "mp3_44100_192", "pcm_24000"];
14
+ * plan allows some of them (pcm_44100 is Pro and above, mp3_44100_192 is
15
+ * Creator and above); the Hook learns which from ElevenLabs' refusal rather
16
+ * than a hard-coded plan table. pcm_24000 works on every plan and every
17
+ * phone, so it is the base every request falls back to. */
18
+ export declare const SPEECH_FORMATS: readonly ["pcm_44100", "mp3_44100_192", "mp3_44100_128", "pcm_24000"];
18
19
  export type SpeechFormat = typeof SPEECH_FORMATS[number];
19
20
  /** How each format is described to the phone: `audioFormat` in the JSON reply
20
21
  * and `X-Phren-Audio` on the streamed one, plus the sample rate on its own. */
@@ -37,6 +38,7 @@ export declare const speechRequest: z.ZodObject<{
37
38
  timestamps: z.ZodOptional<z.ZodBoolean>;
38
39
  voice: z.ZodOptional<z.ZodString>;
39
40
  formats: z.ZodPreprocess<z.ZodOptional<z.ZodArray<z.ZodEnum<{
41
+ mp3_44100_128: "mp3_44100_128";
40
42
  mp3_44100_192: "mp3_44100_192";
41
43
  pcm_24000: "pcm_24000";
42
44
  pcm_44100: "pcm_44100";
@@ -13,16 +13,18 @@ export { DEFAULT_SPEECH_MODEL, DEFAULT_SPEECH_VOICE, FALLBACK_SPEECH_MODEL } fro
13
13
  * it queues straight into its audio engine without decoding. */
14
14
  export const SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
15
15
  /** ElevenLabs output formats the Hook can serve, best first. Each account
16
- * plan allows some of them (Creator refuses pcm_44100, which is Pro and
17
- * above); the Hook learns which from ElevenLabs' refusal rather than a
18
- * hard-coded plan table. pcm_24000 works on every plan and every phone. */
19
- export const SPEECH_FORMATS = ["pcm_44100", "mp3_44100_192", "pcm_24000"];
16
+ * plan allows some of them (pcm_44100 is Pro and above, mp3_44100_192 is
17
+ * Creator and above); the Hook learns which from ElevenLabs' refusal rather
18
+ * than a hard-coded plan table. pcm_24000 works on every plan and every
19
+ * phone, so it is the base every request falls back to. */
20
+ export const SPEECH_FORMATS = ["pcm_44100", "mp3_44100_192", "mp3_44100_128", "pcm_24000"];
20
21
  const BASE_FORMAT = "pcm_24000";
21
22
  /** How each format is described to the phone: `audioFormat` in the JSON reply
22
23
  * and `X-Phren-Audio` on the streamed one, plus the sample rate on its own. */
23
24
  export const SPEECH_FORMAT_INFO = {
24
25
  pcm_44100: { audio: "pcm_s16le;rate=44100;channels=1", sampleRate: 44_100, contentType: "application/octet-stream" },
25
26
  mp3_44100_192: { audio: "mp3;rate=44100;bitrate=192000;channels=1", sampleRate: 44_100, contentType: "audio/mpeg" },
27
+ mp3_44100_128: { audio: "mp3;rate=44100;bitrate=128000;channels=1", sampleRate: 44_100, contentType: "audio/mpeg" },
26
28
  pcm_24000: { audio: SPEECH_AUDIO, sampleRate: 24_000, contentType: "application/octet-stream" },
27
29
  };
28
30
  /** Talk mode waits for the whole sentence on the timestamped path, so a model
@@ -38,8 +38,10 @@ export declare function tmuxBinary(): string | undefined;
38
38
  * where `-L` looks, then `/tmp/tmux-<uid>` when TMUX_TMPDIR points elsewhere
39
39
  * (a server started from a shell with another TMUX_TMPDIR than the Hook's). */
40
40
  export declare function tmuxSocketFolders(env?: NodeJS.ProcessEnv): string[];
41
- /** The tmux sockets in `folder` this user owns, by name (at most 32). A socket
42
- * outside the first folder of `tmuxSocketFolders` is remembered by path. */
41
+ /** The tmux sockets in `folder` this user owns, by name, most recently active
42
+ * first, so a live server sorts ahead of stale socket files left by killed
43
+ * runs. A socket outside the first folder of `tmuxSocketFolders` is remembered
44
+ * by path. */
43
45
  export declare function tmuxSocketsIn(folder: string): Promise<string[]>;
44
46
  /** For tests: replace how tmux and ps run; the returned function restores them. */
45
47
  export declare function setTmuxDeps(replacement: Partial<TmuxDeps>): () => void;
@@ -96,25 +96,28 @@ function socketFlags(socket) {
96
96
  const file = socketPaths.get(socket);
97
97
  return file ? ["-S", file] : ["-L", socket];
98
98
  }
99
- /** The tmux sockets in `folder` this user owns, by name (at most 32). A socket
100
- * outside the first folder of `tmuxSocketFolders` is remembered by path. */
99
+ /** The tmux sockets in `folder` this user owns, by name, most recently active
100
+ * first, so a live server sorts ahead of stale socket files left by killed
101
+ * runs. A socket outside the first folder of `tmuxSocketFolders` is remembered
102
+ * by path. */
101
103
  export async function tmuxSocketsIn(folder) {
102
104
  const uid = process.getuid?.(), primary = tmuxSocketFolders()[0];
103
105
  const names = (await readdir(folder).catch(() => [])).slice(0, 256);
104
106
  const found = [];
105
107
  for (const name of names) {
106
- if (found.length >= 32)
107
- break;
108
108
  if (!tmuxServerName(name))
109
109
  continue;
110
110
  const info = await lstat(path.join(folder, name)).catch(() => undefined);
111
111
  if (!info?.isSocket() || (uid !== undefined && info.uid !== uid))
112
112
  continue;
113
- found.push(name);
113
+ found.push({ name, at: info.mtimeMs });
114
114
  if (folder !== primary && !socketPaths.has(name) && !existsSync(path.join(primary ?? folder, name)))
115
115
  socketPaths.set(name, path.join(folder, name));
116
116
  }
117
- return found;
117
+ found.sort((a, b) => b.at - a.at);
118
+ // Most recent first, then capped: each candidate costs a tmux process
119
+ // per snapshot, and stale files from killed runs sort to the end.
120
+ return found.slice(0, 32).map(entry => entry.name);
118
121
  }
119
122
  const defaultDeps = {
120
123
  binary: tmuxBinary,
@@ -506,9 +509,12 @@ export const tmuxTerminal = {
506
509
  };
507
510
  /** The owner's tmux servers that answer, by Hook server name: the default
508
511
  * socket and every other socket in the user's tmux folders (`tmux -L work`
509
- * is "tmux-work"), at most 16. The hidden server is not among them. */
512
+ * is "tmux-work"), the 16 most recently active. Sockets are ordered by
513
+ * activity, so stale socket files from killed runs can't crowd out a live
514
+ * server. The hidden server is not among them. */
510
515
  async function ownerServers() {
511
516
  const sockets = [...new Set(["default", ...await deps.sockets().catch(() => [])])].filter(socket => socket !== "phren");
517
+ // Sockets arrive most recently active first, so the cap keeps live servers.
512
518
  const names = sockets.flatMap(socket => tmuxServerName(socket) ?? []).slice(0, 16);
513
519
  const running = await Promise.all(names.map(name => tmuxTerminal.ping(name).then(() => true, () => false)));
514
520
  return names.filter((_, index) => running[index]);