@phren/cli 0.3.32 → 0.3.34

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.
@@ -2,3 +2,7 @@
2
2
  * same Mac as its hostname, the hostname's first label and its Bonjour name.
3
3
  * The Hook reports them in /v1/health so a peer can recognize this computer. */
4
4
  export declare function localNames(): string[];
5
+ /** The name a schedule should carry for this computer: the Sharing name on a
6
+ * Mac (the hostname there follows the network, "Mac" or "Mac.example.net"),
7
+ * otherwise the hostname. */
8
+ export declare function stableComputerName(): string;
@@ -11,6 +11,25 @@ export function localNames() {
11
11
  names.push(execFileSync("scutil", ["--get", "LocalHostName"], { encoding: "utf8", timeout: 1_000 }).trim());
12
12
  }
13
13
  catch { /* No Bonjour name set: the hostname forms above still match. */ }
14
+ // The name people see in Sharing ("Sam’s Mac mini"), which the phone and schedules use.
15
+ try {
16
+ names.push(execFileSync("scutil", ["--get", "ComputerName"], { encoding: "utf8", timeout: 1_000 }).trim());
17
+ }
18
+ catch { /* No Sharing name set. */ }
14
19
  }
15
20
  return [...new Set(names.filter(Boolean))];
16
21
  }
22
+ /** The name a schedule should carry for this computer: the Sharing name on a
23
+ * Mac (the hostname there follows the network, "Mac" or "Mac.example.net"),
24
+ * otherwise the hostname. */
25
+ export function stableComputerName() {
26
+ if (process.platform === "darwin") {
27
+ try {
28
+ const name = execFileSync("scutil", ["--get", "ComputerName"], { encoding: "utf8", timeout: 1_000 }).trim();
29
+ if (name)
30
+ return name;
31
+ }
32
+ catch { /* No Sharing name set: fall back to the hostname. */ }
33
+ }
34
+ return hostname();
35
+ }
@@ -24,6 +24,10 @@ export declare function claudeEffortReply(text: string): EffortReply | undefined
24
24
  /** Empty prompts can draw a dim placeholder. Only ANSI evidence that every
25
25
  * character after the prompt is dim distinguishes that from a person's draft. */
26
26
  export declare function emptyComposer(line: string): boolean;
27
+ /** Typing a slash command into a draft or an open menu would corrupt both, so
28
+ * the terminal must show an empty composer and no menu first. The `code` says
29
+ * which: the phone names the cause and offers the terminal. */
30
+ export declare function assertComposerReady(before: string, action: string): void;
27
31
  /** Only a footer below Codex's empty composer proves the active model. Text
28
32
  * in history, a menu, or the startup banner must never confirm a switch. */
29
33
  export declare function codexModelStatus(text: string, model: AgentModel): boolean;
@@ -82,6 +82,21 @@ export function emptyComposer(line) {
82
82
  }
83
83
  return prompt;
84
84
  }
85
+ /** Typing a slash command into a draft or an open menu would corrupt both, so
86
+ * the terminal must show an empty composer and no menu first. The `code` says
87
+ * which: the phone names the cause and offers the terminal. */
88
+ export function assertComposerReady(before, action) {
89
+ const composer = before.split(/\r?\n/).reverse().find(line => /^\s*[›❯>]/.test(stripTerminal(line)));
90
+ if (visibleTerminalChoice(stripTerminal(before))) {
91
+ throw new BridgeError(409, `A menu is open in the terminal. Open terminal to finish it, then ${action}.`, { code: "terminal-menu" });
92
+ }
93
+ if (!composer) {
94
+ throw new BridgeError(409, `Phren couldn't find the terminal's input line. Open terminal to ${action}.`, { code: "terminal-unreadable" });
95
+ }
96
+ if (!emptyComposer(composer)) {
97
+ throw new BridgeError(409, `There's unsent text in the terminal. Send or clear it, then ${action}.`, { code: "terminal-draft" });
98
+ }
99
+ }
85
100
  /** Only a footer below Codex's empty composer proves the active model. Text
86
101
  * in history, a menu, or the startup banner must never confirm a switch. */
87
102
  export function codexModelStatus(text, model) {
@@ -182,10 +197,7 @@ export class ModelSwitcher {
182
197
  let claudeEffort;
183
198
  const before = await this.hooks.paneLines(target, false);
184
199
  // Preserve a person's draft and any pre-existing menu. Never clear it.
185
- const composer = before.split(/\r?\n/).reverse().find(line => /^\s*[›❯>]/.test(stripTerminal(line)));
186
- if (!composer || !emptyComposer(composer) || visibleTerminalChoice(stripTerminal(before))) {
187
- throw new BridgeError(409, "The terminal has a draft or an unreadable prompt. Open terminal before switching models.");
188
- }
200
+ assertComposerReady(before, "switch models");
189
201
  await validate(true);
190
202
  opened = true;
191
203
  this.hooks.menuOpened(target, "/model");
@@ -90,6 +90,8 @@ export interface ScheduleStatus extends Schedule {
90
90
  lastRun: Omit<ScheduleRun, "id" | "scheduleId" | "project"> | null;
91
91
  lastRuns: ScheduleRun[];
92
92
  running: boolean;
93
+ /** Whether this computer owns the schedule: it runs it and answers Run now. */
94
+ owned: boolean;
93
95
  }
94
96
  interface ScheduleDocument {
95
97
  document: Record<string, unknown>;
@@ -121,8 +121,16 @@ export function canonicalComputer(value) {
121
121
  const normalized = value.trim().toLowerCase();
122
122
  return normalized.endsWith(".local") ? normalized.slice(0, -".local".length) : normalized;
123
123
  }
124
+ /** One computer's names differ only in punctuation across macOS ("Sam’s Mac mini",
125
+ * "Sams-Mac-mini"), so letters and digits alone also match. */
126
+ function foldedComputer(value) {
127
+ return canonicalComputer(value).replace(/[^\p{L}\p{N}]/gu, "");
128
+ }
124
129
  export function computerMatches(wanted, current) {
125
- return canonicalComputer(wanted) === canonicalComputer(current);
130
+ if (canonicalComputer(wanted) === canonicalComputer(current))
131
+ return true;
132
+ const folded = foldedComputer(wanted);
133
+ return folded !== "" && folded === foldedComputer(current);
126
134
  }
127
135
  export function scheduleNotifications(schedule) {
128
136
  return new Set(schedule.notify ?? ["finish", "failure"]);
@@ -8,6 +8,8 @@ export declare class Scheduler {
8
8
  private readonly launch;
9
9
  private readonly runsFile;
10
10
  private readonly computer;
11
+ /** Every name this computer answers to; a schedule names one of them. */
12
+ private readonly names;
11
13
  private readonly locateProject;
12
14
  private readonly push?;
13
15
  private readonly log;
@@ -25,6 +27,8 @@ export declare class Scheduler {
25
27
  launch: ScheduleLauncher;
26
28
  runsFile: string;
27
29
  computer?: string | (() => string);
30
+ /** Further names this computer answers to, such as its Hook computer id. */
31
+ aliases?: string[];
28
32
  locateProject?: (project: string) => Promise<string | undefined>;
29
33
  push?: SchedulePushSender;
30
34
  log?: (message: string) => void;
@@ -32,6 +36,7 @@ export declare class Scheduler {
32
36
  private projectDirectories;
33
37
  private projectDirectory;
34
38
  private exclusive;
39
+ private owns;
35
40
  statuses(): Promise<{
36
41
  computer: string;
37
42
  timeZone: string;
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { stat } from "node:fs/promises";
3
- import { hostname } from "node:os";
3
+ import { localNames, stableComputerName } from "./computer-names.js";
4
4
  import path from "node:path";
5
5
  import { BridgeError } from "./protocol.js";
6
6
  import { getProjectSourcePath } from "../project-config.js";
@@ -15,6 +15,8 @@ export class Scheduler {
15
15
  launch;
16
16
  runsFile;
17
17
  computer;
18
+ /** Every name this computer answers to; a schedule names one of them. */
19
+ names;
18
20
  locateProject;
19
21
  push;
20
22
  log;
@@ -35,8 +37,10 @@ export class Scheduler {
35
37
  this.computer = options.computer;
36
38
  else {
37
39
  const computer = options.computer;
38
- this.computer = () => computer ?? hostname();
40
+ this.computer = () => computer ?? stableComputerName();
39
41
  }
42
+ const aliases = options.aliases ?? [];
43
+ this.names = options.computer === undefined ? () => [...localNames(), ...aliases] : () => [this.computer(), ...aliases];
40
44
  this.locateProject = options.locateProject ?? (async () => undefined);
41
45
  this.push = options.push;
42
46
  this.log = options.log ?? (message => console.error(message));
@@ -60,8 +64,11 @@ export class Scheduler {
60
64
  release();
61
65
  }
62
66
  }
67
+ owns(schedule, names = this.names()) {
68
+ return names.some(name => computerMatches(schedule.computer, name));
69
+ }
63
70
  async statuses() {
64
- const runs = await readScheduleRuns(this.runsFile), result = [], computer = this.computer();
71
+ const runs = await readScheduleRuns(this.runsFile), result = [], computer = this.computer(), names = this.names();
65
72
  for (const directory of this.projectDirectories()) {
66
73
  let schedules;
67
74
  try {
@@ -75,8 +82,9 @@ export class Scheduler {
75
82
  const matching = runs.filter(run => (run.scheduleProject ?? run.project) === project && run.scheduleId === schedule.id);
76
83
  const { lastRun: last, lastRuns } = latestScheduleBatch(matching);
77
84
  const running = matching.some(run => runningStatuses.has(run.status));
78
- const due = computerMatches(schedule.computer, computer) ? nextRun(schedule, last) : null;
79
- result.push({ ...schedule, project, lastRuns, nextRun: due?.toISOString() ?? null,
85
+ const due = this.owns(schedule, names) ? nextRun(schedule, last) : null;
86
+ const owned = this.owns(schedule, names);
87
+ result.push({ ...schedule, project, lastRuns, owned, nextRun: due?.toISOString() ?? null,
80
88
  lastRun: last ? { startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}), status: last.status,
81
89
  ...(last.batchId ? { batchId: last.batchId, scheduleProject: last.scheduleProject } : {}),
82
90
  ...(last.reason ? { reason: last.reason } : {}),
@@ -112,7 +120,7 @@ export class Scheduler {
112
120
  if (expectedUpdatedAt !== undefined && Date.parse(expectedUpdatedAt) !== Date.parse(schedule.updatedAt)) {
113
121
  throw new BridgeError(409, "This computer has a different schedule revision. Wait for store sync to finish, refresh the schedule, and try Run now again.");
114
122
  }
115
- if (!computerMatches(schedule.computer, this.computer()))
123
+ if (!this.owns(schedule))
116
124
  throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
117
125
  const runs = await readScheduleRuns(this.runsFile);
118
126
  const matching = runs.filter(run => (run.scheduleProject ?? run.project) === project && run.scheduleId === id);
@@ -155,6 +155,7 @@ export async function serve(version, options = {}) {
155
155
  const codexQuestions = new CodexQuestions(undefined, codexServers);
156
156
  const scheduleStore = defaultPhrenPath();
157
157
  const scheduler = modules.has("schedules") ? new Scheduler({ now: () => new Date(), store: scheduleStore, runsFile: scheduleRunsFile(),
158
+ aliases: [computerID],
158
159
  // A schedule starts in its project's folder, which the Hook resolved itself.
159
160
  launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore),
160
161
  push: { notify: value => agentHooks.push.notifySchedule(value) },
@@ -1,12 +1,11 @@
1
1
  import { open, stat } from "node:fs/promises";
2
2
  import { z } from "zod";
3
3
  import { stripTerminal } from "../terminal-text.js";
4
- import { visibleTerminalChoice } from "./agent-hooks.js";
5
4
  import { claudeSuggestion } from "./claude-suggestion.js";
6
5
  import { codexServers } from "./codex-servers.js";
7
6
  import { validateTarget } from "./herdr.js";
8
7
  import { intervalFromEnv } from "./limits.js";
9
- import { emptyComposer } from "./model-switch.js";
8
+ import { assertComposerReady } from "./model-switch.js";
10
9
  import { claudeFooterMode, permissionModes } from "./permission-mode.js";
11
10
  import { BridgeError, object, PERMISSION_MODES } from "./protocol.js";
12
11
  import { terminalProvider } from "./terminal.js";
@@ -216,10 +215,7 @@ export class SettingsSwitcher {
216
215
  const slash = async (command) => {
217
216
  // Typing into a draft would corrupt both it and the command.
218
217
  const before = await this.hooks.paneLines(target, false);
219
- const composer = before.split(/\r?\n/).reverse().find(line => /^\s*[›❯>]/.test(stripTerminal(line)));
220
- if (!composer || !emptyComposer(composer) || visibleTerminalChoice(stripTerminal(before))) {
221
- throw new BridgeError(409, "The terminal has a draft or an unreadable prompt. Open terminal before changing settings.");
222
- }
218
+ assertComposerReady(before, "change settings");
223
219
  await validate();
224
220
  await terminalProvider().prompt(target.server, target.pane, command);
225
221
  };
@@ -154,6 +154,9 @@ export declare const CLAUDE_REPORT_MAX_AGE_MS: number;
154
154
  * phone's cards, rings or widgets.
155
155
  */
156
156
  export declare function settleClaudeUsage(usage: AccountUsage, now: number): AccountUsage;
157
+ /** `opencode stats` scans OpenCode's whole database, several CPU-seconds on a
158
+ * busy machine, for a rolling seven-day cost that barely moves in a minute. */
159
+ export declare const OPENCODE_STATS_REUSE_MS: number;
157
160
  export declare class AccountUsageReader {
158
161
  private readCodex;
159
162
  private now;
@@ -170,6 +173,8 @@ export declare class AccountUsageReader {
170
173
  private claudePending;
171
174
  private spendingCached;
172
175
  private spendingPending;
176
+ private openCodeCached?;
177
+ private openCodePending?;
173
178
  constructor(readCodex?: typeof readCodexLimits, now?: () => number, readClaudeLive?: (now: Date, home: ClaudeHome) => Promise<AccountUsage | undefined>, readOpenCode?: (now: Date) => Promise<AccountUsage>, readOpenRouter?: (now: Date) => Promise<AccountUsage | undefined>, readOpenCodeGo?: (now: Date) => Promise<AccountUsage>, readCopilot?: (now: Date) => Promise<AccountUsage>, platform?: NodeJS.Platform, readElevenLabs?: (now: Date) => Promise<AccountUsage | undefined>);
174
179
  /** `allAccounts`: one Claude row per home. Otherwise only the default home's, as
175
180
  * before accounts existed, since older phones refuse two rows of one source. */
@@ -180,6 +185,8 @@ export declare class AccountUsageReader {
180
185
  limits(allAccounts?: boolean): Promise<AccountUsage[]>;
181
186
  /** ElevenLabs is read only when the caller shows it: every read spends a request against the key's quota. */
182
187
  private spending;
188
+ /** One `opencode stats` run serves every spending key for `OPENCODE_STATS_REUSE_MS`. */
189
+ private openCode;
183
190
  /** Live first, so the phone's minute-by-minute poll keeps Claude current
184
191
  * even when Claude Code is not running; the local snapshot is the backup.
185
192
  * Off macOS a non-default home reads its own credentials file; on macOS it
@@ -727,6 +727,9 @@ export function settleClaudeUsage(usage, now) {
727
727
  const since = usage.updatedAt?.slice(0, 10);
728
728
  return { ...usage, windows, message: `No usage report from Claude on this computer${since ? ` since ${since}` : ""}. It updates when Claude Code runs here.` };
729
729
  }
730
+ /** `opencode stats` scans OpenCode's whole database, several CPU-seconds on a
731
+ * busy machine, for a rolling seven-day cost that barely moves in a minute. */
732
+ export const OPENCODE_STATS_REUSE_MS = 10 * 60_000;
730
733
  export class AccountUsageReader {
731
734
  readCodex;
732
735
  now;
@@ -743,6 +746,8 @@ export class AccountUsageReader {
743
746
  claudePending = new Map();
744
747
  spendingCached = new Map();
745
748
  spendingPending = new Map();
749
+ openCodeCached;
750
+ openCodePending;
746
751
  constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = now => readOpenCodeUsage("opencode", now), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage, platform = process.platform, readElevenLabs = liveElevenLabsUsage) {
747
752
  this.readCodex = readCodex;
748
753
  this.now = now;
@@ -784,7 +789,7 @@ export class AccountUsageReader {
784
789
  if (!cached || this.now() - cached.at >= 60_000) {
785
790
  const at = this.now();
786
791
  if (!this.spendingPending.has(key)) {
787
- const pending = Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at)),
792
+ const pending = Promise.all([this.openCode(at), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at)),
788
793
  includeCopilot ? this.readCopilot(new Date(at)) : Promise.resolve(undefined),
789
794
  includeElevenLabs ? this.readElevenLabs(new Date(at)).catch(() => undefined) : Promise.resolve(undefined)])
790
795
  .then(([openCode, openCodeGo, openRouter, copilot, elevenLabs]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : []), ...(copilot ? [copilot] : []), ...(elevenLabs ? [elevenLabs] : [])])
@@ -795,6 +800,15 @@ export class AccountUsageReader {
795
800
  }
796
801
  return this.spendingPending.get(key) ?? cached.value;
797
802
  }
803
+ /** One `opencode stats` run serves every spending key for `OPENCODE_STATS_REUSE_MS`. */
804
+ openCode(at) {
805
+ if (this.openCodeCached && at - this.openCodeCached.at < OPENCODE_STATS_REUSE_MS)
806
+ return Promise.resolve(this.openCodeCached.value);
807
+ this.openCodePending ??= this.readOpenCode(new Date(at))
808
+ .then(value => { this.openCodeCached = { at, value }; return value; })
809
+ .finally(() => { this.openCodePending = undefined; });
810
+ return this.openCodePending;
811
+ }
798
812
  /** Live first, so the phone's minute-by-minute poll keeps Claude current
799
813
  * even when Claude Code is not running; the local snapshot is the backup.
800
814
  * Off macOS a non-default home reads its own credentials file; on macOS it