@phren/cli 0.3.31 → 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.
- package/dist/bridge/agent-hooks.js +23 -7
- package/dist/bridge/approval-rules.d.ts +70 -0
- package/dist/bridge/approval-rules.js +231 -0
- package/dist/bridge/authority.d.ts +1 -2
- package/dist/bridge/authority.js +2 -7
- package/dist/bridge/changes.d.ts +4 -0
- package/dist/bridge/changes.js +47 -33
- package/dist/bridge/claude-suggestion.js +1 -1
- package/dist/bridge/dispatch.js +1 -1
- package/dist/bridge/enroll.d.ts +6 -0
- package/dist/bridge/enroll.js +10 -4
- package/dist/bridge/git-worktrees.js +14 -17
- package/dist/bridge/git.d.ts +10 -2
- package/dist/bridge/git.js +148 -107
- package/dist/bridge/health.js +9 -5
- package/dist/bridge/herdr.js +6 -1
- package/dist/bridge/locate.js +14 -1
- package/dist/bridge/projects.d.ts +8 -0
- package/dist/bridge/projects.js +142 -24
- package/dist/bridge/schedule-format.d.ts +10 -0
- package/dist/bridge/schedule-format.js +24 -1
- package/dist/bridge/schedules.d.ts +3 -1
- package/dist/bridge/schedules.js +96 -40
- package/dist/bridge/server-launch.js +39 -15
- package/dist/bridge/server-pane-routes.js +19 -11
- package/dist/bridge/server-routes.d.ts +2 -0
- package/dist/bridge/server-routes.js +36 -8
- package/dist/bridge/speech-key.d.ts +2 -9
- package/dist/bridge/speech-key.js +4 -37
- package/dist/bridge/terminal-tmux.js +22 -4
- package/dist/bridge/tmux-test-server.d.ts +13 -0
- package/dist/bridge/tmux-test-server.js +103 -0
- package/dist/bridge/transcript-claude.d.ts +3 -3
- package/dist/bridge/transcript-claude.js +7 -7
- package/dist/bridge/transcript-codex.js +6 -4
- package/dist/bridge/transcript-preview.js +1 -1
- package/dist/bridge/transcripts.js +14 -3
- package/dist/bridge-hook.mjs +2753 -2216
- package/dist/cli/schedules.js +8 -2
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.js +1 -1
- package/dist/core/project-registry.d.ts +1 -0
- package/dist/core/project-registry.js +6 -2
- package/dist/core/project.d.ts +1 -0
- package/dist/core/project.js +5 -0
- package/dist/modules/registry.js +9 -7
- package/dist/phren-core.js +1 -1
- package/dist/phren-paths.d.ts +2 -2
- package/dist/phren-paths.js +2 -2
- package/dist/store-routing.d.ts +2 -2
- package/dist/store-routing.js +2 -2
- package/dist/sync/git-state.d.ts +13 -0
- package/dist/sync/git-state.js +22 -0
- package/dist/sync/store-merge.d.ts +2 -0
- package/dist/sync/store-merge.js +6 -1
- package/dist/test-global-setup.js +7 -0
- package/dist/tools/data.js +1 -1
- package/dist/tools/finding.js +1 -1
- package/dist/tools/search.js +1 -1
- package/dist/tools/tasks.js +1 -1
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +2 -2
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { markPaneClosed } from "./worker-close.js";
|
|
2
|
-
import { mkdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { mkdir, mkdtemp, readFile, realpath, rmdir } from "node:fs/promises";
|
|
3
3
|
import { phrenStoreRoot } from "./transcripts.js";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
import { homeDir } from "../home-paths.js";
|
|
7
|
+
import { defaultPhrenPath } from "../phren-paths.js";
|
|
7
8
|
import { agentNames, findPane, isConductorName, paneChatState, paneIdentity, servers, snapshot } from "./herdr.js";
|
|
8
9
|
import { agentNotReady, terminalKind, terminalName, terminalProvider } from "./terminal.js";
|
|
9
10
|
import { tmuxScroll } from "./terminal-tmux.js";
|
|
@@ -43,7 +44,7 @@ function effortArgs(kind, effort) {
|
|
|
43
44
|
return ["--reasoning-effort", effort];
|
|
44
45
|
// phren-agent takes low to xhigh, and max as xhigh.
|
|
45
46
|
if (kind === "phren")
|
|
46
|
-
return ["--reasoning", effort
|
|
47
|
+
return ["--reasoning", effort];
|
|
47
48
|
return [];
|
|
48
49
|
}
|
|
49
50
|
/** phren's own agent runs as `phren agent`: the subcommand and its interactive TUI lead its arguments. */
|
|
@@ -105,7 +106,7 @@ export async function sessionUsedTools(session, store = phrenStoreRoot()) {
|
|
|
105
106
|
* `--model` itself; the rest name their provider with `--provider`. Any other
|
|
106
107
|
* model (an OpenRouter id typed by hand) passes through as it is. */
|
|
107
108
|
export function phrenModelArgs(model) {
|
|
108
|
-
const match = /^(anthropic|deepseek|ollama|openrouter)\/(.+)$/.exec(model);
|
|
109
|
+
const match = /^(anthropic|deepseek|ollama|openrouter|openai-compat)\/(.+)$/.exec(model);
|
|
109
110
|
return match ? ["--provider", match[1], "--model", match[2]] : ["--model", model];
|
|
110
111
|
}
|
|
111
112
|
async function prepareConductor(kind, effort, model) {
|
|
@@ -126,6 +127,8 @@ async function prepareConductor(kind, effort, model) {
|
|
|
126
127
|
await atomic(file, definition, 0o644);
|
|
127
128
|
return [...(model ? ["--model", model] : []), "--agent", "conductor", "--variant", effort];
|
|
128
129
|
}
|
|
130
|
+
if (kind === "phren")
|
|
131
|
+
return [...PHREN_AGENT_ARGS, ...(model ? phrenModelArgs(model) : []), "--append-system-prompt-file", briefFile, ...effortArgs(kind, effort)];
|
|
129
132
|
throw new BridgeError(400, "The selected harness cannot run as a conductor.");
|
|
130
133
|
}
|
|
131
134
|
async function targetForPane(server, pane) {
|
|
@@ -178,7 +181,6 @@ async function requireNoConductor(server, before, except) {
|
|
|
178
181
|
}
|
|
179
182
|
/** The phone names the pane's workspace and tab too; the CLI may know only the pane. */
|
|
180
183
|
const paneRequest = z.object({ workspaceId: id.optional(), tabId: id.optional(), paneId: id }).strict();
|
|
181
|
-
const PHREN_NO_CONDUCTOR = "phren agent cannot run as a conductor: it takes no system brief at startup.";
|
|
182
184
|
/** "Make conductor": the owner gives an agent already running in a pane on this computer the role. */
|
|
183
185
|
export async function makeConductor(server, data) {
|
|
184
186
|
const place = paneRequest.parse(data);
|
|
@@ -191,8 +193,6 @@ export async function makeConductor(server, data) {
|
|
|
191
193
|
throw new BridgeError(409, "No agent is running in this pane.");
|
|
192
194
|
if (pane.agent === "copilot")
|
|
193
195
|
throw new BridgeError(400, "Copilot cannot run as a conductor.");
|
|
194
|
-
if (pane.agent === "phren")
|
|
195
|
-
throw new BridgeError(400, PHREN_NO_CONDUCTOR);
|
|
196
196
|
const unchecked = await requireNoConductor(server, before, place.paneId);
|
|
197
197
|
const target = await targetForPane(server, pane);
|
|
198
198
|
await recordConductor(server, pane, "owner", typeof target?.session === "string" ? target.session : undefined);
|
|
@@ -218,7 +218,7 @@ const SHELL_READY_MS = intervalFromEnv("PHREN_SHELL_READY_MS", 15_000);
|
|
|
218
218
|
/** Herdr starts an agent only at an interactive shell prompt and refuses
|
|
219
219
|
* with `agent_pane_busy` ("is not an available shell") before that. A pane
|
|
220
220
|
* created a moment ago is busy only while its login shell starts, which a
|
|
221
|
-
* loaded computer can stretch to seconds (three
|
|
221
|
+
* loaded computer can stretch to seconds (three Devbox dispatches failed
|
|
222
222
|
* this way on 2026-09-27; the same pane took the agent by hand a minute
|
|
223
223
|
* later). Nothing is typed on a refusal, so retry until the shell is up. */
|
|
224
224
|
async function startWhenShellReady(server, pane, agent) {
|
|
@@ -316,7 +316,12 @@ async function stillListed(server, result) {
|
|
|
316
316
|
}
|
|
317
317
|
async function startSession(server, data, options) {
|
|
318
318
|
const role = z.enum(["agent", "conductor"]).default("agent").parse(data.role);
|
|
319
|
-
const
|
|
319
|
+
const agentFolder = z.boolean().default(false).parse(data.agentFolder);
|
|
320
|
+
if (agentFolder && (role !== "agent" || data.project !== undefined || (data.cwd !== undefined && data.cwd !== "") || data.worktree != null)) {
|
|
321
|
+
throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
|
|
322
|
+
}
|
|
323
|
+
const projectDirectory = agentFolder ? undefined
|
|
324
|
+
: z.string().min(1).max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
320
325
|
const worktreeRequest = data.worktree === undefined || data.worktree === null ? undefined : launchWorktreeSchema.parse(data.worktree);
|
|
321
326
|
if (worktreeRequest && role === "conductor")
|
|
322
327
|
throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
|
|
@@ -333,8 +338,8 @@ async function startSession(server, data, options) {
|
|
|
333
338
|
throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude, Codex and Copilot workers.");
|
|
334
339
|
if (role === "conductor" && kind === "copilot")
|
|
335
340
|
throw new BridgeError(400, "Copilot cannot run as a conductor.");
|
|
336
|
-
if (role === "conductor" &&
|
|
337
|
-
throw new BridgeError(400,
|
|
341
|
+
if (role === "conductor" && data.mode === "chat")
|
|
342
|
+
throw new BridgeError(400, "A conductor needs agent mode with tools.");
|
|
338
343
|
const phrenArgs = await phrenLaunchArgs(kind, data);
|
|
339
344
|
// A dispatched worker's or scheduled run's first prompt. It rides on the
|
|
340
345
|
// launch where the harness takes one; elsewhere the caller types it.
|
|
@@ -375,7 +380,7 @@ async function startSession(server, data, options) {
|
|
|
375
380
|
const conductorHere = role === "agent" && workspace ? await conductorPane(server, before) : undefined;
|
|
376
381
|
if (conductorHere && conductorHere.workspace_id === workspace)
|
|
377
382
|
workspace = undefined;
|
|
378
|
-
const args = role === "conductor" ? await prepareConductor(kind, effort, model)
|
|
383
|
+
const args = role === "conductor" ? [...await prepareConductor(kind, effort, model), ...(kind === "phren" ? phrenArgs : [])]
|
|
379
384
|
: [...(kind === "phren" ? [...PHREN_AGENT_ARGS, ...phrenArgs] : []), ...(model && kind === "phren" ? phrenModelArgs(model) : model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
|
|
380
385
|
...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : []), ...(permissionMode && kind === "copilot" ? copilotModeFlags(permissionMode) : [])];
|
|
381
386
|
// A Codex worker runs on a Phren-owned app-server (codex-servers.ts): the
|
|
@@ -401,16 +406,35 @@ async function startSession(server, data, options) {
|
|
|
401
406
|
// Created last, once nothing else can refuse the launch, so a refusal
|
|
402
407
|
// never leaves a worktree or branch behind.
|
|
403
408
|
const worktree = worktreeRequest ? await createLaunchWorktree(projectDirectory, worktreeRequest) : undefined;
|
|
404
|
-
|
|
409
|
+
// The same root as the conductor, chosen by this computer's PHREN_PATH.
|
|
410
|
+
// mkdtemp keeps simultaneous chats with the same title isolated.
|
|
411
|
+
let scratch;
|
|
412
|
+
if (agentFolder) {
|
|
413
|
+
const store = await realpath(defaultPhrenPath());
|
|
414
|
+
// Runtime folders are excluded from project discovery and store sync.
|
|
415
|
+
const runtime = path.join(store, ".runtime");
|
|
416
|
+
await mkdir(runtime, { recursive: true, mode: 0o700 });
|
|
417
|
+
if (await realpath(runtime) !== runtime)
|
|
418
|
+
throw new BridgeError(403, "The runtime folder must be inside the Phren directory.");
|
|
419
|
+
const agents = path.join(runtime, "agents");
|
|
420
|
+
await mkdir(agents, { recursive: true, mode: 0o700 });
|
|
421
|
+
// A pre-existing symlink must not redirect the new folder outside the store.
|
|
422
|
+
if (await realpath(agents) !== agents)
|
|
423
|
+
throw new BridgeError(403, "The agents folder must be inside the Phren directory.");
|
|
424
|
+
scratch = await mkdtemp(path.join(agents, `${new Date().toISOString().slice(0, 10)}-${herdrAgentName(label)}-`));
|
|
425
|
+
}
|
|
426
|
+
const cwd = scratch ?? worktree?.cwd ?? projectDirectory;
|
|
405
427
|
// Claude's folder-trust screen defaults to "No, exit" and Codex's holds the
|
|
406
428
|
// agent too; a folder the Hook picked or just created is trusted up front.
|
|
407
|
-
if (worktree || options.trustFolder)
|
|
408
|
-
await pretrustFolder(kind, cwd, worktree ? `new worktree for ${worktree.branch}` : "project folder", home ? { ...process.env, ...claudeLaunchEnv(home) } : process.env);
|
|
429
|
+
if (scratch || worktree || options.trustFolder)
|
|
430
|
+
await pretrustFolder(kind, cwd, scratch ? "new agent folder" : worktree ? `new worktree for ${worktree.branch}` : "project folder", home ? { ...process.env, ...claudeLaunchEnv(home) } : process.env);
|
|
409
431
|
try {
|
|
410
432
|
await terminalProvider().create(server, { workspace, label, cwd, ...(env ? { env } : {}) });
|
|
411
433
|
}
|
|
412
434
|
catch (error) {
|
|
413
435
|
await worktree?.discard();
|
|
436
|
+
if (scratch)
|
|
437
|
+
await rmdir(scratch).catch(() => undefined);
|
|
414
438
|
throw error;
|
|
415
439
|
}
|
|
416
440
|
let created;
|
|
@@ -512,7 +536,7 @@ async function startSession(server, data, options) {
|
|
|
512
536
|
await new JobRegistry().register({ pane: { server, pane: created.paneId, ...(created.workspaceId ? { workspace: created.workspaceId } : {}), agent: kind, label },
|
|
513
537
|
...(sessionId ? { session: sessionId } : {}), agent: kind, label, command: kind }).catch(() => undefined);
|
|
514
538
|
}
|
|
515
|
-
return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
|
|
539
|
+
return { ok: true, ...created, cwd, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
|
|
516
540
|
// The caller types the brief itself unless it went with the launch.
|
|
517
541
|
...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief,
|
|
518
542
|
briefState: appServer ? briefTurn ?? "unconfirmed" : served ? (servedBrief?.delivered ? "sent" : "uncertain") : briefLaunch ? "sent" : "unconfirmed" } : {}),
|
|
@@ -12,7 +12,7 @@ import { CodexServerUnavailable, codexServers } from "./codex-servers.js";
|
|
|
12
12
|
import { refuseWorkingSlash } from "./model-switch.js";
|
|
13
13
|
import { PERMISSION_MODE_VALUES, refuseAgentOrigin } from "./permission-mode.js";
|
|
14
14
|
import { sessionWebServers } from "./session-servers.js";
|
|
15
|
-
import { repositoryDiff } from "./projects.js";
|
|
15
|
+
import { gitRoot, repositoryDiff, withGitReadDeadline } from "./projects.js";
|
|
16
16
|
import { BridgeError, MAX_FRAME, object, objects, startingTargetSchema, targetSchema } from "./protocol.js";
|
|
17
17
|
import { childAgent, childAgentTree, conversationNamedPaths, targetTranscriptPath } from "./transcripts.js";
|
|
18
18
|
import { sideQuestionText } from "./side-questions.js";
|
|
@@ -42,7 +42,9 @@ export async function gitRepository(pane, target, child, worktree) {
|
|
|
42
42
|
const relation = childAgent(await childAgentTree(target.source, target.session), id);
|
|
43
43
|
if (!relation)
|
|
44
44
|
throw new BridgeError(404, "That agent is not part of this conversation.");
|
|
45
|
-
|
|
45
|
+
if (!relation.cwd)
|
|
46
|
+
throw new BridgeError(409, "This agent has no recorded checkout. Its parent repository cannot be substituted.");
|
|
47
|
+
return trustedDirectory({ cwd: relation.cwd });
|
|
46
48
|
}
|
|
47
49
|
return trustedDirectory(pane);
|
|
48
50
|
}
|
|
@@ -261,6 +263,9 @@ function deliveryReply(agentHooks, id, target, text) {
|
|
|
261
263
|
...(status.state === "queued" ? { queued: true } : {}), ...(status.reason ? { reason: status.reason } : {}) };
|
|
262
264
|
}
|
|
263
265
|
export async function paneRoute(ctx, url, data, response) {
|
|
266
|
+
if (["/v1/diff", "/v1/git/status", "/v1/git/worktrees"].includes(url.pathname)) {
|
|
267
|
+
return withGitReadDeadline(() => paneRouteOnce(ctx, url, data, response, () => { }));
|
|
268
|
+
}
|
|
264
269
|
if (url.pathname !== "/v1/prompt")
|
|
265
270
|
return paneRouteOnce(ctx, url, data, response, () => { });
|
|
266
271
|
// A retried send carries its first attempt's id; the Hook answers it with
|
|
@@ -628,12 +633,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
628
633
|
result = await repositoryDiff(await gitRepository(pane, target, data.child, data.worktree), [], []);
|
|
629
634
|
}
|
|
630
635
|
else if (child !== undefined) {
|
|
631
|
-
|
|
632
|
-
// parent's checkout. The whole repository, no phone-named paths.
|
|
633
|
-
const relation = childAgent(await childAgentTree(target.source, target.session), child);
|
|
634
|
-
if (!relation)
|
|
635
|
-
throw new BridgeError(404, "That agent is not part of this conversation.");
|
|
636
|
-
result = await repositoryDiff(relation.cwd ?? await trustedDirectory(pane), [], []);
|
|
636
|
+
result = await repositoryDiff(await gitRepository(pane, target, child), [], []);
|
|
637
637
|
}
|
|
638
638
|
else {
|
|
639
639
|
const cwd = await trustedDirectory(pane), paths = z.array(z.string().max(4096)).max(24).optional().parse(data.paths) ?? [];
|
|
@@ -655,9 +655,17 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
655
655
|
else if (url.pathname.startsWith("/v1/git/")) {
|
|
656
656
|
// Git routes read the pane's repository, or a spawned child's own
|
|
657
657
|
// worktree, exactly as /v1/diff resolves it.
|
|
658
|
-
|
|
658
|
+
let cwd = await gitRepository(pane, target, data.child, data.worktree);
|
|
659
|
+
if (["stage", "unstage", "discard", "commit", "push", "pr"].some(action => url.pathname === `/v1/git/${action}`)
|
|
660
|
+
&& data.expectedRepository !== undefined) {
|
|
661
|
+
const expected = z.string().min(1).max(4096).refine(value => path.isAbsolute(value) && !value.includes("\0"), "Expected an absolute repository path.").parse(data.expectedRepository);
|
|
662
|
+
const root = await gitRoot(cwd);
|
|
663
|
+
if (root !== expected)
|
|
664
|
+
throw new BridgeError(409, "This pane's checkout changed. Refresh Changes before writing.", { code: "git-checkout-changed" });
|
|
665
|
+
cwd = root; // Execute in the validated root, never a path selected by the client.
|
|
666
|
+
}
|
|
659
667
|
if (url.pathname === "/v1/git/status")
|
|
660
|
-
result = await gitStatus(cwd);
|
|
668
|
+
result = await gitStatus(cwd, z.string().min(1).max(4096).optional().parse(data.untrackedPath));
|
|
661
669
|
else if (url.pathname === "/v1/git/worktrees")
|
|
662
670
|
result = await gitWorktrees(cwd, await worktreeWorkers(target));
|
|
663
671
|
else if (url.pathname === "/v1/git/log")
|
|
@@ -669,7 +677,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
669
677
|
else if (url.pathname === "/v1/git/tree")
|
|
670
678
|
result = await gitTree(cwd, z.string().max(4096).optional().parse(data.path) ?? "", z.boolean().optional().parse(data.ignored) ?? false);
|
|
671
679
|
else if (url.pathname === "/v1/git/stage")
|
|
672
|
-
result = await gitStage(cwd, data.paths);
|
|
680
|
+
result = await gitStage(cwd, data.paths, z.boolean().optional().parse(data.confirmBulk) ?? false);
|
|
673
681
|
else if (url.pathname === "/v1/git/unstage")
|
|
674
682
|
result = await gitUnstage(cwd, data.paths);
|
|
675
683
|
else if (url.pathname === "/v1/git/discard")
|
|
@@ -125,6 +125,8 @@ export declare const capabilities: {
|
|
|
125
125
|
sudoOutcome: boolean;
|
|
126
126
|
previewDeltas: boolean;
|
|
127
127
|
quickChat: boolean;
|
|
128
|
+
agentFolder: boolean;
|
|
129
|
+
launchPermissionMode: boolean;
|
|
128
130
|
};
|
|
129
131
|
export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
|
|
130
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 {
|
|
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, paneDeliveries: 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}$/)
|
|
686
|
-
|
|
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/
|
|
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") };
|
|
@@ -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.
|
|
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
|
|
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.
|
|
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
|
|
67
|
-
|
|
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
|
|
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
|
}
|
|
@@ -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(() => [])])]
|
|
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 =>
|
|
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
|
+
}
|