@phren/cli 0.3.13 → 0.3.14
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/codex-app-server.d.ts +6 -0
- package/dist/bridge/codex-app-server.js +3 -1
- package/dist/bridge/codex-servers.d.ts +25 -1
- package/dist/bridge/codex-servers.js +78 -14
- package/dist/bridge/command.js +1 -1
- package/dist/bridge/dispatch-returns.d.ts +3 -0
- package/dist/bridge/dispatch-returns.js +5 -0
- package/dist/bridge/install.d.ts +8 -1
- package/dist/bridge/install.js +44 -5
- package/dist/bridge-hook.mjs +119 -41
- package/dist/test-global-setup.js +7 -0
- package/package.json +1 -1
|
@@ -124,6 +124,12 @@ export interface SpawnAppServerOptions {
|
|
|
124
124
|
/** Config overrides for every thread the server runs, as `-c key=value`
|
|
125
125
|
* (the value is TOML). */
|
|
126
126
|
config?: string[];
|
|
127
|
+
/** Run the server in this transient systemd user scope (`systemd-run
|
|
128
|
+
* --user --scope`). `detached` alone does not leave the Hook's service:
|
|
129
|
+
* systemd stops a unit by killing its whole cgroup, so a Hook restart would
|
|
130
|
+
* end every server and the tools its turn runs. systemd-run execs the
|
|
131
|
+
* server in place, so the child's pid is the server's. */
|
|
132
|
+
scope?: string;
|
|
127
133
|
}
|
|
128
134
|
/** Start one `codex app-server --listen unix://<socketPath>` and wait until its
|
|
129
135
|
* socket accepts WebSocket connections. The server is the worker's; `stop()`
|
|
@@ -35,8 +35,10 @@ export async function spawnAppServer(options) {
|
|
|
35
35
|
await rm(options.socketPath, { force: true });
|
|
36
36
|
const log = options.logFile ? await open(options.logFile, "a", 0o600) : undefined;
|
|
37
37
|
let child;
|
|
38
|
+
const command = [codexBin, "app-server", ...(options.config ?? []).flatMap(value => ["-c", value]), "--listen", `unix://${options.socketPath}`];
|
|
39
|
+
const [file, ...args] = options.scope ? ["systemd-run", "--user", "--scope", "--quiet", "--collect", `--unit=${options.scope}`, "--", ...command] : command;
|
|
38
40
|
try {
|
|
39
|
-
child = spawn(
|
|
41
|
+
child = spawn(file, args, {
|
|
40
42
|
cwd: options.cwd,
|
|
41
43
|
env,
|
|
42
44
|
detached: options.detached === true,
|
|
@@ -61,7 +61,12 @@ export interface CodexServerDeps {
|
|
|
61
61
|
/** True while `pid` is a running process. */
|
|
62
62
|
alive(pid: number): boolean;
|
|
63
63
|
kill(pid: number): void;
|
|
64
|
+
/** The systemd scope a new server runs in, or undefined to run it in the Hook's own process tree. */
|
|
65
|
+
scope?(serverId: string): string | undefined;
|
|
64
66
|
}
|
|
67
|
+
/** The systemd service cgroup a process runs in (`/proc/<pid>/cgroup`, cgroup
|
|
68
|
+
* v2), or undefined outside a service: a terminal, a scope, macOS. */
|
|
69
|
+
export declare function serviceCgroup(pid?: number | "self"): string | undefined;
|
|
65
70
|
/** `PHREN_CODEX_APP_SERVER=off` keeps every Codex launch on the typed path. */
|
|
66
71
|
export declare function codexAppServerEnabled(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): boolean;
|
|
67
72
|
/** A question on a Hook-run pane reaches the phone as a card either way, but
|
|
@@ -83,6 +88,15 @@ export declare const codexServerId: z.ZodString;
|
|
|
83
88
|
* server report this pane) and the caller's. */
|
|
84
89
|
export declare function serverEnvironment(base: NodeJS.ProcessEnv, extra: Record<string, string>): NodeJS.ProcessEnv;
|
|
85
90
|
export declare function codexServersRoot(): string;
|
|
91
|
+
/** A turn whose server ended before it did: the Hook restarted with the
|
|
92
|
+
* server inside its service, or the server crashed. Nothing will finish it. */
|
|
93
|
+
export interface LostTurn {
|
|
94
|
+
threadId: string;
|
|
95
|
+
turn: string;
|
|
96
|
+
dispatchId?: string;
|
|
97
|
+
at: string;
|
|
98
|
+
}
|
|
99
|
+
export declare const LOST_TURN = "The worker's Codex server stopped before its turn finished (the Phren Hook restarted with it, or it crashed), so the turn will not finish. Resume the thread or dispatch the work again.";
|
|
86
100
|
/** Nothing was sent: the server could not be reached. */
|
|
87
101
|
export declare class CodexServerUnavailable extends Error {
|
|
88
102
|
constructor(message: string);
|
|
@@ -106,6 +120,8 @@ export interface LaunchOptions {
|
|
|
106
120
|
export declare class CodexServers {
|
|
107
121
|
private deps;
|
|
108
122
|
private live;
|
|
123
|
+
/** Turns lost with their server, by `<server>\n<pane>`. */
|
|
124
|
+
private lost;
|
|
109
125
|
private sink?;
|
|
110
126
|
private closed;
|
|
111
127
|
constructor(deps?: CodexServerDeps);
|
|
@@ -170,6 +186,9 @@ export declare class CodexServers {
|
|
|
170
186
|
/** Interrupt the running turn, declining the thread's parked server
|
|
171
187
|
* requests first. False when no turn is known to be running. */
|
|
172
188
|
interrupt(entry: CodexServerEntry): Promise<boolean>;
|
|
189
|
+
/** The turn the pane's worker lost with its server, while that pane still
|
|
190
|
+
* shows `threadId` (any thread when not given). */
|
|
191
|
+
lostTurn(server: string, pane: string, threadId?: string, now?: number): LostTurn | undefined;
|
|
173
192
|
/** The last finished turn of a registered thread and the running one, for
|
|
174
193
|
* the returns loop. */
|
|
175
194
|
turnState(threadId: string): {
|
|
@@ -204,13 +223,18 @@ export declare class CodexServers {
|
|
|
204
223
|
private client;
|
|
205
224
|
private connect;
|
|
206
225
|
private listen;
|
|
226
|
+
/** A server that ended on its own mid-turn: the returns loop reports the turn failed. */
|
|
227
|
+
private markLost;
|
|
207
228
|
private drop;
|
|
208
229
|
private forget;
|
|
209
|
-
private read;
|
|
210
230
|
/** One server's registry writes run in order, each with the entry as it is
|
|
211
231
|
* then, so an earlier write that finishes late never lands over a newer one. */
|
|
212
232
|
private save;
|
|
213
233
|
}
|
|
234
|
+
/** Registered servers still running inside the systemd service `unit`
|
|
235
|
+
* (`phren-hook.service`): stopping it ends them and cuts off their turns.
|
|
236
|
+
* Servers a Hook with scopes started run outside it. */
|
|
237
|
+
export declare function serversInService(unit: string, cgroup?: (pid: number) => string | undefined): Promise<CodexServerEntry[]>;
|
|
214
238
|
/** The Hook's servers: launch, prompt and keys routes, identity and the
|
|
215
239
|
* approval store all see the same registry. */
|
|
216
240
|
export declare const codexServers: CodexServers;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
2
3
|
import { mkdir, mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
|
3
4
|
import { tmpdir } from "node:os";
|
|
4
5
|
import path from "node:path";
|
|
@@ -16,7 +17,9 @@ import { atomic, bridgeRoot, id, object, objects, serverName } from "./protocol.
|
|
|
16
17
|
* approvals (server requests, no hold timeout); whatever the owner does in the
|
|
17
18
|
* pane reaches the same thread. The registry under
|
|
18
19
|
* `<bridge>/codex-servers/<id>/server.json` lets a restarted Hook find each
|
|
19
|
-
* running server again and reconnect to its thread.
|
|
20
|
+
* running server again and reconnect to its thread. Under systemd each server
|
|
21
|
+
* runs in its own scope (`phren-codex-<id>.scope`), outside the Hook's
|
|
22
|
+
* service, so stopping or restarting the Hook does not end it.
|
|
20
23
|
*/
|
|
21
24
|
const REGISTRY = "codex-servers";
|
|
22
25
|
/** A Unix socket path is limited to about 104 bytes (macOS) / 108 (Linux). */
|
|
@@ -24,6 +27,8 @@ const MAX_SOCKET_PATH = 100;
|
|
|
24
27
|
/** A pane that shows no Codex for this long no longer runs the worker. */
|
|
25
28
|
const AGENT_GONE_MS = 120_000;
|
|
26
29
|
const CLIENT_NAME = "phren_hook";
|
|
30
|
+
/** How long a turn lost with its server is reported to the returns loop. */
|
|
31
|
+
const LOST_MS = 24 * 60 * 60 * 1000;
|
|
27
32
|
const QUESTION_METHODS = new Set(["item/tool/requestUserInput", "mcpServer/elicitation/request"]);
|
|
28
33
|
const entrySchema = z.object({
|
|
29
34
|
id: z.string().regex(/^[a-f0-9]{12}$/),
|
|
@@ -74,7 +79,20 @@ const defaultDeps = {
|
|
|
74
79
|
catch { /* already gone */ }
|
|
75
80
|
}
|
|
76
81
|
},
|
|
82
|
+
scope: serverId => process.platform === "linux" && serviceCgroup() ? `phren-codex-${serverId}.scope` : undefined,
|
|
77
83
|
};
|
|
84
|
+
/** The systemd service cgroup a process runs in (`/proc/<pid>/cgroup`, cgroup
|
|
85
|
+
* v2), or undefined outside a service: a terminal, a scope, macOS. */
|
|
86
|
+
export function serviceCgroup(pid = "self") {
|
|
87
|
+
try {
|
|
88
|
+
const line = readFileSync(`/proc/${pid}/cgroup`, "utf8").split("\n").find(candidate => candidate.startsWith("0::"));
|
|
89
|
+
const group = line?.slice(3).trim();
|
|
90
|
+
return group?.endsWith(".service") ? group : undefined;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
78
96
|
/** `PHREN_CODEX_APP_SERVER=off` keeps every Codex launch on the typed path. */
|
|
79
97
|
export function codexAppServerEnabled(env = process.env, platform = process.platform) {
|
|
80
98
|
// The server listens on a unix socket and the pane joins it with
|
|
@@ -117,6 +135,7 @@ export function serverEnvironment(base, extra) {
|
|
|
117
135
|
return { ...env, ...extra };
|
|
118
136
|
}
|
|
119
137
|
export function codexServersRoot() { return path.join(bridgeRoot(), REGISTRY); }
|
|
138
|
+
export const LOST_TURN = "The worker's Codex server stopped before its turn finished (the Phren Hook restarted with it, or it crashed), so the turn will not finish. Resume the thread or dispatch the work again.";
|
|
120
139
|
/** Nothing was sent: the server could not be reached. */
|
|
121
140
|
export class CodexServerUnavailable extends Error {
|
|
122
141
|
constructor(message) { super(message); this.name = "CodexServerUnavailable"; }
|
|
@@ -124,6 +143,8 @@ export class CodexServerUnavailable extends Error {
|
|
|
124
143
|
export class CodexServers {
|
|
125
144
|
deps;
|
|
126
145
|
live = new Map();
|
|
146
|
+
/** Turns lost with their server, by `<server>\n<pane>`. */
|
|
147
|
+
lost = new Map();
|
|
127
148
|
sink;
|
|
128
149
|
closed = false;
|
|
129
150
|
constructor(deps = defaultDeps) {
|
|
@@ -166,8 +187,17 @@ export class CodexServers {
|
|
|
166
187
|
throw new Error(`The Codex server socket path is too long: ${socket}`);
|
|
167
188
|
await mkdir(codexServersRoot(), { recursive: true, mode: 0o700 });
|
|
168
189
|
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
169
|
-
const
|
|
170
|
-
config: serverConfig(), replaceEnv: true, env: serverEnvironment(process.env, { ...(options.env ?? {}), [CODEX_SERVER_ENV]: serverId }) }
|
|
190
|
+
const spawnOptions = { socketPath: socket, cwd: options.cwd, detached: true, logFile: path.join(directory, "server.log"),
|
|
191
|
+
config: serverConfig(), replaceEnv: true, env: serverEnvironment(process.env, { ...(options.env ?? {}), [CODEX_SERVER_ENV]: serverId }) };
|
|
192
|
+
const scope = this.deps.scope?.(serverId);
|
|
193
|
+
const handle = await (scope
|
|
194
|
+
// No systemd-run, or no user manager to ask: the server runs in the
|
|
195
|
+
// Hook's service as before, and a Hook restart ends it.
|
|
196
|
+
? this.deps.spawn({ ...spawnOptions, scope }).catch(error => {
|
|
197
|
+
logger.warn("codex-servers", `Could not start the Codex server in its own scope ${scope}; it will stop with the Hook: ${error instanceof Error ? error.message : String(error)}`);
|
|
198
|
+
return this.deps.spawn(spawnOptions);
|
|
199
|
+
})
|
|
200
|
+
: this.deps.spawn(spawnOptions)).catch(async (error) => {
|
|
171
201
|
await rm(directory, { recursive: true, force: true }).catch(() => undefined);
|
|
172
202
|
throw error;
|
|
173
203
|
});
|
|
@@ -195,6 +225,7 @@ export class CodexServers {
|
|
|
195
225
|
}
|
|
196
226
|
await this.save(entry);
|
|
197
227
|
this.live.set(serverId, live);
|
|
228
|
+
this.lost.delete(paneKey(place.server, place.pane));
|
|
198
229
|
const args = entry.threadId ? ["resume", entry.threadId, "--remote", `unix://${socket}`]
|
|
199
230
|
: ["--remote", `unix://${socket}`, ...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["-c", `model_reasoning_effort=${options.effort}`] : []), ...(options.remoteArgs ?? [])];
|
|
200
231
|
return { entry, args };
|
|
@@ -222,8 +253,10 @@ export class CodexServers {
|
|
|
222
253
|
for (const name of names.slice(0, 256)) {
|
|
223
254
|
if (!codexServerId.safeParse(name).success || [...this.live.values()].some(live => live.entry.id === name))
|
|
224
255
|
continue;
|
|
225
|
-
const entry = await
|
|
256
|
+
const entry = await readEntry(name);
|
|
226
257
|
if (!entry || !this.deps.alive(entry.pid)) {
|
|
258
|
+
if (entry)
|
|
259
|
+
this.markLost(entry);
|
|
227
260
|
await this.forget(name);
|
|
228
261
|
continue;
|
|
229
262
|
}
|
|
@@ -374,6 +407,18 @@ export class CodexServers {
|
|
|
374
407
|
this.sink?.resolved(this.target(live.entry), request.requestId);
|
|
375
408
|
return true;
|
|
376
409
|
}
|
|
410
|
+
/** The turn the pane's worker lost with its server, while that pane still
|
|
411
|
+
* shows `threadId` (any thread when not given). */
|
|
412
|
+
lostTurn(server, pane, threadId, now = Date.now()) {
|
|
413
|
+
const key = paneKey(server, pane), lost = this.lost.get(key);
|
|
414
|
+
if (!lost)
|
|
415
|
+
return undefined;
|
|
416
|
+
if (now - Date.parse(lost.at) >= LOST_MS) {
|
|
417
|
+
this.lost.delete(key);
|
|
418
|
+
return undefined;
|
|
419
|
+
}
|
|
420
|
+
return threadId === undefined || threadId === lost.threadId ? lost : undefined;
|
|
421
|
+
}
|
|
377
422
|
/** The last finished turn of a registered thread and the running one, for
|
|
378
423
|
* the returns loop. */
|
|
379
424
|
turnState(threadId) {
|
|
@@ -390,6 +435,7 @@ export class CodexServers {
|
|
|
390
435
|
if (entry.server !== server)
|
|
391
436
|
continue;
|
|
392
437
|
if (!this.deps.alive(entry.pid)) {
|
|
438
|
+
this.markLost(entry);
|
|
393
439
|
await this.drop(live);
|
|
394
440
|
continue;
|
|
395
441
|
}
|
|
@@ -421,6 +467,7 @@ export class CodexServers {
|
|
|
421
467
|
if (running.includes(live.entry.server))
|
|
422
468
|
continue;
|
|
423
469
|
if (!this.deps.alive(live.entry.pid)) {
|
|
470
|
+
this.markLost(live.entry);
|
|
424
471
|
await this.drop(live);
|
|
425
472
|
continue;
|
|
426
473
|
}
|
|
@@ -481,7 +528,7 @@ export class CodexServers {
|
|
|
481
528
|
this.live.clear();
|
|
482
529
|
}
|
|
483
530
|
/** For tests: forget everything without touching processes. */
|
|
484
|
-
reset() { this.close(); this.closed = false; }
|
|
531
|
+
reset() { this.close(); this.lost.clear(); this.closed = false; }
|
|
485
532
|
/** Resolves once every registry write started so far has finished. */
|
|
486
533
|
async saved() {
|
|
487
534
|
await Promise.all([...this.saving.values()].map(write => write.catch(() => undefined)));
|
|
@@ -600,6 +647,14 @@ export class CodexServers {
|
|
|
600
647
|
const offClose = client.onClose?.(socketClosed);
|
|
601
648
|
live.off = () => { off(); offClose?.(); };
|
|
602
649
|
}
|
|
650
|
+
/** A server that ended on its own mid-turn: the returns loop reports the turn failed. */
|
|
651
|
+
markLost(entry) {
|
|
652
|
+
if (!entry.activeTurn || !entry.threadId)
|
|
653
|
+
return;
|
|
654
|
+
logger.warn("codex-servers", `The Codex server for ${entry.server} ${entry.pane} ended during turn ${entry.activeTurn}`);
|
|
655
|
+
this.lost.set(paneKey(entry.server, entry.pane), { threadId: entry.threadId, turn: entry.activeTurn,
|
|
656
|
+
...(entry.dispatchId ? { dispatchId: entry.dispatchId } : {}), at: new Date().toISOString() });
|
|
657
|
+
}
|
|
603
658
|
async drop(live) {
|
|
604
659
|
live.off?.();
|
|
605
660
|
live.client?.close();
|
|
@@ -610,15 +665,6 @@ export class CodexServers {
|
|
|
610
665
|
async forget(serverId) {
|
|
611
666
|
await rm(path.join(codexServersRoot(), codexServerId.parse(serverId)), { recursive: true, force: true }).catch(() => undefined);
|
|
612
667
|
}
|
|
613
|
-
async read(serverId) {
|
|
614
|
-
try {
|
|
615
|
-
const parsed = entrySchema.safeParse(JSON.parse(await readFile(path.join(codexServersRoot(), serverId, "server.json"), "utf8")));
|
|
616
|
-
return parsed.success && parsed.data.id === serverId ? parsed.data : undefined;
|
|
617
|
-
}
|
|
618
|
-
catch {
|
|
619
|
-
return undefined;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
668
|
/** One server's registry writes run in order, each with the entry as it is
|
|
623
669
|
* then, so an earlier write that finishes late never lands over a newer one. */
|
|
624
670
|
save(entry) {
|
|
@@ -631,6 +677,24 @@ export class CodexServers {
|
|
|
631
677
|
return next;
|
|
632
678
|
}
|
|
633
679
|
}
|
|
680
|
+
const paneKey = (server, pane) => `${server}\n${pane}`;
|
|
681
|
+
async function readEntry(serverId) {
|
|
682
|
+
try {
|
|
683
|
+
const parsed = entrySchema.safeParse(JSON.parse(await readFile(path.join(codexServersRoot(), serverId, "server.json"), "utf8")));
|
|
684
|
+
return parsed.success && parsed.data.id === serverId ? parsed.data : undefined;
|
|
685
|
+
}
|
|
686
|
+
catch {
|
|
687
|
+
return undefined;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
/** Registered servers still running inside the systemd service `unit`
|
|
691
|
+
* (`phren-hook.service`): stopping it ends them and cuts off their turns.
|
|
692
|
+
* Servers a Hook with scopes started run outside it. */
|
|
693
|
+
export async function serversInService(unit, cgroup = serviceCgroup) {
|
|
694
|
+
const names = await readdir(codexServersRoot()).catch(() => []);
|
|
695
|
+
const entries = await Promise.all(names.filter(name => codexServerId.safeParse(name).success).slice(0, 256).map(readEntry));
|
|
696
|
+
return entries.filter((entry) => !!entry && cgroup(entry.pid)?.endsWith(`/${unit}`) === true);
|
|
697
|
+
}
|
|
634
698
|
/** The Hook's servers: launch, prompt and keys routes, identity and the
|
|
635
699
|
* approval store all see the same registry. */
|
|
636
700
|
export const codexServers = new CodexServers();
|
package/dist/bridge/command.js
CHANGED
|
@@ -192,7 +192,7 @@ export async function runBridge(args, version) {
|
|
|
192
192
|
break;
|
|
193
193
|
case "install":
|
|
194
194
|
case "update":
|
|
195
|
-
await install(version, args.includes("--no-service"));
|
|
195
|
+
await install(version, args.includes("--no-service"), args.includes("--force"));
|
|
196
196
|
break;
|
|
197
197
|
case "uninstall":
|
|
198
198
|
await uninstall();
|
|
@@ -2,6 +2,7 @@ import { sessionStalls } from "./stalls.js";
|
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { type OriginPane, type Receipt } from "./dispatch.js";
|
|
4
4
|
import { type BriefArrival } from "./launch-brief.js";
|
|
5
|
+
import { type LostTurn } from "./codex-servers.js";
|
|
5
6
|
import { findGrant } from "./grants.js";
|
|
6
7
|
import { peerRequest, type HookPeer } from "./peers.js";
|
|
7
8
|
import { type Json, type Provider, type Target } from "./protocol.js";
|
|
@@ -99,6 +100,8 @@ export interface WorkerReaders {
|
|
|
99
100
|
approval?: (target: Target) => Json | undefined;
|
|
100
101
|
now?: () => number;
|
|
101
102
|
stall?: typeof sessionStalls.observe;
|
|
103
|
+
/** The turn a Codex pane lost with its app-server, which no Stop will end. */
|
|
104
|
+
lost?: (server: string, pane: string, session?: string) => LostTurn | undefined;
|
|
102
105
|
}
|
|
103
106
|
/** The default readers with the approval reader of the Hook that runs the workers. */
|
|
104
107
|
export declare const workerReaders: (approval: NonNullable<WorkerReaders["approval"]>) => WorkerReaders;
|
|
@@ -4,6 +4,7 @@ import { z } from "zod";
|
|
|
4
4
|
import { logger } from "../logger.js";
|
|
5
5
|
import { arrivalOf, dispatchStatus, updateReceipt } from "./dispatch.js";
|
|
6
6
|
import { briefArrival, briefId } from "./launch-brief.js";
|
|
7
|
+
import { codexServers, LOST_TURN } from "./codex-servers.js";
|
|
7
8
|
import { findGrant } from "./grants.js";
|
|
8
9
|
import { findPane, paneIdentity, sharedSnapshot } from "./herdr.js";
|
|
9
10
|
import { handOff } from "./hand-off.js";
|
|
@@ -57,6 +58,7 @@ const defaultReaders = {
|
|
|
57
58
|
finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(undefined),
|
|
58
59
|
turn: paneTurn,
|
|
59
60
|
stall: (target, pane) => sessionStalls.observe(target, pane),
|
|
61
|
+
lost: (server, pane, session) => codexServers.lostTurn(server, pane, session),
|
|
60
62
|
};
|
|
61
63
|
/** The default readers with the approval reader of the Hook that runs the workers. */
|
|
62
64
|
export const workerReaders = (approval) => ({ ...defaultReaders, approval });
|
|
@@ -131,6 +133,9 @@ export async function workerStates(input, readers = defaultReaders) {
|
|
|
131
133
|
// Another conversation in the same pane means the worker is gone.
|
|
132
134
|
if (expected && current && current !== expected)
|
|
133
135
|
return { state: "gone" };
|
|
136
|
+
const lost = target.source === "codex" ? readers.lost?.(target.server, String(pane.pane_id), expected ?? current) : undefined;
|
|
137
|
+
if (lost)
|
|
138
|
+
return { state: "done", session: lost.threadId, completed: true, endedAt: lost.at, error: LOST_TURN };
|
|
134
139
|
const status = String(pane.agent_status);
|
|
135
140
|
// The record counts only for the conversation this dispatch started, in
|
|
136
141
|
// the terminal still there, and never for another dispatch's worker.
|
package/dist/bridge/install.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type ModuleSnapshot } from "../modules/runtime.js";
|
|
2
|
+
import { type CodexServerEntry } from "./codex-servers.js";
|
|
2
3
|
export declare const forcedCommand = "command=\"sh ~/.local/share/phren/bridge/dispatch\"";
|
|
3
4
|
export declare function upgradeKeys(text: string): {
|
|
4
5
|
text: string;
|
|
@@ -40,7 +41,13 @@ export declare function detectGateway(env?: NodeJS.ProcessEnv): Promise<GatewayK
|
|
|
40
41
|
export declare function gatewayScript(gateway: GatewayKind, environment: GatewayEnvironment): string;
|
|
41
42
|
/** The commands that restart the Hook in `domain`, printed when launchd refuses. */
|
|
42
43
|
export declare function launchCommands(domain: string, plist: string): string[];
|
|
43
|
-
|
|
44
|
+
/** How long install waits for Codex turns that would stop with the Hook. */
|
|
45
|
+
export declare const CODEX_TURN_WAIT_MS: number;
|
|
46
|
+
/** Codex workers still running inside the Hook's service (started by a Hook
|
|
47
|
+
* from before each server got its own scope) stop with it, mid-turn or not.
|
|
48
|
+
* Say which, and wait up to `waitMs` for the running turns to finish. */
|
|
49
|
+
export declare function waitForCodexWorkers(waitMs?: number, inService?: () => Promise<CodexServerEntry[]>, log?: (line: string) => void, pollMs?: number): Promise<void>;
|
|
50
|
+
export declare function install(version: string, noService?: boolean, force?: boolean): Promise<void>;
|
|
44
51
|
export declare function uninstall(): Promise<void>;
|
|
45
52
|
interface SettingsEdit {
|
|
46
53
|
file: string;
|
package/dist/bridge/install.js
CHANGED
|
@@ -18,6 +18,7 @@ import { FAST_HOOK_SOURCE, fastHookPath } from "./hook-fast.js";
|
|
|
18
18
|
import { installAskpass, removeAskpass } from "./sudo.js";
|
|
19
19
|
import { readStoredVoice, SPEECH_VOICE_ENV, writeSpeechVoice } from "./speech-voice.js";
|
|
20
20
|
import { carryCodexHookTrust } from "./codex-hook-trust.js";
|
|
21
|
+
import { serversInService } from "./codex-servers.js";
|
|
21
22
|
const exec = promisify(execFile);
|
|
22
23
|
const label = "com.phren.hook";
|
|
23
24
|
const unit = "phren-hook.service";
|
|
@@ -199,6 +200,30 @@ async function startService() {
|
|
|
199
200
|
await exec("systemctl", ["--user", "enable", "--now", unit]);
|
|
200
201
|
}
|
|
201
202
|
}
|
|
203
|
+
/** How long install waits for Codex turns that would stop with the Hook. */
|
|
204
|
+
export const CODEX_TURN_WAIT_MS = 10 * 60 * 1000;
|
|
205
|
+
/** Codex workers still running inside the Hook's service (started by a Hook
|
|
206
|
+
* from before each server got its own scope) stop with it, mid-turn or not.
|
|
207
|
+
* Say which, and wait up to `waitMs` for the running turns to finish. */
|
|
208
|
+
export async function waitForCodexWorkers(waitMs = CODEX_TURN_WAIT_MS, inService = () => serversInService(unit), log = console.log, pollMs = 5_000) {
|
|
209
|
+
if (process.platform !== "linux")
|
|
210
|
+
return;
|
|
211
|
+
const describe = (entry) => `${entry.pane}${entry.dispatchId ? ` (dispatch ${entry.dispatchId.slice(0, 8)})` : ""}${entry.activeTurn ? ", turn running" : ", idle"}`;
|
|
212
|
+
let workers = await inService();
|
|
213
|
+
if (!workers.length)
|
|
214
|
+
return;
|
|
215
|
+
log(`${workers.length} Codex worker${workers.length === 1 ? "" : "s"} run inside the Phren Hook's service and will stop when it restarts: ${workers.map(describe).join("; ")}.`
|
|
216
|
+
+ " Hooks from this version on start each Codex server in its own scope, so later restarts leave them running.");
|
|
217
|
+
const deadline = Date.now() + waitMs;
|
|
218
|
+
while (workers.some(entry => entry.activeTurn) && Date.now() < deadline) {
|
|
219
|
+
log(`Waiting up to ${Math.ceil((deadline - Date.now()) / 60_000)} min for ${workers.filter(entry => entry.activeTurn).length} running Codex turn(s) to finish. Pass --force to restart now.`);
|
|
220
|
+
await new Promise(resolve => setTimeout(resolve, pollMs));
|
|
221
|
+
workers = await inService();
|
|
222
|
+
}
|
|
223
|
+
const cut = workers.filter(entry => entry.activeTurn);
|
|
224
|
+
if (cut.length)
|
|
225
|
+
log(`Restarting anyway: ${cut.map(describe).join("; ")} will stop mid-turn and return failed.`);
|
|
226
|
+
}
|
|
202
227
|
async function serviceReady(version) {
|
|
203
228
|
for (let i = 0; i < 50; i++) {
|
|
204
229
|
try {
|
|
@@ -211,7 +236,7 @@ async function serviceReady(version) {
|
|
|
211
236
|
}
|
|
212
237
|
return false;
|
|
213
238
|
}
|
|
214
|
-
export async function install(version, noService = false) {
|
|
239
|
+
export async function install(version, noService = false, force = false) {
|
|
215
240
|
if (!["darwin", "linux"].includes(process.platform))
|
|
216
241
|
throw new Error("Phren Hook supports macOS and Linux.");
|
|
217
242
|
if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version))
|
|
@@ -264,8 +289,10 @@ export async function install(version, noService = false) {
|
|
|
264
289
|
else {
|
|
265
290
|
const folder = path.join(homedir(), ".config/systemd/user");
|
|
266
291
|
await mkdir(folder, { recursive: true });
|
|
267
|
-
await atomic(path.join(folder, unit), `[Unit]\nDescription=Phren Hook\n[Service]\nExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve\nNice=-5\nEnvironment=${systemdQuote("PATH=" + environmentPath)} ${systemdQuote("PHREN_BRIDGE_HOME=" + root)} ${systemdQuote("PHREN_HERDR_HOME=" + herdr)} ${systemdQuote("PHREN_PATH=" + modules.store)} ${systemdQuote("PHREN_PROFILE=" + modules.profile)}\nRestart=
|
|
292
|
+
await atomic(path.join(folder, unit), `[Unit]\nDescription=Phren Hook\n[Service]\nExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve\nNice=-5\nEnvironment=${systemdQuote("PATH=" + environmentPath)} ${systemdQuote("PHREN_BRIDGE_HOME=" + root)} ${systemdQuote("PHREN_HERDR_HOME=" + herdr)} ${systemdQuote("PHREN_PATH=" + modules.store)} ${systemdQuote("PHREN_PROFILE=" + modules.profile)}\nRestart=always\nRestartSec=3\nUMask=0077\n[Install]\nWantedBy=default.target\n`);
|
|
268
293
|
}
|
|
294
|
+
if (!force)
|
|
295
|
+
await waitForCodexWorkers();
|
|
269
296
|
await stopService();
|
|
270
297
|
}
|
|
271
298
|
await activate(version);
|
|
@@ -310,7 +337,7 @@ export async function install(version, noService = false) {
|
|
|
310
337
|
}
|
|
311
338
|
console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
|
|
312
339
|
}
|
|
313
|
-
await atomic(path.join(root, "installed.json"), JSON.stringify({ version, previous: previous?.version === version ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
|
|
340
|
+
await atomic(path.join(root, "installed.json"), JSON.stringify({ version, previous: previous?.version === version ? previous.previous : previous?.version, node: process.execPath, gateway, store: modules.store }, null, 2) + "\n");
|
|
314
341
|
// Last, so a failed install restores hooks.json without leaving trust for entries it no longer has.
|
|
315
342
|
await carryCodexHookTrust(program, codexHooksBefore(hookEdits));
|
|
316
343
|
console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
|
|
@@ -518,13 +545,25 @@ export async function rollback() {
|
|
|
518
545
|
const edits = await planAgentHooks(program, false, moduleSnapshot(defaultPhrenPath(), undefined, true), await currentHasFastHook(root));
|
|
519
546
|
await applyAgentHooks(edits);
|
|
520
547
|
await carryCodexHookTrust(program, codexHooksBefore(edits));
|
|
521
|
-
await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version }) + "\n");
|
|
548
|
+
await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version, ...(config.store ? { store: config.store } : {}) }) + "\n");
|
|
522
549
|
}
|
|
523
550
|
export async function reconcileModuleHooks(store, profile) {
|
|
524
551
|
const modules = moduleSnapshot(store, profile);
|
|
525
552
|
const root = bridgeRoot();
|
|
526
553
|
// Synced enablement alone never installs a host service or enrolls a key.
|
|
527
|
-
|
|
554
|
+
const installed = await missingFile(readFile(path.join(root, "installed.json"), "utf8"));
|
|
555
|
+
if (!installed)
|
|
556
|
+
return;
|
|
557
|
+
// The Hook serves the store it was installed with. `phren init` or `link`
|
|
558
|
+
// on another store (a scratch store, a test's) must not stop it or rewrite
|
|
559
|
+
// its agent hooks: a test run inside a Hook-launched worker did exactly that.
|
|
560
|
+
const served = (() => { try {
|
|
561
|
+
return object(JSON.parse(installed)).store;
|
|
562
|
+
}
|
|
563
|
+
catch {
|
|
564
|
+
return undefined;
|
|
565
|
+
} })();
|
|
566
|
+
if (typeof served === "string" && path.resolve(served) !== path.resolve(store))
|
|
528
567
|
return;
|
|
529
568
|
const program = path.join(root, "current/bridge-hook.mjs");
|
|
530
569
|
const edits = await planAgentHooks(program, false, modules, await currentHasFastHook(root));
|
package/dist/bridge-hook.mjs
CHANGED
|
@@ -23851,30 +23851,30 @@ var init_claude_accounts = __esm({
|
|
|
23851
23851
|
|
|
23852
23852
|
// src/bridge/pane-accounts.ts
|
|
23853
23853
|
import path4 from "node:path";
|
|
23854
|
-
function entry(
|
|
23855
|
-
let current2 = known.get(
|
|
23854
|
+
function entry(paneKey3, terminal2) {
|
|
23855
|
+
let current2 = known.get(paneKey3);
|
|
23856
23856
|
if (current2 && terminal2 && current2.terminal && current2.terminal !== terminal2) {
|
|
23857
|
-
known.delete(
|
|
23857
|
+
known.delete(paneKey3);
|
|
23858
23858
|
current2 = void 0;
|
|
23859
23859
|
}
|
|
23860
23860
|
if (!current2) {
|
|
23861
23861
|
while (known.size >= MAX_PANES) known.delete(known.keys().next().value);
|
|
23862
23862
|
current2 = {};
|
|
23863
|
-
known.set(
|
|
23863
|
+
known.set(paneKey3, current2);
|
|
23864
23864
|
}
|
|
23865
23865
|
if (terminal2) current2.terminal = terminal2;
|
|
23866
23866
|
return current2;
|
|
23867
23867
|
}
|
|
23868
|
-
function recordPaneAccount(
|
|
23869
|
-
entry(
|
|
23868
|
+
function recordPaneAccount(paneKey3, accountId, terminal2) {
|
|
23869
|
+
entry(paneKey3, terminal2).launched = accountId;
|
|
23870
23870
|
}
|
|
23871
|
-
function notePaneTranscript(
|
|
23871
|
+
function notePaneTranscript(paneKey3, file2, terminal2) {
|
|
23872
23872
|
if (typeof file2 !== "string" || !path4.isAbsolute(file2) || file2.length > 4096) return;
|
|
23873
23873
|
const home = claudeHomeOfPath(file2);
|
|
23874
|
-
if (home) entry(
|
|
23874
|
+
if (home) entry(paneKey3, terminal2).fromFile = home.id;
|
|
23875
23875
|
}
|
|
23876
|
-
function paneAccount(
|
|
23877
|
-
const current2 = known.get(
|
|
23876
|
+
function paneAccount(paneKey3, terminal2) {
|
|
23877
|
+
const current2 = known.get(paneKey3);
|
|
23878
23878
|
if (!current2 || terminal2 && current2.terminal && current2.terminal !== terminal2) return void 0;
|
|
23879
23879
|
const id2 = current2.fromFile ?? current2.launched;
|
|
23880
23880
|
const home = id2 ? claudeHome(id2) : void 0;
|
|
@@ -32684,8 +32684,10 @@ async function spawnAppServer(options) {
|
|
|
32684
32684
|
await rm4(options.socketPath, { force: true });
|
|
32685
32685
|
const log2 = options.logFile ? await open7(options.logFile, "a", 384) : void 0;
|
|
32686
32686
|
let child;
|
|
32687
|
+
const command = [codexBin, "app-server", ...(options.config ?? []).flatMap((value2) => ["-c", value2]), "--listen", `unix://${options.socketPath}`];
|
|
32688
|
+
const [file2, ...args] = options.scope ? ["systemd-run", "--user", "--scope", "--quiet", "--collect", `--unit=${options.scope}`, "--", ...command] : command;
|
|
32687
32689
|
try {
|
|
32688
|
-
child = spawn2(
|
|
32690
|
+
child = spawn2(file2, args, {
|
|
32689
32691
|
cwd: options.cwd,
|
|
32690
32692
|
env,
|
|
32691
32693
|
detached: options.detached === true,
|
|
@@ -32999,9 +33001,19 @@ var init_codex_app_server = __esm({
|
|
|
32999
33001
|
|
|
33000
33002
|
// src/bridge/codex-servers.ts
|
|
33001
33003
|
import { randomBytes } from "node:crypto";
|
|
33004
|
+
import { readFileSync as readFileSync10 } from "node:fs";
|
|
33002
33005
|
import { mkdir as mkdir8, mkdtemp as mkdtemp2, readdir as readdir7, readFile as readFile12, rm as rm5 } from "node:fs/promises";
|
|
33003
33006
|
import { tmpdir } from "node:os";
|
|
33004
33007
|
import path27 from "node:path";
|
|
33008
|
+
function serviceCgroup(pid = "self") {
|
|
33009
|
+
try {
|
|
33010
|
+
const line = readFileSync10(`/proc/${pid}/cgroup`, "utf8").split("\n").find((candidate) => candidate.startsWith("0::"));
|
|
33011
|
+
const group = line?.slice(3).trim();
|
|
33012
|
+
return group?.endsWith(".service") ? group : void 0;
|
|
33013
|
+
} catch {
|
|
33014
|
+
return void 0;
|
|
33015
|
+
}
|
|
33016
|
+
}
|
|
33005
33017
|
function codexAppServerEnabled(env = process.env, platform = process.platform) {
|
|
33006
33018
|
if (platform === "win32") return false;
|
|
33007
33019
|
return !/^(?:0|off|false|no)$/i.test(env.PHREN_CODEX_APP_SERVER ?? "");
|
|
@@ -33021,7 +33033,20 @@ function serverEnvironment(base, extra) {
|
|
|
33021
33033
|
function codexServersRoot() {
|
|
33022
33034
|
return path27.join(bridgeRoot(), REGISTRY);
|
|
33023
33035
|
}
|
|
33024
|
-
|
|
33036
|
+
async function readEntry(serverId) {
|
|
33037
|
+
try {
|
|
33038
|
+
const parsed = entrySchema.safeParse(JSON.parse(await readFile12(path27.join(codexServersRoot(), serverId, "server.json"), "utf8")));
|
|
33039
|
+
return parsed.success && parsed.data.id === serverId ? parsed.data : void 0;
|
|
33040
|
+
} catch {
|
|
33041
|
+
return void 0;
|
|
33042
|
+
}
|
|
33043
|
+
}
|
|
33044
|
+
async function serversInService(unit2, cgroup = serviceCgroup) {
|
|
33045
|
+
const names = await readdir7(codexServersRoot()).catch(() => []);
|
|
33046
|
+
const entries2 = await Promise.all(names.filter((name) => codexServerId.safeParse(name).success).slice(0, 256).map(readEntry));
|
|
33047
|
+
return entries2.filter((entry2) => !!entry2 && cgroup(entry2.pid)?.endsWith(`/${unit2}`) === true);
|
|
33048
|
+
}
|
|
33049
|
+
var REGISTRY, MAX_SOCKET_PATH, AGENT_GONE_MS, CLIENT_NAME, LOST_MS, QUESTION_METHODS, entrySchema, defaultDeps, BLOCKING_QUESTION_INSTRUCTIONS, CODEX_SERVER_ENV, codexServerId, LOST_TURN, CodexServerUnavailable, CodexServers, paneKey, codexServers;
|
|
33025
33050
|
var init_codex_servers = __esm({
|
|
33026
33051
|
"src/bridge/codex-servers.ts"() {
|
|
33027
33052
|
"use strict";
|
|
@@ -33033,6 +33058,7 @@ var init_codex_servers = __esm({
|
|
|
33033
33058
|
MAX_SOCKET_PATH = 100;
|
|
33034
33059
|
AGENT_GONE_MS = 12e4;
|
|
33035
33060
|
CLIENT_NAME = "phren_hook";
|
|
33061
|
+
LOST_MS = 24 * 60 * 60 * 1e3;
|
|
33036
33062
|
QUESTION_METHODS = /* @__PURE__ */ new Set(["item/tool/requestUserInput", "mcpServer/elicitation/request"]);
|
|
33037
33063
|
entrySchema = external_exports.object({
|
|
33038
33064
|
id: external_exports.string().regex(/^[a-f0-9]{12}$/),
|
|
@@ -33082,11 +33108,13 @@ var init_codex_servers = __esm({
|
|
|
33082
33108
|
} catch {
|
|
33083
33109
|
}
|
|
33084
33110
|
}
|
|
33085
|
-
}
|
|
33111
|
+
},
|
|
33112
|
+
scope: (serverId) => process.platform === "linux" && serviceCgroup() ? `phren-codex-${serverId}.scope` : void 0
|
|
33086
33113
|
};
|
|
33087
33114
|
BLOCKING_QUESTION_INSTRUCTIONS = "When you need the user to decide or supply something you cannot find out yourself, ask with the `request_user_input` tool, which waits for the answer; the user answers it from their phone or this terminal. Do not use `request_user_input_async` for that, and never write a multiple-choice question as a plain message. Ask only when a reasonable assumption would be risky.";
|
|
33088
33115
|
CODEX_SERVER_ENV = "PHREN_CODEX_SERVER";
|
|
33089
33116
|
codexServerId = external_exports.string().regex(/^[a-f0-9]{12}$/);
|
|
33117
|
+
LOST_TURN = "The worker's Codex server stopped before its turn finished (the Phren Hook restarted with it, or it crashed), so the turn will not finish. Resume the thread or dispatch the work again.";
|
|
33090
33118
|
CodexServerUnavailable = class extends Error {
|
|
33091
33119
|
constructor(message) {
|
|
33092
33120
|
super(message);
|
|
@@ -33099,6 +33127,8 @@ var init_codex_servers = __esm({
|
|
|
33099
33127
|
}
|
|
33100
33128
|
deps;
|
|
33101
33129
|
live = /* @__PURE__ */ new Map();
|
|
33130
|
+
/** Turns lost with their server, by `<server>\n<pane>`. */
|
|
33131
|
+
lost = /* @__PURE__ */ new Map();
|
|
33102
33132
|
sink;
|
|
33103
33133
|
closed = false;
|
|
33104
33134
|
setDeps(deps2) {
|
|
@@ -33142,7 +33172,7 @@ var init_codex_servers = __esm({
|
|
|
33142
33172
|
if (Buffer.byteLength(socket) > MAX_SOCKET_PATH) throw new Error(`The Codex server socket path is too long: ${socket}`);
|
|
33143
33173
|
await mkdir8(codexServersRoot(), { recursive: true, mode: 448 });
|
|
33144
33174
|
await mkdir8(directory, { recursive: true, mode: 448 });
|
|
33145
|
-
const
|
|
33175
|
+
const spawnOptions = {
|
|
33146
33176
|
socketPath: socket,
|
|
33147
33177
|
cwd: options.cwd,
|
|
33148
33178
|
detached: true,
|
|
@@ -33150,7 +33180,12 @@ var init_codex_servers = __esm({
|
|
|
33150
33180
|
config: serverConfig(),
|
|
33151
33181
|
replaceEnv: true,
|
|
33152
33182
|
env: serverEnvironment(process.env, { ...options.env ?? {}, [CODEX_SERVER_ENV]: serverId })
|
|
33153
|
-
}
|
|
33183
|
+
};
|
|
33184
|
+
const scope = this.deps.scope?.(serverId);
|
|
33185
|
+
const handle = await (scope ? this.deps.spawn({ ...spawnOptions, scope }).catch((error62) => {
|
|
33186
|
+
logger.warn("codex-servers", `Could not start the Codex server in its own scope ${scope}; it will stop with the Hook: ${error62 instanceof Error ? error62.message : String(error62)}`);
|
|
33187
|
+
return this.deps.spawn(spawnOptions);
|
|
33188
|
+
}) : this.deps.spawn(spawnOptions)).catch(async (error62) => {
|
|
33154
33189
|
await rm5(directory, { recursive: true, force: true }).catch(() => void 0);
|
|
33155
33190
|
throw error62;
|
|
33156
33191
|
});
|
|
@@ -33184,6 +33219,7 @@ var init_codex_servers = __esm({
|
|
|
33184
33219
|
}
|
|
33185
33220
|
await this.save(entry2);
|
|
33186
33221
|
this.live.set(serverId, live);
|
|
33222
|
+
this.lost.delete(paneKey(place.server, place.pane));
|
|
33187
33223
|
const args = entry2.threadId ? ["resume", entry2.threadId, "--remote", `unix://${socket}`] : ["--remote", `unix://${socket}`, ...options.model ? ["--model", options.model] : [], ...options.effort ? ["-c", `model_reasoning_effort=${options.effort}`] : [], ...options.remoteArgs ?? []];
|
|
33188
33224
|
return { entry: entry2, args };
|
|
33189
33225
|
} catch (error62) {
|
|
@@ -33207,8 +33243,9 @@ var init_codex_servers = __esm({
|
|
|
33207
33243
|
const names = await readdir7(codexServersRoot()).catch(() => []);
|
|
33208
33244
|
for (const name of names.slice(0, 256)) {
|
|
33209
33245
|
if (!codexServerId.safeParse(name).success || [...this.live.values()].some((live2) => live2.entry.id === name)) continue;
|
|
33210
|
-
const entry2 = await
|
|
33246
|
+
const entry2 = await readEntry(name);
|
|
33211
33247
|
if (!entry2 || !this.deps.alive(entry2.pid)) {
|
|
33248
|
+
if (entry2) this.markLost(entry2);
|
|
33212
33249
|
await this.forget(name);
|
|
33213
33250
|
continue;
|
|
33214
33251
|
}
|
|
@@ -33345,6 +33382,17 @@ var init_codex_servers = __esm({
|
|
|
33345
33382
|
for (const request9 of parked) this.sink?.resolved(this.target(live.entry), request9.requestId);
|
|
33346
33383
|
return true;
|
|
33347
33384
|
}
|
|
33385
|
+
/** The turn the pane's worker lost with its server, while that pane still
|
|
33386
|
+
* shows `threadId` (any thread when not given). */
|
|
33387
|
+
lostTurn(server, pane, threadId, now = Date.now()) {
|
|
33388
|
+
const key2 = paneKey(server, pane), lost = this.lost.get(key2);
|
|
33389
|
+
if (!lost) return void 0;
|
|
33390
|
+
if (now - Date.parse(lost.at) >= LOST_MS) {
|
|
33391
|
+
this.lost.delete(key2);
|
|
33392
|
+
return void 0;
|
|
33393
|
+
}
|
|
33394
|
+
return threadId === void 0 || threadId === lost.threadId ? lost : void 0;
|
|
33395
|
+
}
|
|
33348
33396
|
/** The last finished turn of a registered thread and the running one, for
|
|
33349
33397
|
* the returns loop. */
|
|
33350
33398
|
turnState(threadId) {
|
|
@@ -33360,6 +33408,7 @@ var init_codex_servers = __esm({
|
|
|
33360
33408
|
const entry2 = live.entry;
|
|
33361
33409
|
if (entry2.server !== server) continue;
|
|
33362
33410
|
if (!this.deps.alive(entry2.pid)) {
|
|
33411
|
+
this.markLost(entry2);
|
|
33363
33412
|
await this.drop(live);
|
|
33364
33413
|
continue;
|
|
33365
33414
|
}
|
|
@@ -33387,6 +33436,7 @@ var init_codex_servers = __esm({
|
|
|
33387
33436
|
for (const live of [...this.live.values()]) {
|
|
33388
33437
|
if (running2.includes(live.entry.server)) continue;
|
|
33389
33438
|
if (!this.deps.alive(live.entry.pid)) {
|
|
33439
|
+
this.markLost(live.entry);
|
|
33390
33440
|
await this.drop(live);
|
|
33391
33441
|
continue;
|
|
33392
33442
|
}
|
|
@@ -33438,6 +33488,7 @@ var init_codex_servers = __esm({
|
|
|
33438
33488
|
/** For tests: forget everything without touching processes. */
|
|
33439
33489
|
reset() {
|
|
33440
33490
|
this.close();
|
|
33491
|
+
this.lost.clear();
|
|
33441
33492
|
this.closed = false;
|
|
33442
33493
|
}
|
|
33443
33494
|
/** Resolves once every registry write started so far has finished. */
|
|
@@ -33541,6 +33592,17 @@ var init_codex_servers = __esm({
|
|
|
33541
33592
|
offClose?.();
|
|
33542
33593
|
};
|
|
33543
33594
|
}
|
|
33595
|
+
/** A server that ended on its own mid-turn: the returns loop reports the turn failed. */
|
|
33596
|
+
markLost(entry2) {
|
|
33597
|
+
if (!entry2.activeTurn || !entry2.threadId) return;
|
|
33598
|
+
logger.warn("codex-servers", `The Codex server for ${entry2.server} ${entry2.pane} ended during turn ${entry2.activeTurn}`);
|
|
33599
|
+
this.lost.set(paneKey(entry2.server, entry2.pane), {
|
|
33600
|
+
threadId: entry2.threadId,
|
|
33601
|
+
turn: entry2.activeTurn,
|
|
33602
|
+
...entry2.dispatchId ? { dispatchId: entry2.dispatchId } : {},
|
|
33603
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
33604
|
+
});
|
|
33605
|
+
}
|
|
33544
33606
|
async drop(live) {
|
|
33545
33607
|
live.off?.();
|
|
33546
33608
|
live.client?.close();
|
|
@@ -33551,14 +33613,6 @@ var init_codex_servers = __esm({
|
|
|
33551
33613
|
async forget(serverId) {
|
|
33552
33614
|
await rm5(path27.join(codexServersRoot(), codexServerId.parse(serverId)), { recursive: true, force: true }).catch(() => void 0);
|
|
33553
33615
|
}
|
|
33554
|
-
async read(serverId) {
|
|
33555
|
-
try {
|
|
33556
|
-
const parsed = entrySchema.safeParse(JSON.parse(await readFile12(path27.join(codexServersRoot(), serverId, "server.json"), "utf8")));
|
|
33557
|
-
return parsed.success && parsed.data.id === serverId ? parsed.data : void 0;
|
|
33558
|
-
} catch {
|
|
33559
|
-
return void 0;
|
|
33560
|
-
}
|
|
33561
|
-
}
|
|
33562
33616
|
/** One server's registry writes run in order, each with the entry as it is
|
|
33563
33617
|
* then, so an earlier write that finishes late never lands over a newer one. */
|
|
33564
33618
|
save(entry2) {
|
|
@@ -33571,6 +33625,8 @@ var init_codex_servers = __esm({
|
|
|
33571
33625
|
return next;
|
|
33572
33626
|
}
|
|
33573
33627
|
};
|
|
33628
|
+
paneKey = (server, pane) => `${server}
|
|
33629
|
+
${pane}`;
|
|
33574
33630
|
codexServers = new CodexServers();
|
|
33575
33631
|
}
|
|
33576
33632
|
});
|
|
@@ -35751,7 +35807,7 @@ var init_package_metadata = __esm({
|
|
|
35751
35807
|
__dirname = path33.dirname(fileURLToPath2(import.meta.url));
|
|
35752
35808
|
ROOT = path33.join(__dirname, "..");
|
|
35753
35809
|
PACKAGE_JSON_PATH = path33.join(ROOT, "package.json");
|
|
35754
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
35810
|
+
BUNDLED_VERSION = true ? "0.3.14" : "0.0.0";
|
|
35755
35811
|
PACKAGE_JSON = readPackageJson();
|
|
35756
35812
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
35757
35813
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -40151,6 +40207,7 @@ async function carryCodexHookTrust(program, before, env = process.env) {
|
|
|
40151
40207
|
}
|
|
40152
40208
|
|
|
40153
40209
|
// src/bridge/install.ts
|
|
40210
|
+
init_codex_servers();
|
|
40154
40211
|
var exec8 = promisify8(execFile9);
|
|
40155
40212
|
var label = "com.phren.hook";
|
|
40156
40213
|
var unit = "phren-hook.service";
|
|
@@ -40305,6 +40362,22 @@ To start it by hand:
|
|
|
40305
40362
|
await exec8("systemctl", ["--user", "enable", "--now", unit]);
|
|
40306
40363
|
}
|
|
40307
40364
|
}
|
|
40365
|
+
var CODEX_TURN_WAIT_MS = 10 * 60 * 1e3;
|
|
40366
|
+
async function waitForCodexWorkers(waitMs = CODEX_TURN_WAIT_MS, inService = () => serversInService(unit), log2 = console.log, pollMs = 5e3) {
|
|
40367
|
+
if (process.platform !== "linux") return;
|
|
40368
|
+
const describe4 = (entry2) => `${entry2.pane}${entry2.dispatchId ? ` (dispatch ${entry2.dispatchId.slice(0, 8)})` : ""}${entry2.activeTurn ? ", turn running" : ", idle"}`;
|
|
40369
|
+
let workers = await inService();
|
|
40370
|
+
if (!workers.length) return;
|
|
40371
|
+
log2(`${workers.length} Codex worker${workers.length === 1 ? "" : "s"} run inside the Phren Hook's service and will stop when it restarts: ${workers.map(describe4).join("; ")}. Hooks from this version on start each Codex server in its own scope, so later restarts leave them running.`);
|
|
40372
|
+
const deadline = Date.now() + waitMs;
|
|
40373
|
+
while (workers.some((entry2) => entry2.activeTurn) && Date.now() < deadline) {
|
|
40374
|
+
log2(`Waiting up to ${Math.ceil((deadline - Date.now()) / 6e4)} min for ${workers.filter((entry2) => entry2.activeTurn).length} running Codex turn(s) to finish. Pass --force to restart now.`);
|
|
40375
|
+
await new Promise((resolve11) => setTimeout(resolve11, pollMs));
|
|
40376
|
+
workers = await inService();
|
|
40377
|
+
}
|
|
40378
|
+
const cut = workers.filter((entry2) => entry2.activeTurn);
|
|
40379
|
+
if (cut.length) log2(`Restarting anyway: ${cut.map(describe4).join("; ")} will stop mid-turn and return failed.`);
|
|
40380
|
+
}
|
|
40308
40381
|
async function serviceReady(version3) {
|
|
40309
40382
|
for (let i = 0; i < 50; i++) {
|
|
40310
40383
|
try {
|
|
@@ -40315,7 +40388,7 @@ async function serviceReady(version3) {
|
|
|
40315
40388
|
}
|
|
40316
40389
|
return false;
|
|
40317
40390
|
}
|
|
40318
|
-
async function install(version3, noService = false) {
|
|
40391
|
+
async function install(version3, noService = false, force = false) {
|
|
40319
40392
|
if (!["darwin", "linux"].includes(process.platform)) throw new Error("Phren Hook supports macOS and Linux.");
|
|
40320
40393
|
if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version3)) throw new Error("Invalid helper version.");
|
|
40321
40394
|
const modules = activateModules(defaultPhrenPath(), void 0, true);
|
|
@@ -40374,13 +40447,14 @@ Description=Phren Hook
|
|
|
40374
40447
|
ExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve
|
|
40375
40448
|
Nice=-5
|
|
40376
40449
|
Environment=${systemdQuote("PATH=" + environmentPath)} ${systemdQuote("PHREN_BRIDGE_HOME=" + root)} ${systemdQuote("PHREN_HERDR_HOME=" + herdr)} ${systemdQuote("PHREN_PATH=" + modules.store)} ${systemdQuote("PHREN_PROFILE=" + modules.profile)}
|
|
40377
|
-
Restart=
|
|
40450
|
+
Restart=always
|
|
40378
40451
|
RestartSec=3
|
|
40379
40452
|
UMask=0077
|
|
40380
40453
|
[Install]
|
|
40381
40454
|
WantedBy=default.target
|
|
40382
40455
|
`);
|
|
40383
40456
|
}
|
|
40457
|
+
if (!force) await waitForCodexWorkers();
|
|
40384
40458
|
await stopService();
|
|
40385
40459
|
}
|
|
40386
40460
|
await activate(version3);
|
|
@@ -40419,7 +40493,7 @@ WantedBy=default.target
|
|
|
40419
40493
|
}
|
|
40420
40494
|
console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
|
|
40421
40495
|
}
|
|
40422
|
-
await atomic(path49.join(root, "installed.json"), JSON.stringify({ version: version3, previous: previous?.version === version3 ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
|
|
40496
|
+
await atomic(path49.join(root, "installed.json"), JSON.stringify({ version: version3, previous: previous?.version === version3 ? previous.previous : previous?.version, node: process.execPath, gateway, store: modules.store }, null, 2) + "\n");
|
|
40423
40497
|
await carryCodexHookTrust(program, codexHooksBefore(hookEdits));
|
|
40424
40498
|
console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
|
|
40425
40499
|
console.log(`SSH gateway: ${gateway}${gateway === "node" ? " (no socat or nc -U found)" : ""}.`);
|
|
@@ -40583,7 +40657,7 @@ async function rollback() {
|
|
|
40583
40657
|
const edits = await planAgentHooks(program, false, activateModules(defaultPhrenPath(), void 0, true), await currentHasFastHook(root));
|
|
40584
40658
|
await applyAgentHooks(edits);
|
|
40585
40659
|
await carryCodexHookTrust(program, codexHooksBefore(edits));
|
|
40586
|
-
await atomic(path49.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config3.previous, previous: config3.version }) + "\n");
|
|
40660
|
+
await atomic(path49.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config3.previous, previous: config3.version, ...config3.store ? { store: config3.store } : {} }) + "\n");
|
|
40587
40661
|
}
|
|
40588
40662
|
|
|
40589
40663
|
// src/bridge/computers.ts
|
|
@@ -42912,7 +42986,7 @@ function buildSets(input2) {
|
|
|
42912
42986
|
init_zod();
|
|
42913
42987
|
init_herdr();
|
|
42914
42988
|
init_protocol();
|
|
42915
|
-
import { lstatSync as lstatSync2, readFileSync as
|
|
42989
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync23 } from "node:fs";
|
|
42916
42990
|
import path61 from "node:path";
|
|
42917
42991
|
var recordSchema = external_exports.object({
|
|
42918
42992
|
server: serverName,
|
|
@@ -42935,7 +43009,7 @@ async function readRoleState() {
|
|
|
42935
43009
|
let text4;
|
|
42936
43010
|
try {
|
|
42937
43011
|
const info = lstatSync2(file2);
|
|
42938
|
-
text4 = info.isFile() && info.size <= 65536 ?
|
|
43012
|
+
text4 = info.isFile() && info.size <= 65536 ? readFileSync23(file2, "utf8") : "";
|
|
42939
43013
|
} catch {
|
|
42940
43014
|
text4 = void 0;
|
|
42941
43015
|
}
|
|
@@ -45659,7 +45733,7 @@ async function showSession(entry2, client, session, text4, options = {}) {
|
|
|
45659
45733
|
}
|
|
45660
45734
|
async function sendServedPrompt(entry2, session, text4, options = {}) {
|
|
45661
45735
|
const client = paneClient(entry2);
|
|
45662
|
-
const shownKey = `${
|
|
45736
|
+
const shownKey = `${paneKey2(entry2)}\0${entry2.pid}`;
|
|
45663
45737
|
const shown = session ? void 0 : shownSessions.get(shownKey);
|
|
45664
45738
|
let id2 = session ?? shown;
|
|
45665
45739
|
try {
|
|
@@ -45710,7 +45784,7 @@ async function rootSession(client, session) {
|
|
|
45710
45784
|
}
|
|
45711
45785
|
var ASK_EVENTS = /* @__PURE__ */ new Set(["permission.asked", "permission.replied", "permission.updated", "question.asked", "question.replied", "question.rejected"]);
|
|
45712
45786
|
var MAX_BACKOFF_MS = 3e4;
|
|
45713
|
-
var
|
|
45787
|
+
var paneKey2 = (entry2) => `${entry2.server}\0${entry2.pane}`;
|
|
45714
45788
|
var PaneServerWatcher = class {
|
|
45715
45789
|
constructor(sink, list = servedPanes, minBackoffMs = 1e3) {
|
|
45716
45790
|
this.sink = sink;
|
|
@@ -45724,7 +45798,7 @@ var PaneServerWatcher = class {
|
|
|
45724
45798
|
closed = false;
|
|
45725
45799
|
tick() {
|
|
45726
45800
|
if (this.closed) return;
|
|
45727
|
-
const current2 = new Map(this.list().map((entry2) => [
|
|
45801
|
+
const current2 = new Map(this.list().map((entry2) => [paneKey2(entry2), entry2]));
|
|
45728
45802
|
for (const [key2, running2] of this.live) {
|
|
45729
45803
|
const entry2 = current2.get(key2);
|
|
45730
45804
|
if (entry2 && entry2.pid === running2.entry.pid && entry2.port === running2.entry.port) {
|
|
@@ -45771,7 +45845,7 @@ var PaneServerWatcher = class {
|
|
|
45771
45845
|
});
|
|
45772
45846
|
return refreshing;
|
|
45773
45847
|
};
|
|
45774
|
-
const running2 = this.live.get(
|
|
45848
|
+
const running2 = this.live.get(paneKey2(entry2));
|
|
45775
45849
|
if (running2?.entry === entry2) running2.refresh = refresh;
|
|
45776
45850
|
while (!signal.aborted) {
|
|
45777
45851
|
try {
|
|
@@ -46050,7 +46124,7 @@ var AgentHooks = class {
|
|
|
46050
46124
|
* answered in the TUI or went away, and their cards go with them. */
|
|
46051
46125
|
async servedAsks(entry2, client, asks) {
|
|
46052
46126
|
if (this.closed) return;
|
|
46053
|
-
const key2 =
|
|
46127
|
+
const key2 = paneKey2(entry2), where = { key: key2, server: entry2.server, pane: entry2.pane };
|
|
46054
46128
|
const expiresAt = Date.now() + SERVED_ASK_MS;
|
|
46055
46129
|
const permissions = /* @__PURE__ */ new Set();
|
|
46056
46130
|
for (const ask of asks.permissions) {
|
|
@@ -49130,7 +49204,7 @@ var FanoutMessages = class {
|
|
|
49130
49204
|
init_wrapper();
|
|
49131
49205
|
import { randomUUID as randomUUID24 } from "node:crypto";
|
|
49132
49206
|
import { chmod as chmod6, lstat as lstat27, mkdir as mkdir29, readFile as readFile47, rm as rm14, unlink as unlink9, writeFile as writeFile11 } from "node:fs/promises";
|
|
49133
|
-
import { readFileSync as
|
|
49207
|
+
import { readFileSync as readFileSync36 } from "node:fs";
|
|
49134
49208
|
import { createServer as createServer3 } from "node:http";
|
|
49135
49209
|
import { cpus as cpus2, hostname as hostname12, loadavg as loadavg2 } from "node:os";
|
|
49136
49210
|
import path107 from "node:path";
|
|
@@ -49931,6 +50005,7 @@ init_zod();
|
|
|
49931
50005
|
init_logger();
|
|
49932
50006
|
import { createHash as createHash20 } from "node:crypto";
|
|
49933
50007
|
init_launch_brief();
|
|
50008
|
+
init_codex_servers();
|
|
49934
50009
|
init_herdr();
|
|
49935
50010
|
init_protocol();
|
|
49936
50011
|
init_terminal();
|
|
@@ -49954,7 +50029,8 @@ var defaultReaders = {
|
|
|
49954
50029
|
identity: (server, pane) => paneIdentity(server, pane),
|
|
49955
50030
|
finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(void 0),
|
|
49956
50031
|
turn: paneTurn,
|
|
49957
|
-
stall: (target, pane) => sessionStalls.observe(target, pane)
|
|
50032
|
+
stall: (target, pane) => sessionStalls.observe(target, pane),
|
|
50033
|
+
lost: (server, pane, session) => codexServers.lostTurn(server, pane, session)
|
|
49958
50034
|
};
|
|
49959
50035
|
var workerReaders = (approval) => ({ ...defaultReaders, approval });
|
|
49960
50036
|
function hookWorkers(hooks) {
|
|
@@ -50010,6 +50086,8 @@ async function workerStates2(input2, readers = defaultReaders) {
|
|
|
50010
50086
|
const current2 = await readers.identity(target.server, pane).catch(() => void 0);
|
|
50011
50087
|
const expected = "session" in target ? target.session : void 0;
|
|
50012
50088
|
if (expected && current2 && current2 !== expected) return { state: "gone" };
|
|
50089
|
+
const lost = target.source === "codex" ? readers.lost?.(target.server, String(pane.pane_id), expected ?? current2) : void 0;
|
|
50090
|
+
if (lost) return { state: "done", session: lost.threadId, completed: true, endedAt: lost.at, error: LOST_TURN };
|
|
50013
50091
|
const status = String(pane.agent_status);
|
|
50014
50092
|
const record2 = await readers.turn?.(target.server, pane, target.source).catch(() => void 0);
|
|
50015
50093
|
const own2 = record2 && record2.terminal === pane.terminal_id && record2.source === target.source && record2.session === (expected ?? current2 ?? record2.session) && !(target.dispatch && record2.dispatch && target.dispatch !== record2.dispatch) ? record2 : void 0;
|
|
@@ -57887,7 +57965,7 @@ async function serve(version3, options = {}) {
|
|
|
57887
57965
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
57888
57966
|
function gatewayTiming() {
|
|
57889
57967
|
try {
|
|
57890
|
-
const parsed = JSON.parse(
|
|
57968
|
+
const parsed = JSON.parse(readFileSync36(path107.join(root, "gateway.json"), "utf8"));
|
|
57891
57969
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
57892
57970
|
} catch {
|
|
57893
57971
|
}
|
|
@@ -58380,7 +58458,7 @@ async function runBridge(args, version3) {
|
|
|
58380
58458
|
break;
|
|
58381
58459
|
case "install":
|
|
58382
58460
|
case "update":
|
|
58383
|
-
await install(version3, args.includes("--no-service"));
|
|
58461
|
+
await install(version3, args.includes("--no-service"), args.includes("--force"));
|
|
58384
58462
|
break;
|
|
58385
58463
|
case "uninstall":
|
|
58386
58464
|
await uninstall();
|
|
@@ -58466,7 +58544,7 @@ async function readSecret(prompt) {
|
|
|
58466
58544
|
// src/bridge/hook-main.ts
|
|
58467
58545
|
init_utils_helpers();
|
|
58468
58546
|
Object.assign(process.env, nonInteractiveGitEnv());
|
|
58469
|
-
runBridge(process.argv.slice(2), "0.3.
|
|
58547
|
+
runBridge(process.argv.slice(2), "0.3.14").then((code) => {
|
|
58470
58548
|
process.exitCode = code;
|
|
58471
58549
|
}).catch((error62) => {
|
|
58472
58550
|
console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
|
|
@@ -47,6 +47,13 @@ function sandboxHomeDir() {
|
|
|
47
47
|
// would point that at their real files, so both fall back to the sandbox.
|
|
48
48
|
delete process.env.CLAUDE_CONFIG_DIR;
|
|
49
49
|
delete process.env.CODEX_HOME;
|
|
50
|
+
// A run inside a Hook-launched worker inherits the Hook's own service
|
|
51
|
+
// variables. PHREN_BRIDGE_HOME pointed every install and init test at the
|
|
52
|
+
// real Hook, and `phren init` on a scratch store ran a real
|
|
53
|
+
// `systemctl --user stop phren-hook.service`. Unset, each falls back to
|
|
54
|
+
// the sandbox home, as on a clean machine.
|
|
55
|
+
for (const name of ["PHREN_BRIDGE_HOME", "PHREN_HERDR_HOME", "PHREN_PROFILE", "PHREN_DISPATCH_ID", "PHREN_CODEX_SERVER"])
|
|
56
|
+
delete process.env[name];
|
|
50
57
|
}
|
|
51
58
|
export async function teardown() {
|
|
52
59
|
if (sandboxHome)
|