@phren/cli 0.3.13 → 0.3.15

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.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-usage.d.ts +2 -1
  3. package/dist/bridge/account-usage.js +8 -1
  4. package/dist/bridge/claude-accounts.d.ts +3 -0
  5. package/dist/bridge/claude-accounts.js +13 -1
  6. package/dist/bridge/codex-app-server.d.ts +6 -0
  7. package/dist/bridge/codex-app-server.js +3 -1
  8. package/dist/bridge/codex-servers.d.ts +25 -1
  9. package/dist/bridge/codex-servers.js +78 -14
  10. package/dist/bridge/command.js +1 -1
  11. package/dist/bridge/conductor-group.d.ts +2 -0
  12. package/dist/bridge/conductor-group.js +17 -5
  13. package/dist/bridge/conductor-sets.js +23 -3
  14. package/dist/bridge/dispatch-command.d.ts +1 -0
  15. package/dist/bridge/dispatch-command.js +40 -2
  16. package/dist/bridge/dispatch-returns.d.ts +24 -1
  17. package/dist/bridge/dispatch-returns.js +125 -12
  18. package/dist/bridge/dispatch.d.ts +76 -0
  19. package/dist/bridge/dispatch.js +7 -0
  20. package/dist/bridge/hand-off-queue.d.ts +3 -0
  21. package/dist/bridge/hand-off-queue.js +9 -0
  22. package/dist/bridge/install.d.ts +8 -1
  23. package/dist/bridge/install.js +44 -5
  24. package/dist/bridge/owner-inbox-view.d.ts +6 -0
  25. package/dist/bridge/owner-inbox-view.js +32 -0
  26. package/dist/bridge/owner-inbox.d.ts +117 -0
  27. package/dist/bridge/owner-inbox.js +120 -0
  28. package/dist/bridge/return-contract.d.ts +35 -0
  29. package/dist/bridge/return-contract.js +10 -0
  30. package/dist/bridge/server-launch.js +12 -1
  31. package/dist/bridge/server-routes.d.ts +5 -0
  32. package/dist/bridge/server-routes.js +22 -1
  33. package/dist/bridge/server.js +37 -1
  34. package/dist/bridge/subscription.d.ts +13 -0
  35. package/dist/bridge/subscription.js +24 -0
  36. package/dist/bridge/terminal-herdr.js +1 -0
  37. package/dist/bridge/terminal-tmux.js +1 -0
  38. package/dist/bridge/terminal.d.ts +1 -0
  39. package/dist/bridge/terminal.js +1 -0
  40. package/dist/bridge/usage.d.ts +6 -0
  41. package/dist/bridge/usage.js +57 -10
  42. package/dist/bridge/worker-close.d.ts +10 -0
  43. package/dist/bridge/worker-close.js +77 -0
  44. package/dist/bridge/worker-reports.d.ts +10 -0
  45. package/dist/bridge/worker-reports.js +63 -0
  46. package/dist/bridge-hook.mjs +5158 -4480
  47. package/dist/cli-registry.js +9 -2
  48. package/dist/modules/registry.js +5 -5
  49. package/dist/test-global-setup.js +7 -0
  50. package/dist/tools/dispatch.js +33 -1
  51. package/package.json +1 -1
  52. package/starter/global/skills/conductor/SKILL.md +35 -0
package/README.md CHANGED
@@ -6,7 +6,7 @@ On startup it walks your phren directory, reads all `.md` files, and builds an i
6
6
 
7
7
  Periodic remote checks are off by default. Enable them with `phren config pull-interval 60` to check shared Git stores every minute while running, coordinated across MCP clients using the same store. Changed refs are fetched and applied only as clean fast-forwards; dirty or diverged stores are deferred. Pulled changes refresh the index and existing managed skill/instruction mirrors. Configure this machine with `phren config pull-interval 600` (ten minutes) or `phren config pull-interval off`. Periodic checks are disabled for project-local stores and the manual preset; existing lifecycle hooks are configured separately.
8
8
 
9
- Public surface: 59 MCP tools across 13 modules (search, tasks, findings, notes, memory, data, graph, sessions, ops/review, skills, hooks, config, extraction).
9
+ Public surface: 76 MCP implementation tools across 16 catalog modules (search, tasks, findings, notes, memory, data, graph, sessions, ops/review, skills, hooks, config, extraction).
10
10
 
11
11
  Notable shipped capabilities:
12
12
  - finding lifecycle tools: `supersede_finding`, `retract_finding`, `resolve_contradiction`, `get_contradictions`
@@ -1,7 +1,7 @@
1
1
  import { type NotLinkedComputer } from "./hand-off.js";
2
2
  import { type HookPeer } from "./peers.js";
3
3
  import { type Json } from "./protocol.js";
4
- import { NEAR_LIMIT_LEFT, type AccountUsage, type UsageWindow } from "./usage.js";
4
+ import { NEAR_LIMIT_LEFT, type AccountUsage, type Subscription, type UsageWindow } from "./usage.js";
5
5
  export { NEAR_LIMIT_LEFT };
6
6
  /**
7
7
  * Every computer's agent usage merged by account, for a conductor choosing
@@ -58,6 +58,7 @@ export interface AccountUsageRow {
58
58
  amountUSD: number;
59
59
  period: string;
60
60
  };
61
+ subscription?: Subscription;
61
62
  updatedAt?: string;
62
63
  /** How old the standing report is, as "4m" or "2d 3h". */
63
64
  age?: string;
@@ -29,7 +29,7 @@ export const STALE_AFTER_MS = 15 * 60_000;
29
29
  const SOURCES = USAGE_SOURCES.join(",");
30
30
  const USAGE_ROUTE = `/v1/usage?${new URLSearchParams({ sources: SOURCES, goPlan: "1", accounts: "all" })}`;
31
31
  const date = (value) => value ? Date.parse(value) : NaN;
32
- const hasData = (usage) => usage.windows.length > 0 || Boolean(usage.spend);
32
+ const hasData = (usage) => usage.windows.length > 0 || Boolean(usage.spend) || Boolean(usage.subscription);
33
33
  const newer = (a, b) => (date(b.usage.updatedAt) || 0) > (date(a.usage.updatedAt) || 0) ? b : a;
34
34
  export function ageText(ms) {
35
35
  const minutes = Math.max(0, Math.round(ms / 60_000));
@@ -106,6 +106,8 @@ export function mergeAccountUsage(reports, now = Date.now()) {
106
106
  continue;
107
107
  }
108
108
  const source = group[0].usage.source;
109
+ const subscriptions = group.filter(item => item.usage.subscription);
110
+ const subscription = subscriptions.sort((a, b) => (date(b.usage.subscription?.checkedAt) || date(b.usage.updatedAt) || 0) - (date(a.usage.subscription?.checkedAt) || date(a.usage.updatedAt) || 0))[0]?.usage.subscription;
109
111
  // One allowance: the freshest report with windows stands whole, never mixed with another read.
110
112
  const withWindows = reporting.filter(item => item.usage.windows.length);
111
113
  const standing = (withWindows.length ? withWindows : reporting).reduce(newer);
@@ -125,6 +127,7 @@ export function mergeAccountUsage(reports, now = Date.now()) {
125
127
  nearLimit: windows.some(w => w.limited) || leftPercent !== undefined && leftPercent < NEAR_LIMIT_LEFT,
126
128
  exhausted: exhausted.length > 0, ...(availableIn ? { availableIn } : {}),
127
129
  ...(spend ? { spend } : {}),
130
+ ...(subscription ? { subscription } : {}),
128
131
  ...(standing.usage.updatedAt ? { updatedAt: standing.usage.updatedAt } : {}),
129
132
  ...(Number.isFinite(updated) ? { age: ageText(now - updated) } : {}),
130
133
  stale: !Number.isFinite(updated) || now - updated > STALE_AFTER_MS || windows.some(w => w.reset),
@@ -228,6 +231,10 @@ export function formatAccountUsage(view) {
228
231
  const flags = [row.exhausted ? `out of quota${row.availableIn ? `, back in ${row.availableIn}` : ""}` : row.nearLimit ? `low, ${row.leftPercent ?? 0}% left` : row.leftPercent !== undefined ? `${row.leftPercent}% left` : "",
229
232
  row.stale ? `stale${row.age ? `, reported ${ago(row.age)}` : ""}` : row.age ? ago(row.age) : ""].filter(Boolean).join("; ");
230
233
  lines.push(`${title(row)} on ${where}${flags ? ` (${flags})` : ""}`);
234
+ if (row.subscription) {
235
+ const sub = row.subscription;
236
+ lines.push(` ${[sub.plan, sub.startedAt ? `since ${sub.startedAt.slice(0, 10)}` : "", sub.renewsAt ? `renews ${sub.renewsEstimated ? "about " : ""}${sub.renewsAt.slice(0, 10)}` : ""].filter(Boolean).join(" · ")}`);
237
+ }
231
238
  for (const w of row.windows) {
232
239
  const used = w.reset ? "reset, no new report" : w.usedPercent !== undefined ? `${w.usedPercent}% used` : w.usedUSD !== undefined ? `$${w.usedUSD.toFixed(2)}${w.limitUSD !== undefined ? ` of $${w.limitUSD.toFixed(2)}` : ""}` : "";
233
240
  lines.push(` ${w.name.padEnd(30)} ${used.padEnd(22)}${w.limited ? "limited now " : ""}${w.resetsIn ? `resets in ${w.resetsIn}` : ""}`.trimEnd());
@@ -1,3 +1,4 @@
1
+ import { type Subscription } from "./subscription.js";
1
2
  export declare const DEFAULT_ACCOUNT = "default";
2
3
  export interface ClaudeHome {
3
4
  /** "default", or the slug of ~/.claude-<slug>. */
@@ -32,6 +33,8 @@ export declare function setAccountLabel(id: string, label: string): Promise<void
32
33
  export declare function claudeAccountKey(home: ClaudeHome): string;
33
34
  /** The login's email, so the phone can name a card merged across computers. Usage rows only. */
34
35
  export declare function claudeAccountEmail(home: ClaudeHome): string | undefined;
36
+ /** The account home's own subscription, independent of the quota snapshot's age. */
37
+ export declare function claudeAccountSubscription(home: ClaudeHome, now?: Date): Subscription | undefined;
35
38
  export declare function claudeAccountRef(home: ClaudeHome, labels?: Record<string, string>): AccountRef;
36
39
  export declare const CODEX_ACCOUNT: AccountRef;
37
40
  /** Only for tests. */
@@ -10,6 +10,7 @@ import path from "node:path";
10
10
  import { dump, load } from "js-yaml";
11
11
  import { claudeConfigDir, homeDir } from "../home-paths.js";
12
12
  import { atomic, bridgeRoot } from "./protocol.js";
13
+ import { monthlyAnniversary, planName, subscriptionDate } from "./subscription.js";
13
14
  export const DEFAULT_ACCOUNT = "default";
14
15
  const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
15
16
  export function isAccountSlug(value) { return value === DEFAULT_ACCOUNT || SLUG.test(value); }
@@ -127,7 +128,10 @@ function oauthIdentity(configFile) {
127
128
  const account = config.oauthAccount && typeof config.oauthAccount === "object" ? config.oauthAccount : {};
128
129
  const uuid = typeof account.accountUuid === "string" && account.accountUuid ? account.accountUuid : undefined;
129
130
  const email = typeof account.emailAddress === "string" && /^[^\s@]{1,64}@[^\s@]{1,190}$/.test(account.emailAddress) ? account.emailAddress : undefined;
130
- const value = { mtimeMs: stat.mtimeMs, size: stat.size, uuid, email };
131
+ const tier = planName(account.organizationRateLimitTier);
132
+ const billing = typeof account.billingType === "string" && /^(?:claude_)?(?:pro|max|team|enterprise)(?:_subscription)?$/.test(account.billingType)
133
+ ? planName(account.billingType.replace(/_subscription$/, "")) : undefined;
134
+ const value = { mtimeMs: stat.mtimeMs, size: stat.size, uuid, email, plan: tier ?? billing, startedAt: subscriptionDate(account.subscriptionCreatedAt) };
131
135
  identityCache.set(configFile, value);
132
136
  return value;
133
137
  }
@@ -142,6 +146,14 @@ export function claudeAccountKey(home) {
142
146
  }
143
147
  /** The login's email, so the phone can name a card merged across computers. Usage rows only. */
144
148
  export function claudeAccountEmail(home) { return oauthIdentity(home.configFile).email; }
149
+ /** The account home's own subscription, independent of the quota snapshot's age. */
150
+ export function claudeAccountSubscription(home, now = new Date()) {
151
+ const { plan, startedAt } = oauthIdentity(home.configFile);
152
+ if (!plan)
153
+ return undefined;
154
+ const renewsAt = startedAt ? monthlyAnniversary(startedAt, now) : undefined;
155
+ return { plan, ...(startedAt ? { startedAt } : {}), ...(renewsAt ? { renewsAt, renewsEstimated: true } : {}), checkedAt: now.toISOString() };
156
+ }
145
157
  export function claudeAccountRef(home, labels = readLabels()) {
146
158
  return { id: home.id, label: accountLabel(home.id, labels), key: claudeAccountKey(home) };
147
159
  }
@@ -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(codexBin, ["app-server", ...(options.config ?? []).flatMap(value => ["-c", value]), "--listen", `unix://${options.socketPath}`], {
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 handle = await this.deps.spawn({ socketPath: socket, cwd: options.cwd, detached: true, logFile: path.join(directory, "server.log"),
170
- config: serverConfig(), replaceEnv: true, env: serverEnvironment(process.env, { ...(options.env ?? {}), [CODEX_SERVER_ENV]: serverId }) }).catch(async (error) => {
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 this.read(name);
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();
@@ -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();
@@ -100,6 +100,8 @@ export declare function buildSets(input: {
100
100
  };
101
101
  answers: readonly PeerAnswer[];
102
102
  computers: readonly Computer[];
103
+ /** Identity rows from peers, used only to recognize names in their set reports. */
104
+ reportedComputers?: readonly Pick<Computer, "id" | "name" | "aliases">[];
103
105
  }): {
104
106
  sets: ComputerSet[];
105
107
  unlinked: Computer[];
@@ -89,9 +89,19 @@ function conductorOf(entries) {
89
89
  * one-way peer. `unlinked` are computers the store knows with no link here.
90
90
  */
91
91
  export function buildSets(input) {
92
- const { local, answers } = input;
92
+ const { local } = input;
93
+ // A peer's directory can name this computer differently from its hostname.
94
+ // Only a matching id establishes that the peer's name belongs to self.
95
+ const reports = input.reportedComputers ?? [];
96
+ const selfReports = local.id ? reports.filter(row => row.id === local.id) : [];
97
+ const selfAnswers = input.answers.filter(answer => answer.ok && local.id && answer.id === local.id);
98
+ const selfNames = [...local.names, local.name, ...selfReports.flatMap(row => [row.name, ...row.aliases]),
99
+ ...selfAnswers.flatMap(answer => [answer.peer.name, answer.peer.address, ...(answer.ok ? answer.names : [])])];
100
+ const reportedSelf = indirectMembers(input.answers, local.names).find(name => selfReports.some(row => [row.name, ...row.aliases].some(alias => computerLabel(alias) === computerLabel(name))));
101
+ const selfName = reportedSelf ?? selfAnswers.map(answer => answer.peer.name).sort()[0] ?? local.name;
102
+ const answers = input.answers.filter(answer => !(answer.ok && local.id && answer.id === local.id));
93
103
  const members = answers.filter(answer => !oneWay(answer));
94
- const computers = [{ name: local.name, ...(local.id ? { id: local.id } : {}), local: true, reachable: true, link: "self",
104
+ const computers = [{ name: selfName, ...(local.id ? { id: local.id } : {}), local: true, reachable: true, link: "self",
95
105
  ...(local.conductor ? { conductor: local.conductor } : {}) }];
96
106
  for (const answer of members) {
97
107
  if (answer.ok)
@@ -101,13 +111,13 @@ export function buildSets(input) {
101
111
  else
102
112
  computers.push({ name: answer.peer.name, reachable: !!answer.disabled, link: "unknown", error: answer.error, ...(answer.code ? { code: answer.code } : {}) });
103
113
  }
104
- const indirect = indirectMembers(answers, local.names);
114
+ const indirect = indirectMembers(answers, selfNames);
105
115
  for (const name of indirect)
106
116
  computers.push({ name, link: "indirect", hint: linkHint(name) });
107
117
  const name = newest([local.set, ...members.map(answer => answer.ok ? answer.set : undefined)]);
108
118
  const own = { id: setId([local.id, ...members.map(answer => answer.ok ? answer.id : undefined)], local.name),
109
119
  ...(name?.name ? { name: name.name, namedAt: name.namedAt } : {}), local: true, computers,
110
- ...conductorOf([{ computer: local.name, conductor: local.conductor }, ...members.map(answer => ({ computer: answer.peer.name, conductor: answer.ok ? answer.conductor : undefined }))]) };
120
+ ...conductorOf([{ computer: selfName, conductor: local.conductor }, ...members.map(answer => ({ computer: answer.peer.name, conductor: answer.ok ? answer.conductor : undefined }))]) };
111
121
  const others = answers.flatMap(answer => {
112
122
  if (!answer.ok || !oneWay(answer))
113
123
  return [];
@@ -117,6 +127,8 @@ export function buildSets(input) {
117
127
  ...conductorOf([{ computer: answer.peer.name, conductor: answer.conductor }]) }];
118
128
  });
119
129
  const indirectLabels = new Set(indirect.map(computerLabel));
120
- const unlinked = input.computers.filter(row => !row.linked && ![row.name, ...row.aliases].some(known => indirectLabels.has(computerLabel(known))));
130
+ const selfLabels = new Set(selfNames.map(computerLabel));
131
+ const unlinked = input.computers.filter(row => !row.local && !row.linked && !(local.id && row.id === local.id)
132
+ && ![row.name, ...row.aliases].some(known => selfLabels.has(computerLabel(known)) || indirectLabels.has(computerLabel(known))));
121
133
  return { sets: [own, ...others], unlinked };
122
134
  }
@@ -1,10 +1,11 @@
1
1
  import { z } from "zod";
2
- import { askPeers, buildSets, localCaller } from "./conductor-group.js";
2
+ import { askPeers, buildSets, indirectMembers, localCaller } from "./conductor-group.js";
3
3
  import { readSetName, saveSetName } from "./conductor-role.js";
4
- import { readComputers } from "./computer-identity.js";
4
+ import { computerLabel, readComputers } from "./computer-identity.js";
5
5
  import { localNames } from "./computer-names.js";
6
6
  import { listsCaller } from "./health.js";
7
7
  import { optionalHookPeers, peerRequest } from "./peers.js";
8
+ import { object } from "./protocol.js";
8
9
  import { localConductor } from "./server-launch.js";
9
10
  const callerSchema = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() });
10
11
  /** `GET /v1/conductor`: this computer's live conductor and what a peer needs
@@ -21,8 +22,27 @@ export async function readSets(info) {
21
22
  const [{ peers, peerError }, conductor, set, { computers }] = await Promise.all([optionalHookPeers(), localConductor(), readSetName(),
22
23
  readComputers({ local: { id: info.computer.id } })]);
23
24
  const answers = await askPeers(peers, await localCaller());
25
+ // Old /v1/conductor replies list peer names without ids. Resolve unknown
26
+ // names through the existing identity directory, also on older Hooks.
27
+ // Skip this extra round when names already identify every member.
28
+ const indirect = new Set(indirectMembers(answers, [info.computer.name, ...(info.computer.aliases ?? []), ...localNames()]).map(computerLabel));
29
+ const reportedComputers = (await Promise.all(answers.map(async (answer) => {
30
+ if (!answer.ok || answer.knowsCaller === false || !answer.peers?.some(name => indirect.has(computerLabel(name))))
31
+ return [];
32
+ try {
33
+ const directory = await peerRequest(answer.peer, "/v1/computers", undefined, 12_000);
34
+ return (Array.isArray(directory.computers) ? directory.computers.slice(0, 64) : []).flatMap(value => {
35
+ const row = object(value);
36
+ return typeof row.id === "string" && typeof row.name === "string" ? [{ id: row.id, name: row.name,
37
+ aliases: (Array.isArray(row.aliases) ? row.aliases : []).filter((name) => typeof name === "string").slice(0, 64) }] : [];
38
+ });
39
+ }
40
+ catch {
41
+ return [];
42
+ } // Missing or offline identity directory keeps the name-only view.
43
+ }))).flat();
24
44
  const view = buildSets({ local: { name: info.computer.name, id: info.computer.id, ...(conductor ? { conductor } : {}), ...(set ? { set } : {}),
25
- names: [info.computer.name, ...(info.computer.aliases ?? []), ...localNames()] }, answers, computers });
45
+ names: [info.computer.name, ...(info.computer.aliases ?? []), ...localNames()] }, answers, computers, reportedComputers });
26
46
  return { ...view, ...(peerError ? { peerError } : {}) };
27
47
  }
28
48
  const setNameValue = z.string().trim().min(1).max(60).refine(t => !/[\x00-\x1f\x7f]/.test(t)).nullable();
@@ -4,3 +4,4 @@ export declare function runHandOff(args: string[]): Promise<number>;
4
4
  /** One line per computer: name, reachability, link and conductor. */
5
5
  export declare function formatSets(view: Json): string;
6
6
  export declare function runConductor(args: string[]): Promise<number>;
7
+ export declare function runOwnerInbox(args: string[]): Promise<number>;
@@ -1,3 +1,5 @@
1
+ import { ownerInboxSchema } from "./owner-inbox.js";
2
+ import { prsSchema } from "./return-contract.js";
1
3
  import { parseArgs } from "node:util";
2
4
  import { hookRequest } from "./client.js";
3
5
  import { dispatchSchema } from "./dispatch.js";
@@ -6,6 +8,14 @@ import { terminalPaneFromEnv } from "./terminal.js";
6
8
  import { addGrant, grantSchema, listNamedGrants, removeGrant } from "./grants.js";
7
9
  import { sessionId } from "./protocol.js";
8
10
  export async function runDispatch(args) {
11
+ if (args[0] === "report") {
12
+ const { values } = parseArgs({ args: args.slice(1), options: { prs: { type: "string" } } });
13
+ const origin = await terminalPaneFromEnv();
14
+ if (!origin || !values.prs)
15
+ throw new Error("Usage inside a worker pane: phren dispatch report --prs <JSON array>");
16
+ console.log(JSON.stringify(await hookRequest("/v1/dispatch/report", { origin, prs: prsSchema.parse(JSON.parse(values.prs)) }), null, 2));
17
+ return 0;
18
+ }
9
19
  if (args.length === 1 && args[0] === "status") {
10
20
  console.log(JSON.stringify(await hookRequest("/v1/dispatch"), null, 2));
11
21
  return 0;
@@ -26,6 +36,7 @@ export async function runDispatch(args) {
26
36
  return 0;
27
37
  }
28
38
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
39
+ "keep-open": { type: "boolean" },
29
40
  harness: { type: "string", default: "codex" }, model: { type: "string" }, effort: { type: "string" }, account: { type: "string" }, "permission-mode": { type: "string" }, prompt: { type: "string" }, label: { type: "string" },
30
41
  "parent-provider": { type: "string" }, "parent-session": { type: "string" }, "parent-computer": { type: "string" },
31
42
  "parent-server": { type: "string" }, "parent-workspace": { type: "string" }, "parent-tab": { type: "string" }, "parent-pane": { type: "string" },
@@ -41,8 +52,8 @@ export async function runDispatch(args) {
41
52
  server: values["parent-server"], workspace: values["parent-workspace"], tab: values["parent-tab"], pane: values["parent-pane"],
42
53
  source: values["parent-provider"], session: values["parent-session"],
43
54
  } : undefined;
44
- const { "permission-mode": permissionMode, ...rest } = values;
45
- const ordinary = { ...Object.fromEntries(Object.entries(rest).filter(([key]) => !key.startsWith("parent-"))), ...(permissionMode !== undefined ? { permissionMode } : {}) };
55
+ const { "permission-mode": permissionMode, "keep-open": keepOpen, ...rest } = values;
56
+ const ordinary = { ...Object.fromEntries(Object.entries(rest).filter(([key]) => !key.startsWith("parent-"))), ...(permissionMode !== undefined ? { permissionMode } : {}), ...(keepOpen ? { closeOnFinish: false } : {}) };
46
57
  const input = dispatchSchema.parse({ computer: positionals[0], project: positionals[1], ...ordinary,
47
58
  ...(parent ? { parent, parentTarget } : {}) });
48
59
  // Run inside an agent's pane, the dispatch remembers that pane for return notices.
@@ -112,6 +123,23 @@ export async function runConductor(args) {
112
123
  console.log(result.stopped ? "This computer has no conductor now." : "This computer had no conductor.");
113
124
  return 0;
114
125
  }
126
+ if (namespace === "integrator") {
127
+ const { values } = parseArgs({ args: args.slice(1), options: { session: { type: "string" }, computer: { type: "string" }, clear: { type: "boolean" } } });
128
+ if (values.clear) {
129
+ console.log(JSON.stringify(await hookRequest("/v1/conductor/integrator", { integrator: null }), null, 2));
130
+ return 0;
131
+ }
132
+ if (!values.session) {
133
+ console.log(JSON.stringify(await hookRequest("/v1/conductor/integrator"), null, 2));
134
+ return 0;
135
+ }
136
+ const { listLiveSessions } = await import("./hand-off.js");
137
+ const live = await listLiveSessions(), session = live.sessions.find(row => row.target?.session === values.session && (values.computer ? row.computer === values.computer : row.local));
138
+ if (!session?.target)
139
+ throw new Error("That integrator is not a live session on the selected computer.");
140
+ console.log(JSON.stringify(await hookRequest("/v1/conductor/integrator", { integrator: { target: session.target, ...(!session.local ? { computer: session.computer } : {}) } }), null, 2));
141
+ return 0;
142
+ }
115
143
  if (namespace === "sets") {
116
144
  if (action === "name") {
117
145
  const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { clear: { type: "boolean" } } });
@@ -161,3 +189,13 @@ export async function runConductor(args) {
161
189
  }
162
190
  throw new Error(CONDUCTOR_USAGE);
163
191
  }
192
+ export async function runOwnerInbox(args) {
193
+ const [action = "list", ...rest] = args;
194
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { computer: { type: "string" }, project: { type: "string" }, id: { type: "string" }, resolution: { type: "string" }, all: { type: "boolean" } } });
195
+ const input = ownerInboxSchema.parse({ action, ...(values.computer ? { computer: values.computer === "local" ? undefined : values.computer } : {}),
196
+ ...(action === "add" ? { title: positionals.join(" "), project: values.project, id: values.id } : {}),
197
+ ...(action === "resolve" ? { id: positionals[0], resolution: values.resolution } : {}),
198
+ ...(values.all ? { includeResolved: true } : {}) });
199
+ console.log(JSON.stringify(await hookRequest("/v1/owner-inbox", input), null, 2));
200
+ return 0;
201
+ }