@phren/cli 0.3.72 → 0.3.74
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/claude-question-dialog.d.ts +2 -3
- package/dist/bridge/claude-question-dialog.js +129 -46
- 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/conductor-sets.d.ts +2 -1
- package/dist/bridge/conductor-sets.js +3 -2
- package/dist/bridge/dialog-observation.d.ts +4 -0
- package/dist/bridge/dialog-observation.js +24 -0
- 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/pane-status.js +2 -19
- 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-pane-routes.d.ts +1 -1
- package/dist/bridge/server-pane-routes.js +12 -9
- package/dist/bridge/server-routes.js +26 -8
- 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 +6 -0
- package/dist/bridge/terminal-tmux.js +38 -11
- package/dist/bridge/terminal.d.ts +5 -1
- package/dist/bridge/transcript-claude.d.ts +7 -0
- package/dist/bridge/transcript-claude.js +227 -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 +22097 -19129
- 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 +3 -3
|
@@ -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;
|
|
@@ -13,6 +13,7 @@ interface Row {
|
|
|
13
13
|
checked?: boolean;
|
|
14
14
|
answered: boolean;
|
|
15
15
|
cursor: boolean;
|
|
16
|
+
wrapped?: boolean;
|
|
16
17
|
}
|
|
17
18
|
export interface ClaudeQuestionScreen {
|
|
18
19
|
kind: "question";
|
|
@@ -32,15 +33,13 @@ export interface ClaudeReviewScreen {
|
|
|
32
33
|
answers: {
|
|
33
34
|
question: string;
|
|
34
35
|
answer: string;
|
|
36
|
+
wrapped?: boolean;
|
|
35
37
|
}[];
|
|
36
38
|
}
|
|
37
39
|
export type ClaudeDialogScreen = ClaudeQuestionScreen | ClaudeReviewScreen;
|
|
38
40
|
/** Claude cuts a question at 2000 characters with "…" while the phone may send
|
|
39
41
|
* more, so the pane's title matches when it is the question's own head. */
|
|
40
42
|
export declare const sameTitle: (shown: string, asked: string) => boolean;
|
|
41
|
-
/** Claude collapses runs of whitespace in a label, and the Hook reads only the
|
|
42
|
-
* first line of one it wraps, so a long label matches by its head. */
|
|
43
|
-
export declare const sameLabel: (shown: string, asked: string) => boolean;
|
|
44
43
|
/** The question dialog the pane is drawing now, or undefined when the last
|
|
45
44
|
* lines are not one: the last tab bar anchors it, and an active dialog ends
|
|
46
45
|
* with its "Esc to cancel" footer or the review's Submit/Cancel rows. */
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { claudeFooterMode } from "./claude-footer-mode.js";
|
|
2
|
+
import { dialogHasClosed } from "./dialog-observation.js";
|
|
1
3
|
import { joinDialogFooters } from "./terminal-dialog-text.js";
|
|
2
4
|
import { BridgeError } from "./protocol.js";
|
|
3
5
|
const TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s+Submit\s*)?(?:→\s*)?$/;
|
|
@@ -12,12 +14,6 @@ export const sameTitle = (shown, asked) => {
|
|
|
12
14
|
return true;
|
|
13
15
|
return shown.endsWith("…") && shown.length > 200 && want.startsWith(shown.slice(0, -1).trimEnd());
|
|
14
16
|
};
|
|
15
|
-
/** Claude collapses runs of whitespace in a label, and the Hook reads only the
|
|
16
|
-
* first line of one it wraps, so a long label matches by its head. */
|
|
17
|
-
export const sameLabel = (shown, asked) => {
|
|
18
|
-
const want = normalize(asked);
|
|
19
|
-
return shown === want || (shown.length >= 30 && want.startsWith(shown));
|
|
20
|
-
};
|
|
21
17
|
/** Claude Code (2.1.284) draws a question that has a line break or is wider
|
|
22
18
|
* than 80 columns inside a dimmed left border, "│ " before each line, on its
|
|
23
19
|
* tab and in the review. The border is not part of the question. */
|
|
@@ -84,8 +80,10 @@ export function claudeQuestionDialog(text) {
|
|
|
84
80
|
last.answer = answer[1];
|
|
85
81
|
// A long question or answer wraps onto the next line.
|
|
86
82
|
else if (last) {
|
|
87
|
-
if (last.answer)
|
|
83
|
+
if (last.answer) {
|
|
88
84
|
last.answer += " " + line;
|
|
85
|
+
last.wrapped = true;
|
|
86
|
+
}
|
|
89
87
|
else
|
|
90
88
|
last.question += " " + line;
|
|
91
89
|
}
|
|
@@ -118,7 +116,7 @@ export function claudeQuestionDialog(text) {
|
|
|
118
116
|
continue;
|
|
119
117
|
}
|
|
120
118
|
const answered = !match[3] && / ✔$/.test(match[4]);
|
|
121
|
-
rows.push({ number, label:
|
|
119
|
+
rows.push({ number, label: match[4], answered, cursor: !!match[1],
|
|
122
120
|
...(match[3] ? { checked: match[3] === "✔" } : {}) });
|
|
123
121
|
}
|
|
124
122
|
if (!title || !chat || cursor === undefined || rows.length < 2)
|
|
@@ -126,6 +124,18 @@ export function claudeQuestionDialog(text) {
|
|
|
126
124
|
// The last row above "Chat about this" is the typed answer ("Type
|
|
127
125
|
// something." until something is typed there).
|
|
128
126
|
const other = rows.pop();
|
|
127
|
+
// Only option labels have a removable selection marker. Other is user
|
|
128
|
+
// input: preserving its raw value prevents "Teal ✔" reconciling as "Teal".
|
|
129
|
+
for (const row of rows)
|
|
130
|
+
if (row.answered)
|
|
131
|
+
row.label = row.label.slice(0, -2).trim();
|
|
132
|
+
const otherLine = body.findIndex(line => Number(ROW.exec(line)?.[2]) === other.number);
|
|
133
|
+
for (const line of body.slice(otherLine + 1)) {
|
|
134
|
+
if (NEXT.test(line) || ROW.test(line) || /^─+$/.test(line.trim()))
|
|
135
|
+
break;
|
|
136
|
+
if (line.trim())
|
|
137
|
+
other.wrapped = true;
|
|
138
|
+
}
|
|
129
139
|
return { kind: "question", tabs, title, multiSelect: rows.some(row => row.checked !== undefined), options: rows, other, ...(cursor !== undefined ? { cursor } : {}) };
|
|
130
140
|
}
|
|
131
141
|
/** A 409 that says whether any key reached the terminal: `question-not-shown`
|
|
@@ -142,6 +152,9 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
142
152
|
const from = options.from ?? 0, submit = options.submit ?? true;
|
|
143
153
|
let sent = false;
|
|
144
154
|
const changed = (message) => refusal(message, sent);
|
|
155
|
+
if (submit && (from !== 0 || answers.length !== questions.length)) {
|
|
156
|
+
throw changed("Cannot verify the full review from a partial answer set; send all answers together or finish in the terminal.");
|
|
157
|
+
}
|
|
145
158
|
const realKeys = io.keys.bind(io);
|
|
146
159
|
io = { ...io, keys: async (keys) => { sent = true; await realKeys(keys); } };
|
|
147
160
|
const sleep = io.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
|
|
@@ -149,7 +162,12 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
149
162
|
// Claude redraws a moment after a key; poll until the expected screen shows.
|
|
150
163
|
const settle = async (check, ms = 2_000) => {
|
|
151
164
|
for (let waited = 0;; waited += 120) {
|
|
152
|
-
const
|
|
165
|
+
const text = await io.read(), screen = claudeQuestionDialog(text);
|
|
166
|
+
// A bare cursor can itself be a partial question redraw. Closure must
|
|
167
|
+
// also have Claude's live footer or working hint, after the dialog cues.
|
|
168
|
+
const closed = !screen && dialogHasClosed(text)
|
|
169
|
+
&& (claudeFooterMode(text) !== undefined || /\besc to interrupt\b/i.test(text));
|
|
170
|
+
const value = check(screen, closed);
|
|
153
171
|
if (value !== undefined || waited >= ms)
|
|
154
172
|
return value;
|
|
155
173
|
await sleep(120);
|
|
@@ -166,6 +184,70 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
166
184
|
// draws its own header. The tabs must be this set's, in this order.
|
|
167
185
|
if (initial.tabs.length !== questions.length)
|
|
168
186
|
throw changed("The terminal is asking a different set of questions.");
|
|
187
|
+
const moveCursor = async (index, screen, to) => {
|
|
188
|
+
const position = (value) => value === "next" ? screen.other.number + 1 : value;
|
|
189
|
+
while (screen.cursor !== to) {
|
|
190
|
+
const at = position(screen.cursor), target = position(to);
|
|
191
|
+
if (at === undefined || target === undefined)
|
|
192
|
+
throw changed("Could not locate the terminal cursor.");
|
|
193
|
+
const next = at + (target > at ? 1 : -1);
|
|
194
|
+
const expected = next === screen.other.number + 1 ? "next" : next;
|
|
195
|
+
await io.keys([target > at ? "down" : "up"]);
|
|
196
|
+
const moved = await settle(value => matches(value, index) && value.cursor === expected ? value : undefined);
|
|
197
|
+
if (!moved)
|
|
198
|
+
throw changed("Could not move and verify the terminal cursor.");
|
|
199
|
+
screen = moved;
|
|
200
|
+
}
|
|
201
|
+
return screen;
|
|
202
|
+
};
|
|
203
|
+
const commandCursor = async (index, screen) => {
|
|
204
|
+
if (screen.other && screen.cursor === screen.other.number)
|
|
205
|
+
screen = await moveCursor(index, screen, screen.other.number - 1);
|
|
206
|
+
if (!screen.options.some(row => row.number === screen.cursor) && !(screen.multiSelect && screen.cursor === "next")) {
|
|
207
|
+
throw changed("The terminal cursor is not on an option or Next row.");
|
|
208
|
+
}
|
|
209
|
+
return screen;
|
|
210
|
+
};
|
|
211
|
+
const enterText = async (index, screen, text) => {
|
|
212
|
+
screen = await moveCursor(index, screen, screen.other.number);
|
|
213
|
+
const existing = screen.other.label;
|
|
214
|
+
if (screen.other.answered)
|
|
215
|
+
throw changed("The existing typed answer ends with an ambiguous selection marker; edit it in the terminal.");
|
|
216
|
+
if (screen.other.wrapped)
|
|
217
|
+
throw changed("The existing typed answer is wrapped and cannot be verified; edit it in the terminal.");
|
|
218
|
+
const placeholder = existing === (screen.multiSelect ? "Type something" : "Type something.");
|
|
219
|
+
// The terminal capture cannot prove an editor shortcut cleared a field,
|
|
220
|
+
// or distinguish a literal placeholder answer from an empty field. Refuse
|
|
221
|
+
// those cases rather than append to a draft or submit an empty answer.
|
|
222
|
+
if ((placeholder && text === existing) || (!placeholder && existing !== text)) {
|
|
223
|
+
throw changed("The existing typed answer differs from the phone's answer or cannot be verified; clear it in the terminal first.");
|
|
224
|
+
}
|
|
225
|
+
const verifyText = async (expected) => {
|
|
226
|
+
const shown = await settle(value => matches(value, index) && value.cursor === screen.other.number
|
|
227
|
+
&& !value.other?.wrapped && value.other?.label === expected && (!screen.multiSelect || value.other.checked) ? value : undefined);
|
|
228
|
+
if (!shown)
|
|
229
|
+
throw changed("The full typed answer did not appear exactly in the terminal.");
|
|
230
|
+
return shown;
|
|
231
|
+
};
|
|
232
|
+
if (placeholder) {
|
|
233
|
+
if (/^[0-9]/.test(text)) {
|
|
234
|
+
// Current Claude versions type digits into Other. Older versions may
|
|
235
|
+
// select (and immediately submit) an option if the field is empty,
|
|
236
|
+
// so establish text ownership without ever probing it with a digit.
|
|
237
|
+
await io.keys(["."]);
|
|
238
|
+
await verifyText(".");
|
|
239
|
+
await io.keys(typedKeys(text));
|
|
240
|
+
await verifyText("." + text);
|
|
241
|
+
// These editor keys cannot submit. If movement/deletion is unsupported
|
|
242
|
+
// or dropped, exact readback refuses before Enter can send the prefix.
|
|
243
|
+
await io.keys(["home", "right", "backspace"]);
|
|
244
|
+
}
|
|
245
|
+
else
|
|
246
|
+
await io.keys(typedKeys(text));
|
|
247
|
+
}
|
|
248
|
+
const shown = await verifyText(text);
|
|
249
|
+
return shown;
|
|
250
|
+
};
|
|
169
251
|
const reach = async (index) => {
|
|
170
252
|
const screen = await settle(value => value);
|
|
171
253
|
if (screen?.kind === "question" && sameTitle(screen.title, questions[index].question))
|
|
@@ -175,15 +257,23 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
175
257
|
if (at < 0)
|
|
176
258
|
throw changed("The terminal is showing a different question.");
|
|
177
259
|
// Arrow keys would edit a typed answer; step off that row first.
|
|
178
|
-
if (screen?.kind === "question"
|
|
179
|
-
await
|
|
260
|
+
if (screen?.kind === "question")
|
|
261
|
+
await commandCursor(at, screen);
|
|
180
262
|
await io.keys(Array(Math.abs(index - at)).fill(index > at ? "right" : "left"));
|
|
181
263
|
const moved = await settle(value => matches(value, index) ? value : undefined);
|
|
182
264
|
if (!moved)
|
|
183
265
|
throw changed("Could not move the terminal to the question being answered.");
|
|
184
266
|
return moved;
|
|
185
267
|
};
|
|
186
|
-
const leaves = (index
|
|
268
|
+
const leaves = (index, mayClose) => (value, closed) => {
|
|
269
|
+
if (mayClose && closed)
|
|
270
|
+
return "gone";
|
|
271
|
+
if (index + 1 < questions.length && matches(value, index + 1))
|
|
272
|
+
return "moved";
|
|
273
|
+
if (index + 1 === questions.length && value?.kind === "review")
|
|
274
|
+
return "moved";
|
|
275
|
+
return undefined;
|
|
276
|
+
};
|
|
187
277
|
for (const [offset, answer] of answers.entries()) {
|
|
188
278
|
const index = from + offset, question = questions[index];
|
|
189
279
|
if (!question)
|
|
@@ -191,58 +281,42 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
191
281
|
const typed = answer.text?.trim() ?? "";
|
|
192
282
|
let screen = await reach(index);
|
|
193
283
|
if (screen.multiSelect !== !!question.multiSelect || screen.options.length !== question.options.length
|
|
194
|
-
|| screen.options.some((row, position) =>
|
|
284
|
+
|| screen.options.some((row, position) => row.label !== normalize(question.options[position].label))) {
|
|
195
285
|
throw changed("The terminal's options differ from the question being answered.");
|
|
196
286
|
}
|
|
197
287
|
if (!screen.multiSelect) {
|
|
198
288
|
if (typed) {
|
|
199
|
-
|
|
200
|
-
await io.keys([String(other.number)]);
|
|
201
|
-
const focused = await settle(value => matches(value, index) && value.cursor === other.number ? value : undefined);
|
|
202
|
-
if (!focused)
|
|
203
|
-
throw changed("Could not open the typed answer.");
|
|
204
|
-
await io.keys(typedKeys(typed));
|
|
205
|
-
const shown = await settle(value => matches(value, index) && value.other && normalize(value.other.label).startsWith(normalize(typed).slice(0, 20)) ? value : undefined);
|
|
206
|
-
if (!shown)
|
|
207
|
-
throw changed("The typed answer did not appear in the terminal.");
|
|
289
|
+
await enterText(index, screen, typed);
|
|
208
290
|
await io.keys(["enter"]);
|
|
209
291
|
}
|
|
210
292
|
else {
|
|
293
|
+
screen = await commandCursor(index, screen);
|
|
211
294
|
await io.keys([String(screen.options[answer.options[0]].number)]);
|
|
212
295
|
}
|
|
213
|
-
if (!await settle(leaves(index), ANSWERED_MS))
|
|
214
|
-
throw changed("The terminal did not
|
|
296
|
+
if (!await settle(leaves(index, questions.length === 1), ANSWERED_MS))
|
|
297
|
+
throw changed("The terminal did not confirm taking the answer.");
|
|
215
298
|
continue;
|
|
216
299
|
}
|
|
300
|
+
screen = await commandCursor(index, screen);
|
|
217
301
|
// Multi-select: toggle only the boxes that differ, one key per write
|
|
218
302
|
// (Ink reads "13" in one write as a single input and toggles nothing),
|
|
219
303
|
// and check each box before the next.
|
|
220
304
|
const rows = [...screen.options, ...(screen.other ? [screen.other] : [])];
|
|
221
305
|
for (const [position, row] of rows.entries()) {
|
|
222
|
-
const wanted = position < screen.options.length ? answer.options.includes(position) : !!row.
|
|
306
|
+
const wanted = position < screen.options.length ? answer.options.includes(position) : !!typed && row.label === typed;
|
|
223
307
|
if (wanted === !!row.checked)
|
|
224
308
|
continue;
|
|
225
309
|
const box = (value) => matches(value, index)
|
|
226
310
|
? !!(position < value.options.length ? value.options[position] : value.other)?.checked : undefined;
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
screen = await settle(value => box(value) === wanted ? value : undefined, 1_000) ?? screen;
|
|
232
|
-
}
|
|
233
|
-
if (box(screen) !== wanted)
|
|
311
|
+
screen = await commandCursor(index, screen);
|
|
312
|
+
await io.keys([String(row.number)]);
|
|
313
|
+
const toggled = await settle(value => box(value) === wanted ? value : undefined);
|
|
314
|
+
if (!toggled)
|
|
234
315
|
throw changed("The terminal's checkboxes did not match the answer.");
|
|
316
|
+
screen = toggled;
|
|
235
317
|
}
|
|
236
318
|
if (typed) {
|
|
237
|
-
|
|
238
|
-
if (cursor !== other.number)
|
|
239
|
-
await io.keys(Array(Math.abs(other.number - cursor)).fill(other.number > cursor ? "down" : "up"));
|
|
240
|
-
if (!await settle(value => matches(value, index) && value.cursor === other.number ? value : undefined))
|
|
241
|
-
throw changed("Could not reach the typed answer row.");
|
|
242
|
-
await io.keys(typedKeys(typed));
|
|
243
|
-
const shown = await settle(value => matches(value, index) && value.other?.checked && normalize(value.other.label).startsWith(normalize(typed).slice(0, 20)) ? value : undefined);
|
|
244
|
-
if (!shown)
|
|
245
|
-
throw changed("The typed answer did not appear in the terminal.");
|
|
319
|
+
screen = await enterText(index, screen, typed);
|
|
246
320
|
// Tab moves from the typed row to Next; Enter there leaves the question.
|
|
247
321
|
await io.keys(["tab"]);
|
|
248
322
|
if (!await settle(value => matches(value, index) && value.cursor === "next" ? value : undefined))
|
|
@@ -251,23 +325,32 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
251
325
|
}
|
|
252
326
|
else {
|
|
253
327
|
// Tab from the typed row would stop on Next instead of leaving.
|
|
254
|
-
|
|
328
|
+
screen = await commandCursor(index, screen);
|
|
329
|
+
await io.keys(["tab"]);
|
|
255
330
|
}
|
|
256
|
-
if (!await settle(leaves(index), ANSWERED_MS))
|
|
331
|
+
if (!await settle(leaves(index, false), ANSWERED_MS))
|
|
257
332
|
throw changed("The terminal did not move past the question.");
|
|
258
333
|
}
|
|
259
334
|
if (!submit)
|
|
260
335
|
return;
|
|
261
|
-
const review = await settle(value => value?.kind === "review" ? value
|
|
336
|
+
const review = await settle((value, closed) => value?.kind === "review" ? value
|
|
337
|
+
: questions.length === 1 && !questions[0].multiSelect && closed ? "gone" : undefined, ANSWERED_MS);
|
|
262
338
|
// A lone single-select question submits on its digit.
|
|
263
339
|
if (review === "gone")
|
|
264
340
|
return;
|
|
265
341
|
if (!review)
|
|
266
342
|
throw changed("The terminal did not reach the review of the answers.");
|
|
267
343
|
if (review.answers.length !== questions.length || review.answers.some((row, position) => !sameTitle(normalize(row.question), questions[position].question) || !row.answer)) {
|
|
268
|
-
throw changed("
|
|
344
|
+
throw changed("The terminal's review does not contain every expected question and answer.");
|
|
345
|
+
}
|
|
346
|
+
for (const [offset, answer] of answers.entries()) {
|
|
347
|
+
const index = from + offset, question = questions[index], text = answer.text?.trim() ?? "";
|
|
348
|
+
const labels = question.options.filter((_, position) => answer.options.includes(position)).map(option => normalize(option.label));
|
|
349
|
+
const expected = question.multiSelect ? [...labels, ...(text ? [text] : [])].join(", ") : text || labels[0];
|
|
350
|
+
if (review.answers[index]?.wrapped || review.answers[index]?.answer !== expected)
|
|
351
|
+
throw changed("The terminal's review does not exactly match the phone's answers.");
|
|
269
352
|
}
|
|
270
353
|
await io.keys(["1"]);
|
|
271
|
-
if (await settle(
|
|
354
|
+
if (await settle((_value, closed) => closed ? "gone" : undefined, ANSWERED_MS) !== "gone")
|
|
272
355
|
throw changed("The terminal did not submit the answers.");
|
|
273
356
|
}
|
|
@@ -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 {
|