@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
|
@@ -12,7 +12,7 @@ import { ownerRequest, requestPeer } from "./request-origin.js";
|
|
|
12
12
|
import { listMoves, moveSessionFields, readMove } from "./session-move.js";
|
|
13
13
|
import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
|
|
14
14
|
import { ownerInboxView } from "./owner-inbox-view.js";
|
|
15
|
-
import { closeFinishedWorker, closeOwnPane } from "./worker-close.js";
|
|
15
|
+
import { cancelDispatch, closeFinishedWorker, closeOwnPane } from "./worker-close.js";
|
|
16
16
|
import { reportWorker, readIntegrator, setIntegrator } from "./worker-reports.js";
|
|
17
17
|
import { sessionStalls } from "./stalls.js";
|
|
18
18
|
import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
|
|
@@ -25,7 +25,7 @@ import { handOff } from "./hand-off.js";
|
|
|
25
25
|
import { BUILTIN_MODULES, disabledHint } from "../modules/registry.js";
|
|
26
26
|
import { homeDir } from "../home-paths.js";
|
|
27
27
|
import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
|
|
28
|
-
import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./dispatch.js";
|
|
28
|
+
import { dispatchProjectDirectory, dispatchStatus, originPaneSchema, reconcileInterruptedDispatches } from "./dispatch.js";
|
|
29
29
|
import { hookWorkers } from "./dispatch-returns.js";
|
|
30
30
|
import { remoteChildren } from "./dispatch-tree.js";
|
|
31
31
|
import { briefArrival, briefId, briefRoot, launchesWithBrief, readLaunchBrief } from "./launch-brief.js";
|
|
@@ -218,6 +218,7 @@ export function workspacesReader(ctx) {
|
|
|
218
218
|
if (agents.length !== 1)
|
|
219
219
|
continue;
|
|
220
220
|
const chat = chatStates.get(agents[0]);
|
|
221
|
+
tab.browserWatch = chat?.browserWatch ?? "unknown";
|
|
221
222
|
if (chat?.starting === true)
|
|
222
223
|
tab.starting = true;
|
|
223
224
|
// After the identity probe above, which is what learns a pane's transcript.
|
|
@@ -532,6 +533,7 @@ export function createRouteHandler(ctx) {
|
|
|
532
533
|
result = { integrator: await readIntegrator() ?? null };
|
|
533
534
|
break;
|
|
534
535
|
case "/v1/dispatch":
|
|
536
|
+
await reconcileInterruptedDispatches();
|
|
535
537
|
result = { dispatches: await dispatchStatus() };
|
|
536
538
|
break;
|
|
537
539
|
// A session move (session-move.ts) by its id, or this computer's recent moves.
|
|
@@ -1235,6 +1237,12 @@ export function createRouteHandler(ctx) {
|
|
|
1235
1237
|
else if (url.pathname === "/v1/dispatch/close") {
|
|
1236
1238
|
result = await closeFinishedWorker(data, ctx.handOffs);
|
|
1237
1239
|
}
|
|
1240
|
+
else if (url.pathname === "/v1/dispatch/cancel") {
|
|
1241
|
+
// Cancel a running dispatch by id: stop its agent and close its pane.
|
|
1242
|
+
if (request.headers?.["x-phren-origin"] === "peer")
|
|
1243
|
+
throw new BridgeError(403, "A peer cannot cancel a dispatch on this computer.");
|
|
1244
|
+
result = await cancelDispatch(data);
|
|
1245
|
+
}
|
|
1238
1246
|
else if (url.pathname === "/v1/dispatch/close-self") {
|
|
1239
1247
|
result = await closeOwnPane(data);
|
|
1240
1248
|
}
|
|
@@ -1255,6 +1263,14 @@ export function createRouteHandler(ctx) {
|
|
|
1255
1263
|
else if (url.pathname === "/v1/dispatch/workers") {
|
|
1256
1264
|
result = await hookWorkers(agentHooks)(data);
|
|
1257
1265
|
}
|
|
1266
|
+
else if (url.pathname === "/v1/dispatch/returns/ack") {
|
|
1267
|
+
// `phren dispatch wait` acknowledges only the dispatch it followed,
|
|
1268
|
+
// never the other returns a conductor on this Hook still needs.
|
|
1269
|
+
if (request.headers?.["x-phren-origin"] === "peer")
|
|
1270
|
+
throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
|
|
1271
|
+
const body = z.object({ dispatch: z.string().uuid() }).strict().parse(data);
|
|
1272
|
+
result = await ctx.returns.acknowledgeOne(body.dispatch);
|
|
1273
|
+
}
|
|
1258
1274
|
else if (url.pathname === "/v1/dispatch/returns" && url.searchParams.get("peek") === "1") {
|
|
1259
1275
|
// The unread returns, left unread: a watcher (`phren dispatch returns --watch`) beside an agent
|
|
1260
1276
|
// conductor, which still takes them. Read here, never forwarded to a successor, which would take them.
|
|
@@ -1278,8 +1294,9 @@ export function createRouteHandler(ctx) {
|
|
|
1278
1294
|
result = await conductorCall("grants-add", grant, origin, async () => ({ ok: true, grant: await addGrant(grant) }));
|
|
1279
1295
|
}
|
|
1280
1296
|
else if (url.pathname === "/v1/authority" || url.pathname === "/v1/authority/confirm") {
|
|
1281
|
-
// The owner writes the policy from the phone; an agent's call names its
|
|
1282
|
-
|
|
1297
|
+
// The owner writes the policy from the phone; an agent's call names its
|
|
1298
|
+
// pane and a peer computer's arrives through its key's scope.
|
|
1299
|
+
if (!ownerRequest(request, data))
|
|
1283
1300
|
throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
|
|
1284
1301
|
result = url.pathname === "/v1/authority" ? { ok: true, authority: await setProjectAuthority(data, "phone") }
|
|
1285
1302
|
: { ok: true, confirmation: await confirmAuthority(data, "phone") };
|
|
@@ -1299,7 +1316,7 @@ export function createRouteHandler(ctx) {
|
|
|
1299
1316
|
result = await nameSet(data);
|
|
1300
1317
|
}
|
|
1301
1318
|
else if (url.pathname === "/v1/sets/link") {
|
|
1302
|
-
result = await linkSetMember(data);
|
|
1319
|
+
result = await linkSetMember(data, request);
|
|
1303
1320
|
}
|
|
1304
1321
|
else if (url.pathname === "/v1/push/register") {
|
|
1305
1322
|
// Registration is kept for when a key is added; the reply says whether push works now.
|
|
@@ -1307,8 +1324,9 @@ export function createRouteHandler(ctx) {
|
|
|
1307
1324
|
result = { ok: true, configured: agentHooks.push.status.configured };
|
|
1308
1325
|
}
|
|
1309
1326
|
else if (url.pathname === "/v1/sudo/answer") {
|
|
1310
|
-
// The owner answers from the phone; an agent's call names its pane
|
|
1311
|
-
|
|
1327
|
+
// The owner answers from the phone; an agent's call names its pane and
|
|
1328
|
+
// a peer computer's arrives through its key's scope.
|
|
1329
|
+
if (!ownerRequest(request, data))
|
|
1312
1330
|
throw new BridgeError(403, "Only the owner answers a sudo request, from the phone.");
|
|
1313
1331
|
let parsed;
|
|
1314
1332
|
try {
|
|
@@ -1402,7 +1420,7 @@ export function createRouteHandler(ctx) {
|
|
|
1402
1420
|
result = await changeApprovalRule(data, "DELETE");
|
|
1403
1421
|
}
|
|
1404
1422
|
else if (url.pathname === "/v1/authority") {
|
|
1405
|
-
if (data
|
|
1423
|
+
if (!ownerRequest(request, data))
|
|
1406
1424
|
throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
|
|
1407
1425
|
result = { ok: true, authority: await clearProjectAuthority(data, "phone") };
|
|
1408
1426
|
}
|
package/dist/bridge/server.js
CHANGED
|
@@ -9,6 +9,7 @@ import { AccountFailover } from "./account-failover.js";
|
|
|
9
9
|
import { ownerInboxSources } from "./owner-inbox-sources.js";
|
|
10
10
|
import { OwnerInbox } from "./owner-inbox.js";
|
|
11
11
|
import { closeFinishedWorker } from "./worker-close.js";
|
|
12
|
+
import { cleanupIdempotencyLocks, markHookServerProcess } from "./dispatch-idempotency.js";
|
|
12
13
|
import { isLocalComputer } from "./dispatch-hosts.js";
|
|
13
14
|
import { hookPeers, peerRequest } from "./peers.js";
|
|
14
15
|
import { handOff } from "./hand-off.js";
|
|
@@ -37,7 +38,7 @@ import { approvalPushCapability } from "./push.js";
|
|
|
37
38
|
import { startChangeRetention } from "./changes.js";
|
|
38
39
|
import { CodeReindexer, CodeRoutes } from "./code-routes.js";
|
|
39
40
|
import { WorkspaceContextUsage } from "./context.js";
|
|
40
|
-
import { DispatchService } from "./dispatch.js";
|
|
41
|
+
import { DispatchService, reconcileInterruptedDispatches } from "./dispatch.js";
|
|
41
42
|
import { DispatchReturns, hookWorkers } from "./dispatch-returns.js";
|
|
42
43
|
import { findPane, paneChatState, paneIdentity, recentServers, sharedSnapshot, snapshot, validateTarget } from "./herdr.js";
|
|
43
44
|
import { LaunchLimiter } from "./limits.js";
|
|
@@ -79,11 +80,14 @@ import { CodexAuthKeeper, codexAuthRefreshEnabled } from "./codex-auth-refresh.j
|
|
|
79
80
|
import { localNames } from "./computer-names.js";
|
|
80
81
|
import { startStoreSyncLoop } from "../sync/store-sync.js";
|
|
81
82
|
import { SocketBudget, socketIdentity, socketKind } from "./socket-budget.js";
|
|
83
|
+
import { logger } from "../logger.js";
|
|
82
84
|
export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
|
|
83
85
|
export { streamCloseReason } from "./server-stream.js";
|
|
84
86
|
export { herdrAgentName, launchSession } from "./server-launch.js";
|
|
85
87
|
export async function serve(version, options = {}) {
|
|
86
88
|
process.umask(0o077);
|
|
89
|
+
markHookServerProcess();
|
|
90
|
+
await cleanupIdempotencyLocks().catch(error => logger.warn("dispatch", `Could not clean leftover idempotency locks: ${error instanceof Error ? error.message : String(error)}`));
|
|
87
91
|
const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
|
|
88
92
|
if (!modules.has("hook"))
|
|
89
93
|
throw new BridgeError(404, disabledHint("hook"));
|
|
@@ -126,6 +130,9 @@ export async function serve(version, options = {}) {
|
|
|
126
130
|
localWorkers: hookWorkers(agentHooks),
|
|
127
131
|
close: async (receipt, verifiedPeer) => {
|
|
128
132
|
const data = { target: receipt.target, dispatch: receipt.moves?.slice().reverse().find(move => move.to.computer)?.id ?? receipt.id, turn: receipt.closePending.turn };
|
|
133
|
+
// Keyed dispatches are local-only: close on this Hook, never over a peer.
|
|
134
|
+
if (receipt.idempotencyKey)
|
|
135
|
+
return closeFinishedWorker(data, handOffs);
|
|
129
136
|
if (receipt.computerId === computerID)
|
|
130
137
|
return closeFinishedWorker(data, handOffs);
|
|
131
138
|
const peer = verifiedPeer ?? (await hookPeers().catch(() => [])).find(peer => peer.name === receipt.computer);
|
|
@@ -272,6 +279,10 @@ export async function serve(version, options = {}) {
|
|
|
272
279
|
throw new Error("Phren Hook is already running.");
|
|
273
280
|
await unlink(socketPath());
|
|
274
281
|
}
|
|
282
|
+
// Only the Hook that owns the socket reconciles dispatch state: a second
|
|
283
|
+
// `bridge serve` stops above before touching any receipt or key record.
|
|
284
|
+
if (dispatches)
|
|
285
|
+
await reconcileInterruptedDispatches().catch(error => logger.warn("dispatch", `Could not reconcile interrupted dispatches: ${error instanceof Error ? error.message : String(error)}`));
|
|
275
286
|
const storePulls = new StorePulls(scheduleStore);
|
|
276
287
|
const gitboyWebhooks = new GitboyWebhooks(root, storeId => storePulls.request(storeId), undefined, scheduler ? event => scheduler.ingestEvent(event) : undefined);
|
|
277
288
|
const browsers = new BrowserRegistry(root);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** The script's file name in a version's folder, beside `bridge-hook.mjs`. */
|
|
2
|
+
export declare const FAST_STATUS_LINE_FILE = "claude-statusline.mjs";
|
|
3
|
+
export declare const fastStatusLinePath: (versionDir: string) => string;
|
|
4
|
+
/** The owner's status line under any number of Phren wrappers: what a status line that is Phren's wraps,
|
|
5
|
+
* down to one that is not. `null` when the innermost wrapped none; a value that is not Phren's is returned as is.
|
|
6
|
+
* Phren's is the quoted node, the quoted bundle or forwarder (whichever node and Hook folder it named),
|
|
7
|
+
* `usage-statusline` and the wrapped status line as base64. Self-contained: the forwarder embeds its source. */
|
|
8
|
+
export declare function unwrapStatusLine(value: unknown): unknown;
|
|
9
|
+
export declare const FAST_STATUS_LINE_SOURCE: string;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Claude Code runs its status line command on every refresh, from every
|
|
2
|
+
// session. Loading the Hook bundle for each one cost about a second of CPU, and
|
|
3
|
+
// installs under a different node wrapped the previous wrapper, so one refresh
|
|
4
|
+
// ran a chain of bundles. Install writes this small script into each version's
|
|
5
|
+
// folder beside the bundle: it posts the status line's input to the running
|
|
6
|
+
// Hook, which records the usage, and runs the owner's own status line, if any.
|
|
7
|
+
//
|
|
8
|
+
// It must stay dependency-free. When no Hook answers, nothing is recorded: the
|
|
9
|
+
// Hook is what serves the usage, and the next refresh after it starts records it.
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
/** The script's file name in a version's folder, beside `bridge-hook.mjs`. */
|
|
12
|
+
export const FAST_STATUS_LINE_FILE = "claude-statusline.mjs";
|
|
13
|
+
export const fastStatusLinePath = (versionDir) => path.join(versionDir, FAST_STATUS_LINE_FILE);
|
|
14
|
+
/** The owner's status line under any number of Phren wrappers: what a status line that is Phren's wraps,
|
|
15
|
+
* down to one that is not. `null` when the innermost wrapped none; a value that is not Phren's is returned as is.
|
|
16
|
+
* Phren's is the quoted node, the quoted bundle or forwarder (whichever node and Hook folder it named),
|
|
17
|
+
* `usage-statusline` and the wrapped status line as base64. Self-contained: the forwarder embeds its source. */
|
|
18
|
+
export function unwrapStatusLine(value) {
|
|
19
|
+
const phren = /^'(?:[^']|'\\'')*' '(?:[^']|'\\'')*\/(?:bridge-hook|claude-statusline)\.mjs' usage-statusline ([A-Za-z0-9+/=]{1,32768})$/;
|
|
20
|
+
for (let depth = 0; depth < 16; depth++) {
|
|
21
|
+
const command = value && typeof value === "object" && !Array.isArray(value) ? value.command : undefined;
|
|
22
|
+
const match = typeof command === "string" ? phren.exec(command) : null;
|
|
23
|
+
if (!match)
|
|
24
|
+
return value;
|
|
25
|
+
value = JSON.parse(Buffer.from(match[1], "base64").toString());
|
|
26
|
+
}
|
|
27
|
+
throw new Error("Invalid Phren status line");
|
|
28
|
+
}
|
|
29
|
+
export const FAST_STATUS_LINE_SOURCE = `// Installed by Phren Hook: Claude Code's status line, reported to the running Hook.
|
|
30
|
+
import { spawn } from "node:child_process";
|
|
31
|
+
import { request } from "node:http";
|
|
32
|
+
import { homedir } from "node:os";
|
|
33
|
+
import path from "node:path";
|
|
34
|
+
const env = process.env, encoded = process.argv[3] ?? "";
|
|
35
|
+
const unwrapStatusLine = ${unwrapStatusLine.toString()};
|
|
36
|
+
if (process.argv[2] === "usage-statusline" && /^[A-Za-z0-9+/=]{1,32768}$/.test(encoded)) {
|
|
37
|
+
let input = "", oversized = false;
|
|
38
|
+
for await (const chunk of process.stdin) { input += chunk.toString(); if (input.length > 262_144) { oversized = true; break; } }
|
|
39
|
+
const data = oversized ? undefined : JSON.stringify({ configDir: env.CLAUDE_CONFIG_DIR, input });
|
|
40
|
+
const socketPath = path.join(env.PHREN_BRIDGE_HOME || path.join(homedir(), ".local/share/phren/bridge"), "agent.sock");
|
|
41
|
+
const reported = data === undefined ? undefined : new Promise(resolve => {
|
|
42
|
+
const req = request({ socketPath, path: "/usage-statusline", method: "POST", timeout: 2_000,
|
|
43
|
+
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => { res.resume(); res.on("end", resolve); res.on("error", resolve); });
|
|
44
|
+
req.on("error", resolve); req.on("timeout", () => { req.destroy(); resolve(); }); req.end(data);
|
|
45
|
+
});
|
|
46
|
+
let previous;
|
|
47
|
+
try { previous = unwrapStatusLine(JSON.parse(Buffer.from(encoded, "base64").toString())); } catch { /* Nothing of the owner's to show. */ }
|
|
48
|
+
// The owner's own status line, run just as Claude ran it before the Hook was installed.
|
|
49
|
+
const shown = previous && typeof previous.command === "string" ? new Promise(resolve => {
|
|
50
|
+
const child = spawn("/bin/sh", ["-c", previous.command], { stdio: ["pipe", "inherit", "inherit"] });
|
|
51
|
+
child.on("error", resolve); child.on("exit", resolve);
|
|
52
|
+
child.stdin.on("error", () => {}); child.stdin.end(input);
|
|
53
|
+
}) : undefined;
|
|
54
|
+
await Promise.all([reported, shown]);
|
|
55
|
+
}
|
|
56
|
+
`;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Json } from "./protocol.js";
|
|
2
|
-
import type { TerminalPane, TerminalProvider } from "./terminal.js";
|
|
2
|
+
import type { AgentStart, TerminalPane, TerminalProvider } from "./terminal.js";
|
|
3
3
|
/** Who reports phren-agent's lifecycle to Herdr, which does not detect it itself. */
|
|
4
4
|
export declare const PHREN_REPORT_SOURCE = "phren-hook";
|
|
5
5
|
/** A word for a POSIX shell, quoted only when it needs it. */
|
|
@@ -7,6 +7,10 @@ export declare function shellWord(word: string): string;
|
|
|
7
7
|
/** What the Hook types into a Herdr pane's shell to start phren-agent:
|
|
8
8
|
* the agent, then Herdr's report of it released once it exits. */
|
|
9
9
|
export declare function phrenCommandLine(args: string[]): string;
|
|
10
|
+
/** The exact command Herdr types for a keyed launch. */
|
|
11
|
+
export declare function herdrExplicitCommand(agent: AgentStart): string;
|
|
12
|
+
/** sh, bash or zsh only: the keyed wrapper is a POSIX shell command line. */
|
|
13
|
+
export declare function shellFromProcessInfo(info: Json): string | undefined;
|
|
10
14
|
/** A Herdr snapshot's panes in the provider's shape; Herdr's agent report becomes hints. */
|
|
11
15
|
export declare function herdrPanes(server: string, s: Json): TerminalPane[];
|
|
12
16
|
export declare const herdrTerminal: TerminalProvider;
|
|
@@ -5,7 +5,7 @@ import { browserEnv } from "./browser-env.js";
|
|
|
5
5
|
// the provider existed.
|
|
6
6
|
import { herdrSocketPath, rpc, snapshot } from "./herdr.js";
|
|
7
7
|
import { BridgeError, object, objects } from "./protocol.js";
|
|
8
|
-
import { agentFromCommand } from "./terminal-tmux.js";
|
|
8
|
+
import { agentFromCommand, explicitAgentCommand } from "./terminal-tmux.js";
|
|
9
9
|
const text = (value) => typeof value === "string" && value ? value : undefined;
|
|
10
10
|
/** Who reports phren-agent's lifecycle to Herdr, which does not detect it itself. */
|
|
11
11
|
export const PHREN_REPORT_SOURCE = "phren-hook";
|
|
@@ -71,6 +71,66 @@ async function startPhren(server, pane, { name, args, timeoutMs }) {
|
|
|
71
71
|
await rpc(server, "pane.report_agent", { pane_id: pane, source: PHREN_REPORT_SOURCE, agent: "phren", state: "idle" });
|
|
72
72
|
await rpc(server, "agent.rename", { target: pane, name }).catch(() => undefined);
|
|
73
73
|
}
|
|
74
|
+
/** The exact command Herdr types for a keyed launch. */
|
|
75
|
+
export function herdrExplicitCommand(agent) {
|
|
76
|
+
return explicitAgentCommand(agent.kind, agent.args, agent.env ?? {});
|
|
77
|
+
}
|
|
78
|
+
/** sh, bash or zsh only: the keyed wrapper is a POSIX shell command line. */
|
|
79
|
+
export function shellFromProcessInfo(info) {
|
|
80
|
+
const shellPid = info.shell_pid;
|
|
81
|
+
const processes = objects(info.foreground_processes);
|
|
82
|
+
const shell = processes.find(p => p.pid === shellPid) ?? processes[0];
|
|
83
|
+
const command = typeof shell?.cmdline === "string" ? shell.cmdline.trim().split(/\s+/)[0] : "";
|
|
84
|
+
const name = command.split("/").pop()?.replace(/^-/, "");
|
|
85
|
+
return name && ["sh", "bash", "zsh"].includes(name) ? name : undefined;
|
|
86
|
+
}
|
|
87
|
+
/** Keyed launches: type our explicit `env -i` command at the pane's fresh shell. */
|
|
88
|
+
async function startExplicit(server, pane, { kind, args, timeoutMs, env, freshPane }) {
|
|
89
|
+
if (!freshPane)
|
|
90
|
+
throw new BridgeError(409, "A keyed Herdr launch needs a pane this launch just created; refusing to type into a reused pane.");
|
|
91
|
+
const readyBy = Date.now() + Math.min(timeoutMs, 15_000);
|
|
92
|
+
let stable = "", stableSince = 0;
|
|
93
|
+
for (;;) {
|
|
94
|
+
const info = object((await rpc(server, "pane.process_info", { pane_id: pane })).process_info);
|
|
95
|
+
const shellPid = info.shell_pid;
|
|
96
|
+
const processes = objects(info.foreground_processes);
|
|
97
|
+
const pids = processes.map(p => p.pid);
|
|
98
|
+
const foreground = Number.isSafeInteger(shellPid) && info.foreground_process_group_id === shellPid;
|
|
99
|
+
const shell = shellFromProcessInfo(info);
|
|
100
|
+
if (foreground && !shell)
|
|
101
|
+
throw new BridgeError(409, "Herdr: keyed launches support only sh, bash and zsh pane shells; this shell is not supported.");
|
|
102
|
+
const idle = foreground && !!shell && pids.length > 0 && pids.every(pid => pid === shellPid);
|
|
103
|
+
if (idle) {
|
|
104
|
+
const key = JSON.stringify([shellPid, pids]);
|
|
105
|
+
if (key !== stable) {
|
|
106
|
+
stable = key;
|
|
107
|
+
stableSince = Date.now();
|
|
108
|
+
}
|
|
109
|
+
if (Date.now() - stableSince >= 300)
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
stable = "";
|
|
114
|
+
stableSince = 0;
|
|
115
|
+
}
|
|
116
|
+
if (Date.now() >= readyBy)
|
|
117
|
+
throw new BridgeError(409, `Herdr: agent target pane ${pane} did not reach an idle shell prompt.`, { herdrCode: "agent_pane_busy" });
|
|
118
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
119
|
+
}
|
|
120
|
+
await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["ctrl+u"] });
|
|
121
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
122
|
+
await rpc(server, "pane.send_text", { pane_id: pane, text: herdrExplicitCommand({ name: "", kind, args, timeoutMs, env, freshPane }) });
|
|
123
|
+
await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["Enter"] });
|
|
124
|
+
const deadline = Date.now() + Math.min(timeoutMs, 30_000);
|
|
125
|
+
for (;;) {
|
|
126
|
+
const info = object((await rpc(server, "pane.process_info", { pane_id: pane })).process_info);
|
|
127
|
+
if (objects(info.foreground_processes).some(p => typeof p.cmdline === "string" && agentFromCommand(p.cmdline) === kind))
|
|
128
|
+
return;
|
|
129
|
+
if (Date.now() >= deadline)
|
|
130
|
+
throw new BridgeError(504, `${kind} did not start in the Herdr pane. Check that it is installed and on the login shell's PATH.`);
|
|
131
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
74
134
|
/** A Herdr snapshot's panes in the provider's shape; Herdr's agent report becomes hints. */
|
|
75
135
|
export function herdrPanes(server, s) {
|
|
76
136
|
return objects(s.panes).filter(p => typeof p.pane_id === "string" && typeof p.tab_id === "string" && typeof p.workspace_id === "string").map(p => {
|
|
@@ -159,6 +219,10 @@ export const herdrTerminal = {
|
|
|
159
219
|
await startPhren(server, pane, agent);
|
|
160
220
|
return;
|
|
161
221
|
}
|
|
222
|
+
if (agent.envExact) {
|
|
223
|
+
await startExplicit(server, pane, agent);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
162
226
|
// Herdr waits up to `timeout_ms` for the agent to become ready; the socket waits a little longer.
|
|
163
227
|
await rpc(server, "agent.start", { name, kind, pane_id: pane, timeout_ms: timeoutMs, ...(args.length ? { args } : {}) }, undefined, timeoutMs + 5_000);
|
|
164
228
|
},
|
|
@@ -46,6 +46,8 @@ export declare function tmuxSocketFolders(env?: NodeJS.ProcessEnv): string[];
|
|
|
46
46
|
export declare function tmuxSocketsIn(folder: string, strict?: boolean): Promise<string[]>;
|
|
47
47
|
/** For tests: replace how tmux and ps run; the returned function restores them. */
|
|
48
48
|
export declare function setTmuxDeps(replacement: Partial<TmuxDeps>): () => void;
|
|
49
|
+
/** The exact keyed-launch command: shell init, then `env -i` with only the explicit environment. */
|
|
50
|
+
export declare function explicitAgentCommand(kind: string, args: string[], env: Record<string, string>): string;
|
|
49
51
|
declare const SIGILS: {
|
|
50
52
|
readonly s: "$";
|
|
51
53
|
readonly w: "@";
|
|
@@ -74,6 +76,10 @@ export declare function tmuxSnapshot(server: string): Promise<Json>;
|
|
|
74
76
|
export declare function tmuxKey(key: string): string | undefined;
|
|
75
77
|
/** send-keys calls for `keys`, in order: named keys together, literal characters with -l. */
|
|
76
78
|
export declare function sendKeysCalls(pane: string, keys: string[]): string[][];
|
|
79
|
+
/** tmux reads the names and directories it is handed as formats, so `#(…)`
|
|
80
|
+
* would run a command and `#{…}` read a variable. A doubled `#` is a literal
|
|
81
|
+
* one. Option values (`set-option`) are not formats and take text as it is. */
|
|
82
|
+
export declare function tmuxLiteral(text: string): string;
|
|
77
83
|
export declare const tmuxTerminal: TerminalProvider;
|
|
78
84
|
/** The tmux servers the Hook drives, as `/v1/muxes` lists servers: the owner's
|
|
79
85
|
* servers that answer, and (unless `hidden: false`) the hidden server whenever
|
|
@@ -191,6 +191,20 @@ function socketOf(server) {
|
|
|
191
191
|
throw new BridgeError(400, "This is not a tmux server.");
|
|
192
192
|
return socket;
|
|
193
193
|
}
|
|
194
|
+
const shellQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
195
|
+
/** The exact keyed-launch command: shell init, then `env -i` with only the explicit environment. */
|
|
196
|
+
export function explicitAgentCommand(kind, args, env) {
|
|
197
|
+
const expanded = new Set(["HOME", "USER", "LOGNAME", "PATH", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR"]);
|
|
198
|
+
const assignments = Object.entries(env).map(([key, value]) => expanded.has(key) ? `${key}="$${key}"` : `${key}=${shellQuote(value)}`);
|
|
199
|
+
const harness = [kind, ...args];
|
|
200
|
+
if (env.PHREN_WORKER_ID_FILE) {
|
|
201
|
+
// Record the exec'd process identity before handing the same PID to the
|
|
202
|
+
// harness. The command line carries paths and arguments only, never a secret.
|
|
203
|
+
const script = `umask 077; printf "%s %s\\n" "$$" "$(ps -o lstart= -p $$ | tr -s " ")" > "$PHREN_WORKER_ID_FILE.tmp" && mv "$PHREN_WORKER_ID_FILE.tmp" "$PHREN_WORKER_ID_FILE" && exec "$@"`;
|
|
204
|
+
return `exec env -i ${assignments.join(" ")} /bin/sh -c ${shellQuote(script)} phren-worker ${harness.map(shellQuote).join(" ")}`.replace(/\s+$/, "");
|
|
205
|
+
}
|
|
206
|
+
return `exec env -i ${assignments.join(" ")} ${harness.map(shellQuote).join(" ")}`.replace(/\s+$/, "");
|
|
207
|
+
}
|
|
194
208
|
const tmux = (server, args, options) => deps.run(socketOf(server), args, options);
|
|
195
209
|
// tmux ids carry sigils the Hook's ids do not allow: session $3, window @5,
|
|
196
210
|
// pane %12 become s3, w5 and p12, and back.
|
|
@@ -310,7 +324,7 @@ export async function tmuxSnapshot(server) {
|
|
|
310
324
|
const title = row.pane_title && row.pane_title !== host && row.pane_title !== short ? plainTitle(row.pane_title) : undefined;
|
|
311
325
|
panes.push({ pane_id: pane, tab_id: tab, workspace_id: workspace, terminal_id: terminal, cwd: row.pane_current_path || undefined,
|
|
312
326
|
foreground_cwd: row.pane_current_path || undefined, title, ...(row["@phren_label"] ? { label: row["@phren_label"] } : {}),
|
|
313
|
-
...(agent ? { agent, agent_status: status?.status ?? (hooked ? "unknown" : "idle"), ...(status?.seq ? { state_change_seq: status.seq } : {}) } : {}),
|
|
327
|
+
...(agent ? { agent, agent_pid: running.find(p => agentFromCommand(p.args) === agent)?.pid, agent_status: status?.status ?? (hooked ? "unknown" : "idle"), ...(status?.seq ? { state_change_seq: status.seq } : {}) } : {}),
|
|
314
328
|
...(agent && name ? { agent_name: name } : {}) });
|
|
315
329
|
if (agent && name)
|
|
316
330
|
agents.push({ name, pane_id: pane });
|
|
@@ -392,6 +406,12 @@ function loginShell() {
|
|
|
392
406
|
// Only a POSIX shell takes the launcher script below.
|
|
393
407
|
return shell && /^(sh|bash|zsh|ksh|dash)$/.test(path.basename(shell)) && existsSync(shell) ? shell : "/bin/sh";
|
|
394
408
|
}
|
|
409
|
+
/** tmux reads the names and directories it is handed as formats, so `#(…)`
|
|
410
|
+
* would run a command and `#{…}` read a variable. A doubled `#` is a literal
|
|
411
|
+
* one. Option values (`set-option`) are not formats and take text as it is. */
|
|
412
|
+
export function tmuxLiteral(text) {
|
|
413
|
+
return text.replace(/#/g, "##");
|
|
414
|
+
}
|
|
395
415
|
/** A session name tmux accepts: no "." or ":" and nothing unprintable. */
|
|
396
416
|
function sessionName(label, taken) {
|
|
397
417
|
const base = (label ?? "phren").replace(/[.:\x00-\x1f\x7f]/g, "_").trim().slice(0, 60) || "phren";
|
|
@@ -446,8 +466,8 @@ export const tmuxTerminal = {
|
|
|
446
466
|
await tmux(server, ["send-keys", "-t", target, "Enter"], { signal });
|
|
447
467
|
},
|
|
448
468
|
async create(server, { workspace, label, cwd }) {
|
|
449
|
-
const directory = cwd && path.isAbsolute(cwd) ? ["-c", cwd] : [];
|
|
450
|
-
const name = label ? ["-n", label.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 100)] : [];
|
|
469
|
+
const directory = cwd && path.isAbsolute(cwd) ? ["-c", tmuxLiteral(cwd)] : [];
|
|
470
|
+
const name = label ? ["-n", tmuxLiteral(label.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 100))] : [];
|
|
451
471
|
// `-P -F` prints the new pane's ids, so the caller knows it without diffing the pane list.
|
|
452
472
|
const printed = ["-P", "-F", "#{session_id} #{window_id} #{pane_id}"];
|
|
453
473
|
const created = (output) => {
|
|
@@ -457,9 +477,9 @@ export const tmuxTerminal = {
|
|
|
457
477
|
if (workspace)
|
|
458
478
|
return created(await tmux(server, ["new-window", "-d", ...printed, "-t", `${toTmuxId(workspace, "s")}:`, ...directory, ...name]));
|
|
459
479
|
const taken = new Set((await tmux(server, ["list-sessions", "-F", "#{session_name}"]).catch(() => "")).split("\n").filter(Boolean));
|
|
460
|
-
return created(await tmux(server, ["new-session", "-d", ...printed, "-s", sessionName(label, taken), "-x", "200", "-y", "50", ...directory, ...name]));
|
|
480
|
+
return created(await tmux(server, ["new-session", "-d", ...printed, "-s", tmuxLiteral(sessionName(label, taken)), "-x", "200", "-y", "50", ...directory, ...name]));
|
|
461
481
|
},
|
|
462
|
-
async startAgent(server, pane, { name, kind, args, timeoutMs, env }) {
|
|
482
|
+
async startAgent(server, pane, { name, kind, args, timeoutMs, env, envExact }) {
|
|
463
483
|
if (!["claude", "codex", "copilot", "opencode", "phren"].includes(kind))
|
|
464
484
|
throw new BridgeError(400, "This agent cannot be started in tmux.");
|
|
465
485
|
await requireDirectExec();
|
|
@@ -472,10 +492,17 @@ export const tmuxTerminal = {
|
|
|
472
492
|
// the pane falls back to that shell when it exits. The harness and its
|
|
473
493
|
// arguments are the script's positional parameters, never script text.
|
|
474
494
|
const shell = loginShell();
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
495
|
+
if (envExact) {
|
|
496
|
+
const command = explicitAgentCommand(kind, args, env ?? {});
|
|
497
|
+
await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", tmuxLiteral(row.pane_current_path)] : []),
|
|
498
|
+
"--", shell, "-l", "-c", command]);
|
|
499
|
+
}
|
|
500
|
+
else {
|
|
501
|
+
// Variables for the agent alone (a dispatch id) ride on the respawn.
|
|
502
|
+
const variables = Object.entries(env ?? {}).flatMap(([key, value]) => ["-e", `${key}=${value}`]);
|
|
503
|
+
await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", tmuxLiteral(row.pane_current_path)] : []), ...variables,
|
|
504
|
+
"--", shell, "-l", "-c", 'shell="$1"; shift; "$@"; exec "$shell" -l', "phren", shell, kind, ...args]);
|
|
505
|
+
}
|
|
479
506
|
// Started once the harness is the pane's foreground program.
|
|
480
507
|
const deadline = Date.now() + Math.min(timeoutMs, 30_000);
|
|
481
508
|
for (;;) {
|
|
@@ -513,7 +540,7 @@ export const tmuxTerminal = {
|
|
|
513
540
|
if (operation === "focus")
|
|
514
541
|
await tmux(server, ["select-window", "-t", target]);
|
|
515
542
|
else if (operation === "rename")
|
|
516
|
-
await tmux(server, ["rename-window", "-t", target, (label ?? "").replace(/[\x00-\x1f\x7f]/g, " ")]);
|
|
543
|
+
await tmux(server, ["rename-window", "-t", target, tmuxLiteral((label ?? "").replace(/[\x00-\x1f\x7f]/g, " "))]);
|
|
517
544
|
else
|
|
518
545
|
await tmux(server, ["kill-window", "-t", target]);
|
|
519
546
|
return;
|
|
@@ -525,7 +552,7 @@ export const tmuxTerminal = {
|
|
|
525
552
|
if (operation === "focus")
|
|
526
553
|
return;
|
|
527
554
|
if (operation === "rename")
|
|
528
|
-
await tmux(server, ["rename-session", "-t", target, sessionName(label, new Set())]);
|
|
555
|
+
await tmux(server, ["rename-session", "-t", target, tmuxLiteral(sessionName(label, new Set()))]);
|
|
529
556
|
else
|
|
530
557
|
await tmux(server, ["kill-session", "-t", target]);
|
|
531
558
|
},
|
|
@@ -74,6 +74,10 @@ export interface AgentStart {
|
|
|
74
74
|
args: string[];
|
|
75
75
|
timeoutMs: number;
|
|
76
76
|
env?: Record<string, string>;
|
|
77
|
+
/** The env is the complete environment: run the harness through `env -i`, never an overlay. */
|
|
78
|
+
envExact?: boolean;
|
|
79
|
+
/** This launch created the pane, so a keyed Herdr launch may type into its fresh shell. */
|
|
80
|
+
freshPane?: boolean;
|
|
77
81
|
}
|
|
78
82
|
/**
|
|
79
83
|
* Key names are the Hook's vocabulary: "enter", "esc", "up", "down", "tab",
|
|
@@ -92,7 +96,7 @@ export interface TerminalProvider {
|
|
|
92
96
|
* (`tab_id`, `workspace_id`, `label`, `agent_status`) and `panes`
|
|
93
97
|
* (`pane_id`, `tab_id`, `workspace_id`, `terminal_id`, `cwd`,
|
|
94
98
|
* `foreground_cwd`, `title`, `label`, `agent`, `agent_status`,
|
|
95
|
-
* `agent_name`, `state_change_seq`), plus `focused_workspace_id` /
|
|
99
|
+
* `agent_name`, `state_change_seq`, optional already-resolved `agent_pid`), plus `focused_workspace_id` /
|
|
96
100
|
* `focused_tab_id` / `focused_pane_id`. `terminal_id` names the terminal
|
|
97
101
|
* instance, so a pane reused by a new shell is a different terminal.
|
|
98
102
|
*/
|
|
@@ -40,6 +40,13 @@ export declare function isNarration(block: Record<string, unknown>): boolean;
|
|
|
40
40
|
* second result for the same call, so the phone can show what the skill said;
|
|
41
41
|
* every other hidden row stays private. */
|
|
42
42
|
export declare function skillBody(raw: Json): Json | undefined;
|
|
43
|
+
/** A message another agent sent this session (a teammate, a subagent's
|
|
44
|
+
* hand-back or another Claude session), which Claude Code delivers as a hidden
|
|
45
|
+
* user row when the agent is idle, or a queued_command attachment mid-turn,
|
|
46
|
+
* both naming it with `origin.kind: "peer"`. The terminal shows it as
|
|
47
|
+
* "Message from @name"; only the sender's name and the words cross, never the
|
|
48
|
+
* envelope, socket path or ids. */
|
|
49
|
+
export declare function peerMessage(raw: Json, includeSidechain?: boolean): Json | undefined;
|
|
43
50
|
/** A phren UserPromptSubmit injection, as `{ type: "phren_hook_context",
|
|
44
51
|
* parentUuid, content }`, or undefined for any other row. */
|
|
45
52
|
export declare function phrenHookContext(raw: Json, includeSidechain?: boolean): Json | undefined;
|