@phren/cli 0.3.30 → 0.3.32

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 (81) hide show
  1. package/dist/bridge/agent-hooks.d.ts +5 -55
  2. package/dist/bridge/agent-hooks.js +45 -162
  3. package/dist/bridge/approval-rules.d.ts +70 -0
  4. package/dist/bridge/approval-rules.js +231 -0
  5. package/dist/bridge/authority.d.ts +1 -2
  6. package/dist/bridge/authority.js +2 -7
  7. package/dist/bridge/changes.d.ts +4 -0
  8. package/dist/bridge/changes.js +47 -33
  9. package/dist/bridge/claude-suggestion.js +1 -1
  10. package/dist/bridge/codex-servers.d.ts +12 -0
  11. package/dist/bridge/codex-servers.js +35 -3
  12. package/dist/bridge/codex-thread-origin.d.ts +12 -0
  13. package/dist/bridge/codex-thread-origin.js +31 -0
  14. package/dist/bridge/dispatch.js +1 -1
  15. package/dist/bridge/enroll.d.ts +6 -0
  16. package/dist/bridge/enroll.js +10 -4
  17. package/dist/bridge/git-worktrees.js +14 -17
  18. package/dist/bridge/git.d.ts +10 -2
  19. package/dist/bridge/git.js +148 -107
  20. package/dist/bridge/hand-off-queue.d.ts +10 -0
  21. package/dist/bridge/hand-off-queue.js +33 -10
  22. package/dist/bridge/health.js +9 -5
  23. package/dist/bridge/herdr.js +6 -1
  24. package/dist/bridge/hook-main.js +12 -2
  25. package/dist/bridge/locate.js +14 -1
  26. package/dist/bridge/projects.d.ts +8 -0
  27. package/dist/bridge/projects.js +142 -24
  28. package/dist/bridge/prompt-deliveries.d.ts +99 -0
  29. package/dist/bridge/prompt-deliveries.js +327 -0
  30. package/dist/bridge/prompt-once.d.ts +2 -0
  31. package/dist/bridge/prompt-once.js +2 -0
  32. package/dist/bridge/schedule-format.d.ts +10 -0
  33. package/dist/bridge/schedule-format.js +24 -1
  34. package/dist/bridge/schedules.d.ts +3 -1
  35. package/dist/bridge/schedules.js +96 -40
  36. package/dist/bridge/server-launch.js +39 -15
  37. package/dist/bridge/server-pane-routes.js +91 -45
  38. package/dist/bridge/server-routes.d.ts +3 -0
  39. package/dist/bridge/server-routes.js +36 -8
  40. package/dist/bridge/server-stream.js +4 -2
  41. package/dist/bridge/server.js +12 -3
  42. package/dist/bridge/speech-key.d.ts +2 -9
  43. package/dist/bridge/speech-key.js +4 -37
  44. package/dist/bridge/sudo.d.ts +1 -1
  45. package/dist/bridge/sudo.js +51 -17
  46. package/dist/bridge/terminal-tmux.js +22 -4
  47. package/dist/bridge/tmux-test-server.d.ts +13 -0
  48. package/dist/bridge/tmux-test-server.js +103 -0
  49. package/dist/bridge/transcript-claude.d.ts +3 -3
  50. package/dist/bridge/transcript-claude.js +7 -7
  51. package/dist/bridge/transcript-codex.js +6 -4
  52. package/dist/bridge/transcript-preview.js +1 -1
  53. package/dist/bridge/transcripts.js +14 -3
  54. package/dist/bridge-hook.mjs +16011 -14121
  55. package/dist/cli/schedules.js +8 -2
  56. package/dist/cli/session-stop.js +9 -1
  57. package/dist/cli-registry.js +1 -1
  58. package/dist/core/project-registry.d.ts +1 -0
  59. package/dist/core/project-registry.js +6 -2
  60. package/dist/core/project.d.ts +1 -0
  61. package/dist/core/project.js +5 -0
  62. package/dist/generated/memory-ui-graph.browser.js +328 -333
  63. package/dist/init/setup.js +2 -2
  64. package/dist/memory-ui-graph.runtime.js +328 -333
  65. package/dist/modules/registry.js +9 -7
  66. package/dist/phren-core.js +1 -1
  67. package/dist/phren-paths.d.ts +2 -2
  68. package/dist/phren-paths.js +2 -2
  69. package/dist/store-routing.d.ts +2 -2
  70. package/dist/store-routing.js +2 -2
  71. package/dist/sync/git-state.d.ts +13 -0
  72. package/dist/sync/git-state.js +22 -0
  73. package/dist/sync/store-merge.d.ts +2 -0
  74. package/dist/sync/store-merge.js +6 -1
  75. package/dist/test-global-setup.js +7 -0
  76. package/dist/tools/data.js +1 -1
  77. package/dist/tools/finding.js +1 -1
  78. package/dist/tools/search.js +1 -1
  79. package/dist/tools/tasks.js +1 -1
  80. package/package.json +8 -8
  81. package/starter/global/skills/conductor/SKILL.md +2 -2
@@ -119,11 +119,14 @@ export declare const capabilities: {
119
119
  promptOnce: boolean;
120
120
  promptStatus: boolean;
121
121
  deliveryFrames: boolean;
122
+ paneDeliveries: boolean;
122
123
  resources: boolean;
123
124
  sudo: boolean;
124
125
  sudoOutcome: boolean;
125
126
  previewDeltas: boolean;
126
127
  quickChat: boolean;
128
+ agentFolder: boolean;
129
+ launchPermissionMode: boolean;
127
130
  };
128
131
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
129
132
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -16,6 +16,7 @@ import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./di
16
16
  import { hookWorkers } from "./dispatch-returns.js";
17
17
  import { remoteChildren } from "./dispatch-tree.js";
18
18
  import { briefArrival, briefId } from "./launch-brief.js";
19
+ import { listApprovalRules, changeApprovalRule } from "./approval-rules.js";
19
20
  import { addGrant, listNamedGrants, removeGrant } from "./grants.js";
20
21
  import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
21
22
  import { readComputers } from "./computer-identity.js";
@@ -28,7 +29,8 @@ import { storeRoute } from "./memory-store.js";
28
29
  import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
29
30
  import { paneAccountField, paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
30
31
  import { locateProject } from "./locate.js";
31
- import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projects.js";
32
+ import { gitStatus } from "./git.js";
33
+ import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
32
34
  import { approvalDecisions, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
33
35
  import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
34
36
  import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, runningChildAgents, targetTranscriptPath } from "./transcripts.js";
@@ -74,13 +76,17 @@ async function childActivity(source, session) {
74
76
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
75
77
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
76
78
  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 };
79
+ 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, agentFolder: true, launchPermissionMode: true };
78
80
  export function capabilitiesForModules(snapshot) {
79
81
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
80
82
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
81
83
  for (const name of ["memory", "tasks", "hook", "git", "schedules"])
82
84
  if (snapshot.has(name))
83
85
  result[name] = true;
86
+ if (snapshot.has("hook"))
87
+ result.approvalRules = { version: 2, effects: ["always-ask", "deny"], harnesses: ["claude"], events: ["PermissionRequest"], tools: ["Bash"], inputField: "command", conductorTools: false, mcpTools: false, preExecution: false };
88
+ if (snapshot.has("schedules"))
89
+ result.scheduleProjects = true;
84
90
  if (snapshot.has("tasks")) {
85
91
  result.taskDependencies = true;
86
92
  result.taskWriterSafety = true;
@@ -341,6 +347,9 @@ export function createRouteHandler(ctx) {
341
347
  case "/v1/dispatch/arrival":
342
348
  result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
343
349
  break;
350
+ case "/v1/approval-rules":
351
+ result = { rules: await listApprovalRules(undefined, z.string().regex(/^[A-Za-z0-9+/]{43}=$/).optional().parse(url.searchParams.get("pairedKey") ?? undefined)) };
352
+ break;
344
353
  case "/v1/conductor/grants":
345
354
  result = { grants: await listNamedGrants() };
346
355
  break;
@@ -418,6 +427,14 @@ export function createRouteHandler(ctx) {
418
427
  case "/v1/files":
419
428
  result = { files: await listUploads("files") };
420
429
  break;
430
+ case "/v1/git/status": {
431
+ result = await withGitReadDeadline(async () => {
432
+ const target = targetFromURL(url), pane = await validateTarget(target);
433
+ const cwd = await gitRepository(pane, target, url.searchParams.get("child") ?? undefined, url.searchParams.get("worktree") ?? undefined);
434
+ return gitStatus(cwd, z.string().min(1).max(4096).optional().parse(url.searchParams.get("untrackedPath") ?? undefined));
435
+ });
436
+ break;
437
+ }
421
438
  case "/v1/files/resolve": {
422
439
  const target = targetFromURL(url), pane = await validateTarget(target);
423
440
  const cwd = await gitRepository(pane, target, url.searchParams.get("child") ?? undefined, url.searchParams.get("worktree") ?? undefined);
@@ -682,8 +699,10 @@ export function createRouteHandler(ctx) {
682
699
  result = await scheduler.statuses();
683
700
  }
684
701
  else if (url.pathname === "/v1/schedules/run") {
685
- const input = z.object({ project: z.string().min(1).max(200), id: z.string().regex(/^[a-f0-9]{8}$/) }).parse(data);
686
- result = { ok: true, run: await scheduler.launchNow(input.project, input.id) };
702
+ const input = z.object({ project: z.string().min(1).max(200), id: z.string().regex(/^[a-f0-9]{8}$/),
703
+ expectedUpdatedAt: z.string().datetime({ offset: true }).optional() }).parse(data);
704
+ const runs = await scheduler.launchNow(input.project, input.id, false, input.expectedUpdatedAt);
705
+ result = { ok: runs.every(run => run.status !== "failed"), run: runs[0], runs };
687
706
  }
688
707
  else if (url.pathname === "/v1/schedules/history") {
689
708
  const input = z.object({ project: z.string().min(1).max(200).optional(), id: z.string().regex(/^[a-f0-9]{8}$/).optional(),
@@ -733,6 +752,9 @@ export function createRouteHandler(ctx) {
733
752
  await ctx.returns.answerApproval(body.id, body.decision, body.actionId, body.origin);
734
753
  result = { ok: true };
735
754
  }
755
+ else if (url.pathname === "/v1/approval-rules") {
756
+ result = await changeApprovalRule(data, "POST");
757
+ }
736
758
  else if (url.pathname === "/v1/conductor/grants") {
737
759
  result = { ok: true, grant: await addGrant(data) };
738
760
  }
@@ -800,7 +822,7 @@ export function createRouteHandler(ctx) {
800
822
  else if (url.pathname === "/v1/projects/add") {
801
823
  // Enrolling a repository with phren from the phone: an existing
802
824
  // checkout, or a clone. Serialized like launches — one at a time.
803
- result = await launches.run(async () => enrollProject(z.object({ directory: z.string().max(4096).optional(), cloneUrl: z.string().max(512).optional() }).parse(data)));
825
+ result = await launches.run(async () => enrollProject(z.object({ directory: z.string().max(4096).optional(), cloneUrl: z.string().max(512).optional(), project: z.string().max(100).optional(), store: z.string().max(200).optional() }).parse(data)));
804
826
  }
805
827
  else if (url.pathname === "/v1/simulators/action") {
806
828
  result = await simulatorAct(z.string().parse(data.udid), z.object({ action: z.string(), bundleId: z.string().optional(), url: z.string().optional(), x: z.number().optional(), y: z.number().optional(), text: z.string().optional(), submit: z.boolean().optional() }).parse(data));
@@ -810,12 +832,15 @@ export function createRouteHandler(ctx) {
810
832
  result = await launches.run(async () => {
811
833
  if (data.role === "conductor" && !modules.has("conductor"))
812
834
  throw new BridgeError(404, disabledHint("conductor"));
835
+ if (data.agentFolder === true && (data.role === "conductor" || data.project !== undefined || (data.cwd !== undefined && data.cwd !== "") || data.worktree != null)) {
836
+ throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
837
+ }
813
838
  if (data.project !== undefined && data.cwd !== undefined)
814
839
  throw new BridgeError(400, "Choose project or cwd, not both.");
815
840
  // A conductor belongs to no one project: without a folder it starts in
816
841
  // this computer's phren store and dispatches into any project from there.
817
842
  const storeRooted = data.role === "conductor" && data.project === undefined && (data.cwd === undefined || data.cwd === "");
818
- const cwd = storeRooted ? await launchDirectory(defaultPhrenPath(), [], [defaultPhrenPath()])
843
+ const cwd = data.agentFolder === true ? undefined : storeRooted ? await launchDirectory(defaultPhrenPath(), [], [defaultPhrenPath()])
819
844
  : data.project !== undefined ? await dispatchProjectDirectory(data.project)
820
845
  : await launchDirectory(data.cwd, await journal.recent(), locatedDirectories);
821
846
  // A project the Hook resolved (a dispatch) is a folder it may trust; a folder the phone named is not.
@@ -833,10 +858,13 @@ export function createRouteHandler(ctx) {
833
858
  }
834
859
  }
835
860
  else if (request.method === "DELETE") {
836
- if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority")
861
+ if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority" && url.pathname !== "/v1/approval-rules")
837
862
  throw new BridgeError(404, "Unknown Phren Hook route.");
838
863
  const data = await body(request);
839
- if (url.pathname === "/v1/authority") {
864
+ if (url.pathname === "/v1/approval-rules") {
865
+ result = await changeApprovalRule(data, "DELETE");
866
+ }
867
+ else if (url.pathname === "/v1/authority") {
840
868
  if (data.origin !== undefined)
841
869
  throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
842
870
  result = { ok: true, authority: await clearProjectAuthority(data, "phone") };
@@ -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.
@@ -6,18 +6,12 @@
6
6
  export declare const SPEECH_KEY_ENV = "ELEVENLABS_API_KEY";
7
7
  export type SpeechKeySource = "environment" | "file";
8
8
  export declare function speechKeyFile(): string;
9
- /** Where the key lived before phren kept its own: the mina trailer config. It
10
- * is read once to migrate and never written or deleted. */
11
- export declare function legacySpeechKeyFile(env?: NodeJS.ProcessEnv): string;
12
9
  export declare function writeSpeechKey(key: string, file?: string): Promise<void>;
13
10
  export interface SpeechKeyPaths {
14
11
  env?: NodeJS.ProcessEnv;
15
12
  file?: string;
16
- legacy?: string;
17
13
  }
18
- /** ELEVENLABS_API_KEY, else the stored key. When nothing is stored yet and the
19
- * mina trailer config has a key, it is copied here once and read from here
20
- * after. */
14
+ /** ELEVENLABS_API_KEY, else the stored key. */
21
15
  export declare function resolveSpeechKey(paths?: SpeechKeyPaths): Promise<{
22
16
  key: string;
23
17
  source: SpeechKeySource;
@@ -28,6 +22,5 @@ export interface SpeechKeyStatus {
28
22
  detail: string;
29
23
  problem?: boolean;
30
24
  }
31
- /** Whether this computer has a key, for doctor. Never the key itself, and it
32
- * doesn't migrate: a read-only check. */
25
+ /** Whether this computer has a key, for doctor. Never the key itself. */
33
26
  export declare function speechKeyStatus(paths?: SpeechKeyPaths): Promise<SpeechKeyStatus>;
@@ -1,6 +1,5 @@
1
1
  import { mkdir, readFile, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { homeDir } from "../home-paths.js";
4
3
  import { atomic, bridgeRoot } from "./protocol.js";
5
4
  /** The ElevenLabs key for spoken replies and Scribe dictation. It is machine
6
5
  * config, like apns.json: it lives in the Hook's own directory, mode 600, and
@@ -11,11 +10,6 @@ export const SPEECH_KEY_ENV = "ELEVENLABS_API_KEY";
11
10
  export function speechKeyFile() {
12
11
  return path.join(bridgeRoot(), "elevenlabs.json");
13
12
  }
14
- /** Where the key lived before phren kept its own: the mina trailer config. It
15
- * is read once to migrate and never written or deleted. */
16
- export function legacySpeechKeyFile(env = process.env) {
17
- return path.join(homeDir(env), ".config", "mina-trailer.json");
18
- }
19
13
  function clean(value) {
20
14
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
21
15
  }
@@ -40,14 +34,6 @@ async function readStored(file) {
40
34
  return { state: "invalid" };
41
35
  }
42
36
  }
43
- async function readLegacy(file) {
44
- try {
45
- return clean(JSON.parse(await readFile(file, "utf8")).elevenlabs_api_key);
46
- }
47
- catch {
48
- return undefined;
49
- }
50
- }
51
37
  export async function writeSpeechKey(key, file = speechKeyFile()) {
52
38
  const value = clean(key);
53
39
  if (!value)
@@ -55,34 +41,19 @@ export async function writeSpeechKey(key, file = speechKeyFile()) {
55
41
  await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
56
42
  await atomic(file, JSON.stringify({ apiKey: value }) + "\n", 0o600);
57
43
  }
58
- /** ELEVENLABS_API_KEY, else the stored key. When nothing is stored yet and the
59
- * mina trailer config has a key, it is copied here once and read from here
60
- * after. */
44
+ /** ELEVENLABS_API_KEY, else the stored key. */
61
45
  export async function resolveSpeechKey(paths = {}) {
62
46
  const env = paths.env ?? process.env;
63
47
  const fromEnv = clean(env[SPEECH_KEY_ENV]);
64
48
  if (fromEnv)
65
49
  return { key: fromEnv, source: "environment" };
66
- const file = paths.file ?? speechKeyFile();
67
- const stored = await readStored(file);
68
- if (stored.state === "ok")
69
- return { key: stored.key, source: "file" };
70
- if (stored.state !== "missing")
71
- return undefined;
72
- const legacy = await readLegacy(paths.legacy ?? legacySpeechKeyFile(env));
73
- if (!legacy)
74
- return undefined;
75
- try {
76
- await writeSpeechKey(legacy, file);
77
- }
78
- catch { /* use it this once; the next call tries again */ }
79
- return { key: legacy, source: "file" };
50
+ const stored = await readStored(paths.file ?? speechKeyFile());
51
+ return stored.state === "ok" ? { key: stored.key, source: "file" } : undefined;
80
52
  }
81
53
  export async function readSpeechKey() {
82
54
  return (await resolveSpeechKey())?.key;
83
55
  }
84
- /** Whether this computer has a key, for doctor. Never the key itself, and it
85
- * doesn't migrate: a read-only check. */
56
+ /** Whether this computer has a key, for doctor. Never the key itself. */
86
57
  export async function speechKeyStatus(paths = {}) {
87
58
  const env = paths.env ?? process.env;
88
59
  const file = paths.file ?? speechKeyFile();
@@ -98,9 +69,5 @@ export async function speechKeyStatus(paths = {}) {
98
69
  case "unsafe": return { configured: false, problem: true, detail: `${file} is readable by other users; run chmod 600 on it` };
99
70
  case "invalid": return { configured: false, problem: true, detail: `${file} has no apiKey; ${setup}` };
100
71
  }
101
- const legacy = paths.legacy ?? legacySpeechKeyFile(env);
102
- if (await readLegacy(legacy)) {
103
- return { configured: true, detail: `not stored yet; the Hook copies it from ${legacy} on first use` };
104
- }
105
72
  return { configured: false, detail: `no ElevenLabs key, so spoken replies and Scribe dictation are off; ${setup}` };
106
73
  }
@@ -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 });
@@ -14,7 +14,7 @@
14
14
  import { execFile } from "node:child_process";
15
15
  import { accessSync, constants, existsSync, statSync } from "node:fs";
16
16
  import { lstat, readdir } from "node:fs/promises";
17
- import { hostname, userInfo } from "node:os";
17
+ import { hostname, tmpdir, userInfo } from "node:os";
18
18
  import path from "node:path";
19
19
  import { BridgeError, objects, serverName } from "./protocol.js";
20
20
  import { harnessStatus } from "./harness-status.js";
@@ -511,14 +511,32 @@ export const tmuxTerminal = {
511
511
  * socket and every other socket in the user's tmux folders (`tmux -L work`
512
512
  * is "tmux-work"), the 16 most recently active. Sockets are ordered by
513
513
  * activity, so stale socket files from killed runs can't crowd out a live
514
- * server. The hidden server is not among them. */
514
+ * server. The hidden server is not among them, nor a test's private server
515
+ * (by its socket name, or its sessions all in a test's temp folder). */
515
516
  async function ownerServers() {
516
- const sockets = [...new Set(["default", ...await deps.sockets().catch(() => [])])].filter(socket => socket !== "phren");
517
+ const sockets = [...new Set(["default", ...await deps.sockets().catch(() => [])])]
518
+ .filter(socket => socket !== "phren" && !isTestName(socket));
517
519
  // Sockets arrive most recently active first, so the cap keeps live servers.
518
520
  const names = sockets.flatMap(socket => tmuxServerName(socket) ?? []).slice(0, 16);
519
- const running = await Promise.all(names.map(name => tmuxTerminal.ping(name).then(() => true, () => false)));
521
+ const running = await Promise.all(names.map(name => tmux(name, ["list-sessions", "-F", "#{session_path}"], { timeoutMs: 3_000 })
522
+ .then(text => !isTestServer(text.split("\n").filter(Boolean)), () => false)));
520
523
  return names.filter((_, index) => running[index]);
521
524
  }
525
+ /** A name a test gives its private server or temp folder: a "test", "tests"
526
+ * or "it" word (phren-test-123, phren-scroll-test-123, phren-tmux-it-Qc4LM8). */
527
+ function isTestName(name) {
528
+ return /(^|[-_.])(tests?|it)([-_.]|$)/i.test(name) || /^phren.*test/i.test(name);
529
+ }
530
+ /** A server every session of which starts in a test's temp folder (a temp
531
+ * folder named like a test, or phren's own `phren-*` scratch folders): what a
532
+ * killed test run leaves behind on a socket with an ordinary name. */
533
+ function isTestServer(sessionPaths) {
534
+ const roots = [...new Set([tmpdir(), "/tmp", "/var/tmp"].map(root => path.resolve(root)))];
535
+ return sessionPaths.length > 0 && sessionPaths.every(folder => roots.some(root => {
536
+ const rest = path.relative(root, path.resolve(folder));
537
+ return rest !== "" && !rest.startsWith("..") && !path.isAbsolute(rest) && rest.split(path.sep).some(part => isTestName(part) || part.startsWith("phren-"));
538
+ }));
539
+ }
522
540
  /** The tmux servers the Hook drives, as `/v1/muxes` lists servers: the owner's
523
541
  * servers that answer, and (unless `hidden: false`) the hidden server whenever
524
542
  * tmux is installed (a launch starts it). An already running hidden server
@@ -0,0 +1,13 @@
1
+ /** The test socket for this process: `phren-<kind>-test-<pid>`. */
2
+ export declare function testSocketName(kind?: string): string;
3
+ /** A detached shell that kills the server on `socket` and removes its socket
4
+ * files once `pid` is gone. Answers its own pid. */
5
+ export declare function startWatchdog(pid: number, binary: string, socket: string): number | undefined;
6
+ /** Registers the teardown of the server on `socket` before the test starts it.
7
+ * `stop` is idempotent and synchronous, so the exit hook can call it too. */
8
+ export declare function privateTmuxServer(binary: string, socket: string): {
9
+ stop: () => void;
10
+ };
11
+ /** Kills the servers and removes the sockets earlier test runs left behind:
12
+ * test sockets whose owning process is gone. */
13
+ export declare function sweepTestServers(binary?: string): string[];
@@ -0,0 +1,103 @@
1
+ // A real tmux server on a private socket for an integration test, torn down
2
+ // however the run ends: afterAll, the worker's exit or a signal, or (when the
3
+ // worker is killed outright, as a timed-out or interrupted run can be) a
4
+ // watchdog that outlives it. A leaked server shows on the phone as sessions
5
+ // nobody can close, and its socket piles up in the tmux folder.
6
+ import { execFileSync, spawn } from "node:child_process";
7
+ import { readdirSync, unlinkSync } from "node:fs";
8
+ import path from "node:path";
9
+ import { tmuxSocketFolders } from "./terminal-tmux.js";
10
+ /** A test socket's name ends with the pid of the process that owns it. */
11
+ const TEST_SOCKET = /^phren-(?:[a-z]+-)*test(?:-[a-z]+)*-(\d+)$/;
12
+ /** The test socket for this process: `phren-<kind>-test-<pid>`. */
13
+ export function testSocketName(kind) {
14
+ return `phren-${kind ? `${kind}-` : ""}test-${process.pid}`;
15
+ }
16
+ function removeServer(binary, socket) {
17
+ try {
18
+ execFileSync(binary, ["-L", socket, "kill-server"], { stdio: "ignore", timeout: 5_000 });
19
+ }
20
+ catch { /* already gone */ }
21
+ // tmux can leave the socket file behind when the server is killed.
22
+ for (const dir of tmuxSocketFolders()) {
23
+ try {
24
+ unlinkSync(path.join(dir, socket));
25
+ }
26
+ catch { /* none */ }
27
+ }
28
+ }
29
+ const WATCHDOG = `pid=$1; tmux=$2; sock=$3; shift 3
30
+ while kill -0 "$pid" 2>/dev/null; do sleep 1; done
31
+ "$tmux" -L "$sock" kill-server 2>/dev/null
32
+ rm -f "$@"`;
33
+ /** A detached shell that kills the server on `socket` and removes its socket
34
+ * files once `pid` is gone. Answers its own pid. */
35
+ export function startWatchdog(pid, binary, socket) {
36
+ const files = tmuxSocketFolders().map(dir => path.join(dir, socket));
37
+ const child = spawn("/bin/sh", ["-c", WATCHDOG, "phren-tmux-watchdog", String(pid), binary, socket, ...files], { detached: true, stdio: "ignore" });
38
+ child.unref();
39
+ return child.pid;
40
+ }
41
+ /** Registers the teardown of the server on `socket` before the test starts it.
42
+ * `stop` is idempotent and synchronous, so the exit hook can call it too. */
43
+ export function privateTmuxServer(binary, socket) {
44
+ let stopped = false;
45
+ const watchdog = startWatchdog(process.pid, binary, socket);
46
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
47
+ const onSignal = (signal) => {
48
+ stop();
49
+ // Nobody else handles it: die of it as the worker would have.
50
+ if (process.listenerCount(signal) === 0)
51
+ process.kill(process.pid, signal);
52
+ };
53
+ function stop() {
54
+ if (stopped)
55
+ return;
56
+ stopped = true;
57
+ process.removeListener("exit", stop);
58
+ for (const signal of signals)
59
+ process.removeListener(signal, onSignal);
60
+ removeServer(binary, socket);
61
+ if (watchdog) {
62
+ try {
63
+ process.kill(watchdog);
64
+ }
65
+ catch { /* already gone */ }
66
+ }
67
+ }
68
+ process.once("exit", stop);
69
+ for (const signal of signals)
70
+ process.once(signal, onSignal);
71
+ return { stop };
72
+ }
73
+ /** Kills the servers and removes the sockets earlier test runs left behind:
74
+ * test sockets whose owning process is gone. */
75
+ export function sweepTestServers(binary = "tmux") {
76
+ const swept = [];
77
+ for (const dir of tmuxSocketFolders()) {
78
+ let names;
79
+ try {
80
+ names = readdirSync(dir);
81
+ }
82
+ catch {
83
+ continue;
84
+ }
85
+ for (const name of names) {
86
+ const pid = Number(TEST_SOCKET.exec(name)?.[1]);
87
+ if (!pid || pid === process.pid || alive(pid))
88
+ continue;
89
+ removeServer(binary, name);
90
+ swept.push(name);
91
+ }
92
+ }
93
+ return swept;
94
+ }
95
+ function alive(pid) {
96
+ try {
97
+ process.kill(pid, 0);
98
+ return true;
99
+ }
100
+ catch (error) {
101
+ return error.code === "EPERM";
102
+ }
103
+ }
@@ -2,9 +2,9 @@ import { type Json } from "./protocol.js";
2
2
  import type { ChildAgentRelation } from "./transcripts.js";
3
3
  /** The checkout a Claude sub-agent edits in. Claude Code writes the isolated
4
4
  * worktree into the child's `.meta.json`; an older child falls back to the
5
- * `cwd` its own first rows record when that folder is a linked worktree (its
6
- * `.git` is a file). A child working in the parent's checkout gets nothing,
7
- * and a worktree already removed is not offered. */
5
+ * `cwd` its own first rows record. Preserve shared and missing checkout paths
6
+ * too: Git routes must fail explicitly when a checkout disappears, never
7
+ * substitute the parent repository. */
8
8
  export declare function claudeChildCheckout(file: string): Promise<Pick<ChildAgentRelation, "cwd" | "worktreeName" | "branch">>;
9
9
  export declare function claudeChildAgents(file: string, session: string): Promise<ChildAgentRelation[]>;
10
10
  /** How long a background skill's transcript may sit unchanged before it is