@phren/cli 0.3.39 → 0.3.41

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.
@@ -1,3 +1,4 @@
1
+ import { type LinkResult, linkComputer } from "./link.js";
1
2
  import { type Json } from "./protocol.js";
2
3
  /** The Hook routes for linked computer sets (docs/conductor-sets.md). */
3
4
  interface LocalInfo {
@@ -17,4 +18,8 @@ export declare function readSets(info: LocalInfo): Promise<Json>;
17
18
  * on to every reachable member; a member's relay (with `namedAt`) is kept
18
19
  * when newer than the name held, and goes no further. */
19
20
  export declare function nameSet(data: Json): Promise<Json>;
21
+ /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
22
+ * on the computer whose set lists `name` as indirect or one-way, over this
23
+ * computer's own ssh login, one link at a time. */
24
+ export declare function linkSetMember(data: Json, link?: typeof linkComputer): Promise<LinkResult>;
20
25
  export {};
@@ -1,11 +1,12 @@
1
1
  import { z } from "zod";
2
- import { askPeers, buildSets, indirectMembers, localCaller } from "./conductor-group.js";
3
- import { readSetName, saveSetName } from "./conductor-role.js";
4
2
  import { computerLabel, readComputers } from "./computer-identity.js";
5
3
  import { localNames } from "./computer-names.js";
4
+ import { askPeers, buildSets, indirectMembers, localCaller } from "./conductor-group.js";
5
+ import { readSetName, saveSetName } from "./conductor-role.js";
6
6
  import { listsCaller } from "./health.js";
7
+ import { linkComputer } from "./link.js";
7
8
  import { optionalHookPeers, peerRequest } from "./peers.js";
8
- import { object } from "./protocol.js";
9
+ import { BridgeError, object } from "./protocol.js";
9
10
  import { localConductor } from "./server-launch.js";
10
11
  const callerSchema = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() });
11
12
  /** `GET /v1/conductor`: this computer's live conductor and what a peer needs
@@ -77,3 +78,22 @@ export async function nameSet(data) {
77
78
  }));
78
79
  return { ok: true, name: input.name, namedAt, told: told.sort(), unreachable: unreachable.sort((a, b) => a.computer.localeCompare(b.computer)) };
79
80
  }
81
+ const linkInput = z.object({ name: z.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,252}$/, "A computer name or ssh host.") }).strict();
82
+ let linking;
83
+ /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
84
+ * on the computer whose set lists `name` as indirect or one-way, over this
85
+ * computer's own ssh login, one link at a time. */
86
+ export async function linkSetMember(data, link = linkComputer) {
87
+ if (data && typeof data === "object" && "origin" in data)
88
+ throw new BridgeError(403, "Only the owner links computers, from the phone or `phren bridge link` in their own terminal.");
89
+ const { name } = linkInput.parse(data);
90
+ if (linking)
91
+ throw new BridgeError(409, `Already linking ${linking}. Try again when it finishes.`);
92
+ linking = name;
93
+ try {
94
+ return await link(name);
95
+ }
96
+ finally {
97
+ linking = undefined;
98
+ }
99
+ }
@@ -106,11 +106,29 @@ export async function candidateRepos(activity, env = process.env) {
106
106
  return undefined;
107
107
  }
108
108
  };
109
+ // The journal repeats a few folders hundreds of times: one git call each.
110
+ const roots = new Map();
111
+ const rootOf = (directory) => {
112
+ let root = roots.get(directory);
113
+ if (!root) {
114
+ root = toplevel(directory);
115
+ roots.set(directory, root);
116
+ }
117
+ return root;
118
+ };
119
+ const activityDirectory = (event) => typeof event.directory === "string" && path.isAbsolute(event.directory) ? event.directory : undefined;
120
+ // Look the folders up eight at a time: a folder where git stalls (macOS can
121
+ // hold ~/Downloads from a background process) costs its 5 s timeout once.
122
+ const pending = [...new Set(activity.map(activityDirectory).filter((d) => !!d))];
123
+ await Promise.all(Array.from({ length: Math.min(8, pending.length) }, async () => {
124
+ for (let directory = pending.shift(); directory !== undefined; directory = pending.shift())
125
+ await rootOf(directory);
126
+ }));
109
127
  for (const event of [...activity].reverse()) {
110
- const directory = typeof event.directory === "string" ? event.directory : undefined;
111
- if (!directory || !path.isAbsolute(directory))
128
+ const directory = activityDirectory(event);
129
+ if (!directory)
112
130
  continue;
113
- const root = await toplevel(directory);
131
+ const root = await rootOf(directory);
114
132
  if (root)
115
133
  await offer(root, "activity", typeof event.at === "string" ? event.at : undefined);
116
134
  }
@@ -120,7 +138,7 @@ export async function candidateRepos(activity, env = process.env) {
120
138
  const directory = JSON.parse(`"${match[1]}"`);
121
139
  if (!path.isAbsolute(directory))
122
140
  continue;
123
- const root = await toplevel(directory);
141
+ const root = await rootOf(directory);
124
142
  if (root)
125
143
  await offer(root, "herdr");
126
144
  }
@@ -18,8 +18,17 @@ export interface StoreSync {
18
18
  lastPushAt?: string;
19
19
  lastSuccessfulPushAt?: string;
20
20
  consecutiveFailures?: number;
21
+ lastSuccessfulPullAt?: string;
22
+ /** The newest successful pull or push. */
23
+ lastSyncedAt?: string;
24
+ /** Both the store and its remote have commits the other lacks. */
25
+ diverged?: boolean;
26
+ /** No successful sync for over STORE_STALE_MS while the store has a remote. */
27
+ stale?: boolean;
21
28
  /** The last sync failure in plain words, only while the store is failing. */
22
29
  error?: string;
30
+ /** One line a computer list shows as is when the store needs attention. */
31
+ warning?: string;
23
32
  degraded: boolean;
24
33
  }
25
34
  export interface LastScheduledRun {
@@ -121,6 +130,12 @@ export declare function toolVersion(tool: string, executable?: string, args?: st
121
130
  export declare function clearVersionCache(): void;
122
131
  /** Branch and ahead/behind against the upstream as last fetched; nothing is fetched here. */
123
132
  export declare function storeSync(store: string): Promise<StoreSync[]>;
133
+ /**
134
+ * The degraded stores' warnings for the overview: the last answer at once,
135
+ * refreshed in the background once a minute old, so the overview never
136
+ * waits on Git.
137
+ */
138
+ export declare function cachedStoreWarnings(store: string, now?: number): string[];
124
139
  /** The newest run in schedule-runs.jsonl, with its schedule's name when the project still has it. */
125
140
  export declare function lastScheduledRun(store: string, runsFile?: string): Promise<LastScheduledRun | null>;
126
141
  /** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
@@ -13,6 +13,7 @@ import { BridgeError, bridgeRoot, errorCode } from "./protocol.js";
13
13
  import { canonicalComputer, latestScheduleBatch, readScheduleDocument, readScheduleRuns, scheduleRunsFile } from "./schedules.js";
14
14
  import { countGit } from "./metrics.js";
15
15
  import { tmuxHealth } from "./terminal-tmux.js";
16
+ import { lastSyncedAt, STORE_STALE_MS, storeWarning } from "../sync/store-sync.js";
16
17
  const exec = promisify(execFile);
17
18
  /** The running servers the Hook lists (Herdr's, else tmux's) and tmux's own state. */
18
19
  export async function terminalHealth() {
@@ -126,14 +127,43 @@ export async function storeSync(store) {
126
127
  result.lastSuccessfulPushAt = sync.lastSuccessfulPushAt;
127
128
  if (sync?.consecutiveFailures)
128
129
  result.consecutiveFailures = sync.consecutiveFailures;
130
+ if (sync?.lastSuccessfulPullAt)
131
+ result.lastSuccessfulPullAt = sync.lastSuccessfulPullAt;
132
+ const synced = lastSyncedAt(sync);
133
+ if (synced)
134
+ result.lastSyncedAt = synced;
129
135
  const failing = sync?.lastPushStatus !== undefined && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
130
136
  const pullFailed = sync?.lastPullStatus === "error";
131
137
  if (failing || pullFailed)
132
- result.error = plainError(sync?.lastPushDetail || sync?.lastPullDetail) ?? `Last sync: ${sync?.lastPushStatus ?? "pull failed"}`;
133
- result.degraded = assessSyncOutage(sync).degraded;
138
+ result.error = plainError(sync?.lastError || sync?.lastPushDetail || sync?.lastPullDetail) ?? `Last sync: ${sync?.lastPushStatus ?? "pull failed"}`;
139
+ if (upstream) {
140
+ result.diverged = (result.ahead ?? 0) > 0 && (result.behind ?? 0) > 0;
141
+ result.stale = !synced || Date.now() - Date.parse(synced) > STORE_STALE_MS;
142
+ }
143
+ result.degraded = assessSyncOutage(sync).degraded || result.diverged === true || result.stale === true;
144
+ const warning = storeWarning(result);
145
+ if (warning && result.degraded)
146
+ result.warning = warning;
134
147
  return result;
135
148
  }));
136
149
  }
150
+ const warningCache = new Map();
151
+ /**
152
+ * The degraded stores' warnings for the overview: the last answer at once,
153
+ * refreshed in the background once a minute old, so the overview never
154
+ * waits on Git.
155
+ */
156
+ export function cachedStoreWarnings(store, now = Date.now()) {
157
+ const entry = warningCache.get(store) ?? { at: 0, value: [] };
158
+ warningCache.set(store, entry);
159
+ if (now - entry.at > 60_000 && !entry.refreshing) {
160
+ entry.refreshing = storeSync(store)
161
+ .then(stores => { entry.value = stores.flatMap(item => item.warning ? [item.warning] : []); entry.at = Date.now(); })
162
+ .catch(() => { entry.at = Date.now(); })
163
+ .finally(() => { entry.refreshing = undefined; });
164
+ }
165
+ return entry.value;
166
+ }
137
167
  /** The newest run in schedule-runs.jsonl, with its schedule's name when the project still has it. */
138
168
  export async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
139
169
  const runs = await readScheduleRuns(runsFile).catch(() => []);
@@ -105,6 +105,7 @@ export declare const capabilities: {
105
105
  sideQuestions: boolean;
106
106
  dispatch: boolean;
107
107
  conductorSets: boolean;
108
+ setLink: boolean;
108
109
  ownerInbox: boolean;
109
110
  workerReports: boolean;
110
111
  queuedHandOff: boolean;
@@ -40,13 +40,13 @@ import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js
40
40
  import { currentModel, currentStep } from "./steps.js";
41
41
  import { capacityRoom, usageForCaller } from "./usage.js";
42
42
  import { readFinalTurn } from "./schedule-watch.js";
43
- import { healthDetails, listsCaller } from "./health.js";
43
+ import { cachedStoreWarnings, healthDetails, listsCaller } from "./health.js";
44
44
  import { defaultPhrenPath } from "../shared.js";
45
45
  import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
46
46
  import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
47
47
  import { renameSession } from "./session-rename.js";
48
48
  import { launchSession, makeConductor, stopConductor, workspaceAction } from "./server-launch.js";
49
- import { conductorAnswer, nameSet, readSets } from "./conductor-sets.js";
49
+ import { conductorAnswer, linkSetMember, nameSet, readSets } from "./conductor-sets.js";
50
50
  import { conductorPane } from "./conductor-role.js";
51
51
  import { hookMetrics } from "./metrics.js";
52
52
  import { SPEECH_FORMATS, streamSpeech } from "./speech.js";
@@ -78,7 +78,7 @@ async function childActivity(source, session) {
78
78
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
79
79
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
80
80
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
81
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
81
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
82
82
  export function capabilitiesForModules(snapshot) {
83
83
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
84
84
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -266,7 +266,9 @@ export function workspacesReader(ctx) {
266
266
  expired = true;
267
267
  clearTimeout(timer);
268
268
  const mux = terminalMux(server);
269
- return { ...workspaces, kind: mux.kind, mux, phren: info };
269
+ // A diverged or long-unsynced store, for the computer list (health.ts storeWarning).
270
+ const storeWarnings = cachedStoreWarnings(defaultPhrenPath());
271
+ return { ...workspaces, kind: mux.kind, mux, phren: info, ...(storeWarnings.length ? { storeWarnings } : {}) };
270
272
  };
271
273
  }
272
274
  /** One read-only GET to every linked peer, each answer or its error by computer name. */
@@ -829,6 +831,9 @@ export function createRouteHandler(ctx) {
829
831
  else if (url.pathname === "/v1/sets/name") {
830
832
  result = await nameSet(data);
831
833
  }
834
+ else if (url.pathname === "/v1/sets/link") {
835
+ result = await linkSetMember(data);
836
+ }
832
837
  else if (url.pathname === "/v1/push/register") {
833
838
  // Registration is kept for when a key is added; the reply says whether push works now.
834
839
  await agentHooks.push.register(data);
@@ -63,6 +63,7 @@ import { targetTranscriptPath } from "./transcripts.js";
63
63
  import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
64
64
  import { CodexAuthKeeper, codexAuthRefreshEnabled } from "./codex-auth-refresh.js";
65
65
  import { localNames } from "./computer-names.js";
66
+ import { startStoreSyncLoop } from "../sync/store-sync.js";
66
67
  export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
67
68
  export { streamCloseReason } from "./server-stream.js";
68
69
  export { herdrAgentName, launchSession } from "./server-launch.js";
@@ -299,6 +300,8 @@ export async function serve(version, options = {}) {
299
300
  const codexAuthTimer = codexAuth ? setInterval(() => { void codexAuth.tick().catch(() => { }); }, 60 * 60_000) : undefined;
300
301
  if (codexAuth)
301
302
  setTimeout(() => { void codexAuth.tick().catch(() => { }); }, 60_000).unref();
303
+ // Every store converges with its remote even when no agent session runs here (store-sync.ts).
304
+ const storeSync = startStoreSyncLoop(scheduleStore);
302
305
  const canaryTimer = setInterval(() => { countTick("canary"); void dailyCanaryDue().then(due => due ? canary("daily") : undefined).catch(() => { }); }, 10 * 60_000);
303
306
  let recording = false;
304
307
  const activityTimer = setInterval(() => {
@@ -346,7 +349,7 @@ export async function serve(version, options = {}) {
346
349
  })().finally(() => { recording = false; }).catch(() => { });
347
350
  }, 5000);
348
351
  await new Promise(resolve => {
349
- const stop = () => { fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
352
+ const stop = () => { storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
350
353
  process.once("SIGTERM", stop);
351
354
  process.once("SIGINT", stop);
352
355
  });