@phren/cli 0.3.30 → 0.3.31

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.
@@ -74,7 +74,7 @@ async function childActivity(source, session) {
74
74
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
75
75
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
76
76
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
77
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true };
77
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true };
78
78
  export function capabilitiesForModules(snapshot) {
79
79
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
80
80
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -219,11 +219,13 @@ export function transcriptStreams(ctx) {
219
219
  }
220
220
  }
221
221
  if (deliveryFrames) {
222
- for (const { deliveryId, state } of agentHooks.deliveriesFor(target)) {
222
+ // Every message typed into this pane, also those sent while an
223
+ // earlier conversation was showing there.
224
+ for (const { deliveryId, state, reason } of agentHooks.deliveries.forPane(target)) {
223
225
  if (sentDelivery.get(deliveryId) === state)
224
226
  continue;
225
227
  sentDelivery.set(deliveryId, state);
226
- send(client, { type: "delivery", ...conversation, deliveryId, state });
228
+ send(client, { type: "delivery", ...conversation, deliveryId, state, ...(reason ? { reason } : {}) });
227
229
  }
228
230
  }
229
231
  first = false;
@@ -27,7 +27,7 @@ import { CodeReindexer, CodeRoutes } from "./code-routes.js";
27
27
  import { WorkspaceContextUsage } from "./context.js";
28
28
  import { DispatchService } from "./dispatch.js";
29
29
  import { DispatchReturns, hookWorkers } from "./dispatch-returns.js";
30
- import { findPane, paneChatState, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
30
+ import { findPane, paneChatState, paneIdentity, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
31
31
  import { LaunchLimiter } from "./limits.js";
32
32
  import { locateProject } from "./locate.js";
33
33
  import { BridgeError, bridgeRoot, objects, PROTOCOL, provider, socketPath, targetSchema } from "./protocol.js";
@@ -84,7 +84,7 @@ export async function serve(version, options = {}) {
84
84
  : undefined;
85
85
  const locatedDirectories = new Set();
86
86
  const journal = new ActivityJournal();
87
- const agentHooks = new AgentHooks(undefined, modules);
87
+ const agentHooks = new AgentHooks(undefined, modules, path.join(bridgeRoot(), "deliveries.json"));
88
88
  // Follows what dispatched workers do and tells the dispatching agent.
89
89
  const returns = dispatches ? new DispatchReturns({
90
90
  localWorkers: hookWorkers(agentHooks),
@@ -140,6 +140,11 @@ export async function serve(version, options = {}) {
140
140
  const sideQuestions = new SideQuestions();
141
141
  const handOffs = dispatches ? new HandOffQueue({
142
142
  validate: target => validateTarget(target, false, true),
143
+ current: async (target) => {
144
+ const pane = findPane(await snapshot(target.server), target);
145
+ const session = pane ? await paneIdentity(target.server, pane, true) : undefined;
146
+ return pane && session ? { session, terminal: pane.terminal_id } : undefined;
147
+ },
143
148
  notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false }),
144
149
  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),
145
150
  }) : undefined;
@@ -257,7 +262,8 @@ export async function serve(version, options = {}) {
257
262
  // Codex panes on the Hook's own app-servers: their requests become
258
263
  // approval cards, and servers a previous Hook started are rejoined.
259
264
  codexServers.setSink({ request: (target, request, answer) => agentHooks.codexRequest(target, request, answer),
260
- resolved: (target, requestId) => agentHooks.codexResolved(target, requestId) });
265
+ resolved: (target, requestId) => agentHooks.codexResolved(target, requestId),
266
+ threadChanged: previous => agentHooks.deliveries.threadChanged(previous) });
261
267
  await codexServers.adopt().catch(() => { });
262
268
  void scheduler?.tick().catch(() => { });
263
269
  const scheduleTimer = scheduler ? setInterval(() => { countTick("schedules"); void scheduler.tick().catch(() => { }); }, 30_000) : undefined;
@@ -288,6 +294,9 @@ export async function serve(version, options = {}) {
288
294
  const name = String(server.session), current = await sharedSnapshot(name, 4000);
289
295
  await tabActivity.observe(name, current);
290
296
  await journal.record(name, objects(current.panes));
297
+ // Phone messages a pane still holds: fail loudly when it closed,
298
+ // restarted or finished without them.
299
+ await agentHooks.deliveries.observe(name, objects(current.panes)).catch(() => { });
291
300
  // A Codex app-server whose pane closed is stopped; a dead one forgotten.
292
301
  await codexServers.reap(name, current).catch(() => { });
293
302
  // Approvals drawn in a terminal reach a phone with phren closed.
@@ -91,7 +91,7 @@ export interface ProcessRecord {
91
91
  line: string;
92
92
  /** Environment names, where the platform shows them (Linux). */
93
93
  env?: string[];
94
- /** When it started (`ps -o lstart`), to tell it from a later process with its pid. */
94
+ /** When it started (procfs start ticks on Linux, `ps -o lstart` elsewhere), to distinguish a recycled pid. */
95
95
  started?: string;
96
96
  }
97
97
  /** One process's parent, effective uid, name and arguments. */
@@ -1,7 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { EventEmitter } from "node:events";
4
- import { existsSync } from "node:fs";
4
+ import { existsSync, readlinkSync } from "node:fs";
5
5
  import { open, readdir, readFile, readlink, unlink } from "node:fs/promises";
6
6
  import { request } from "node:http";
7
7
  import path from "node:path";
@@ -107,6 +107,30 @@ export async function readProcess(pid) {
107
107
  if (!Number.isInteger(pid) || pid <= 1)
108
108
  return undefined;
109
109
  try {
110
+ if (process.platform === "linux") {
111
+ const base = `/proc/${pid}`;
112
+ const [status, stat, cmdline, env] = await Promise.all([
113
+ readFile(`${base}/status`, "utf8"),
114
+ readFile(`${base}/stat`, "utf8"),
115
+ readFile(`${base}/cmdline`, "utf8"),
116
+ readFile(`${base}/environ`, "utf8").catch(() => undefined),
117
+ ]);
118
+ const ppid = /^PPid:\s+(\d+)$/m.exec(status)?.[1];
119
+ const euid = /^Uid:\s+\d+\s+(\d+)/m.exec(status)?.[1];
120
+ const name = /^Name:\s+(.+)$/m.exec(status)?.[1];
121
+ // Field 22 is the process's start tick. The comm field can contain
122
+ // spaces or parentheses, so split only after its closing parenthesis.
123
+ const start = (value) => value.slice(value.lastIndexOf(")") + 2).trim().split(/\s+/)[19];
124
+ const started = start(stat);
125
+ if (!ppid || !euid || !name || !started || !/^\d+$/.test(started))
126
+ return undefined;
127
+ // Refuse a recycled pid rather than combining two process records.
128
+ if (start(await readFile(`${base}/stat`, "utf8")) !== started)
129
+ return undefined;
130
+ const argv = cmdline.split("\0").filter(Boolean);
131
+ return { ppid: Number(ppid), euid: Number(euid), name: path.basename(name), argv, line: argv.join(" "), started,
132
+ ...(env === undefined ? {} : { env: env.split("\0").filter(Boolean).map(item => item.split("=", 1)[0]) }) };
133
+ }
110
134
  const { stdout } = await exec("ps", ["-ww", "-o", "ppid=", "-o", "uid=", "-o", "comm=", "-p", String(pid)], { timeout: 3_000, maxBuffer: 65_536 });
111
135
  const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(stdout.trim().split("\n")[0] ?? "");
112
136
  if (!match)
@@ -114,12 +138,8 @@ export async function readProcess(pid) {
114
138
  const args = await exec("ps", ["-ww", "-o", "args=", "-p", String(pid)], { timeout: 3_000, maxBuffer: 65_536 });
115
139
  const line = args.stdout.trim();
116
140
  const started = (await exec("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 3_000, maxBuffer: 4_096 }).catch(() => ({ stdout: "" }))).stdout.trim();
117
- let argv = line.split(/\s+/).filter(Boolean), env;
118
- if (process.platform === "linux") {
119
- argv = await readFile(`/proc/${pid}/cmdline`, "utf8").then(text => text.split("\0").filter(Boolean)).catch(() => argv);
120
- env = await readFile(`/proc/${pid}/environ`, "utf8").then(text => text.split("\0").filter(Boolean).map(item => item.split("=", 1)[0])).catch(() => undefined);
121
- }
122
- return { ppid: Number(match[1]), euid: Number(match[2]), name: path.basename(match[3]), argv, line, ...(env ? { env } : {}), ...(started ? { started } : {}) };
141
+ const argv = line.split(/\s+/).filter(Boolean);
142
+ return { ppid: Number(match[1]), euid: Number(match[2]), name: path.basename(match[3]), argv, line, ...(started ? { started } : {}) };
123
143
  }
124
144
  catch {
125
145
  return undefined;
@@ -133,16 +153,30 @@ export async function stdoutReaders(pid, allowed) {
133
153
  const target = await readlink(`/proc/${pid}/fd/1`);
134
154
  if (!/^pipe:\[\d+\]$/.test(target))
135
155
  return "other";
136
- for (const entry of await readdir("/proc")) {
137
- const holder = Number(entry);
138
- if (!Number.isInteger(holder) || holder === pid || allowed.includes(holder))
139
- continue;
140
- const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
141
- for (const fd of fds)
142
- if (await readlink(`/proc/${holder}/fd/${fd}`).catch(() => "") === target)
143
- return "other";
144
- }
145
- return "sudo";
156
+ const holders = (await readdir("/proc")).map(Number)
157
+ .filter(holder => Number.isInteger(holder) && holder !== pid && !allowed.includes(holder));
158
+ let next = 0, other = false;
159
+ // Busy machines can have thousands of descriptors. Bound the process
160
+ // concurrency while checking every visible descriptor of each holder.
161
+ await Promise.all(Array.from({ length: Math.min(16, holders.length) }, async () => {
162
+ while (!other && next < holders.length) {
163
+ const holder = holders[next++];
164
+ const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
165
+ // procfs links are kernel metadata, without disk I/O. Reading a
166
+ // holder's links directly avoids thousands of thread-pool jobs;
167
+ // the directory awaits above still yield between holders.
168
+ for (const fd of fds) {
169
+ try {
170
+ if (readlinkSync(`/proc/${holder}/fd/${fd}`) === target) {
171
+ other = true;
172
+ break;
173
+ }
174
+ }
175
+ catch { /* The descriptor closed or its process exited. */ }
176
+ }
177
+ }
178
+ }));
179
+ return other ? "other" : "sudo";
146
180
  }
147
181
  // macOS: each pipe end has its own address, and `n->` names the other end.
148
182
  const own = await exec("lsof", ["-nP", "-a", "-p", String(pid), "-d", "1", "-F", "tdn"], { timeout: 5_000, maxBuffer: 65_536 });