@phren/cli 0.3.16 → 0.3.18

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 (46) 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/permission-mode.d.ts +48 -0
  12. package/dist/bridge/permission-mode.js +144 -0
  13. package/dist/bridge/protocol.d.ts +4 -0
  14. package/dist/bridge/protocol.js +3 -0
  15. package/dist/bridge/resources.d.ts +38 -5
  16. package/dist/bridge/resources.js +110 -19
  17. package/dist/bridge/server-launch.js +8 -0
  18. package/dist/bridge/server-pane-routes.d.ts +2 -0
  19. package/dist/bridge/server-pane-routes.js +12 -2
  20. package/dist/bridge/server-routes.d.ts +3 -1
  21. package/dist/bridge/server-routes.js +8 -6
  22. package/dist/bridge/server-stream.js +14 -2
  23. package/dist/bridge/server.js +4 -2
  24. package/dist/bridge/session-activity.d.ts +13 -0
  25. package/dist/bridge/session-activity.js +27 -2
  26. package/dist/bridge/settings-switch.d.ts +19 -7
  27. package/dist/bridge/settings-switch.js +21 -29
  28. package/dist/bridge/speech.d.ts +6 -4
  29. package/dist/bridge/speech.js +6 -4
  30. package/dist/bridge/terminal-tmux.d.ts +4 -2
  31. package/dist/bridge/terminal-tmux.js +13 -7
  32. package/dist/bridge/transcript-claude.d.ts +9 -1
  33. package/dist/bridge/transcript-claude.js +50 -1
  34. package/dist/bridge/transcript-codex.js +23 -3
  35. package/dist/bridge/transcripts.d.ts +5 -1
  36. package/dist/bridge/transcripts.js +13 -3
  37. package/dist/bridge-hook.mjs +1169 -546
  38. package/dist/computers/command.js +2 -1
  39. package/dist/fanout/opencode-serve.js +3 -2
  40. package/dist/hooks.d.ts +3 -0
  41. package/dist/hooks.js +41 -6
  42. package/dist/init/setup.js +6 -3
  43. package/dist/modules/registry.js +2 -2
  44. package/dist/tools/dispatch.js +3 -2
  45. package/package.json +1 -1
  46. package/plugins/opencode/phren-transcript.js +4 -4
@@ -1,3 +1,4 @@
1
+ import { type CleanupReport, type JobSource, type ProcessLike, type TrackedJob } from "./job-registry.js";
1
2
  /**
2
3
  * This computer's live resources for `GET /v1/resources`, the overview
3
4
  * stream's `resources` frames and the memory-free `phren computers` surface:
@@ -29,6 +30,10 @@ export interface HeavyProcess {
29
30
  memoryBytes: number;
30
31
  /** Why this process group is listed; resource use does not establish session activity. */
31
32
  resourceReason?: "cpu" | "memory" | "tracked";
33
+ /** The harness that owns the job, when a pane or a registered group says so. */
34
+ agent?: string;
35
+ /** True when the group is one the Hook registered for a dispatched worker. */
36
+ tracked?: boolean;
32
37
  pane?: PaneRef;
33
38
  }
34
39
  export interface ComputerResources {
@@ -69,15 +74,15 @@ export interface ComputerResources {
69
74
  level: "ok" | "busy" | "stressed";
70
75
  warnings: Array<"load-high" | "memory-low" | "disk-low" | "battery-low">;
71
76
  }
72
- export interface ProcessRow {
73
- pid: number;
74
- ppid: number;
77
+ /** A `ps` row; `pgid` is the process group the job registry attributes work by. */
78
+ export interface ProcessRow extends ProcessLike {
75
79
  cpu: number;
76
80
  rssKB: number;
77
81
  command: string;
78
82
  args: string;
79
83
  }
80
- /** `ps -axo pid=,ppid=,pcpu=,rss=,comm=` paired with the `args=` listing by pid. */
84
+ /** `ps -axo pid=,ppid=,pgid=,pcpu=,rss=,comm=` paired with the `args=` listing by
85
+ * pid. The older five-column stats (no pgid) still parse, with pgid 0. */
81
86
  export declare function parsePs(stats: string, args: string): ProcessRow[];
82
87
  /** What kind of heavy job a process is, if any. */
83
88
  export declare function heavyKind(row: ProcessRow): {
@@ -95,7 +100,7 @@ export declare function heavyKind(row: ProcessRow): {
95
100
  * On Linux, ps pcpu is a process lifetime average, so these cutoffs can miss
96
101
  * daemons that spike briefly.
97
102
  */
98
- export declare function heavyProcesses(rows: ProcessRow[], owners?: Map<number, PaneRef>, limit?: number): HeavyProcess[];
103
+ export declare function heavyProcesses(rows: ProcessRow[], owners?: Map<number, PaneRef>, jobs?: readonly TrackedJob[], limit?: number): HeavyProcess[];
99
104
  /** `pmset -g batt`: "Now drawing from 'AC Power'" then " -InternalBattery-0 (id=…) 87%; charging; …". */
100
105
  export declare function parsePmset(output: string): ComputerResources["battery"];
101
106
  /** `sysctl vm.swapusage`: "total = 2048.00M used = 798.50M free = …". */
@@ -104,6 +109,20 @@ export declare function parseSwap(output: string): number | undefined;
104
109
  export declare function parseMeminfo(text: string): ComputerResources["memory"];
105
110
  /** Gauge fill and warnings from the numbers. */
106
111
  export declare function assess(value: Omit<ComputerResources, "pressure" | "level" | "warnings">): Pick<ComputerResources, "pressure" | "level" | "warnings">;
112
+ /** Seconds from `ps`'s `etime` (`[[dd-]hh:]mm:ss`), or undefined. */
113
+ export declare function parseEtime(value: string): number | undefined;
114
+ /** Each row's start time (epoch ms, to about a second) from a `pid=,etime=`
115
+ * listing. The job registry checks a process group's leader by it, so a group
116
+ * id the system reused for another program is never signalled. */
117
+ export declare function withStartTimes(rows: ProcessRow[], elapsed: string, now: number): ProcessRow[];
118
+ /** Every pane of every terminal server this computer knows, or undefined when
119
+ * any server's snapshot could not be read. Cleanup ends a job only when its
120
+ * pane is missing from a complete listing: a pane that merely failed to
121
+ * answer, or sat past a display cap, must never look gone. */
122
+ export declare function livePanes(): Promise<{
123
+ panes: Set<string>;
124
+ servers: Set<string>;
125
+ } | undefined>;
107
126
  /** Every pid a Herdr or tmux pane holds (its shell and foreground), for naming a job's pane. */
108
127
  export declare function paneOwners(): Promise<Map<number, PaneRef>>;
109
128
  export interface ResourceDeps {
@@ -112,6 +131,12 @@ export interface ResourceDeps {
112
131
  home: () => string;
113
132
  processes: () => Promise<ProcessRow[]>;
114
133
  owners: () => Promise<Map<number, PaneRef>>;
134
+ /** Every live pane and the servers listed, or undefined when the listing is incomplete (see `livePanes`). */
135
+ panes: () => Promise<{
136
+ panes: Set<string>;
137
+ servers: Set<string>;
138
+ } | undefined>;
139
+ jobs?: JobSource;
115
140
  }
116
141
  export declare function collectResources(deps: ResourceDeps): Promise<ComputerResources>;
117
142
  /** One collection at a time, reused for `RESOURCES_MAX_AGE_MS`. */
@@ -120,6 +145,14 @@ export declare class ResourceMonitor {
120
145
  private cached?;
121
146
  private pending?;
122
147
  private readonly deps;
148
+ private readonly registry;
123
149
  constructor(deps?: Partial<ResourceDeps>, maxAgeMs?: number);
124
150
  read(): Promise<ComputerResources>;
151
+ /**
152
+ * End only the registered process groups whose owning pane is gone. The
153
+ * registry (job-registry.ts) does the safety checks; a failed pane read ends
154
+ * nothing. Never the Hook's own service, never an owner's session, never an
155
+ * unregistered process.
156
+ */
157
+ cleanupJobs(): Promise<CleanupReport>;
125
158
  }
@@ -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 } : {}),
@@ -2,6 +2,7 @@ import type { ServerResponse } from "node:http";
2
2
  import type { AgentHooks } from "./agent-hooks.js";
3
3
  import { type WorktreeWorker } from "./git-worktrees.js";
4
4
  import { type ModelSwitcher } from "./model-switch.js";
5
+ import { type PermissionModeSwitcher } from "./permission-mode.js";
5
6
  import type { SettingsSwitcher } from "./settings-switch.js";
6
7
  import { type Json, type Target } from "./protocol.js";
7
8
  import type { CodexQuestions } from "./questions.js";
@@ -13,6 +14,7 @@ export interface PaneRouteContext {
13
14
  agentHooks: AgentHooks;
14
15
  modelSwitcher: ModelSwitcher;
15
16
  settingsSwitcher: SettingsSwitcher;
17
+ permissionModeSwitcher: PermissionModeSwitcher;
16
18
  codexQuestions: CodexQuestions;
17
19
  sideQuestions: SideQuestions;
18
20
  }
@@ -10,6 +10,7 @@ import { agentNotReady, terminalProvider } from "./terminal.js";
10
10
  import { AppServerRpcError } from "./codex-app-server.js";
11
11
  import { CodexServerUnavailable, codexServers } from "./codex-servers.js";
12
12
  import { refuseWorkingSlash } from "./model-switch.js";
13
+ import { PERMISSION_MODE_VALUES, refuseAgentOrigin } from "./permission-mode.js";
13
14
  import { sessionWebServers } from "./session-servers.js";
14
15
  import { repositoryDiff } from "./projects.js";
15
16
  import { BridgeError, MAX_FRAME, object, objects, startingTargetSchema, targetSchema } from "./protocol.js";
@@ -255,7 +256,7 @@ export async function paneRoute(ctx, url, data, response) {
255
256
  return promptOnce.run(id, promptScope(object(data.target), String(data.text ?? "")), async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
256
257
  }
257
258
  export async function paneRouteOnce(ctx, url, data, response, typing) {
258
- const { agentHooks, modelSwitcher, settingsSwitcher, codexQuestions, sideQuestions } = ctx;
259
+ const { agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions } = ctx;
259
260
  let result;
260
261
  if (url.pathname === "/v1/keys" && object(data.target).starting === true) {
261
262
  // A folder-trust or login prompt comes before the agent has a
@@ -328,10 +329,11 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
328
329
  const target = targetSchema.parse(data.target);
329
330
  // Uploads store bytes without answering or interrupting the agent.
330
331
  // They still require fresh identity, just like prompt mutations.
331
- const sendsInput = ["/v1/prompt", "/v1/keys", "/v1/secret", "/v1/model", "/v1/settings"].includes(url.pathname);
332
+ const sendsInput = ["/v1/prompt", "/v1/keys", "/v1/secret", "/v1/model", "/v1/settings", "/v1/agents/permission-mode"].includes(url.pathname);
332
333
  if (sendsInput) {
333
334
  modelSwitcher.assertAvailable(target);
334
335
  settingsSwitcher.assertAvailable(target);
336
+ permissionModeSwitcher.assertAvailable(target);
335
337
  sideQuestions.assertAvailable(target);
336
338
  }
337
339
  // A key press is how a prompt the agent draws in its terminal gets
@@ -341,6 +343,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
341
343
  if (sendsInput) {
342
344
  modelSwitcher.assertAvailable(target);
343
345
  settingsSwitcher.assertAvailable(target);
346
+ permissionModeSwitcher.assertAvailable(target);
344
347
  sideQuestions.assertAvailable(target);
345
348
  }
346
349
  if (url.pathname === "/v1/prompt") {
@@ -483,6 +486,13 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
483
486
  else if (url.pathname === "/v1/settings") {
484
487
  result = await settingsSwitcher.switch(target, data);
485
488
  }
489
+ else if (url.pathname === "/v1/agents/permission-mode") {
490
+ // The owner's own choice from the phone: no authority ceiling applies.
491
+ // An agent's call carries its pane as `origin` and is refused, so no
492
+ // agent can raise its own or another pane's mode past its ceiling.
493
+ refuseAgentOrigin(data && typeof data === "object" && "origin" in data ? data.origin ?? null : undefined);
494
+ result = await permissionModeSwitcher.set(target, z.enum(PERMISSION_MODE_VALUES).parse(data.mode));
495
+ }
486
496
  else if (url.pathname === "/v1/keys" && await agentHooks.servedKeys(target, z.array(z.enum(ANSWER_KEYS)).min(1).max(4).parse(data.keys), String(pane.agent_status))) {
487
497
  // A served OpenCode pane: Esc aborts its turn or declines its question,
488
498
  // a digit answers its question, over its own API.
@@ -14,6 +14,7 @@ import type { CodexQuestions } from "./questions.js";
14
14
  import type { TabActivityStore } from "./tab-activity.js";
15
15
  import type { ModelCatalog } from "./models.js";
16
16
  import type { ModelSwitcher } from "./model-switch.js";
17
+ import type { PermissionModeSwitcher } from "./permission-mode.js";
17
18
  import type { SettingsSwitcher } from "./settings-switch.js";
18
19
  import type { SideQuestions } from "./side-questions.js";
19
20
  import { type AccountUsageReader } from "./usage.js";
@@ -61,6 +62,7 @@ export interface RouteContext {
61
62
  modelCatalog: ModelCatalog;
62
63
  modelSwitcher: ModelSwitcher;
63
64
  settingsSwitcher: SettingsSwitcher;
65
+ permissionModeSwitcher: PermissionModeSwitcher;
64
66
  sideQuestions: SideQuestions;
65
67
  accountUsage: AccountUsageReader;
66
68
  resources: ResourceMonitor;
@@ -107,7 +109,7 @@ export declare const capabilities: {
107
109
  speech: boolean;
108
110
  speechTimestamps: boolean;
109
111
  speechVoices: boolean;
110
- speechFormats: ("mp3_44100_192" | "pcm_24000" | "pcm_44100")[];
112
+ speechFormats: ("mp3_44100_128" | "mp3_44100_192" | "pcm_24000" | "pcm_44100")[];
111
113
  transcribe: boolean;
112
114
  memoryStore: boolean;
113
115
  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,24 @@ 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, permissionMode, permissionModes } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed)
181
+ : { settings: settingsCapabilities(target.source, codexServed), settingsState: undefined, suggestion: undefined, permissionMode: undefined, permissionModes: 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 } : {}),
195
+ // The mode Claude's footer shows and the cycle its picker offers,
196
+ // only from a confident read (a Claude pane's readable footer).
197
+ ...(permissionMode ? { permissionMode, permissionModes } : {}),
186
198
  ...(historyHealth.stalled ? { historyStalled: true, historyStalledSince: historyHealth.since } : {}),
187
199
  modules: info.modules, store: info.store, profile: info.profile, generation: info.generation,
188
200
  capabilities: { ...activeCapabilities, asyncQuestions: codexQuestions.availableFor(target),
@@ -36,6 +36,7 @@ import { childAgentTree } from "./transcripts.js";
36
36
  import { ModelCatalog } from "./models.js";
37
37
  import { ModelSwitcher } from "./model-switch.js";
38
38
  import { SettingsSwitcher } from "./settings-switch.js";
39
+ import { PermissionModeSwitcher } from "./permission-mode.js";
39
40
  import { SideQuestions } from "./side-questions.js";
40
41
  import { AccountUsageReader } from "./usage.js";
41
42
  import { ResourceMonitor } from "./resources.js";
@@ -134,11 +135,12 @@ export async function serve(version, options = {}) {
134
135
  const modelCatalog = options.modelCatalog ?? new ModelCatalog();
135
136
  const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
136
137
  const settingsSwitcher = new SettingsSwitcher(agentHooks);
138
+ const permissionModeSwitcher = new PermissionModeSwitcher(agentHooks);
137
139
  const sideQuestions = new SideQuestions();
138
140
  const handOffs = dispatches ? new HandOffQueue({
139
141
  validate: target => validateTarget(target, false, true),
140
142
  notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false }),
141
- send: async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing),
143
+ send: async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing),
142
144
  }) : undefined;
143
145
  const contextUsage = new WorkspaceContextUsage();
144
146
  const accountUsage = options.accountUsage ?? new AccountUsageReader();
@@ -206,7 +208,7 @@ export async function serve(version, options = {}) {
206
208
  sudo: agentHooks.sudo,
207
209
  });
208
210
  const http = createServer(createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
209
- journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
211
+ journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
210
212
  fanoutMessages, canary, streams, returns, handOffs, inbox }));
211
213
  http.requestTimeout = 20_000;
212
214
  http.headersTimeout = 10_000;
@@ -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: