@phren/cli 0.3.3 → 0.3.5
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.d.ts +6 -0
- package/dist/bridge/agent-hooks.js +66 -25
- package/dist/bridge/canary.d.ts +4 -0
- package/dist/bridge/canary.js +17 -4
- package/dist/bridge/changes.d.ts +7 -0
- package/dist/bridge/changes.js +6 -1
- package/dist/bridge/client.js +2 -1
- package/dist/bridge/command.js +7 -5
- package/dist/bridge/conductor-group.d.ts +1 -0
- package/dist/bridge/conductor-group.js +4 -3
- package/dist/bridge/dispatch-command.js +2 -2
- package/dist/bridge/fanouts.js +6 -2
- package/dist/bridge/hand-off.d.ts +1 -0
- package/dist/bridge/hand-off.js +3 -2
- package/dist/bridge/harness-status.d.ts +12 -0
- package/dist/bridge/harness-status.js +153 -0
- package/dist/bridge/health.d.ts +18 -0
- package/dist/bridge/health.js +30 -4
- package/dist/bridge/herdr.d.ts +6 -0
- package/dist/bridge/herdr.js +62 -8
- package/dist/bridge/install.js +4 -0
- package/dist/bridge/model-switch.d.ts +4 -1
- package/dist/bridge/model-switch.js +12 -7
- package/dist/bridge/models.js +3 -2
- package/dist/bridge/pane-status.d.ts +37 -0
- package/dist/bridge/pane-status.js +139 -0
- package/dist/bridge/pane-text.d.ts +3 -11
- package/dist/bridge/pane-text.js +9 -16
- package/dist/bridge/peers.js +9 -6
- package/dist/bridge/prompt-once.d.ts +26 -0
- package/dist/bridge/prompt-once.js +69 -0
- package/dist/bridge/protocol.d.ts +10 -0
- package/dist/bridge/protocol.js +10 -0
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-launch.d.ts +10 -1
- package/dist/bridge/schedule-launch.js +29 -3
- package/dist/bridge/schedule-watch.js +1 -1
- package/dist/bridge/schedules.d.ts +10 -0
- package/dist/bridge/schedules.js +40 -0
- package/dist/bridge/server-launch.js +12 -10
- package/dist/bridge/server-pane-routes.js +23 -9
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +1 -1
- package/dist/bridge/session-servers.js +5 -6
- package/dist/bridge/side-questions.js +6 -5
- package/dist/bridge/terminal-choice.d.ts +12 -5
- package/dist/bridge/terminal-choice.js +66 -0
- package/dist/bridge/terminal-herdr.d.ts +5 -0
- package/dist/bridge/terminal-herdr.js +57 -0
- package/dist/bridge/terminal-tmux.d.ts +111 -0
- package/dist/bridge/terminal-tmux.js +549 -0
- package/dist/bridge/terminal.d.ts +119 -0
- package/dist/bridge/terminal.js +66 -0
- package/dist/bridge/transcript-claude.d.ts +6 -0
- package/dist/bridge/transcript-claude.js +20 -0
- package/dist/bridge/transcript-opencode.js +1 -1
- package/dist/bridge/transcript-preview.d.ts +5 -0
- package/dist/bridge/transcript-preview.js +52 -2
- package/dist/bridge/transport.js +10 -4
- package/dist/bridge-hook.mjs +4852 -3391
- package/dist/cli-registry.js +7 -0
- package/dist/entrypoint.js +2 -1
- package/dist/init/init.js +4 -0
- package/dist/link/doctor.js +33 -30
- package/dist/modules/agent-package.d.ts +35 -0
- package/dist/modules/agent-package.js +133 -0
- package/dist/modules/registry.js +2 -2
- package/dist/session/utils.js +1 -1
- package/dist/tools/dispatch.js +2 -2
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +97 -6
package/dist/bridge/health.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type TmuxHealth } from "./terminal-tmux.js";
|
|
1
2
|
/** One tool's installed version, or why there is none. */
|
|
2
3
|
export interface ToolVersion {
|
|
3
4
|
tool: string;
|
|
@@ -35,6 +36,8 @@ export interface PeerHealth {
|
|
|
35
36
|
ms: number;
|
|
36
37
|
error?: string;
|
|
37
38
|
version?: string;
|
|
39
|
+
/** Why an unreachable peer failed, as a stable offline code (docs/phren-hook.md#offline-reasons). */
|
|
40
|
+
code?: string;
|
|
38
41
|
/** Whether the peer's own hooks.yaml lists this computer; null when its Hook is too old to say. */
|
|
39
42
|
listsBack: boolean | null;
|
|
40
43
|
}
|
|
@@ -79,7 +82,22 @@ export interface HealthDetails {
|
|
|
79
82
|
devices?: number;
|
|
80
83
|
};
|
|
81
84
|
canary: CanaryResult | null;
|
|
85
|
+
terminal: TerminalHealth;
|
|
82
86
|
}
|
|
87
|
+
/** Which terminal multiplexer the Hook drives, per running server, and tmux's state. */
|
|
88
|
+
export interface TerminalHealth {
|
|
89
|
+
/** "herdr" while a Herdr server answers, else "tmux" when tmux can host agents, else "none". */
|
|
90
|
+
provider: "herdr" | "tmux" | "none";
|
|
91
|
+
servers: {
|
|
92
|
+
name: string;
|
|
93
|
+
provider: "herdr" | "tmux";
|
|
94
|
+
}[];
|
|
95
|
+
tmux: TmuxHealth;
|
|
96
|
+
}
|
|
97
|
+
/** The running servers the Hook lists (Herdr's, else tmux's) and tmux's own state. */
|
|
98
|
+
export declare function terminalHealth(): Promise<TerminalHealth>;
|
|
99
|
+
/** One line on the terminal: the provider, its servers and tmux's state. */
|
|
100
|
+
export declare function describeTerminal(terminal: TerminalHealth): string;
|
|
83
101
|
export interface HealthOptions {
|
|
84
102
|
/** The running Hook's own version; undefined when asked from outside a Hook. */
|
|
85
103
|
hookVersion?: string;
|
package/dist/bridge/health.js
CHANGED
|
@@ -8,10 +8,32 @@ import { getProjectDirs } from "../phren-paths.js";
|
|
|
8
8
|
import { resolveAllStores } from "../store-registry.js";
|
|
9
9
|
import { publicComputerKey } from "./computers.js";
|
|
10
10
|
import { hookPeers, peerRequest } from "./peers.js";
|
|
11
|
-
import { BridgeError, bridgeRoot } from "./protocol.js";
|
|
11
|
+
import { BridgeError, bridgeRoot, errorCode } from "./protocol.js";
|
|
12
12
|
import { canonicalComputer, readScheduleDocument, readScheduleRuns, scheduleRunsFile } from "./schedules.js";
|
|
13
13
|
import { countGit } from "./metrics.js";
|
|
14
|
+
import { tmuxHealth } from "./terminal-tmux.js";
|
|
14
15
|
const exec = promisify(execFile);
|
|
16
|
+
/** The running servers the Hook lists (Herdr's, else tmux's) and tmux's own state. */
|
|
17
|
+
export async function terminalHealth() {
|
|
18
|
+
const [{ servers }, tmux] = await Promise.all([import("./herdr.js"), tmuxHealth()]);
|
|
19
|
+
const running = (await servers().catch(() => [])).map(server => ({ name: String(server.session),
|
|
20
|
+
provider: server.terminal === "tmux" ? "tmux" : "herdr" }));
|
|
21
|
+
const provider = running.some(server => server.provider === "herdr") ? "herdr" : running.length ? "tmux" : "none";
|
|
22
|
+
return { provider, servers: running, tmux };
|
|
23
|
+
}
|
|
24
|
+
/** One line on the terminal: the provider, its servers and tmux's state. */
|
|
25
|
+
export function describeTerminal(terminal) {
|
|
26
|
+
const tmux = terminal.tmux;
|
|
27
|
+
const hidden = tmux.hidden ? `hidden server ${tmux.hidden.running ? `running (${tmux.hidden.sessions ?? 0} session${tmux.hidden.sessions === 1 ? "" : "s"})` : "not started"}` : undefined;
|
|
28
|
+
const tmuxText = tmux.state === "off" ? "tmux off (PHREN_TMUX=off)" : tmux.state === "missing" ? "tmux not installed"
|
|
29
|
+
: [`tmux ${tmux.version ?? "(version unknown)"}`, tmux.launches === false ? "too old to start agents (needs 3.0)" : undefined, hidden].filter(Boolean).join(", ");
|
|
30
|
+
const names = terminal.servers.map(server => server.name).join(", ");
|
|
31
|
+
if (terminal.provider === "herdr")
|
|
32
|
+
return `herdr (${names}); ${tmuxText}`;
|
|
33
|
+
if (terminal.provider === "tmux")
|
|
34
|
+
return `tmux (${names}); ${tmuxText}`;
|
|
35
|
+
return `none: Herdr is not running; ${tmuxText}`;
|
|
36
|
+
}
|
|
15
37
|
const VERSION_TIMEOUT_MS = 3_000;
|
|
16
38
|
const VERSION_CACHE_MS = 5 * 60_000;
|
|
17
39
|
const PEER_TIMEOUT_MS = 5_000;
|
|
@@ -171,7 +193,8 @@ async function probePeer(peer, caller) {
|
|
|
171
193
|
catch (error) {
|
|
172
194
|
const reason = error instanceof BridgeError && error.status === 504 ? "No answer within 5 seconds."
|
|
173
195
|
: error instanceof Error ? error.message : "Unreachable.";
|
|
174
|
-
|
|
196
|
+
const code = errorCode(error);
|
|
197
|
+
return { name: peer.name, reachable: false, ms: Date.now() - started, error: plainError(reason), ...(code ? { code } : {}), listsBack: null };
|
|
175
198
|
}
|
|
176
199
|
}
|
|
177
200
|
export function canaryFile(root = bridgeRoot()) { return path.join(root, "canary.json"); }
|
|
@@ -210,7 +233,7 @@ export async function healthDetails(options) {
|
|
|
210
233
|
}
|
|
211
234
|
return { configured: true, computers: await Promise.all(peers.map(peer => probePeer(peer, { name, hostKey }))) };
|
|
212
235
|
})();
|
|
213
|
-
const [versions, stores, lastRun, peers, canary, push] = await Promise.all([
|
|
236
|
+
const [versions, stores, lastRun, peers, canary, push, terminal] = await Promise.all([
|
|
214
237
|
Promise.all([
|
|
215
238
|
Promise.resolve(options.hookVersion ? { tool: "hook", status: "ok", version: options.hookVersion } : { tool: "hook", status: "missing", detail: "Phren Hook is not running." }),
|
|
216
239
|
...["herdr", "claude", "codex", "copilot", "opencode"].map(tool => toolVersion(tool)),
|
|
@@ -220,13 +243,14 @@ export async function healthDetails(options) {
|
|
|
220
243
|
peersPromise,
|
|
221
244
|
readCanary(),
|
|
222
245
|
options.push ? Promise.resolve(options.push) : pushConfigured(),
|
|
246
|
+
terminalHealth(),
|
|
223
247
|
]);
|
|
224
248
|
return {
|
|
225
249
|
product: "phren-hook", computer: { name, ...(options.computerId ? { id: options.computerId } : {}) }, checkedAt: new Date().toISOString(),
|
|
226
250
|
versions, stores,
|
|
227
251
|
schedules: { running: options.scheduler ? options.scheduler.running : null,
|
|
228
252
|
...(options.scheduler?.lastTickAt ? { lastTickAt: options.scheduler.lastTickAt.toISOString() } : {}), lastRun },
|
|
229
|
-
peers, push, canary,
|
|
253
|
+
peers, push, canary, terminal,
|
|
230
254
|
};
|
|
231
255
|
}
|
|
232
256
|
/** Plain lines for `phren status`. */
|
|
@@ -251,6 +275,8 @@ export function formatHealth(health, color) {
|
|
|
251
275
|
: peer.listsBack === false ? `${yellow}one-way${reset} ${dim}(${peer.name} does not list this computer)${reset}` : `${green}ok${reset} ${dim}${peer.ms} ms${reset}`;
|
|
252
276
|
lines.push(` ${dim}peer${reset} ${peer.name} ${state}`);
|
|
253
277
|
}
|
|
278
|
+
if (health.terminal)
|
|
279
|
+
lines.push(` ${dim}terminal${reset} ${health.terminal.provider === "none" ? `${yellow}${describeTerminal(health.terminal)}${reset}` : describeTerminal(health.terminal)}`);
|
|
254
280
|
lines.push(` ${dim}push${reset} ${health.push.configured ? `${green}configured${reset}` : `${dim}not configured${reset}`}`);
|
|
255
281
|
if (health.canary) {
|
|
256
282
|
const failed = health.canary.steps.filter(step => step.status === "failed");
|
package/dist/bridge/herdr.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { BridgeError, type Json, type Target, type StartingTarget } from "./protocol.js";
|
|
2
2
|
export declare function herdrRoot(): string;
|
|
3
|
+
/** Where Herdr's socket for `server` lives. */
|
|
4
|
+
export declare function herdrSocketPath(server: string): string;
|
|
3
5
|
/** The Herdr pane this process runs in, from the variables Herdr sets for
|
|
4
6
|
* every pane: the server its socket belongs to plus the pane's ids. */
|
|
5
7
|
export declare function herdrPaneFromEnv(env?: NodeJS.ProcessEnv): {
|
|
@@ -72,6 +74,10 @@ export declare function paneIdentity(server: string, pane: Json, fresh?: boolean
|
|
|
72
74
|
* lands in the new one and its UserPromptSubmit check refuses it, every time.
|
|
73
75
|
* The process log Copilot names by PID records each switch as it happens. */
|
|
74
76
|
export declare function copilotForegroundSession(pids: number[], home?: string): Promise<string | undefined>;
|
|
77
|
+
/** The conversation phren's OpenCode plugin says this process shows (it
|
|
78
|
+
* records it by PID on each prompt), when its transcript exists. Herdr's own
|
|
79
|
+
* OpenCode integration may be missing; this does not depend on it. */
|
|
80
|
+
export declare function opencodePidSession(pids: number[], root?: string): Promise<string | undefined>;
|
|
75
81
|
/** Bind first-send permission to the actual terminal/process, never a cwd or
|
|
76
82
|
* a guessed conversation. Tokens expire naturally when the Hook/process restarts. */
|
|
77
83
|
export declare function paneChatState(server: string, pane: Json, options?: {
|
package/dist/bridge/herdr.js
CHANGED
|
@@ -11,8 +11,14 @@ import { recordedSession } from "./agent-hook-stores.js";
|
|
|
11
11
|
import { tabActivityKey } from "./tab-activity.js";
|
|
12
12
|
import { intervalFromEnv } from "./limits.js";
|
|
13
13
|
import { countHerdr, countIdentity } from "./metrics.js";
|
|
14
|
+
import { phrenStoreRoot } from "./transcripts.js";
|
|
15
|
+
// terminal.ts and terminal-tmux.ts import this module, so it reaches them at
|
|
16
|
+
// call time; a static import back would be an import cycle.
|
|
17
|
+
const terminal = () => import("./terminal.js");
|
|
14
18
|
const exec = promisify(execFile);
|
|
15
19
|
export function herdrRoot() { return process.env.PHREN_HERDR_HOME || path.join(homedir(), ".config/herdr"); }
|
|
20
|
+
/** Where Herdr's socket for `server` lives. */
|
|
21
|
+
export function herdrSocketPath(server) { return herdrSocket(server); }
|
|
16
22
|
function herdrSocket(server) {
|
|
17
23
|
serverName.parse(server);
|
|
18
24
|
return path.join(herdrRoot(), ...(server === "default" ? [] : ["sessions", server]), "herdr.sock");
|
|
@@ -38,7 +44,9 @@ export function herdrSocketError(error) {
|
|
|
38
44
|
: code === "EACCES" || code === "EPERM" ? "this user may not open Herdr's socket"
|
|
39
45
|
: undefined;
|
|
40
46
|
const tag = code && /^[A-Z0-9_]{1,32}$/.test(code) ? code : "unknown error";
|
|
41
|
-
|
|
47
|
+
const offline = code === "ENOENT" ? "herdr-not-running" : code === "ECONNREFUSED" ? "herdr-stale-socket"
|
|
48
|
+
: code === "EACCES" || code === "EPERM" ? "herdr-permission" : "herdr-unreachable";
|
|
49
|
+
return new BridgeError(503, `Herdr is not reachable on this computer (${tag}${reason ? `: ${reason}` : ""}).`, { code: offline });
|
|
42
50
|
}
|
|
43
51
|
const optionalReadFailures = new Map();
|
|
44
52
|
/**
|
|
@@ -60,7 +68,7 @@ export async function rpc(server, method, params = {}, signal, timeoutMs = 10_00
|
|
|
60
68
|
countHerdr(method);
|
|
61
69
|
const metadata = await stat(socket).catch(error => { throw herdrSocketError(error); });
|
|
62
70
|
if (!metadata.isSocket() || (process.getuid && metadata.uid !== process.getuid()))
|
|
63
|
-
throw new BridgeError(503, "The Herdr socket is unavailable.");
|
|
71
|
+
throw new BridgeError(503, "The Herdr socket is unavailable.", { code: "herdr-permission" });
|
|
64
72
|
return new Promise((resolve, reject) => {
|
|
65
73
|
const client = connect(socket);
|
|
66
74
|
const key = requestID();
|
|
@@ -79,7 +87,7 @@ export async function rpc(server, method, params = {}, signal, timeoutMs = 10_00
|
|
|
79
87
|
return;
|
|
80
88
|
}
|
|
81
89
|
signal?.addEventListener("abort", abort, { once: true });
|
|
82
|
-
client.setTimeout(timeoutMs, () => finish(new BridgeError(504, "Herdr did not answer. Refresh before trying again.")));
|
|
90
|
+
client.setTimeout(timeoutMs, () => finish(new BridgeError(504, "Herdr did not answer. Refresh before trying again.", { code: "herdr-timeout" })));
|
|
83
91
|
client.on("error", error => finish(herdrSocketError(error)));
|
|
84
92
|
client.on("end", () => finish(new BridgeError(503, "Herdr closed the request before confirming it.")));
|
|
85
93
|
client.on("connect", () => client.write(JSON.stringify({ id: key, method, params }) + "\n"));
|
|
@@ -139,7 +147,10 @@ export async function servers() {
|
|
|
139
147
|
}
|
|
140
148
|
}));
|
|
141
149
|
const running = results.filter((v) => v !== null);
|
|
142
|
-
|
|
150
|
+
// Without a running Herdr, tmux: the owner's server and the Hook's hidden one.
|
|
151
|
+
if (!running.length)
|
|
152
|
+
running.push(...await import("./terminal-tmux.js").then(tmux => tmux.tmuxServers()).catch(() => []));
|
|
153
|
+
knownServers = running.map(server => String(server.session));
|
|
143
154
|
return running;
|
|
144
155
|
}
|
|
145
156
|
/** How old a shared `session.snapshot` may be for readers that poll: open
|
|
@@ -151,7 +162,7 @@ const inFlightSnapshots = new Map();
|
|
|
151
162
|
/** A fresh snapshot. Its answer also becomes the shared one, so pollers reuse it. */
|
|
152
163
|
export async function snapshot(server) {
|
|
153
164
|
const started = Date.now();
|
|
154
|
-
const value =
|
|
165
|
+
const value = await (await terminal()).terminalProvider().snapshot(server);
|
|
155
166
|
const current = sharedSnapshots.get(server);
|
|
156
167
|
// A slower request that started before the current answer never replaces it.
|
|
157
168
|
if (!current || current.at <= started) {
|
|
@@ -253,8 +264,7 @@ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChan
|
|
|
253
264
|
/** Only file descriptors held by this pane's foreground processes establish identity.
|
|
254
265
|
* A directory match, latest log, or focused tab must never select a conversation. */
|
|
255
266
|
async function foregroundPids(server, pane) {
|
|
256
|
-
const
|
|
257
|
-
const pids = objects(info.foreground_processes).map(p => p.pid).filter((p) => Number.isSafeInteger(p) && Number(p) > 0).slice(0, 16);
|
|
267
|
+
const pids = (await (await terminal()).terminalProvider().processes(server, String(pane.pane_id))).foregroundPids.filter(p => Number.isSafeInteger(p) && p > 0).slice(0, 16);
|
|
258
268
|
return pids.sort((a, b) => a - b);
|
|
259
269
|
}
|
|
260
270
|
async function processLogs(pids) {
|
|
@@ -295,7 +305,13 @@ async function resolveIdentity(server, pane, fresh) {
|
|
|
295
305
|
const result = identityFromProcesses(server, pane, pids);
|
|
296
306
|
if (identities.size >= 128)
|
|
297
307
|
identities.delete(identities.keys().next().value);
|
|
298
|
-
|
|
308
|
+
const entry = { at: Date.now(), result };
|
|
309
|
+
// The evidence is as old as its answer, not its question: lsof on a busy
|
|
310
|
+
// Mac can outlast the cache window, and a probe stamped when it started
|
|
311
|
+
// would already be stale to paneChatState, which then never reports the
|
|
312
|
+
// brand-new conversation it just proved as starting.
|
|
313
|
+
void result.then(() => { entry.at = Date.now(); }, () => { });
|
|
314
|
+
identities.set(key, entry);
|
|
299
315
|
return { sessionId: (await result).sessionId, pids };
|
|
300
316
|
}
|
|
301
317
|
export async function paneIdentity(server, pane, fresh = false) {
|
|
@@ -339,7 +355,45 @@ export async function copilotForegroundSession(pids, home = copilotHome()) {
|
|
|
339
355
|
}
|
|
340
356
|
return current;
|
|
341
357
|
}
|
|
358
|
+
/** The conversation phren's OpenCode plugin says this process shows (it
|
|
359
|
+
* records it by PID on each prompt), when its transcript exists. Herdr's own
|
|
360
|
+
* OpenCode integration may be missing; this does not depend on it. */
|
|
361
|
+
export async function opencodePidSession(pids, root = phrenStoreRoot()) {
|
|
362
|
+
const folder = path.join(root, ".runtime", "sessions");
|
|
363
|
+
let current, latest = -Infinity;
|
|
364
|
+
for (const pid of pids) {
|
|
365
|
+
const file = await open(path.join(folder, `opencode-pid-${pid}.json`), "r").catch(() => undefined);
|
|
366
|
+
if (!file)
|
|
367
|
+
continue;
|
|
368
|
+
try {
|
|
369
|
+
const { size } = await file.stat();
|
|
370
|
+
if (size > 4_096)
|
|
371
|
+
continue;
|
|
372
|
+
const value = object(JSON.parse((await file.readFile()).toString("utf8")));
|
|
373
|
+
const session = typeof value.session === "string" && /^ses_[0-9A-Za-z]{1,64}$/.test(value.session) ? value.session : undefined;
|
|
374
|
+
const at = Date.parse(String(value.at));
|
|
375
|
+
if (!session || !(at > latest))
|
|
376
|
+
continue;
|
|
377
|
+
if (!(await stat(path.join(folder, `opencode-${session}.events.jsonl`)).catch(() => undefined)))
|
|
378
|
+
continue;
|
|
379
|
+
current = session;
|
|
380
|
+
latest = at;
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
finally {
|
|
386
|
+
await file.close();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return current;
|
|
390
|
+
}
|
|
342
391
|
async function identityFromProcesses(server, pane, pids) {
|
|
392
|
+
if (pane.agent === "opencode") {
|
|
393
|
+
const bound = await opencodePidSession(pids).catch(() => undefined);
|
|
394
|
+
if (bound)
|
|
395
|
+
return { sessionId: bound, noTranscriptLogs: false };
|
|
396
|
+
}
|
|
343
397
|
if (pane.agent === "copilot") {
|
|
344
398
|
const current = await copilotForegroundSession(pids).catch(() => undefined);
|
|
345
399
|
// A conversation nothing was sent to yet has no transcript: the pane is
|
package/dist/bridge/install.js
CHANGED
|
@@ -239,6 +239,10 @@ export async function install(version, noService = false) {
|
|
|
239
239
|
if (await applyOpencodePlugin()) {
|
|
240
240
|
console.log("opencode chat: restart any opencode session started before now so it loads the transcript plugin.");
|
|
241
241
|
}
|
|
242
|
+
// phren-agent calls the installed bundle itself, so it has no settings to edit.
|
|
243
|
+
if ((await import("../modules/agent-package.js")).agentInstalled()) {
|
|
244
|
+
console.log("phren-agent chat: found; it reports to this Hook itself, so restart any phren-agent session started before now.");
|
|
245
|
+
}
|
|
242
246
|
const keys = path.join(homedir(), ".ssh/authorized_keys");
|
|
243
247
|
const keyStat = await lstat(keys).catch(() => null);
|
|
244
248
|
if (keyStat && !keyStat.isSymbolicLink() && keyStat.isFile()) {
|
|
@@ -2,8 +2,11 @@ import { AgentHooks } from "./agent-hooks.js";
|
|
|
2
2
|
import { ModelCatalog, type AgentModel } from "./models.js";
|
|
3
3
|
import { type Json, type Target } from "./protocol.js";
|
|
4
4
|
export declare const MODEL_BUSY = "This agent is working. The model switch can happen when the turn ends. Choose Switch after this turn.";
|
|
5
|
+
export declare const SLASH_BUSY = "This agent is working. Slash commands run between turns; send it again when this turn ends.";
|
|
5
6
|
/** Busy slash commands must never enter the harness's text queue. Claude's
|
|
6
|
-
* `/btw` side question is the one made to run beside a working turn.
|
|
7
|
+
* `/btw` side question is the one made to run beside a working turn. Only
|
|
8
|
+
* `/model` is told about the model switch; any other command (`/yolo`,
|
|
9
|
+
* `/compact`) is told it runs between turns. */
|
|
7
10
|
export declare function refuseWorkingSlash(pane: Json, text: string, source?: string): void;
|
|
8
11
|
/** The levels Claude Code's `/effort` takes (2.1.280) when the catalogue
|
|
9
12
|
* lists none for a model; Claude still refuses one the model lacks. */
|
|
@@ -1,18 +1,23 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { visibleTerminalChoice } from "./agent-hooks.js";
|
|
3
|
-
import {
|
|
3
|
+
import { validateTarget } from "./herdr.js";
|
|
4
|
+
import { terminalProvider } from "./terminal.js";
|
|
4
5
|
import { ModelCatalog } from "./models.js";
|
|
5
6
|
import { BridgeError } from "./protocol.js";
|
|
6
7
|
import { sideQuestionText } from "./side-questions.js";
|
|
7
8
|
import { stripTerminal } from "../terminal-text.js";
|
|
8
9
|
export const MODEL_BUSY = "This agent is working. The model switch can happen when the turn ends. Choose Switch after this turn.";
|
|
10
|
+
export const SLASH_BUSY = "This agent is working. Slash commands run between turns; send it again when this turn ends.";
|
|
9
11
|
/** Busy slash commands must never enter the harness's text queue. Claude's
|
|
10
|
-
* `/btw` side question is the one made to run beside a working turn.
|
|
12
|
+
* `/btw` side question is the one made to run beside a working turn. Only
|
|
13
|
+
* `/model` is told about the model switch; any other command (`/yolo`,
|
|
14
|
+
* `/compact`) is told it runs between turns. */
|
|
11
15
|
export function refuseWorkingSlash(pane, text, source) {
|
|
12
16
|
if (source && sideQuestionText(source, text) !== undefined)
|
|
13
17
|
return;
|
|
14
|
-
if (pane.agent_status
|
|
15
|
-
|
|
18
|
+
if (pane.agent_status !== "working" || !/^\s*\//.test(text))
|
|
19
|
+
return;
|
|
20
|
+
throw new BridgeError(409, /^\s*\/model(?:\s|$)/.test(text) ? MODEL_BUSY : SLASH_BUSY);
|
|
16
21
|
}
|
|
17
22
|
const request = z.object({ model: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._\[\]:/-]{0,99}$/),
|
|
18
23
|
effort: z.enum(["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]).optional() });
|
|
@@ -126,7 +131,7 @@ export class ModelSwitcher {
|
|
|
126
131
|
};
|
|
127
132
|
const keys = async (values) => {
|
|
128
133
|
await validate();
|
|
129
|
-
await
|
|
134
|
+
await terminalProvider().sendKeys(target.server, target.pane, values);
|
|
130
135
|
};
|
|
131
136
|
const waitFor = async (read, step, ansi = false) => {
|
|
132
137
|
const deadline = Date.now() + this.timeout;
|
|
@@ -168,7 +173,7 @@ export class ModelSwitcher {
|
|
|
168
173
|
await validate(true);
|
|
169
174
|
opened = true;
|
|
170
175
|
this.hooks.menuOpened(target, "/model");
|
|
171
|
-
await
|
|
176
|
+
await terminalProvider().prompt(target.server, target.pane, target.source === "codex" ? "/model" : `/model ${id}`);
|
|
172
177
|
if (target.source === "codex") {
|
|
173
178
|
let menu = await waitFor(text => {
|
|
174
179
|
const choice = visibleTerminalChoice(text);
|
|
@@ -214,7 +219,7 @@ export class ModelSwitcher {
|
|
|
214
219
|
// `/effort` after the model, so the new model's own default never
|
|
215
220
|
// replaces the chosen level.
|
|
216
221
|
await validate(true);
|
|
217
|
-
await
|
|
222
|
+
await terminalProvider().prompt(target.server, target.pane, `/effort ${chosenEffort}`);
|
|
218
223
|
const reply = await waitFor(text => claudeEffortReply(text), "Claude's effort confirmation");
|
|
219
224
|
if ("error" in reply)
|
|
220
225
|
throw new BridgeError(409, reply.error);
|
package/dist/bridge/models.js
CHANGED
|
@@ -176,7 +176,7 @@ function claudeVersion(executable = "claude") {
|
|
|
176
176
|
child.stdout.on("data", (chunk) => { if (out.length < 4_096)
|
|
177
177
|
out += chunk; });
|
|
178
178
|
child.on("error", () => { clearTimeout(timer); resolve(undefined); });
|
|
179
|
-
child.on("
|
|
179
|
+
child.on("close", () => { clearTimeout(timer); resolve(/\d+\.\d+\.\d+/.exec(out)?.[0]); });
|
|
180
180
|
});
|
|
181
181
|
}
|
|
182
182
|
/** The live catalogue when Claude Code has one cached on this computer,
|
|
@@ -202,8 +202,9 @@ export async function readOpenCodeModels(executable = "opencode", configDir = pa
|
|
|
202
202
|
child.stdout.setEncoding("utf8");
|
|
203
203
|
child.stdout.on("data", (chunk) => { if (out.length < 262_144)
|
|
204
204
|
out += chunk; });
|
|
205
|
+
// "close", not "exit": the process can exit before its stdout is read.
|
|
205
206
|
child.on("error", finish);
|
|
206
|
-
child.on("
|
|
207
|
+
child.on("close", finish);
|
|
207
208
|
});
|
|
208
209
|
const ids = [...new Set(listed.split(/\r?\n/).map(line => line.trim()).filter(line => /^[a-z0-9~.-]+\/[^\s]+$/i.test(line)))].slice(0, 400);
|
|
209
210
|
if (!ids.length)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** The status a lifecycle event leaves the agent in; undefined for events that say nothing about it. */
|
|
2
|
+
export declare function eventStatus(event: unknown): string | undefined;
|
|
3
|
+
/** Records the status of the agent in `pane`, which runs in terminal instance
|
|
4
|
+
* `terminal`, and answers it with its sequence number. */
|
|
5
|
+
export declare function notePaneStatus(server: string, pane: string, terminal: string, status: string, at?: number): {
|
|
6
|
+
status: string;
|
|
7
|
+
seq: number;
|
|
8
|
+
};
|
|
9
|
+
/** A blocked pane whose dialog is gone was answered in the terminal: the
|
|
10
|
+
* agent went back to work. Only after `minimumMs`, so a request whose
|
|
11
|
+
* dialog is still being drawn is not settled early. */
|
|
12
|
+
export declare function settleBlockedPane(server: string, pane: string, minimumMs?: number): void;
|
|
13
|
+
/** The pane's last known status while `terminal` still runs there: from
|
|
14
|
+
* memory, else from the binding file the last lifecycle event wrote. */
|
|
15
|
+
export declare function paneStatus(server: string, pane: string, terminal: string): Promise<{
|
|
16
|
+
status: string;
|
|
17
|
+
seq: number;
|
|
18
|
+
} | undefined>;
|
|
19
|
+
/** Whether `screen` (a pane's visible lines, with or without colors) shows a
|
|
20
|
+
* dialog waiting for `agent`'s owner. Stricter than the readers that answer
|
|
21
|
+
* a dialog, because it runs while the agent is still writing: Claude's and
|
|
22
|
+
* phren-agent's numbered rows count only with their "Esc to cancel" footer,
|
|
23
|
+
* OpenCode's only as its own permission prompt. */
|
|
24
|
+
export declare function screenDialog(agent: string, screen: string): boolean;
|
|
25
|
+
/** The status of a pane after a look at its screen: blocked while a working
|
|
26
|
+
* agent shows a dialog there (`screenDialog`), else `base` unchanged. `read`
|
|
27
|
+
* answers the pane's visible lines; it runs only for a working pane, at most
|
|
28
|
+
* once per DIALOG_READ_MS per pane. */
|
|
29
|
+
export declare function dialogStatus(server: string, pane: string, terminal: string, agent: string, base: {
|
|
30
|
+
status: string;
|
|
31
|
+
seq: number;
|
|
32
|
+
} | undefined, read: () => Promise<string>): Promise<{
|
|
33
|
+
status: string;
|
|
34
|
+
seq: number;
|
|
35
|
+
} | undefined>;
|
|
36
|
+
/** For tests. */
|
|
37
|
+
export declare function resetPaneStatus(): void;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Agent status for panes whose terminal does not report one (tmux). Herdr
|
|
2
|
+
// watches its agents and says "working", "idle" or "blocked"; tmux knows only
|
|
3
|
+
// processes. Claude, Codex and phren-agent tell the Hook themselves through
|
|
4
|
+
// their lifecycle hooks (agent-hooks.ts), so the last event a pane's agent
|
|
5
|
+
// sent is its status: a submitted prompt or a tool call means working, a
|
|
6
|
+
// finished turn or a fresh session idle, a permission request blocked. The
|
|
7
|
+
// event is also kept in the pane's binding file, so a restarted Hook does not
|
|
8
|
+
// forget a pane's status. OpenCode and Copilot say it elsewhere
|
|
9
|
+
// (harness-status.ts); the snapshot notes what they say here, so every change
|
|
10
|
+
// gets a sequence number too.
|
|
11
|
+
//
|
|
12
|
+
// A harness that draws a permission dialog in its terminal with no hook
|
|
13
|
+
// behind it (Codex, OpenCode, Copilot, Claude's auto-mode fallback) still
|
|
14
|
+
// looks "working" to all of that. While a pane is working its screen is read,
|
|
15
|
+
// at most once per DIALOG_READ_MS, and a dialog there makes the pane blocked
|
|
16
|
+
// until the dialog is gone.
|
|
17
|
+
import { readFile } from "node:fs/promises";
|
|
18
|
+
import { stripTerminal } from "../terminal-text.js";
|
|
19
|
+
import { bindingPath } from "./agent-hook-stores.js";
|
|
20
|
+
import { claudeQuestionDialog } from "./claude-question-dialog.js";
|
|
21
|
+
import { intervalFromEnv } from "./limits.js";
|
|
22
|
+
import { object } from "./protocol.js";
|
|
23
|
+
import { numberedDialog, opencodePermissionDialog, visibleTerminalChoice } from "./terminal-choice.js";
|
|
24
|
+
/** A working pane's screen is read for a dialog at most once per this window. */
|
|
25
|
+
const DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3_000);
|
|
26
|
+
const EVENT_STATUS = {
|
|
27
|
+
SessionStart: "idle", UserPromptSubmit: "working", PreToolUse: "working", PostToolUse: "working",
|
|
28
|
+
PreCompact: "working", Stop: "idle", PermissionRequest: "blocked",
|
|
29
|
+
};
|
|
30
|
+
/** The status a lifecycle event leaves the agent in; undefined for events that say nothing about it. */
|
|
31
|
+
export function eventStatus(event) {
|
|
32
|
+
return typeof event === "string" && Object.hasOwn(EVENT_STATUS, event) ? EVENT_STATUS[event] : undefined;
|
|
33
|
+
}
|
|
34
|
+
const entries = new Map();
|
|
35
|
+
/** Climbs with every change, like Herdr's state_change_seq, so the phone can order "just finished" first. */
|
|
36
|
+
let sequence = 0;
|
|
37
|
+
const key = (server, pane) => `${server}\0${pane}`;
|
|
38
|
+
/** Records the status of the agent in `pane`, which runs in terminal instance
|
|
39
|
+
* `terminal`, and answers it with its sequence number. */
|
|
40
|
+
export function notePaneStatus(server, pane, terminal, status, at = Date.now()) {
|
|
41
|
+
const id = key(server, pane), current = entries.get(id);
|
|
42
|
+
if (current && current.terminal === terminal && current.status === status) {
|
|
43
|
+
current.at = at;
|
|
44
|
+
return { status, seq: current.seq };
|
|
45
|
+
}
|
|
46
|
+
entries.delete(id);
|
|
47
|
+
while (entries.size >= 512)
|
|
48
|
+
entries.delete(entries.keys().next().value);
|
|
49
|
+
const entry = { terminal, status, seq: ++sequence, at };
|
|
50
|
+
entries.set(id, entry);
|
|
51
|
+
return { status, seq: entry.seq };
|
|
52
|
+
}
|
|
53
|
+
/** A blocked pane whose dialog is gone was answered in the terminal: the
|
|
54
|
+
* agent went back to work. Only after `minimumMs`, so a request whose
|
|
55
|
+
* dialog is still being drawn is not settled early. */
|
|
56
|
+
export function settleBlockedPane(server, pane, minimumMs = 3_000) {
|
|
57
|
+
const id = key(server, pane), current = entries.get(id), dialog = dialogs.get(id);
|
|
58
|
+
if (current?.status === "blocked" && Date.now() - current.at >= minimumMs)
|
|
59
|
+
notePaneStatus(server, pane, current.terminal, "working");
|
|
60
|
+
if (dialog?.shown && Date.now() - dialog.shown.at >= minimumMs) {
|
|
61
|
+
// The screen can show the answered dialog a moment longer: the next read
|
|
62
|
+
// waits a whole window.
|
|
63
|
+
dialog.shown = undefined;
|
|
64
|
+
dialog.cleared = ++sequence;
|
|
65
|
+
dialog.readAt = Date.now();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** The pane's last known status while `terminal` still runs there: from
|
|
69
|
+
* memory, else from the binding file the last lifecycle event wrote. */
|
|
70
|
+
export async function paneStatus(server, pane, terminal) {
|
|
71
|
+
const current = entries.get(key(server, pane));
|
|
72
|
+
if (current && current.terminal === terminal)
|
|
73
|
+
return { status: current.status, seq: current.seq };
|
|
74
|
+
if (current)
|
|
75
|
+
return undefined;
|
|
76
|
+
try {
|
|
77
|
+
const value = object(JSON.parse(await readFile(bindingPath(server, pane), "utf8")));
|
|
78
|
+
const status = eventStatus(value.event);
|
|
79
|
+
if (value.terminal !== terminal || !status)
|
|
80
|
+
return undefined;
|
|
81
|
+
const at = Date.parse(String(value.at));
|
|
82
|
+
return notePaneStatus(server, pane, terminal, status, Number.isFinite(at) ? at : Date.now());
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** Whether `screen` (a pane's visible lines, with or without colors) shows a
|
|
89
|
+
* dialog waiting for `agent`'s owner. Stricter than the readers that answer
|
|
90
|
+
* a dialog, because it runs while the agent is still writing: Claude's and
|
|
91
|
+
* phren-agent's numbered rows count only with their "Esc to cancel" footer,
|
|
92
|
+
* OpenCode's only as its own permission prompt. */
|
|
93
|
+
export function screenDialog(agent, screen) {
|
|
94
|
+
const text = stripTerminal(screen);
|
|
95
|
+
if (agent === "opencode")
|
|
96
|
+
return !!opencodePermissionDialog(screen);
|
|
97
|
+
if (agent === "codex" || agent === "copilot")
|
|
98
|
+
return !!visibleTerminalChoice(text);
|
|
99
|
+
if (agent === "claude" && claudeQuestionDialog(text))
|
|
100
|
+
return true;
|
|
101
|
+
return /Esc to cancel/i.test(text) && !!numberedDialog(text);
|
|
102
|
+
}
|
|
103
|
+
const dialogs = new Map();
|
|
104
|
+
/** The status of a pane after a look at its screen: blocked while a working
|
|
105
|
+
* agent shows a dialog there (`screenDialog`), else `base` unchanged. `read`
|
|
106
|
+
* answers the pane's visible lines; it runs only for a working pane, at most
|
|
107
|
+
* once per DIALOG_READ_MS per pane. */
|
|
108
|
+
export async function dialogStatus(server, pane, terminal, agent, base, read) {
|
|
109
|
+
const id = key(server, pane);
|
|
110
|
+
if (base?.status !== "working") {
|
|
111
|
+
dialogs.delete(id);
|
|
112
|
+
return base;
|
|
113
|
+
}
|
|
114
|
+
let entry = dialogs.get(id);
|
|
115
|
+
if (!entry || entry.terminal !== terminal) {
|
|
116
|
+
entry = { terminal, readAt: 0 };
|
|
117
|
+
dialogs.delete(id);
|
|
118
|
+
while (dialogs.size >= 512)
|
|
119
|
+
dialogs.delete(dialogs.keys().next().value);
|
|
120
|
+
dialogs.set(id, entry);
|
|
121
|
+
}
|
|
122
|
+
const now = Date.now();
|
|
123
|
+
if (now - entry.readAt >= DIALOG_READ_MS) {
|
|
124
|
+
entry.readAt = now;
|
|
125
|
+
// A failed read says nothing: the pane keeps what it had.
|
|
126
|
+
const shown = await read().then(screen => screenDialog(agent, screen), () => undefined);
|
|
127
|
+
if (shown === true && !entry.shown)
|
|
128
|
+
entry.shown = { at: now, seq: ++sequence };
|
|
129
|
+
else if (shown === false && entry.shown) {
|
|
130
|
+
entry.shown = undefined;
|
|
131
|
+
entry.cleared = ++sequence;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (entry.shown)
|
|
135
|
+
return { status: "blocked", seq: entry.shown.seq };
|
|
136
|
+
return { status: base.status, seq: Math.max(base.seq, entry.cleared ?? 0) };
|
|
137
|
+
}
|
|
138
|
+
/** For tests. */
|
|
139
|
+
export function resetPaneStatus() { entries.clear(); dialogs.clear(); }
|
|
@@ -1,15 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* including one whose agent is still starting. */
|
|
4
|
-
method: "agent.read" | "pane.read";
|
|
5
|
-
source: "visible" | "recent";
|
|
6
|
-
lines: number;
|
|
7
|
-
stripAnsi?: boolean;
|
|
8
|
-
/** Herdr 0.9 answers plain text whatever `strip_ansi` says; "ansi" keeps the styles. */
|
|
9
|
-
format?: "ansi";
|
|
10
|
-
timeoutMs?: number;
|
|
1
|
+
import { type ScreenRead } from "./terminal.js";
|
|
2
|
+
export interface PaneTextRequest extends ScreenRead {
|
|
11
3
|
/** Names the read in the once-per-target warning; without it a failure is silent. */
|
|
12
4
|
what?: string;
|
|
13
5
|
}
|
|
14
|
-
/** What a pane draws, or "" when
|
|
6
|
+
/** What a pane draws, or "" when the terminal cannot say. */
|
|
15
7
|
export declare function readPaneText(server: string, pane: string, request: PaneTextRequest): Promise<string>;
|
package/dist/bridge/pane-text.js
CHANGED
|
@@ -1,23 +1,16 @@
|
|
|
1
|
-
// The one reader of pane text. It
|
|
2
|
-
//
|
|
3
|
-
import { noteOptionalReadFailure
|
|
4
|
-
import {
|
|
5
|
-
/**
|
|
6
|
-
function readText(result) {
|
|
7
|
-
const read = object(result.read ?? result);
|
|
8
|
-
return typeof read.text === "string" ? read.text : "";
|
|
9
|
-
}
|
|
10
|
-
/** What a pane draws, or "" when Herdr cannot say: callers treat the text as optional. */
|
|
1
|
+
// The one reader of pane text. It reads through the terminal provider and
|
|
2
|
+
// turns a failure into "": every caller treats the text as optional.
|
|
3
|
+
import { noteOptionalReadFailure } from "./herdr.js";
|
|
4
|
+
import { terminalProvider } from "./terminal.js";
|
|
5
|
+
/** What a pane draws, or "" when the terminal cannot say. */
|
|
11
6
|
export async function readPaneText(server, pane, request) {
|
|
12
|
-
const
|
|
13
|
-
source: request.source, lines: request.lines, strip_ansi: request.stripAnsi ?? true,
|
|
14
|
-
...(request.format ? { format: request.format } : {}) };
|
|
7
|
+
const { what, ...read } = request;
|
|
15
8
|
try {
|
|
16
|
-
return
|
|
9
|
+
return await terminalProvider().readScreen(server, pane, read);
|
|
17
10
|
}
|
|
18
11
|
catch (error) {
|
|
19
|
-
if (
|
|
20
|
-
noteOptionalReadFailure(
|
|
12
|
+
if (what)
|
|
13
|
+
noteOptionalReadFailure(what, `${server}/${pane}`, error);
|
|
21
14
|
return "";
|
|
22
15
|
}
|
|
23
16
|
}
|