@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
@@ -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=on-failure\nRestartSec=3\nUMask=0077\n[Install]\nWantedBy=default.target\n`);
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
- if (!await missingFile(readFile(path.join(root, "installed.json"))))
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));
@@ -0,0 +1,6 @@
1
+ import { type Json } from "./protocol.js";
2
+ import { type OwnerInbox } from "./owner-inbox.js";
3
+ /** Aggregate each Hook's own inbox once, without recursively listing peers.
4
+ * inboxComputer identifies the Hook to send a resolution to; computer on a
5
+ * dispatch row names the worker and can be a different computer. */
6
+ export declare function ownerInboxView(inbox: OwnerInbox, input: unknown, localOnly?: boolean): Promise<Json>;
@@ -0,0 +1,32 @@
1
+ import { BridgeError, objects } from "./protocol.js";
2
+ import { hookPeers, peerRequest } from "./peers.js";
3
+ import { ownerInboxSchema } from "./owner-inbox.js";
4
+ import { isLocalComputer } from "./dispatch-hosts.js";
5
+ /** Aggregate each Hook's own inbox once, without recursively listing peers.
6
+ * inboxComputer identifies the Hook to send a resolution to; computer on a
7
+ * dispatch row names the worker and can be a different computer. */
8
+ export async function ownerInboxView(inbox, input, localOnly = false) {
9
+ const data = ownerInboxSchema.parse(input);
10
+ const { computer, ...local } = data;
11
+ const peers = await hookPeers().catch(() => []);
12
+ if (computer && computer !== "local" && !isLocalComputer(computer)) {
13
+ const peer = peers.find(peer => peer.name === computer);
14
+ if (!peer)
15
+ throw new BridgeError(404, "That inbox computer is not linked.");
16
+ return peerRequest(peer, "/v1/owner-inbox", local);
17
+ }
18
+ const result = await inbox.run(local);
19
+ if (data.action !== "list" || localOnly)
20
+ return result;
21
+ const items = objects(result.items).map(item => ({ ...item, inboxComputer: "local" })), unreachable = [];
22
+ await Promise.all(peers.map(async (peer) => {
23
+ try {
24
+ const view = await peerRequest(peer, `/v1/owner-inbox?local=1${data.includeResolved ? "&includeResolved=true" : ""}`);
25
+ items.push(...objects(view.items).map(item => ({ ...item, inboxComputer: peer.name })));
26
+ }
27
+ catch (error) {
28
+ unreachable.push({ computer: peer.name, error: error instanceof Error ? error.message : "Unreachable." });
29
+ }
30
+ }));
31
+ return { ok: true, items, unreachable };
32
+ }
@@ -0,0 +1,117 @@
1
+ import { z } from "zod";
2
+ import { type Json } from "./protocol.js";
3
+ export declare const inboxTargetSchema: z.ZodUnion<readonly [z.ZodObject<{
4
+ server: z.ZodString;
5
+ workspace: z.ZodString;
6
+ tab: z.ZodString;
7
+ pane: z.ZodString;
8
+ source: z.ZodEnum<{
9
+ claude: "claude";
10
+ codex: "codex";
11
+ copilot: "copilot";
12
+ opencode: "opencode";
13
+ phren: "phren";
14
+ }>;
15
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
16
+ }, z.core.$strip>, z.ZodObject<{
17
+ server: z.ZodString;
18
+ workspace: z.ZodString;
19
+ tab: z.ZodString;
20
+ pane: z.ZodString;
21
+ source: z.ZodEnum<{
22
+ claude: "claude";
23
+ codex: "codex";
24
+ copilot: "copilot";
25
+ opencode: "opencode";
26
+ phren: "phren";
27
+ }>;
28
+ starting: z.ZodLiteral<true>;
29
+ startingToken: z.ZodString;
30
+ }, z.core.$strip>]>;
31
+ declare const itemSchema: z.ZodObject<{
32
+ id: z.ZodString;
33
+ kind: z.ZodEnum<{
34
+ blocked: "blocked";
35
+ manual: "manual";
36
+ "needs-you": "needs-you";
37
+ }>;
38
+ title: z.ZodString;
39
+ createdAt: z.ZodString;
40
+ updatedAt: z.ZodString;
41
+ state: z.ZodEnum<{
42
+ open: "open";
43
+ resolved: "resolved";
44
+ }>;
45
+ resolvedAt: z.ZodOptional<z.ZodString>;
46
+ resolution: z.ZodOptional<z.ZodString>;
47
+ project: z.ZodOptional<z.ZodString>;
48
+ computer: z.ZodOptional<z.ZodString>;
49
+ target: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
50
+ server: z.ZodString;
51
+ workspace: z.ZodString;
52
+ tab: z.ZodString;
53
+ pane: z.ZodString;
54
+ source: z.ZodEnum<{
55
+ claude: "claude";
56
+ codex: "codex";
57
+ copilot: "copilot";
58
+ opencode: "opencode";
59
+ phren: "phren";
60
+ }>;
61
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
62
+ }, z.core.$strip>, z.ZodObject<{
63
+ server: z.ZodString;
64
+ workspace: z.ZodString;
65
+ tab: z.ZodString;
66
+ pane: z.ZodString;
67
+ source: z.ZodEnum<{
68
+ claude: "claude";
69
+ codex: "codex";
70
+ copilot: "copilot";
71
+ opencode: "opencode";
72
+ phren: "phren";
73
+ }>;
74
+ starting: z.ZodLiteral<true>;
75
+ startingToken: z.ZodString;
76
+ }, z.core.$strip>]>>;
77
+ dispatch: z.ZodOptional<z.ZodString>;
78
+ actionId: z.ZodOptional<z.ZodString>;
79
+ source: z.ZodOptional<z.ZodString>;
80
+ live: z.ZodOptional<z.ZodBoolean>;
81
+ }, z.core.$strict>;
82
+ export type InboxItem = z.infer<typeof itemSchema>;
83
+ export declare const ownerInboxSchema: z.ZodObject<{
84
+ action: z.ZodDefault<z.ZodEnum<{
85
+ add: "add";
86
+ list: "list";
87
+ resolve: "resolve";
88
+ }>>;
89
+ title: z.ZodOptional<z.ZodString>;
90
+ project: z.ZodOptional<z.ZodString>;
91
+ id: z.ZodOptional<z.ZodString>;
92
+ resolution: z.ZodOptional<z.ZodString>;
93
+ includeResolved: z.ZodOptional<z.ZodBoolean>;
94
+ computer: z.ZodOptional<z.ZodString>;
95
+ }, z.core.$strict>;
96
+ export interface InboxSource {
97
+ source: string;
98
+ kind: "needs-you" | "blocked";
99
+ title: string;
100
+ project?: string;
101
+ computer?: string;
102
+ target?: z.infer<typeof inboxTargetSchema>;
103
+ dispatch?: string;
104
+ actionId?: string;
105
+ }
106
+ /** Hook-owned inbox. Return reads do not resolve owner work. Live sources
107
+ * disappearing are retained as no-longer-live until explicitly resolved. */
108
+ export declare class OwnerInbox {
109
+ private readonly sources;
110
+ private readonly file;
111
+ private pending;
112
+ constructor(sources?: () => Promise<InboxSource[]>, file?: string);
113
+ private read;
114
+ run(input: unknown): Promise<Json>;
115
+ tick(): Promise<void>;
116
+ }
117
+ export {};
@@ -0,0 +1,120 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema, startingTargetSchema, computerName } from "./protocol.js";
6
+ import { dispatchStatus } from "./dispatch.js";
7
+ const title = z.string().trim().min(1).max(500).refine(s => !/[\x00-\x1f\x7f]/.test(s));
8
+ export const inboxTargetSchema = z.union([targetSchema, startingTargetSchema]);
9
+ const itemSchema = z.object({
10
+ id: z.string().uuid(), kind: z.enum(["manual", "needs-you", "blocked"]), title,
11
+ createdAt: z.string().datetime(), updatedAt: z.string().datetime(), state: z.enum(["open", "resolved"]),
12
+ resolvedAt: z.string().datetime().optional(), resolution: z.string().max(2000).optional(),
13
+ project: z.string().max(200).optional(), computer: z.string().max(253).optional(),
14
+ target: inboxTargetSchema.optional(), dispatch: z.string().uuid().optional(), actionId: z.string().max(200).optional(),
15
+ source: z.string().max(500).optional(), live: z.boolean().optional(),
16
+ }).strict();
17
+ export const ownerInboxSchema = z.object({
18
+ action: z.enum(["add", "list", "resolve"]).default("list"),
19
+ title: title.optional(), project: z.string().max(200).optional(),
20
+ id: z.string().uuid().optional(), resolution: z.string().max(2000).optional(),
21
+ includeResolved: z.boolean().optional(), computer: computerName.optional(),
22
+ }).strict();
23
+ const uuidOf = (source) => { const h = createHash("sha256").update(source).digest("hex"); return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`; };
24
+ /** Hook-owned inbox. Return reads do not resolve owner work. Live sources
25
+ * disappearing are retained as no-longer-live until explicitly resolved. */
26
+ export class OwnerInbox {
27
+ sources;
28
+ file;
29
+ pending = Promise.resolve();
30
+ constructor(sources = async () => [], file = path.join(bridgeRoot(), "owner-inbox.json")) {
31
+ this.sources = sources;
32
+ this.file = file;
33
+ }
34
+ async read() {
35
+ const info = await lstat(this.file).catch(error => { if (error.code === "ENOENT")
36
+ return undefined; throw error; });
37
+ if (!info)
38
+ return [];
39
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 4 * 1024 * 1024)
40
+ throw new BridgeError(409, "The owner inbox cannot be read safely.");
41
+ return z.array(itemSchema).max(10000).parse(JSON.parse(await readFile(this.file, "utf8")));
42
+ }
43
+ run(input) {
44
+ const run = this.pending.then(async () => {
45
+ const data = ownerInboxSchema.parse(input), rows = await this.read(), at = new Date().toISOString();
46
+ const sources = [];
47
+ for (const receipt of await dispatchStatus()) {
48
+ const returned = receipt.returned;
49
+ if (receipt.closedAt || !returned || !["needs-you", "blocked"].includes(returned.state))
50
+ continue;
51
+ if (receipt.worker && receipt.worker.state !== returned.state && !receipt.approval)
52
+ continue;
53
+ const actionId = receipt.approval?.actionId;
54
+ sources.push({ source: `dispatch:${receipt.id}:${actionId ?? returned.at}`, kind: returned.state,
55
+ title: (receipt.approval?.request ?? returned.question ?? returned.reply ?? `${receipt.label} needs input`).replace(/[\x00-\x1f\x7f]+/g, " ").slice(0, 500),
56
+ project: receipt.project, computer: receipt.computer, ...("session" in (receipt.target ?? {}) ? { target: receipt.target } : {}), dispatch: receipt.id, ...(actionId ? { actionId } : {}) });
57
+ }
58
+ for (const source of await this.sources()) {
59
+ if (source.actionId && sources.some(other => other.actionId === source.actionId && JSON.stringify(other.target) === JSON.stringify(source.target)))
60
+ continue;
61
+ sources.push(source);
62
+ }
63
+ let changed = false;
64
+ const live = new Set(sources.map(s => s.source));
65
+ for (const row of rows)
66
+ if (row.source && row.live !== live.has(row.source)) {
67
+ row.live = live.has(row.source);
68
+ row.updatedAt = at;
69
+ changed = true;
70
+ }
71
+ for (const source of sources) {
72
+ const existing = rows.find(row => row.source === source.source);
73
+ if (existing)
74
+ continue; // Resolved sources do not resurrect on a poll.
75
+ if (rows.length >= 10000)
76
+ throw new BridgeError(409, "The owner inbox is full.");
77
+ rows.push(itemSchema.parse({ ...source, id: uuidOf(source.source), state: "open", live: true, createdAt: at, updatedAt: at }));
78
+ changed = true;
79
+ }
80
+ if (data.action === "add") {
81
+ if (!data.title)
82
+ throw new BridgeError(400, "Name the owner inbox item.");
83
+ const item = itemSchema.parse({ id: data.id ?? randomUUID(), kind: "manual", title: data.title, state: "open", createdAt: at, updatedAt: at, ...(data.project ? { project: data.project } : {}) });
84
+ const prior = rows.find(row => row.id === item.id);
85
+ if (prior && (prior.title !== item.title || prior.project !== item.project || prior.kind !== "manual"))
86
+ throw new BridgeError(409, "This inbox id names another item.");
87
+ if (!prior) {
88
+ if (rows.length >= 10000)
89
+ throw new BridgeError(409, "The owner inbox is full.");
90
+ rows.push(item);
91
+ changed = true;
92
+ }
93
+ if (changed)
94
+ await atomicInPrivateDir(this.file, rows);
95
+ return { ok: true, item: prior ?? item };
96
+ }
97
+ if (data.action === "resolve") {
98
+ const item = rows.find(row => row.id === data.id);
99
+ if (!item)
100
+ throw new BridgeError(404, "No owner inbox item with that id.");
101
+ if (item.state !== "resolved") {
102
+ item.state = "resolved";
103
+ item.resolvedAt = at;
104
+ item.updatedAt = at;
105
+ item.resolution = data.resolution;
106
+ changed = true;
107
+ }
108
+ if (changed)
109
+ await atomicInPrivateDir(this.file, rows);
110
+ return { ok: true, item };
111
+ }
112
+ if (changed)
113
+ await atomicInPrivateDir(this.file, rows);
114
+ return { ok: true, items: rows.filter(row => data.includeResolved || row.state === "open").sort((a, b) => a.createdAt.localeCompare(b.createdAt)) };
115
+ });
116
+ this.pending = run.catch(() => { });
117
+ return run;
118
+ }
119
+ async tick() { await this.run({ action: "list" }); }
120
+ }
@@ -0,0 +1,35 @@
1
+ import { z } from "zod";
2
+ export declare const reportText: (max: number) => z.ZodString;
3
+ export declare const pullRequestSchema: z.ZodObject<{
4
+ url: z.ZodURL;
5
+ repo: z.ZodString;
6
+ branch: z.ZodString;
7
+ tests: z.ZodString;
8
+ notes: z.ZodOptional<z.ZodString>;
9
+ }, z.core.$strict>;
10
+ export declare const prsSchema: z.ZodArray<z.ZodObject<{
11
+ url: z.ZodURL;
12
+ repo: z.ZodString;
13
+ branch: z.ZodString;
14
+ tests: z.ZodString;
15
+ notes: z.ZodOptional<z.ZodString>;
16
+ }, z.core.$strict>>;
17
+ export type PullRequest = z.infer<typeof pullRequestSchema>;
18
+ export declare const integratorSchema: z.ZodObject<{
19
+ computer: z.ZodOptional<z.ZodString>;
20
+ target: z.ZodObject<{
21
+ server: z.ZodString;
22
+ workspace: z.ZodString;
23
+ tab: z.ZodString;
24
+ pane: z.ZodString;
25
+ source: z.ZodEnum<{
26
+ claude: "claude";
27
+ codex: "codex";
28
+ copilot: "copilot";
29
+ opencode: "opencode";
30
+ phren: "phren";
31
+ }>;
32
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
33
+ }, z.core.$strip>;
34
+ }, z.core.$strict>;
35
+ export type Integrator = z.infer<typeof integratorSchema>;
@@ -0,0 +1,10 @@
1
+ import { z } from "zod";
2
+ import { computerName, targetSchema } from "./protocol.js";
3
+ export const reportText = (max) => z.string().max(max).refine(s => !/[\x00-\x08\x0b-\x1f\x7f]/.test(s));
4
+ export const pullRequestSchema = z.object({
5
+ url: z.url().max(1000).refine(url => { const parsed = new URL(url); return parsed.protocol === "https:" && !parsed.username && !parsed.password; }, "Use an HTTPS PR URL."),
6
+ repo: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).max(200),
7
+ branch: reportText(200).min(1), tests: reportText(2000), notes: reportText(4000).optional(),
8
+ }).strict();
9
+ export const prsSchema = z.array(pullRequestSchema).min(1).max(16).refine(rows => Buffer.byteLength(JSON.stringify(rows), "utf8") <= 24000, "PR evidence must fit within 24000 UTF-8 bytes.");
10
+ export const integratorSchema = z.object({ computer: computerName.optional(), target: targetSchema }).strict();
@@ -1,3 +1,4 @@
1
+ import { markPaneClosed } from "./worker-close.js";
1
2
  import { mkdir, readFile } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { fileURLToPath } from "node:url";
@@ -441,9 +442,19 @@ export async function workspaceAction(server, operation, data) {
441
442
  throw new BridgeError(400, "Choose a Herdr destination.");
442
443
  else if (pane && operation === "focus")
443
444
  await terminalProvider().focusPane(server, pane);
445
+ else if (pane && operation === "close") {
446
+ const row = objects(s.panes).find(p => p.pane_id === pane);
447
+ await markPaneClosed(server, row);
448
+ await terminalProvider().closePane(server, pane);
449
+ }
444
450
  else if (pane)
445
451
  throw new BridgeError(400, "This pane action is not available.");
446
- else
452
+ else {
453
+ if (operation === "close")
454
+ for (const row of objects(s.panes).filter(row => (!workspace || row.workspace_id === workspace) && (!tab || row.tab_id === tab))) {
455
+ await markPaneClosed(server, row);
456
+ }
447
457
  await terminalProvider().groupAction(server, operation, { workspace, tab }, label);
458
+ }
448
459
  return { ok: true };
449
460
  }
@@ -1,3 +1,4 @@
1
+ import type { OwnerInbox } from "./owner-inbox.js";
1
2
  import type { HandOffQueue } from "./hand-off-queue.js";
2
3
  import type { IncomingMessage, ServerResponse } from "node:http";
3
4
  import type { FanoutMessages } from "./fanout-messages.js";
@@ -52,6 +53,7 @@ export interface RouteContext {
52
53
  dispatches?: DispatchService;
53
54
  returns?: DispatchReturns;
54
55
  handOffs?: HandOffQueue;
56
+ inbox?: OwnerInbox;
55
57
  agentHooks: AgentHooks;
56
58
  journal: ActivityJournal;
57
59
  tabActivity: TabActivityStore;
@@ -95,6 +97,9 @@ export declare const capabilities: {
95
97
  sideQuestions: boolean;
96
98
  dispatch: boolean;
97
99
  conductorSets: boolean;
100
+ ownerInbox: boolean;
101
+ workerReports: boolean;
102
+ queuedHandOff: boolean;
98
103
  approvalPush: string;
99
104
  simulators: boolean;
100
105
  code: boolean;
@@ -1,3 +1,6 @@
1
+ import { ownerInboxView } from "./owner-inbox-view.js";
2
+ import { closeFinishedWorker } from "./worker-close.js";
3
+ import { reportWorker, readIntegrator, setIntegrator } from "./worker-reports.js";
1
4
  import { sessionStalls } from "./stalls.js";
2
5
  import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
3
6
  import path from "node:path";
@@ -67,7 +70,7 @@ async function childActivity(source, session) {
67
70
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
68
71
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
69
72
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
70
- files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, resources: true, sudo: true, sudoOutcome: true };
73
+ files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, resources: true, sudo: true, sudoOutcome: true };
71
74
  export function capabilitiesForModules(snapshot) {
72
75
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
73
76
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -290,6 +293,12 @@ export function createRouteHandler(ctx) {
290
293
  result = { computer: info.computer, version, ...await listsCaller(caller) };
291
294
  break;
292
295
  }
296
+ case "/v1/owner-inbox":
297
+ result = await ownerInboxView(ctx.inbox, { action: "list", includeResolved: url.searchParams.get("includeResolved") === "true" }, url.searchParams.get("local") === "1");
298
+ break;
299
+ case "/v1/conductor/integrator":
300
+ result = { integrator: await readIntegrator() ?? null };
301
+ break;
293
302
  case "/v1/dispatch":
294
303
  result = { dispatches: await dispatchStatus() };
295
304
  break;
@@ -626,6 +635,18 @@ export function createRouteHandler(ctx) {
626
635
  await streamSpeech(data, response);
627
636
  return;
628
637
  }
638
+ else if (url.pathname === "/v1/owner-inbox") {
639
+ result = await ownerInboxView(ctx.inbox, data);
640
+ }
641
+ else if (url.pathname === "/v1/conductor/integrator") {
642
+ result = await setIntegrator(data.integrator);
643
+ }
644
+ else if (url.pathname === "/v1/dispatch/report") {
645
+ result = await reportWorker(data);
646
+ }
647
+ else if (url.pathname === "/v1/dispatch/close") {
648
+ result = await closeFinishedWorker(data, ctx.handOffs);
649
+ }
629
650
  else if (url.pathname === "/v1/hand-off") {
630
651
  result = await ctx.handOffs.enqueue(data);
631
652
  }
@@ -1,3 +1,7 @@
1
+ import { OwnerInbox, inboxTargetSchema } from "./owner-inbox.js";
2
+ import { closeFinishedWorker } from "./worker-close.js";
3
+ import { isLocalComputer } from "./dispatch-hosts.js";
4
+ import { hookPeers, peerRequest } from "./peers.js";
1
5
  import { handOff } from "./hand-off.js";
2
6
  import { sessionStalls } from "./stalls.js";
3
7
  import { HandOffQueue } from "./hand-off-queue.js";
@@ -82,6 +86,15 @@ export async function serve(version, options = {}) {
82
86
  // Follows what dispatched workers do and tells the dispatching agent.
83
87
  const returns = dispatches ? new DispatchReturns({
84
88
  localWorkers: hookWorkers(agentHooks),
89
+ close: async (receipt) => {
90
+ const data = { target: receipt.target, dispatch: receipt.id, turn: receipt.closePending.turn };
91
+ if (isLocalComputer(receipt.computer))
92
+ return closeFinishedWorker(data, handOffs);
93
+ const peer = (await hookPeers()).find(peer => peer.name === receipt.computer);
94
+ if (!peer)
95
+ throw new BridgeError(503, "The worker's computer is offline.");
96
+ return peerRequest(peer, "/v1/dispatch/close", data);
97
+ },
85
98
  localAnswer: (target, actionId, decision) => agentHooks.answer(target, actionId, decision),
86
99
  // A worker's request the worker's own Hook did not push reaches this Hook's phone.
87
100
  onApproval: (receipt, approval) => {
@@ -96,6 +109,28 @@ export async function serve(version, options = {}) {
96
109
  if ("approvalPush" in activeCapabilities) {
97
110
  Object.defineProperty(activeCapabilities, "approvalPush", { enumerable: true, get: () => approvalPushCapability(agentHooks.push.status) });
98
111
  }
112
+ const inbox = dispatches ? new OwnerInbox(async () => {
113
+ const items = [];
114
+ for (const server of await recentServers()) {
115
+ const name = String(server.session), state = await sharedSnapshot(name, 4000);
116
+ for (const pane of objects(state.panes)) {
117
+ const chat = await paneChatState(name, pane, { tokenWhenIdentified: false }).catch(() => ({}));
118
+ const parsed = inboxTargetSchema.safeParse({ server: name, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent,
119
+ ...(chat.sessionId ? { session: chat.sessionId } : { starting: true, startingToken: chat.startingToken }) });
120
+ if (!parsed.success)
121
+ continue;
122
+ const target = parsed.data, approval = "session" in target ? agentHooks.workerApproval(target) : undefined, question = "session" in target ? agentHooks.servedQuestion(target) : undefined, terminal = "session" in target ? agentHooks.terminalPrompt(target) : undefined;
123
+ const request = approval?.request ?? (question ? "The worker has a question for the owner." : undefined) ?? terminal?.message
124
+ ?? (["blocked", "waiting"].includes(String(pane.agent_status)) ? `${pane.agent} needs terminal input.` : undefined);
125
+ if (!request)
126
+ continue;
127
+ const source = `prompt:${JSON.stringify(target)}:${approval?.actionId ?? JSON.stringify(question ?? terminal)}`;
128
+ items.push({ source, kind: "blocked", title: String(request).replace(/[\x00-\x1f\x7f]+/g, " ").slice(0, 500), target,
129
+ ...(approval?.actionId ? { actionId: approval.actionId } : {}) });
130
+ }
131
+ }
132
+ return items;
133
+ }) : undefined;
99
134
  const modelCatalog = options.modelCatalog ?? new ModelCatalog();
100
135
  const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
101
136
  const settingsSwitcher = new SettingsSwitcher(agentHooks);
@@ -172,7 +207,7 @@ export async function serve(version, options = {}) {
172
207
  });
173
208
  const http = createServer(createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
174
209
  journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
175
- fanoutMessages, canary, streams, returns, handOffs }));
210
+ fanoutMessages, canary, streams, returns, handOffs, inbox }));
176
211
  http.requestTimeout = 20_000;
177
212
  http.headersTimeout = 10_000;
178
213
  http.maxHeadersCount = 32;
@@ -265,6 +300,7 @@ export async function serve(version, options = {}) {
265
300
  // loop throttles its own peer polls and never holds up activity.
266
301
  void handOffs?.tick().catch(() => { });
267
302
  void returns?.tick();
303
+ void inbox?.tick().catch(() => { });
268
304
  })().finally(() => { recording = false; }).catch(() => { });
269
305
  }, 5000);
270
306
  await new Promise(resolve => {
@@ -0,0 +1,13 @@
1
+ /** Public subscription metadata only. Credentials never enter this contract. */
2
+ export interface Subscription {
3
+ plan: string;
4
+ startedAt?: string;
5
+ renewsAt?: string;
6
+ renewsEstimated?: boolean;
7
+ checkedAt?: string;
8
+ }
9
+ /** Provider identifiers, not arbitrary free text or credentials. */
10
+ export declare function planName(value: unknown): string | undefined;
11
+ export declare function subscriptionDate(value: unknown): string | undefined;
12
+ /** Next anniversary in UTC, always using the original day (Jan 31 -> Feb 28 -> Mar 31). */
13
+ export declare function monthlyAnniversary(startedAt: string, now: Date): string | undefined;
@@ -0,0 +1,24 @@
1
+ /** Provider identifiers, not arbitrary free text or credentials. */
2
+ export function planName(value) {
3
+ if (typeof value !== "string" || !/^[a-z0-9_+ -]{1,64}$/i.test(value) || !value.trim())
4
+ return undefined;
5
+ return value.trim().replace(/^default_claude_/, "").replace(/^claude_/, "").split(/[_ -]+/)
6
+ .map(word => /^\d+x$/i.test(word) ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
7
+ }
8
+ export function subscriptionDate(value) {
9
+ const time = typeof value === "string" && /^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(value) ? Date.parse(value)
10
+ : typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value < 32_503_680_000 ? value * 1000 : NaN;
11
+ return Number.isFinite(time) && time > 0 && time < 32_503_680_000_000 ? new Date(time).toISOString() : undefined;
12
+ }
13
+ /** Next anniversary in UTC, always using the original day (Jan 31 -> Feb 28 -> Mar 31). */
14
+ export function monthlyAnniversary(startedAt, now) {
15
+ const start = new Date(startedAt);
16
+ if (!Number.isFinite(start.getTime()) || start > now)
17
+ return undefined;
18
+ const candidate = (month) => {
19
+ const lastDay = new Date(Date.UTC(now.getUTCFullYear(), month + 1, 0)).getUTCDate();
20
+ return new Date(Date.UTC(now.getUTCFullYear(), month, Math.min(start.getUTCDate(), lastDay), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds(), start.getUTCMilliseconds()));
21
+ };
22
+ const next = candidate(now.getUTCMonth());
23
+ return (next > now ? next : candidate(now.getUTCMonth() + 1)).toISOString();
24
+ }
@@ -56,6 +56,7 @@ export const herdrTerminal = {
56
56
  return { HERDR_ENV: "1", HERDR_SOCKET_PATH: herdrSocketPath(server), HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane };
57
57
  },
58
58
  async focusPane(server, pane) { await rpc(server, "pane.focus", { pane_id: pane }); },
59
+ async closePane(server, pane) { await rpc(server, "pane.close", { pane_id: pane }); },
59
60
  async renamePane(server, pane, label) { await rpc(server, "pane.rename", { pane_id: pane, label }); },
60
61
  async groupAction(server, operation, { workspace, tab }, label) {
61
62
  await rpc(server, `${tab ? "tab" : "workspace"}.${operation}`, { ...(tab ? { tab_id: tab } : { workspace_id: workspace }), ...(label ? { label } : {}) });
@@ -480,6 +480,7 @@ export const tmuxTerminal = {
480
480
  await tmux(server, ["select-window", "-t", target]);
481
481
  await tmux(server, ["select-pane", "-t", target]);
482
482
  },
483
+ async closePane(server, pane) { await tmux(server, ["kill-pane", "-t", toTmuxId(pane, "p")]); },
483
484
  async groupAction(server, operation, { workspace, tab }, label) {
484
485
  if (tab) {
485
486
  const target = toTmuxId(tab, "w");