@phren/cli 0.3.72 → 0.3.73
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 +11 -1
- package/dist/bridge/browser-env.d.ts +1 -1
- package/dist/bridge/browser-env.js +34 -10
- package/dist/bridge/browser-watch.d.ts +12 -0
- package/dist/bridge/browser-watch.js +83 -0
- package/dist/bridge/claude-account-setup.js +3 -1
- package/dist/bridge/claude-accounts.d.ts +5 -1
- package/dist/bridge/claude-accounts.js +36 -6
- package/dist/bridge/codex-servers.d.ts +2 -0
- package/dist/bridge/codex-servers.js +1 -1
- package/dist/bridge/command.js +24 -5
- package/dist/bridge/dispatch-clone.d.ts +33 -0
- package/dist/bridge/dispatch-clone.js +176 -0
- package/dist/bridge/dispatch-command.d.ts +14 -0
- package/dist/bridge/dispatch-command.js +98 -13
- package/dist/bridge/dispatch-idempotency.d.ts +85 -0
- package/dist/bridge/dispatch-idempotency.js +235 -0
- package/dist/bridge/dispatch-returns.d.ts +6 -0
- package/dist/bridge/dispatch-returns.js +131 -1
- package/dist/bridge/dispatch-wait.d.ts +32 -0
- package/dist/bridge/dispatch-wait.js +177 -0
- package/dist/bridge/dispatch.d.ts +68 -2
- package/dist/bridge/dispatch.js +839 -25
- package/dist/bridge/fanouts.js +20 -3
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/git-credential.d.ts +44 -0
- package/dist/bridge/git-credential.js +113 -0
- package/dist/bridge/git-host-auth.d.ts +9 -1
- package/dist/bridge/git-host-auth.js +18 -5
- package/dist/bridge/git-host-gitboy.js +8 -1
- package/dist/bridge/git-hosts.d.ts +12 -1
- package/dist/bridge/git-publish.js +3 -2
- package/dist/bridge/herdr.d.ts +4 -0
- package/dist/bridge/herdr.js +29 -3
- package/dist/bridge/install.d.ts +1 -1
- package/dist/bridge/install.js +8 -4
- package/dist/bridge/launch-worktree.d.ts +2 -0
- package/dist/bridge/launch-worktree.js +5 -1
- package/dist/bridge/protocol.d.ts +7 -0
- package/dist/bridge/schedule-watch.js +13 -2
- package/dist/bridge/server-launch.d.ts +2 -0
- package/dist/bridge/server-launch.js +251 -145
- package/dist/bridge/server-routes.js +18 -2
- package/dist/bridge/server.js +12 -1
- package/dist/bridge/status-line-fast.d.ts +9 -0
- package/dist/bridge/status-line-fast.js +56 -0
- package/dist/bridge/terminal-herdr.d.ts +5 -1
- package/dist/bridge/terminal-herdr.js +65 -1
- package/dist/bridge/terminal-tmux.d.ts +2 -0
- package/dist/bridge/terminal-tmux.js +27 -6
- package/dist/bridge/terminal.d.ts +5 -1
- package/dist/bridge/transcript-claude.js +192 -112
- package/dist/bridge/transcript-preview.d.ts +2 -1
- package/dist/bridge/transcript-preview.js +85 -3
- package/dist/bridge/transcripts.js +17 -11
- package/dist/bridge/turn-records.js +16 -4
- package/dist/bridge/usage.d.ts +7 -1
- package/dist/bridge/usage.js +47 -31
- package/dist/bridge/worker-close.d.ts +15 -0
- package/dist/bridge/worker-close.js +304 -3
- package/dist/bridge/worker-identity.d.ts +51 -0
- package/dist/bridge/worker-identity.js +289 -0
- package/dist/bridge-hook.mjs +20857 -18606
- package/dist/cli/browser-hint.d.ts +2 -0
- package/dist/cli/browser-hint.js +21 -0
- package/dist/cli/hooks-context.d.ts +2 -2
- package/dist/cli/hooks-context.js +3 -3
- package/dist/cli/hooks.js +20 -11
- package/dist/cli-registry.js +5 -3
- package/dist/modules/registry.js +1 -1
- package/package.json +1 -1
|
@@ -36,6 +36,7 @@ import { classifyClaudeInput, parseInputCategory } from "./input-classification.
|
|
|
36
36
|
import { noteTurn as recordTurn, readTurn, turnPhase } from "./turn-records.js";
|
|
37
37
|
import { PromptDeliveries } from "./prompt-deliveries.js";
|
|
38
38
|
import { countTick } from "./metrics.js";
|
|
39
|
+
import { recordClaudeStatusLine } from "./usage.js";
|
|
39
40
|
import { briefId, briefIdInPrompt, briefLabel, recordBriefArrival } from "./launch-brief.js";
|
|
40
41
|
import { appServerApproval, appServerDecision, conductorCall, OPENCODE_APPROVAL_OPTIONS, opencodePermissionReply } from "./agent-hook-asks.js";
|
|
41
42
|
import { SudoBroker } from "./sudo.js";
|
|
@@ -1776,7 +1777,7 @@ export class AgentHooks {
|
|
|
1776
1777
|
await this.sudo.handle(req, res);
|
|
1777
1778
|
return;
|
|
1778
1779
|
}
|
|
1779
|
-
if (req.method !== "POST" || !["/hook", "/conductor-context"].includes(req.url ?? ""))
|
|
1780
|
+
if (req.method !== "POST" || !["/hook", "/conductor-context", "/usage-statusline"].includes(req.url ?? ""))
|
|
1780
1781
|
throw new Error("Invalid callback");
|
|
1781
1782
|
let size = 0;
|
|
1782
1783
|
const chunks = [];
|
|
@@ -1787,6 +1788,15 @@ export class AgentHooks {
|
|
|
1787
1788
|
chunks.push(bytes);
|
|
1788
1789
|
}
|
|
1789
1790
|
const body = object(JSON.parse(Buffer.concat(chunks).toString()));
|
|
1791
|
+
// Claude Code's status line, from the forwarder (status-line-fast.ts): usage recorded here, in the
|
|
1792
|
+
// running Hook, rather than by a bundle started for every refresh.
|
|
1793
|
+
if (req.url === "/usage-statusline") {
|
|
1794
|
+
if (typeof body.input !== "string" || (body.configDir !== undefined && typeof body.configDir !== "string"))
|
|
1795
|
+
throw new Error("Invalid status line");
|
|
1796
|
+
await recordClaudeStatusLine(JSON.parse(body.input), body.configDir);
|
|
1797
|
+
res.end("{}");
|
|
1798
|
+
return;
|
|
1799
|
+
}
|
|
1790
1800
|
// OpenCode and phren-agent ask when building the root session's system prompt. Resolve
|
|
1791
1801
|
// its process against the current conductor; no inherited pane env or
|
|
1792
1802
|
// plugin callback may create a session binding or a turn record here.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export declare function browserShimPath(): string;
|
|
2
2
|
export declare function browserEnv(session: string, existing?: string): Record<string, string>;
|
|
3
|
-
export declare function printBrowserEnv(session?: string): void;
|
|
3
|
+
export declare function printBrowserEnv(session?: string, format?: "shell" | "json" | "fish"): void;
|
|
4
4
|
/** Ask sockets are independent of producer sockets; closing one cancels its help request. */
|
|
5
5
|
export declare function runBrowser(args: string[]): Promise<number>;
|
|
@@ -10,25 +10,49 @@ export function browserShimPath() {
|
|
|
10
10
|
const local = fileURLToPath(new URL("./browser-shim/phren-playwright.cjs", import.meta.url));
|
|
11
11
|
return existsSync(local) ? local : fileURLToPath(new URL("./bridge/browser-shim/phren-playwright.cjs", import.meta.url));
|
|
12
12
|
}
|
|
13
|
-
|
|
13
|
+
function installedBrowserShimPath() {
|
|
14
14
|
const installed = path.join(bridgeRoot(), "current/bridge/browser-shim/phren-playwright.cjs");
|
|
15
|
-
|
|
15
|
+
return realpathSync(existsSync(installed) ? installed : browserShimPath());
|
|
16
|
+
}
|
|
17
|
+
export function browserEnv(session, existing = process.env.NODE_OPTIONS ?? "") {
|
|
18
|
+
const shim = installedBrowserShimPath();
|
|
16
19
|
const requireOption = `--require=${JSON.stringify(shim)}`;
|
|
17
20
|
return { NODE_OPTIONS: `${existing}${existing ? " " : ""}${requireOption}`, PHREN_BROWSER_SOCKET: browserSocketPath(), PHREN_BROWSER_SESSION: session };
|
|
18
21
|
}
|
|
19
|
-
export function printBrowserEnv(session = process.env.PHREN_BROWSER_SESSION
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
export function printBrowserEnv(session = process.env.PHREN_BROWSER_SESSION || process.env.HERDR_PANE_ID || process.env.TMUX_PANE || `manual-${process.ppid}`, format = "shell") {
|
|
23
|
+
const env = browserEnv(session);
|
|
24
|
+
if (format === "json") {
|
|
25
|
+
console.log(JSON.stringify(env));
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
for (const [key, value] of Object.entries(env)) {
|
|
29
|
+
const quoted = format === "fish" ? "'" + value.replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "'" : "'" + value.replace(/'/g, "'\\''") + "'";
|
|
30
|
+
console.log(format === "fish" ? `set -gx ${key} ${quoted};` : `export ${key}=${quoted}`);
|
|
31
|
+
}
|
|
32
|
+
// A comment remains shell-evaluable, including paths containing newlines.
|
|
33
|
+
const bun = `Bun 1.4.2: bun --preload '${installedBrowserShimPath().replace(/'/g, "'\\''")}' run.mjs; also call the shim's initPage({ page }) after newPage(): Bun bypasses automatic interception.`;
|
|
34
|
+
console.log(bun.split("\n").map(line => `# ${line}`).join("\n"));
|
|
22
35
|
}
|
|
23
36
|
/** Ask sockets are independent of producer sockets; closing one cancels its help request. */
|
|
24
37
|
export async function runBrowser(args) {
|
|
25
|
-
|
|
26
|
-
|
|
38
|
+
const usage = 'Usage: phren browser env [--session <name>] [--json | --fish] | phren browser ask "<reason>" [--browser <id>] [--timeout <seconds, default 900>]';
|
|
39
|
+
if (args.length === 0 || args.includes("--help")) {
|
|
40
|
+
console.log(usage + '\nStart Playwright after: eval "$(phren browser env)" (preserves NODE_OPTIONS).\nFish: phren browser env --fish | source\nBun: bun --preload <shim> run.mjs (also call shim.initPage({ page }); see env output).');
|
|
27
41
|
return 0;
|
|
28
42
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
43
|
+
if (args[0] === "env") {
|
|
44
|
+
let session, format = "shell";
|
|
45
|
+
for (let i = 1; i < args.length; i++) {
|
|
46
|
+
if (args[i] === "--session" && args[i + 1] && !args[i + 1].startsWith("--"))
|
|
47
|
+
session = args[++i];
|
|
48
|
+
else if ((args[i] === "--json" || args[i] === "--fish") && format === "shell")
|
|
49
|
+
format = args[i] === "--json" ? "json" : "fish";
|
|
50
|
+
else {
|
|
51
|
+
console.error(usage);
|
|
52
|
+
return 1;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
printBrowserEnv(session, format);
|
|
32
56
|
return 0;
|
|
33
57
|
}
|
|
34
58
|
let browserId, timeout = 900;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { BrowserWatch, Json } from "./protocol.js";
|
|
2
|
+
/** Successful Hook launches provide evidence without inspecting an environment. */
|
|
3
|
+
export declare function noteBrowserLaunch(pids: readonly number[], env: Record<string, string> | undefined, place?: {
|
|
4
|
+
server: string;
|
|
5
|
+
pane: Json;
|
|
6
|
+
}): void;
|
|
7
|
+
/** Never await process inspection on a session-list path. Only inspect the
|
|
8
|
+
* agent PID the caller already resolved; no ps subprocesses on macOS. */
|
|
9
|
+
export declare function browserWatch(pid: number | undefined): BrowserWatch;
|
|
10
|
+
/** A reported conversation can skip PID lookup. Reuse only this launch's
|
|
11
|
+
* terminal, harness and conversation; a replacement retires the evidence. */
|
|
12
|
+
export declare function paneBrowserWatch(server: string, pane: Json, session: string | undefined, pid?: number): BrowserWatch;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
const cache = new Map();
|
|
3
|
+
const launched = new Map();
|
|
4
|
+
const panes = new Map();
|
|
5
|
+
const paneKey = (server, pane) => JSON.stringify([server, pane]);
|
|
6
|
+
const TTL = 30_000;
|
|
7
|
+
/** Successful Hook launches provide evidence without inspecting an environment. */
|
|
8
|
+
export function noteBrowserLaunch(pids, env, place) {
|
|
9
|
+
if (!env?.PHREN_BROWSER_SOCKET || env.PHREN_BROWSER_WATCH === "0" || !env.PHREN_BROWSER_SESSION || !env.NODE_OPTIONS?.includes("--require="))
|
|
10
|
+
return;
|
|
11
|
+
if (place && pids[0] && place.pane.terminal_id) {
|
|
12
|
+
if (panes.size >= 512)
|
|
13
|
+
panes.delete(panes.keys().next().value);
|
|
14
|
+
panes.set(paneKey(place.server, place.pane.pane_id), { terminal: place.pane.terminal_id, source: place.pane.agent, pid: pids[0] });
|
|
15
|
+
}
|
|
16
|
+
for (const pid of pids) {
|
|
17
|
+
if (launched.size >= 512)
|
|
18
|
+
launched.delete(launched.keys().next().value);
|
|
19
|
+
launched.set(pid, Date.now());
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Never await process inspection on a session-list path. Only inspect the
|
|
23
|
+
* agent PID the caller already resolved; no ps subprocesses on macOS. */
|
|
24
|
+
export function browserWatch(pid) {
|
|
25
|
+
if (!pid || !Number.isSafeInteger(pid) || pid <= 0)
|
|
26
|
+
return "unknown";
|
|
27
|
+
const now = Date.now();
|
|
28
|
+
const launch = launched.get(pid);
|
|
29
|
+
// Bare PID evidence expires to bound PID reuse; pane-bound evidence below
|
|
30
|
+
// also checks the terminal, harness and conversation.
|
|
31
|
+
if (launch !== undefined && now - launch < TTL) {
|
|
32
|
+
try {
|
|
33
|
+
process.kill(pid, 0);
|
|
34
|
+
return "on";
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
launched.delete(pid);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
launched.delete(pid);
|
|
41
|
+
const entry = cache.get(pid);
|
|
42
|
+
if (entry && now - entry.at < TTL)
|
|
43
|
+
return entry.value;
|
|
44
|
+
if (process.platform !== "linux")
|
|
45
|
+
return "unknown";
|
|
46
|
+
if (cache.size >= 512)
|
|
47
|
+
cache.delete(cache.keys().next().value);
|
|
48
|
+
const next = { at: now, value: "unknown" };
|
|
49
|
+
cache.set(pid, next);
|
|
50
|
+
void readFile(`/proc/${pid}/environ`, "utf8").then(text => {
|
|
51
|
+
const env = Object.fromEntries(text.split("\0").filter(Boolean).map(line => {
|
|
52
|
+
const eq = line.indexOf("=");
|
|
53
|
+
return [line.slice(0, eq), line.slice(eq + 1)];
|
|
54
|
+
}));
|
|
55
|
+
next.value = env.PHREN_BROWSER_SOCKET && env.PHREN_BROWSER_SESSION
|
|
56
|
+
&& env.NODE_OPTIONS?.includes("--require=") && env.PHREN_BROWSER_WATCH !== "0" ? "on" : "off";
|
|
57
|
+
}, () => { });
|
|
58
|
+
return next.value;
|
|
59
|
+
}
|
|
60
|
+
/** A reported conversation can skip PID lookup. Reuse only this launch's
|
|
61
|
+
* terminal, harness and conversation; a replacement retires the evidence. */
|
|
62
|
+
export function paneBrowserWatch(server, pane, session, pid) {
|
|
63
|
+
const key = paneKey(server, pane.pane_id), launch = panes.get(key);
|
|
64
|
+
if (launch) {
|
|
65
|
+
if (launch.terminal !== pane.terminal_id || launch.source !== pane.agent
|
|
66
|
+
|| (pid !== undefined && pid !== launch.pid) || (launch.session && session && launch.session !== session)) {
|
|
67
|
+
panes.delete(key);
|
|
68
|
+
launched.delete(launch.pid);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
launch.session ??= session;
|
|
72
|
+
try {
|
|
73
|
+
process.kill(launch.pid, 0);
|
|
74
|
+
return "on";
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
panes.delete(key);
|
|
78
|
+
launched.delete(launch.pid);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return browserWatch(pid);
|
|
83
|
+
}
|
|
@@ -4,7 +4,7 @@ import { chmod, lstat, mkdir, readFile, symlink } from "node:fs/promises";
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
6
|
import { homeDir } from "../home-paths.js";
|
|
7
|
-
import { claudeHome, claudeHomes, DEFAULT_ACCOUNT, isAccountSlug, setAccountLabel } from "./claude-accounts.js";
|
|
7
|
+
import { claudeHome, claudeHomes, DEFAULT_ACCOUNT, forgetClaudeHomes, isAccountSlug, setAccountLabel } from "./claude-accounts.js";
|
|
8
8
|
import { atomic } from "./protocol.js";
|
|
9
9
|
/** Entries of the default home every account shares by symlink. */
|
|
10
10
|
export const SHARED_ENTRIES = ["settings.json", "CLAUDE.md", "skills", "agents", "commands", "plugins"];
|
|
@@ -107,6 +107,8 @@ export async function addClaudeAccount(slug, opts = {}) {
|
|
|
107
107
|
linked.push(name);
|
|
108
108
|
}
|
|
109
109
|
await mergeMcpServers(path.join(dir, ".claude.json"), await mcpServersOf(source.configFile));
|
|
110
|
+
// The listing may predate this home or its .claude.json (an interrupted add): list again.
|
|
111
|
+
forgetClaudeHomes();
|
|
110
112
|
if (opts.label)
|
|
111
113
|
await setAccountLabel(slug, opts.label);
|
|
112
114
|
return { id: slug, dir, linked, created, ...(keychain === "unknown" ? { warning: KEYCHAIN_UNKNOWN_WARNING } : {}) };
|
|
@@ -18,7 +18,9 @@ export interface AccountRef {
|
|
|
18
18
|
email?: string;
|
|
19
19
|
}
|
|
20
20
|
export declare function isAccountSlug(value: string): boolean;
|
|
21
|
-
/** Every Claude home on this computer, default first, then by slug.
|
|
21
|
+
/** Every Claude home on this computer, default first, then by slug. The Hook asks several times per pane
|
|
22
|
+
* per overview, so a listing is reused for HOMES_REUSE_MS, and after that while the home folder and
|
|
23
|
+
* every `.claude-*` folder in it are unchanged, up to HOMES_MAX_AGE_MS. */
|
|
22
24
|
export declare function claudeHomes(env?: NodeJS.ProcessEnv): ClaudeHome[];
|
|
23
25
|
export declare function claudeHome(id: string | undefined, env?: NodeJS.ProcessEnv): ClaudeHome | undefined;
|
|
24
26
|
/** The home a transcript or other file lives in, by longest matching directory. */
|
|
@@ -66,6 +68,8 @@ export declare function claudeAccountRef(home: ClaudeHome, labels?: Record<strin
|
|
|
66
68
|
export declare function claudeLoginFingerprint(home: ClaudeHome): string | undefined;
|
|
67
69
|
export declare const CODEX_ACCOUNT: AccountRef;
|
|
68
70
|
/** Only for tests. */
|
|
71
|
+
/** Drop the cached home listing, so a home made in this process is seen at once. */
|
|
72
|
+
export declare function forgetClaudeHomes(): void;
|
|
69
73
|
export declare function clearAccountCaches(): void;
|
|
70
74
|
/** `unknown`: Claude gave no answer (timeout, crash, unparseable), which must not block a launch. */
|
|
71
75
|
export interface AuthStatus {
|
|
@@ -21,20 +21,48 @@ function defaultHome(env) {
|
|
|
21
21
|
// Claude keeps .claude.json inside CLAUDE_CONFIG_DIR when set, else beside ~/.claude.
|
|
22
22
|
return { id: DEFAULT_ACCOUNT, dir, configFile: path.join(configured ? dir : homeDir(env), ".claude.json"), isDefault: true };
|
|
23
23
|
}
|
|
24
|
-
|
|
24
|
+
const mtimeOf = (dir) => { try {
|
|
25
|
+
return statSync(dir).mtimeMs;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return -1;
|
|
29
|
+
} };
|
|
30
|
+
const homesCache = new Map();
|
|
31
|
+
/** How long a listing stands even when its folders changed: Claude rewrites each `.claude.json` through
|
|
32
|
+
* temp files beside it every few seconds, so their mtimes alone would rarely let a listing be reused. */
|
|
33
|
+
const HOMES_REUSE_MS = 2_000;
|
|
34
|
+
/** The longest a listing stands on unchanged mtimes: a home made within one coarse mtime tick of the
|
|
35
|
+
* last listing would otherwise stay unseen until another folder changed. */
|
|
36
|
+
const HOMES_MAX_AGE_MS = 60_000;
|
|
37
|
+
/** Every Claude home on this computer, default first, then by slug. The Hook asks several times per pane
|
|
38
|
+
* per overview, so a listing is reused for HOMES_REUSE_MS, and after that while the home folder and
|
|
39
|
+
* every `.claude-*` folder in it are unchanged, up to HOMES_MAX_AGE_MS. */
|
|
25
40
|
export function claudeHomes(env = process.env) {
|
|
26
|
-
const
|
|
27
|
-
const
|
|
41
|
+
const first = defaultHome(env), home = homeDir(env), key = `${home}\0${first.dir}\0${first.configFile}`;
|
|
42
|
+
const cached = homesCache.get(key), now = Date.now();
|
|
43
|
+
if (cached && (now - cached.at < HOMES_REUSE_MS
|
|
44
|
+
|| (now - cached.at < HOMES_MAX_AGE_MS && mtimeOf(home) === cached.home && cached.candidates.every(candidate => mtimeOf(candidate.dir) === candidate.mtime))))
|
|
45
|
+
return [...cached.homes];
|
|
46
|
+
const homeMtime = mtimeOf(home);
|
|
47
|
+
const homes = listClaudeHomes(first, home);
|
|
48
|
+
homesCache.set(key, { at: now, home: homeMtime, candidates: homes.candidates, homes: homes.homes });
|
|
49
|
+
while (homesCache.size > 16)
|
|
50
|
+
homesCache.delete(homesCache.keys().next().value);
|
|
51
|
+
return [...homes.homes];
|
|
52
|
+
}
|
|
53
|
+
function listClaudeHomes(first, home) {
|
|
54
|
+
const homes = [first], candidates = [];
|
|
28
55
|
let names = [];
|
|
29
56
|
try {
|
|
30
57
|
names = readdirSync(home);
|
|
31
58
|
}
|
|
32
59
|
catch {
|
|
33
|
-
return homes;
|
|
60
|
+
return { homes, candidates };
|
|
34
61
|
}
|
|
35
62
|
for (const name of names.sort()) {
|
|
36
63
|
if (!name.startsWith(".claude-"))
|
|
37
64
|
continue;
|
|
65
|
+
candidates.push({ dir: path.join(home, name), mtime: mtimeOf(path.join(home, name)) });
|
|
38
66
|
const id = name.slice(".claude-".length);
|
|
39
67
|
if (!SLUG.test(id) || id === DEFAULT_ACCOUNT)
|
|
40
68
|
continue;
|
|
@@ -50,7 +78,7 @@ export function claudeHomes(env = process.env) {
|
|
|
50
78
|
}
|
|
51
79
|
homes.push({ id, dir, configFile: path.join(dir, ".claude.json"), isDefault: false });
|
|
52
80
|
}
|
|
53
|
-
return homes;
|
|
81
|
+
return { homes, candidates };
|
|
54
82
|
}
|
|
55
83
|
export function claudeHome(id, env = process.env) {
|
|
56
84
|
const wanted = id?.trim() || DEFAULT_ACCOUNT;
|
|
@@ -235,7 +263,9 @@ export function claudeLoginFingerprint(home) {
|
|
|
235
263
|
}
|
|
236
264
|
export const CODEX_ACCOUNT = { id: DEFAULT_ACCOUNT, label: "Codex", key: "codex" };
|
|
237
265
|
/** Only for tests. */
|
|
238
|
-
|
|
266
|
+
/** Drop the cached home listing, so a home made in this process is seen at once. */
|
|
267
|
+
export function forgetClaudeHomes() { homesCache.clear(); }
|
|
268
|
+
export function clearAccountCaches() { identityCache.clear(); authCache.clear(); homesCache.clear(); }
|
|
239
269
|
const AUTH_CACHE_MS = 5 * 60_000;
|
|
240
270
|
const AUTH_TIMEOUT_MS = 10_000;
|
|
241
271
|
const SIGNED_OUT_CACHE_MS = 30_000;
|
|
@@ -117,6 +117,8 @@ export interface LaunchOptions {
|
|
|
117
117
|
remoteArgs?: string[];
|
|
118
118
|
/** Layered over the Hook's environment for the server and its hooks. */
|
|
119
119
|
env?: Record<string, string>;
|
|
120
|
+
/** `env` is the complete environment; do not inherit the Hook's process env. */
|
|
121
|
+
envExact?: boolean;
|
|
120
122
|
dispatchId?: string;
|
|
121
123
|
}
|
|
122
124
|
export declare class CodexServers {
|
|
@@ -188,7 +188,7 @@ export class CodexServers {
|
|
|
188
188
|
await mkdir(codexServersRoot(), { recursive: true, mode: 0o700 });
|
|
189
189
|
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
190
190
|
const spawnOptions = { socketPath: socket, cwd: options.cwd, detached: true, logFile: path.join(directory, "server.log"),
|
|
191
|
-
config: serverConfig(), replaceEnv: true, env: serverEnvironment(process.env, { ...(options.env ?? {}), [CODEX_SERVER_ENV]: serverId }) };
|
|
191
|
+
config: serverConfig(), replaceEnv: true, env: serverEnvironment(options.envExact ? {} : process.env, { ...(options.env ?? {}), [CODEX_SERVER_ENV]: serverId }) };
|
|
192
192
|
const scope = this.deps.scope?.(serverId);
|
|
193
193
|
const handle = await (scope
|
|
194
194
|
// No systemd-run, or no user manager to ask: the server runs in the
|
package/dist/bridge/command.js
CHANGED
|
@@ -10,6 +10,7 @@ import { object, provider, socketPath } from "./protocol.js";
|
|
|
10
10
|
import { apnsSetupSteps } from "./push.js";
|
|
11
11
|
import { speechKeyFile, speechKeyStatus, writeSpeechKey } from "./speech-key.js";
|
|
12
12
|
import { gitHostsFile, listHostTokens, writeHostToken } from "./git-host-auth.js";
|
|
13
|
+
import { gitCredentialCommand } from "./git-credential.js";
|
|
13
14
|
import { hostInfo, PROVIDERS } from "./git-hosts.js";
|
|
14
15
|
import { clearSpeechModel, clearSpeechVoice, DEFAULT_SPEECH_MODEL, FALLBACK_SPEECH_MODEL, resolveSpeechModel, resolveSpeechRegion, resolveSpeechVoice, SPEECH_REGIONS, speechModelId, speechRegion, speechVoiceFile, voiceId, writeSpeechModel, writeSpeechRegion, writeSpeechVoice } from "./speech-voice.js";
|
|
15
16
|
import { AccountUsageReader, captureClaudeUsage } from "./usage.js";
|
|
@@ -149,6 +150,17 @@ export async function runBridge(args, version) {
|
|
|
149
150
|
console.log(`Stored the ElevenLabs key in ${speechKeyFile()} (mode 600).`);
|
|
150
151
|
break;
|
|
151
152
|
}
|
|
153
|
+
case "git-credential": {
|
|
154
|
+
// Git runs this helper with get/store/erase. Only get answers, and only
|
|
155
|
+
// from the Hook's stored gitboy token; store and erase do nothing.
|
|
156
|
+
let request = "";
|
|
157
|
+
for await (const chunk of process.stdin)
|
|
158
|
+
request += chunk;
|
|
159
|
+
const output = await gitCredentialCommand(args[1], request);
|
|
160
|
+
if (output)
|
|
161
|
+
process.stdout.write(output);
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
152
164
|
case "git-host": {
|
|
153
165
|
// Tokens for GitLab and gitboy, which the Hook reads over HTTP; GitHub keeps gh's sign-in.
|
|
154
166
|
const [, action = "list", domain, kind] = args;
|
|
@@ -159,7 +171,7 @@ export async function runBridge(args, version) {
|
|
|
159
171
|
if (!hosts.length)
|
|
160
172
|
console.log("No GitLab or gitboy tokens stored. Add one with phren bridge git-host set <domain> gitlab|gitboy.");
|
|
161
173
|
for (const host of hosts)
|
|
162
|
-
console.log(`${host.domain} ${host.kind}${host.user ? ` @${host.user}` : ""}`);
|
|
174
|
+
console.log(`${host.domain} ${host.kind}${host.agent ? " agent token" : ""}${host.user ? ` @${host.user}` : ""}`);
|
|
163
175
|
}
|
|
164
176
|
else if (action === "set" && domain && (kind === "gitlab" || kind === "gitboy") && args.length === 4) {
|
|
165
177
|
// The token comes from stdin, never argv, so it stays out of ps and shell history.
|
|
@@ -167,9 +179,16 @@ export async function runBridge(args, version) {
|
|
|
167
179
|
if (!token)
|
|
168
180
|
throw new Error("No token given.");
|
|
169
181
|
const host = hostInfo(kind, { domain: domain.toLowerCase(), webUrl: null, remote: null, source: "none" });
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
182
|
+
const identity = await PROVIDERS[kind].whoami(process.cwd(), host, token);
|
|
183
|
+
const user = identity.user;
|
|
184
|
+
const agent = identity.agent ?? identity.agent_token;
|
|
185
|
+
await writeHostToken(domain, kind, token, user || undefined, undefined, !!agent);
|
|
186
|
+
if (agent) {
|
|
187
|
+
const expires = agent.expires_at ? `, expires ${agent.expires_at.slice(0, 10)}` : "";
|
|
188
|
+
console.log(`Connected ${domain} (gitboy agent token as @${user}${expires}). Stored in ${gitHostsFile()} (mode 600).`);
|
|
189
|
+
}
|
|
190
|
+
else
|
|
191
|
+
console.log(`Connected ${domain} (${kind})${user ? ` as @${user}` : ""}. Stored in ${gitHostsFile()} (mode 600).`);
|
|
173
192
|
}
|
|
174
193
|
else if (action === "remove" && domain && args.length === 3) {
|
|
175
194
|
await writeHostToken(domain, "gitlab", "");
|
|
@@ -308,7 +327,7 @@ export async function runBridge(args, version) {
|
|
|
308
327
|
console.error(`warning: ${push.warning}`);
|
|
309
328
|
break;
|
|
310
329
|
}
|
|
311
|
-
default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|git-host|speech-key set|speech-voice|speech-model|speech-region>");
|
|
330
|
+
default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|git-host|git-credential|speech-key set|speech-voice|speech-model|speech-region>");
|
|
312
331
|
}
|
|
313
332
|
return 0;
|
|
314
333
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** A keyed dispatch's isolated checkout. The clone and its managed global
|
|
2
|
+
* config are outside the user's checkout and are removed with the dispatch. */
|
|
3
|
+
export interface DispatchClonePaths {
|
|
4
|
+
cloneDir: string;
|
|
5
|
+
gitConfigFile: string;
|
|
6
|
+
agentTokenFile: string;
|
|
7
|
+
/** The wrapper's PID/start-time record, beside the clone. */
|
|
8
|
+
workerFile?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function dispatchClonePaths(dispatchId: string): DispatchClonePaths;
|
|
11
|
+
/** Canonical path inside the managed clone root, or a refusal. */
|
|
12
|
+
export declare function assertManagedClonePath(candidate: string): Promise<string>;
|
|
13
|
+
export interface DispatchClone extends DispatchClonePaths {
|
|
14
|
+
/** Where the agent starts: the same folder inside the clone as the project folder in its repository. */
|
|
15
|
+
cwd: string;
|
|
16
|
+
path: string;
|
|
17
|
+
branch: string;
|
|
18
|
+
discard(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/** Only the keys a keyed worker may inherit: no user URL-specific overrides. */
|
|
21
|
+
export declare function writeManagedConfig(file: string, domain: string, checkout: string): Promise<void>;
|
|
22
|
+
/** The start folder inside the clone, refusing a symlink or a path that escapes it. */
|
|
23
|
+
export declare function cloneStartDirectory(cloneDir: string, root: string, checkout: string): Promise<string>;
|
|
24
|
+
/** A fresh clone with only our managed global config, never the user's checkout config. */
|
|
25
|
+
export declare function createDispatchClone(checkout: string, request: {
|
|
26
|
+
branch: string;
|
|
27
|
+
dispatchId: string;
|
|
28
|
+
paths?: DispatchClonePaths;
|
|
29
|
+
}): Promise<DispatchClone>;
|
|
30
|
+
/** Remove a dispatch's clone, managed config and token file; only paths this Hook made. */
|
|
31
|
+
export declare function removeDispatchClone(paths: Partial<DispatchClonePaths> | undefined): Promise<void>;
|
|
32
|
+
/** Keep the clone (recoverable work) but remove the token and managed config immediately. */
|
|
33
|
+
export declare function removeDispatchSecrets(paths: Partial<DispatchClonePaths> | undefined): Promise<void>;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { chmod, lstat, mkdir, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { nonInteractiveGitEnv } from "../utils-helpers.js";
|
|
6
|
+
import { countGit } from "./metrics.js";
|
|
7
|
+
import { gitRoot } from "./projects.js";
|
|
8
|
+
import { EMPTY_TREE } from "./launch-worktree.js";
|
|
9
|
+
import { credentialFreeRemote, keyedExplicitEnv, removeAgentTokenFile } from "./git-credential.js";
|
|
10
|
+
import { detectHost } from "./git-hosts.js";
|
|
11
|
+
import { BridgeError, bridgeRoot } from "./protocol.js";
|
|
12
|
+
import { workerFilePath } from "./worker-identity.js";
|
|
13
|
+
export function dispatchClonePaths(dispatchId) {
|
|
14
|
+
const root = path.join(bridgeRoot(), "clones");
|
|
15
|
+
const cloneDir = path.join(root, dispatchId);
|
|
16
|
+
return {
|
|
17
|
+
cloneDir,
|
|
18
|
+
gitConfigFile: path.join(root, `${dispatchId}.gitconfig`),
|
|
19
|
+
agentTokenFile: path.join(cloneDir, ".git", "phren-agent-token"),
|
|
20
|
+
workerFile: workerFilePath(dispatchId),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const managedRoot = () => path.join(bridgeRoot(), "clones");
|
|
24
|
+
async function canonicalManagedRoot() {
|
|
25
|
+
const root = managedRoot();
|
|
26
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
27
|
+
return realpath(root);
|
|
28
|
+
}
|
|
29
|
+
/** Canonical path inside the managed clone root, or a refusal. */
|
|
30
|
+
export async function assertManagedClonePath(candidate) {
|
|
31
|
+
const root = await canonicalManagedRoot();
|
|
32
|
+
const resolved = await realpath(candidate).catch(() => path.resolve(candidate));
|
|
33
|
+
const rel = path.relative(root, resolved);
|
|
34
|
+
if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) {
|
|
35
|
+
throw new BridgeError(403, "The keyed clone path is outside Phren's managed clone folder.");
|
|
36
|
+
}
|
|
37
|
+
return resolved;
|
|
38
|
+
}
|
|
39
|
+
const exec = promisify(execFile);
|
|
40
|
+
async function git(args, env = nonInteractiveGitEnv(process.env)) {
|
|
41
|
+
countGit("dispatch-clone");
|
|
42
|
+
return (await exec("git", args, { timeout: 120_000, maxBuffer: 1_048_576, env })).stdout;
|
|
43
|
+
}
|
|
44
|
+
function configValue(value) {
|
|
45
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
|
|
46
|
+
}
|
|
47
|
+
async function userValue(checkout, key) {
|
|
48
|
+
try {
|
|
49
|
+
return (await git(["-C", checkout, "config", "--get", key])).trim() || undefined;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Only the keys a keyed worker may inherit: no user URL-specific overrides. */
|
|
56
|
+
export async function writeManagedConfig(file, domain, checkout) {
|
|
57
|
+
await assertManagedClonePath(file);
|
|
58
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
59
|
+
const lines = [
|
|
60
|
+
"[credential]",
|
|
61
|
+
"\thelper =",
|
|
62
|
+
`[credential "https://${domain}"]`,
|
|
63
|
+
"\thelper = !phren bridge git-credential",
|
|
64
|
+
"\tuseHttpPath = false",
|
|
65
|
+
"[core]",
|
|
66
|
+
"\tsshCommand = false",
|
|
67
|
+
"\thooksPath = /dev/null",
|
|
68
|
+
];
|
|
69
|
+
const name = await userValue(checkout, "user.name");
|
|
70
|
+
const email = await userValue(checkout, "user.email");
|
|
71
|
+
if (name || email) {
|
|
72
|
+
lines.push("[user]");
|
|
73
|
+
if (name)
|
|
74
|
+
lines.push(`\tname = ${configValue(name)}`);
|
|
75
|
+
if (email)
|
|
76
|
+
lines.push(`\temail = ${configValue(email)}`);
|
|
77
|
+
}
|
|
78
|
+
await writeFile(file, `${lines.join("\n")}\n`, { mode: 0o600, flag: "wx" });
|
|
79
|
+
await chmod(file, 0o600);
|
|
80
|
+
}
|
|
81
|
+
/** The start folder inside the clone, refusing a symlink or a path that escapes it. */
|
|
82
|
+
export async function cloneStartDirectory(cloneDir, root, checkout) {
|
|
83
|
+
const clone = await realpath(cloneDir);
|
|
84
|
+
const inside = path.relative(root, await realpath(checkout));
|
|
85
|
+
if (!inside || inside.startsWith("..") || path.isAbsolute(inside))
|
|
86
|
+
return clone;
|
|
87
|
+
const candidate = path.join(clone, inside);
|
|
88
|
+
const info = await lstat(candidate).catch(() => undefined);
|
|
89
|
+
if (!info)
|
|
90
|
+
return clone;
|
|
91
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
92
|
+
throw new BridgeError(409, "The project folder in the keyed clone is a symlink or not a directory.");
|
|
93
|
+
const real = await realpath(candidate);
|
|
94
|
+
const rel = path.relative(clone, real);
|
|
95
|
+
if (!rel || rel.startsWith("..") || path.isAbsolute(rel))
|
|
96
|
+
throw new BridgeError(403, "The project folder in the keyed clone points outside it.");
|
|
97
|
+
return real;
|
|
98
|
+
}
|
|
99
|
+
/** A fresh clone with only our managed global config, never the user's checkout config. */
|
|
100
|
+
export async function createDispatchClone(checkout, request) {
|
|
101
|
+
const root = await gitRoot(checkout);
|
|
102
|
+
if (!root)
|
|
103
|
+
throw new BridgeError(409, "This folder is not a Git repository, so it cannot be cloned for a keyed dispatch.");
|
|
104
|
+
const host = await detectHost(checkout, request.branch);
|
|
105
|
+
if (host.kind !== "gitboy" || !host.domain)
|
|
106
|
+
throw new BridgeError(409, "A keyed worktree dispatch needs a gitboy checkout.");
|
|
107
|
+
const url = credentialFreeRemote(host);
|
|
108
|
+
const paths = request.paths ?? dispatchClonePaths(request.dispatchId);
|
|
109
|
+
await assertManagedClonePath(paths.cloneDir);
|
|
110
|
+
await assertManagedClonePath(paths.gitConfigFile);
|
|
111
|
+
await assertManagedClonePath(paths.agentTokenFile);
|
|
112
|
+
if (await stat(paths.cloneDir).then(() => true, () => false))
|
|
113
|
+
throw new BridgeError(409, "This dispatch's clone folder already exists.");
|
|
114
|
+
await mkdir(path.dirname(paths.cloneDir), { recursive: true, mode: 0o700 });
|
|
115
|
+
await writeManagedConfig(paths.gitConfigFile, host.domain, checkout);
|
|
116
|
+
const env = keyedExplicitEnv(process.env, {
|
|
117
|
+
GIT_CONFIG_GLOBAL: paths.gitConfigFile,
|
|
118
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
119
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
120
|
+
GIT_ASKPASS: "false",
|
|
121
|
+
SSH_ASKPASS: "false",
|
|
122
|
+
});
|
|
123
|
+
try {
|
|
124
|
+
await git(["-c", "core.hooksPath=/dev/null", "clone", "--no-checkout", "--reference-if-able", root, "--dissociate", url, paths.cloneDir], env);
|
|
125
|
+
await git(["-C", paths.cloneDir, "-c", "core.hooksPath=/dev/null", `--attr-source=${EMPTY_TREE}`, "checkout", "-b", request.branch], env);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
await rm(paths.cloneDir, { recursive: true, force: true }).catch(() => undefined);
|
|
129
|
+
await unlink(paths.gitConfigFile).catch(() => undefined);
|
|
130
|
+
const detail = error instanceof Error && "stderr" in error ? String(error.stderr ?? "").trim().split("\n").at(-1) : "";
|
|
131
|
+
throw new BridgeError(409, `Git could not create the keyed clone${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
|
|
132
|
+
}
|
|
133
|
+
const clone = await realpath(paths.cloneDir);
|
|
134
|
+
const cwd = await cloneStartDirectory(clone, root, checkout);
|
|
135
|
+
return {
|
|
136
|
+
...paths,
|
|
137
|
+
cwd,
|
|
138
|
+
path: clone,
|
|
139
|
+
branch: request.branch,
|
|
140
|
+
async discard() {
|
|
141
|
+
await removeDispatchClone(paths);
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** Remove a dispatch's clone, managed config and token file; only paths this Hook made. */
|
|
146
|
+
export async function removeDispatchClone(paths) {
|
|
147
|
+
if (!paths)
|
|
148
|
+
return;
|
|
149
|
+
const remove = async (candidate, removeOne) => {
|
|
150
|
+
if (!candidate)
|
|
151
|
+
return;
|
|
152
|
+
try {
|
|
153
|
+
await removeOne(await assertManagedClonePath(candidate));
|
|
154
|
+
}
|
|
155
|
+
catch { /* outside the managed root: never touch it */ }
|
|
156
|
+
};
|
|
157
|
+
await remove(paths.cloneDir, canonical => rm(canonical, { recursive: true, force: true }));
|
|
158
|
+
await remove(paths.gitConfigFile, canonical => unlink(canonical));
|
|
159
|
+
await remove(paths.agentTokenFile, canonical => removeAgentTokenFile(canonical));
|
|
160
|
+
await remove(paths.workerFile, canonical => unlink(canonical));
|
|
161
|
+
}
|
|
162
|
+
/** Keep the clone (recoverable work) but remove the token and managed config immediately. */
|
|
163
|
+
export async function removeDispatchSecrets(paths) {
|
|
164
|
+
if (!paths)
|
|
165
|
+
return;
|
|
166
|
+
const remove = async (candidate, removeOne) => {
|
|
167
|
+
if (!candidate)
|
|
168
|
+
return;
|
|
169
|
+
try {
|
|
170
|
+
await removeOne(await assertManagedClonePath(candidate));
|
|
171
|
+
}
|
|
172
|
+
catch { /* outside the managed root: never touch it */ }
|
|
173
|
+
};
|
|
174
|
+
await remove(paths.gitConfigFile, canonical => unlink(canonical));
|
|
175
|
+
await remove(paths.agentTokenFile, canonical => removeAgentTokenFile(canonical));
|
|
176
|
+
}
|
|
@@ -1,5 +1,19 @@
|
|
|
1
|
+
import type { Readable } from "node:stream";
|
|
2
|
+
import { type DispatchInput } from "./dispatch.js";
|
|
1
3
|
import { type Json } from "./protocol.js";
|
|
2
4
|
export declare function runDispatch(args: string[]): Promise<number>;
|
|
5
|
+
/** The brief limit shared with dispatchSchema. */
|
|
6
|
+
export declare const PROMPT_LIMIT = 32768;
|
|
7
|
+
/** A brief from a file, or stdin for `-`. The text never goes through argv. */
|
|
8
|
+
export declare function readPromptFile(file: string, stdin?: Readable): Promise<string>;
|
|
9
|
+
/** The dispatch form's argv, prompt file/stdin and defaults, without reaching a Hook. */
|
|
10
|
+
export declare function dispatchInputFromArgs(args: string[], stdin?: Readable): Promise<DispatchInput>;
|
|
11
|
+
/** Exactly one of a dispatch id and an idempotency key, for `dispatch close`. */
|
|
12
|
+
export declare function closeRequestFromArgs(args: string[]): {
|
|
13
|
+
dispatch: string;
|
|
14
|
+
} | {
|
|
15
|
+
idempotencyKey: string;
|
|
16
|
+
};
|
|
3
17
|
export declare function runHandOff(args: string[]): Promise<number>;
|
|
4
18
|
/** `phren move`: a live session, named by its session id or its pane id (`wC9:p1`), to another agent, through its computer's Hook (session-move.ts). */
|
|
5
19
|
export declare function runMove(args: string[]): Promise<number>;
|