@phren/cli 0.3.14 → 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 (44) 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/conductor-group.d.ts +2 -0
  7. package/dist/bridge/conductor-group.js +17 -5
  8. package/dist/bridge/conductor-sets.js +23 -3
  9. package/dist/bridge/dispatch-command.d.ts +1 -0
  10. package/dist/bridge/dispatch-command.js +40 -2
  11. package/dist/bridge/dispatch-returns.d.ts +21 -1
  12. package/dist/bridge/dispatch-returns.js +120 -12
  13. package/dist/bridge/dispatch.d.ts +76 -0
  14. package/dist/bridge/dispatch.js +7 -0
  15. package/dist/bridge/hand-off-queue.d.ts +3 -0
  16. package/dist/bridge/hand-off-queue.js +9 -0
  17. package/dist/bridge/owner-inbox-view.d.ts +6 -0
  18. package/dist/bridge/owner-inbox-view.js +32 -0
  19. package/dist/bridge/owner-inbox.d.ts +117 -0
  20. package/dist/bridge/owner-inbox.js +120 -0
  21. package/dist/bridge/return-contract.d.ts +35 -0
  22. package/dist/bridge/return-contract.js +10 -0
  23. package/dist/bridge/server-launch.js +12 -1
  24. package/dist/bridge/server-routes.d.ts +5 -0
  25. package/dist/bridge/server-routes.js +22 -1
  26. package/dist/bridge/server.js +37 -1
  27. package/dist/bridge/subscription.d.ts +13 -0
  28. package/dist/bridge/subscription.js +24 -0
  29. package/dist/bridge/terminal-herdr.js +1 -0
  30. package/dist/bridge/terminal-tmux.js +1 -0
  31. package/dist/bridge/terminal.d.ts +1 -0
  32. package/dist/bridge/terminal.js +1 -0
  33. package/dist/bridge/usage.d.ts +6 -0
  34. package/dist/bridge/usage.js +57 -10
  35. package/dist/bridge/worker-close.d.ts +10 -0
  36. package/dist/bridge/worker-close.js +77 -0
  37. package/dist/bridge/worker-reports.d.ts +10 -0
  38. package/dist/bridge/worker-reports.js +63 -0
  39. package/dist/bridge-hook.mjs +5087 -4487
  40. package/dist/cli-registry.js +9 -2
  41. package/dist/modules/registry.js +5 -5
  42. package/dist/tools/dispatch.js +33 -1
  43. package/package.json +1 -1
  44. package/starter/global/skills/conductor/SKILL.md +35 -0
@@ -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");
@@ -111,6 +111,7 @@ export interface TerminalProvider {
111
111
  }): Record<string, string> | undefined;
112
112
  focusPane(server: string, pane: string): Promise<void>;
113
113
  /** Sets the pane's own label (Herdr's pane label, a tmux pane option), shown by the Hook as the session's name. */
114
+ closePane(server: string, pane: string): Promise<void>;
114
115
  renamePane(server: string, pane: string, label: string): Promise<void>;
115
116
  /** Focuses, renames or closes a whole tab (when `tab` is set) or workspace. */
116
117
  groupAction(server: string, operation: "focus" | "rename" | "close", group: {
@@ -53,6 +53,7 @@ export const routedTerminal = {
53
53
  startAgent: (server, pane, agent) => route(server).startAgent(server, pane, agent),
54
54
  paneEnv: (server, place) => route(server).paneEnv?.(server, place),
55
55
  focusPane: (server, pane) => route(server).focusPane(server, pane),
56
+ closePane: (server, pane) => route(server).closePane(server, pane),
56
57
  renamePane: (server, pane, label) => route(server).renamePane(server, pane, label),
57
58
  groupAction: (server, operation, group, label) => route(server).groupAction(server, operation, group, label),
58
59
  };
@@ -1,5 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { type AccountRef, type ClaudeHome } from "./claude-accounts.js";
3
+ import { type Subscription } from "./subscription.js";
4
+ export type { Subscription } from "./subscription.js";
3
5
  export interface UsageWindow {
4
6
  id: string;
5
7
  name: string;
@@ -29,6 +31,7 @@ export interface AccountUsage {
29
31
  updatedAt?: string;
30
32
  message?: string;
31
33
  spend?: UsageSpend;
34
+ subscription?: Subscription;
32
35
  /** Opaque key identity used only to avoid counting one OpenRouter key twice. */
33
36
  accountId?: string;
34
37
  /** Which Claude report fed this account: the status-line rate_limits payload
@@ -39,6 +42,9 @@ export interface AccountUsage {
39
42
  account?: AccountRef;
40
43
  }
41
44
  export declare function codexUsage(value: unknown, now?: Date): AccountUsage;
45
+ /** Display metadata from the ID token's claims only, never an authentication decision. */
46
+ export declare function codexSubscription(idToken: unknown, now?: Date): Subscription | undefined;
47
+ export declare function readCodexSubscription(file?: string, now?: Date): Promise<Subscription | undefined>;
42
48
  /** Parse OpenCode's own cost ledger. `stats --days 7` is a rolling local view. */
43
49
  export declare function openCodeUsage(output: string, now?: Date): AccountUsage;
44
50
  /** Read the authoritative cost that OpenCode records for its local sessions. */
@@ -3,14 +3,15 @@ import { createHash } from "node:crypto";
3
3
  import { statSync } from "node:fs";
4
4
  import { lstat, open, readFile, readdir } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
- import { claudeConfigDir } from "../home-paths.js";
6
+ import { claudeConfigDir, codexHome } from "../home-paths.js";
7
7
  import path from "node:path";
8
8
  import { promisify } from "node:util";
9
9
  import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
10
10
  import { stripTerminal } from "../terminal-text.js";
11
11
  import { codexExecutable } from "./codex-binary.js";
12
12
  import { readSpeechKey } from "./speech-key.js";
13
- import { CODEX_ACCOUNT, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
13
+ import { CODEX_ACCOUNT, claudeAccountSubscription, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
14
+ import { planName, subscriptionDate } from "./subscription.js";
14
15
  const exec = promisify(execFile);
15
16
  /** The status-line snapshot: `usage/claude.json` for the default home, `usage/claude-<id>.json` for others. */
16
17
  const claudeFile = (home) => path.join(bridgeRoot(), "usage", home && !home.isDefault ? `claude-${home.id}.json` : "claude.json");
@@ -49,6 +50,44 @@ export function codexUsage(value, now = new Date()) {
49
50
  return { source: "codex", windows, updatedAt: now.toISOString(),
50
51
  ...(!windows.length ? { message: "Codex has not reported account limits. Sign in with your ChatGPT account in Codex on this computer." } : {}) };
51
52
  }
53
+ /** Display metadata from the ID token's claims only, never an authentication decision. */
54
+ export function codexSubscription(idToken, now = new Date()) {
55
+ if (typeof idToken !== "string" || idToken.length > 65_536)
56
+ return undefined;
57
+ const parts = idToken.split(".");
58
+ if (parts.length !== 3 || !/^[A-Za-z0-9_-]+$/.test(parts[1]))
59
+ return undefined;
60
+ try {
61
+ const claims = object(JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")));
62
+ const auth = object(claims["https://api.openai.com/auth"]);
63
+ const plan = planName(auth.chatgpt_plan_type);
64
+ if (!plan)
65
+ return undefined;
66
+ const startedAt = subscriptionDate(auth.chatgpt_subscription_active_start);
67
+ const renewsAt = subscriptionDate(auth.chatgpt_subscription_active_until);
68
+ return { plan, ...(startedAt ? { startedAt } : {}), ...(renewsAt ? { renewsAt } : {}), checkedAt: now.toISOString() };
69
+ }
70
+ catch {
71
+ return undefined;
72
+ }
73
+ }
74
+ export async function readCodexSubscription(file = path.join(codexHome(), "auth.json"), now = new Date()) {
75
+ try {
76
+ const handle = await open(file, "r");
77
+ try {
78
+ const stat = await handle.stat();
79
+ if (!stat.isFile() || stat.size > 131_072)
80
+ return undefined;
81
+ return codexSubscription(object(object(JSON.parse(await handle.readFile("utf8"))).tokens).id_token, now);
82
+ }
83
+ finally {
84
+ await handle.close();
85
+ }
86
+ }
87
+ catch {
88
+ return undefined;
89
+ }
90
+ }
52
91
  /** Parse OpenCode's own cost ledger. `stats --days 7` is a rolling local view. */
53
92
  export function openCodeUsage(output, now = new Date()) {
54
93
  const plain = stripTerminal(output);
@@ -224,7 +263,9 @@ export function openCodeGoUsage(windows, refusals, now, hasKey, planError) {
224
263
  reached.length ? `Go is refusing requests: the ${reached.join(" and ")} limit is reached.` : undefined,
225
264
  refused,
226
265
  ].filter(Boolean).join(" ");
227
- return { source: "opencode-go", windows, updatedAt: now.toISOString(), ...(message ? { message } : {}) };
266
+ const renewsAt = windows.find(w => w.id === "opencode-go:plan:30d")?.resetsAt;
267
+ const subscription = hasKey ? { plan: "Go", ...(renewsAt ? { renewsAt } : {}), checkedAt: now.toISOString() } : undefined;
268
+ return { source: "opencode-go", windows, ...(subscription ? { subscription } : {}), updatedAt: now.toISOString(), ...(message ? { message } : {}) };
228
269
  }
229
270
  /** The accounts one caller can read: the sources it names, and Go's plan
230
271
  * windows only for a caller that asked for them (`goPlan=1`). */
@@ -299,12 +340,16 @@ async function liveOpenRouterUsage(now) {
299
340
  export function elevenLabsUsage(value, now = new Date()) {
300
341
  const sub = object(value);
301
342
  const used = sub.character_count, limit = sub.character_limit;
343
+ const plan = planName(sub.tier);
344
+ const renewsAt = subscriptionDate(object(sub.next_invoice).next_payment_attempt_unix);
345
+ const subscription = plan ? { plan, ...(renewsAt ? { renewsAt } : {}), checkedAt: now.toISOString() } : undefined;
346
+ const metadata = subscription ? { subscription } : {};
302
347
  const count = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
303
348
  if (!count(used) || !count(limit) || limit === 0) {
304
- return { source: "elevenlabs", windows: [], updatedAt: now.toISOString(), message: "ElevenLabs did not report a character limit for this key." };
349
+ return { source: "elevenlabs", ...metadata, windows: [], updatedAt: now.toISOString(), message: "ElevenLabs did not report a character limit for this key." };
305
350
  }
306
351
  const entry = window("elevenlabs:characters", "Characters this period", Math.min(100, Math.round(used / limit * 1000) / 10), sub.next_character_count_reset_unix);
307
- return { source: "elevenlabs", windows: entry ? [{ ...entry, usedCharacters: used, limitCharacters: limit }] : [], updatedAt: now.toISOString() };
352
+ return { source: "elevenlabs", ...metadata, windows: entry ? [{ ...entry, usedCharacters: used, limitCharacters: limit }] : [], updatedAt: now.toISOString() };
308
353
  }
309
354
  /** The key the Hook already uses for /v1/speech, sent only to ElevenLabs; the answer carries counts, never the key. */
310
355
  export async function fetchElevenLabsUsage(key, fetchImpl = fetch, now = new Date()) {
@@ -596,9 +641,10 @@ export function copilotUsage(value, now = new Date()) {
596
641
  continue;
597
642
  windows.push({ id: key, name: names[key] ?? key, usedPercent: Math.round((100 - remaining) * 10) / 10, ...(reset ? { resetsAt: reset } : {}) });
598
643
  }
599
- const plan = safeText(result.copilot_plan);
600
- const notes = [plan ? `Plan: ${plan}.` : "", unlimited.length ? `Unlimited: ${unlimited.join(", ")}.` : ""].filter(Boolean).join(" ");
644
+ const plan = planName(result.copilot_plan);
645
+ const notes = [safeText(result.copilot_plan) ? `Plan: ${safeText(result.copilot_plan)}.` : "", unlimited.length ? `Unlimited: ${unlimited.join(", ")}.` : ""].filter(Boolean).join(" ");
601
646
  return { source: "copilot", windows, updatedAt: now.toISOString(),
647
+ ...(plan ? { subscription: { plan, ...(reset ? { renewsAt: reset } : {}), checkedAt: now.toISOString() } } : {}),
602
648
  ...(notes || !windows.length ? { message: notes || "GitHub reported no Copilot quotas for this account." } : {}) };
603
649
  }
604
650
  /** The first GitHub CLI found; the Hook's service PATH may not include Homebrew. */
@@ -724,10 +770,11 @@ export class AccountUsageReader {
724
770
  const homes = allAccounts ? claudeHomes() : claudeHomes().slice(0, 1);
725
771
  const claudeRow = async (home) => {
726
772
  const email = claudeAccountEmail(home);
727
- return { ...settleClaudeUsage(await this.claude(home), this.now()), account: { ...claudeAccountRef(home), ...(email ? { email } : {}) } };
773
+ const subscription = claudeAccountSubscription(home, new Date(this.now()));
774
+ return { ...settleClaudeUsage(await this.claude(home), this.now()), ...(subscription ? { subscription } : {}), account: { ...claudeAccountRef(home), ...(email ? { email } : {}) } };
728
775
  };
729
- const [codexValue, claude] = await Promise.all([codex, Promise.all(homes.map(claudeRow))]);
730
- return [{ ...codexValue, account: CODEX_ACCOUNT }, ...claude];
776
+ const [codexValue, claude, subscription] = await Promise.all([codex, Promise.all(homes.map(claudeRow)), readCodexSubscription(undefined, new Date(this.now()))]);
777
+ return [{ ...codexValue, ...(subscription ? { subscription } : {}), account: CODEX_ACCOUNT }, ...claude];
731
778
  }
732
779
  /** ElevenLabs is read only when the caller shows it: every read spends a request against the key's quota. */
733
780
  async spending(includeCopilot, includeElevenLabs) {
@@ -0,0 +1,10 @@
1
+ import { type Json, type Target, type StartingTarget } from "./protocol.js";
2
+ import type { HandOffQueue } from "./hand-off-queue.js";
3
+ type ClosedTarget = Target | StartingTarget;
4
+ export declare function markWorkerClosed(target: ClosedTarget, terminal: string): Promise<void>;
5
+ export declare function intentionallyClosed(target: ClosedTarget): Promise<boolean>;
6
+ export declare function markPaneClosed(server: string, pane: Json): Promise<void>;
7
+ /** Called on the worker's computer only after the sender read the done return.
8
+ * Recheck this exact ended turn and skip any new work, background work or inbox. */
9
+ export declare function closeFinishedWorker(input: unknown, queue?: HandOffQueue): Promise<Json>;
10
+ export {};