@phren/cli 0.3.54 → 0.3.55

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,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { readFileSync, realpathSync } from "node:fs";
2
+ import { readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
3
4
  import { lstat, open, readdir, realpath } from "node:fs/promises";
4
5
  import path from "node:path";
5
6
  import { BridgeError } from "./protocol.js";
@@ -325,19 +326,92 @@ export function invalidatePullsForDomain(domain) {
325
326
  if (JSON.parse(key)[1] === normalized)
326
327
  credentialReads.delete(key);
327
328
  pullsCache.invalidate(key => key.split("\0")[1] === normalized);
329
+ pullsTargets.clear();
330
+ }
331
+ // Finding a checkout's root, branch and host costs about eight git subprocesses. The answer
332
+ // only changes when HEAD or a git config file does, so it is reused per cwd while those are
333
+ // unchanged, for at most PULLS_TARGET_TTL_MS (which also bounds what a config `include` or a
334
+ // nested repository could hide). Concurrent polls share one lookup.
335
+ const PULLS_TARGET_TTL_MS = 10_000;
336
+ const pullsTargets = new Map();
337
+ function fileStamp(file) {
338
+ try {
339
+ const info = statSync(file);
340
+ return `${info.mtimeMs}:${info.size}:${info.ino}`;
341
+ }
342
+ catch {
343
+ return "-";
344
+ }
345
+ }
346
+ /** A cheap freshness signal: HEAD's text and the stamps of the repository's and the user's git config files. */
347
+ function pullsSignature(root) {
348
+ const parts = [];
349
+ const dotGit = path.join(root, ".git");
350
+ let gitDir = dotGit;
351
+ try {
352
+ const link = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, "utf8"));
353
+ if (link)
354
+ gitDir = path.resolve(root, link[1].trim());
355
+ }
356
+ catch { /* a directory: the main checkout */ }
357
+ let common = gitDir;
358
+ try {
359
+ common = path.resolve(gitDir, readFileSync(path.join(gitDir, "commondir"), "utf8").trim());
360
+ }
361
+ catch { /* gitDir is the common one */ }
362
+ let head;
363
+ try {
364
+ head = readFileSync(path.join(gitDir, "HEAD"), "utf8");
365
+ }
366
+ catch {
367
+ head = "?";
368
+ }
369
+ const home = homedir();
370
+ parts.push(head, fileStamp(path.join(common, "config")), fileStamp(path.join(gitDir, "config.worktree")), fileStamp(process.env.GIT_CONFIG_GLOBAL || path.join(home, ".gitconfig")), fileStamp(path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "git", "config")));
371
+ return parts.join("\0");
372
+ }
373
+ async function pullsTarget(cwd) {
374
+ const hit = pullsTargets.get(cwd);
375
+ if (hit && Date.now() - hit.at < PULLS_TARGET_TTL_MS) {
376
+ try {
377
+ const { target, signature } = await hit.value;
378
+ if (pullsSignature(target.root) === signature)
379
+ return target;
380
+ }
381
+ catch (error) {
382
+ // A shared lookup that failed fails its own callers; the next call looks again.
383
+ if (pullsTargets.get(cwd) === hit)
384
+ pullsTargets.delete(cwd);
385
+ throw error;
386
+ }
387
+ }
388
+ const entry = { at: Date.now(), value: withIndependentGitReadDeadline(async () => {
389
+ const root = await repository(cwd);
390
+ // Signed before the reads below, so a change made while they run is seen by the next call.
391
+ const signature = pullsSignature(root);
392
+ const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
393
+ const host = await detectHost(root, branch);
394
+ const { apiHost } = await tokenDestination(root, host);
395
+ return { target: { root, branch, host: { ...host, apiHost } }, signature };
396
+ }) };
397
+ pullsTargets.set(cwd, entry);
398
+ if (pullsTargets.size > 64)
399
+ pullsTargets.delete(pullsTargets.keys().next().value);
400
+ try {
401
+ return (await entry.value).target;
402
+ }
403
+ catch (error) {
404
+ if (pullsTargets.get(cwd) === entry)
405
+ pullsTargets.delete(cwd);
406
+ throw error;
407
+ }
328
408
  }
329
409
  /** Open pull or merge requests and the checked-out branch's own (any state)
330
410
  * with its checks, from whichever host the remote is on (git-hosts.ts). A
331
411
  * host that cannot answer (a missing CLI, a stubbed provider, an unknown
332
412
  * domain) is `{ available: false, reason, message }`, never an error. */
333
413
  export async function gitPulls(cwd, retried = false) {
334
- const { root, branch, host } = await withIndependentGitReadDeadline(async () => {
335
- const root = await repository(cwd);
336
- const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
337
- const host = await detectHost(root, branch);
338
- const { apiHost } = await tokenDestination(root, host);
339
- return { root, branch, host: { ...host, apiHost } };
340
- });
414
+ const { root, branch, host } = await pullsTarget(cwd);
341
415
  const provider = providerFor(host);
342
416
  const credential = await credentialIdentity(host);
343
417
  const key = repositoryId(root) + "\0" + (host.domain ?? "").toLowerCase().replace(/\.$/, "") + "\0" + JSON.stringify([branch, host, credential]);
@@ -417,7 +417,7 @@ export async function webServers() {
417
417
  const servers = await serversCache.get("listeners", scanWebServers);
418
418
  if (!servers.some(server => server.pid !== undefined) || Date.now() - (scanStarted.get(servers) ?? 0) < LISTENER_TRUST_MS)
419
419
  return servers;
420
- const live = await readListeners().catch(() => undefined);
420
+ const live = await sharedListeners();
421
421
  // The table could not be read (ss timed out, no lsof): ownership cannot be verified, so none is claimed.
422
422
  if (!live)
423
423
  return servers.map(({ pid: _pid, ...server }) => ({ ...server, unverified: true }));
@@ -426,6 +426,11 @@ export async function webServers() {
426
426
  serversCache.invalidate(() => true);
427
427
  return kept;
428
428
  }
429
+ /** Concurrent ownership checks share one socket-table read; a read is never reused once it has settled. */
430
+ let listenersInFlight;
431
+ function sharedListeners() {
432
+ return listenersInFlight ??= readListeners().catch(() => undefined).finally(() => { listenersInFlight = undefined; });
433
+ }
429
434
  /** The key `addListener` files a server under: its host with the port always spelled out (a URL's host drops the default one). */
430
435
  export function listenerKey(server) {
431
436
  return `${server.origin.includes("[::1]") ? "[::1]" : "127.0.0.1"}:${server.port}`;
@@ -459,13 +464,13 @@ async function scanWebServers() {
459
464
  .sort((a, b) => Number(a.port >= EPHEMERAL_PORT) - Number(b.port >= EPHEMERAL_PORT) || a.port - b.port)
460
465
  .slice(0, 64);
461
466
  const found = [];
462
- for (let i = 0; i < candidates.length; i += 8) {
463
- await Promise.all(candidates.slice(i, i + 8).map(async (server) => {
464
- const name = await probe(server.port, server.origin.includes("[::1]") ? "::1" : "127.0.0.1");
465
- if (name !== null)
466
- found.push({ ...server, name });
467
- }));
468
- }
467
+ // Every probe is bounded (1.2 s) and loopback-only, so they all run at once: in groups of eight
468
+ // a handful of listeners that accept and never answer cost 1.2 s per group.
469
+ await Promise.all(candidates.map(async (server) => {
470
+ const name = await probe(server.port, server.origin.includes("[::1]") ? "::1" : "127.0.0.1");
471
+ if (name !== null)
472
+ found.push({ ...server, name });
473
+ }));
469
474
  const listing = found.sort((a, b) => a.port - b.port);
470
475
  scanStarted.set(listing, started);
471
476
  return listing;
@@ -68,6 +68,7 @@ import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
68
68
  import { CodexAuthKeeper, codexAuthRefreshEnabled } from "./codex-auth-refresh.js";
69
69
  import { localNames } from "./computer-names.js";
70
70
  import { startStoreSyncLoop } from "../sync/store-sync.js";
71
+ import { SocketBudget, socketIdentity, socketKind } from "./socket-budget.js";
71
72
  export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
72
73
  export { streamCloseReason } from "./server-stream.js";
73
74
  export { herdrAgentName, launchSession } from "./server-launch.js";
@@ -268,7 +269,7 @@ export async function serve(version, options = {}) {
268
269
  http.headersTimeout = 10_000;
269
270
  http.maxHeadersCount = 32;
270
271
  const ws = new WebSocketServer({ noServer: true, maxPayload: 65_536, perMessageDeflate: false });
271
- const socketPools = new Map();
272
+ const socketPools = new SocketBudget();
272
273
  http.on("upgrade", (request, socket, head) => {
273
274
  try {
274
275
  const url = new URL(request.url || "/", "http://phren.local");
@@ -279,20 +280,14 @@ export async function serve(version, options = {}) {
279
280
  requireRoute(modules, "WS", url.pathname);
280
281
  // Parsed before the upgrade: an invalid server name is refused as the other routes refuse it.
281
282
  const overviewServer = url.pathname === "/v1/overview" ? selectedServer(url) : undefined;
282
- // Each client kind has its own pool of 16, so a desktop that holds many
283
- // sockets never evicts the phone's (and the reverse). The header is a
284
- // fairness hint between already-authorized clients, not an identity.
285
- const pool = request.headers["x-phren-client"] === "desktop" ? "desktop" : "default";
283
+ // Sockets are budgeted per authenticated identity (socket-budget.ts); the
284
+ // x-phren-client header only picks a sub-pool inside that budget.
285
+ const identity = socketIdentity(request), kind = socketKind(request);
286
286
  ws.handleUpgrade(request, socket, head, client => {
287
- const members = socketPools.get(pool) ?? new Set();
288
- socketPools.set(pool, members);
289
- members.add(client);
290
- client.once("close", () => members.delete(client));
291
- while (members.size > 16) {
292
- const oldest = members.values().next().value;
287
+ client.once("close", () => socketPools.remove(client));
288
+ for (const oldest of socketPools.add(client, identity, kind)) {
293
289
  oldest.close(1008, "Too many connections; reconnect");
294
290
  oldest.terminate();
295
- members.delete(oldest);
296
291
  ws.clients.delete(oldest);
297
292
  }
298
293
  if (overviewServer !== undefined) {
@@ -0,0 +1,29 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ /** Sockets one identity may hold per client kind, and in all. */
3
+ export declare const SOCKETS_PER_KIND = 16;
4
+ export declare const SOCKETS_PER_IDENTITY = 32;
5
+ /** Every identity together; the backstop if identities themselves multiply. */
6
+ export declare const SOCKETS_TOTAL = 128;
7
+ /**
8
+ * Who a WebSocket belongs to, from what the Hook itself trusts rather than a
9
+ * client hint: a peer key's gateway rebuilds its request with `x-phren-origin:
10
+ * peer` and the peer's fingerprint, so that is its own identity; everything
11
+ * else arrives on the owner's local socket or the owner's SSH pipe and is the
12
+ * owner. `x-phren-client` only picks a sub-pool inside the identity.
13
+ */
14
+ export declare function socketIdentity(request: Pick<IncomingMessage, "headers">): string;
15
+ export declare const socketKind: (request: Pick<IncomingMessage, "headers">) => string;
16
+ /** Admits sockets oldest-first under the per-kind, per-identity and total caps. */
17
+ export declare class SocketBudget<S> {
18
+ private readonly limits;
19
+ private readonly entries;
20
+ constructor(limits?: {
21
+ kind: number;
22
+ identity: number;
23
+ total: number;
24
+ });
25
+ /** Register a socket; returns the sockets to close to stay inside the caps. */
26
+ add(socket: S, identity: string, kind: string): S[];
27
+ remove(socket: S): void;
28
+ count(identity?: string): number;
29
+ }
@@ -0,0 +1,62 @@
1
+ import { requestPeer } from "./request-origin.js";
2
+ /** Sockets one identity may hold per client kind, and in all. */
3
+ export const SOCKETS_PER_KIND = 16;
4
+ export const SOCKETS_PER_IDENTITY = 32;
5
+ /** Every identity together; the backstop if identities themselves multiply. */
6
+ export const SOCKETS_TOTAL = 128;
7
+ /**
8
+ * Who a WebSocket belongs to, from what the Hook itself trusts rather than a
9
+ * client hint: a peer key's gateway rebuilds its request with `x-phren-origin:
10
+ * peer` and the peer's fingerprint, so that is its own identity; everything
11
+ * else arrives on the owner's local socket or the owner's SSH pipe and is the
12
+ * owner. `x-phren-client` only picks a sub-pool inside the identity.
13
+ */
14
+ export function socketIdentity(request) {
15
+ const peer = requestPeer(request);
16
+ return peer ? `peer:${peer.fingerprint}` : "owner";
17
+ }
18
+ export const socketKind = (request) => request.headers["x-phren-client"] === "desktop" ? "desktop" : "default";
19
+ /** Admits sockets oldest-first under the per-kind, per-identity and total caps. */
20
+ export class SocketBudget {
21
+ limits;
22
+ entries = new Set();
23
+ constructor(limits = { kind: SOCKETS_PER_KIND, identity: SOCKETS_PER_IDENTITY, total: SOCKETS_TOTAL }) {
24
+ this.limits = limits;
25
+ }
26
+ /** Register a socket; returns the sockets to close to stay inside the caps. */
27
+ add(socket, identity, kind) {
28
+ const entry = { socket, identity, kind };
29
+ this.entries.add(entry);
30
+ const evicted = [];
31
+ const drop = (match) => {
32
+ const oldest = [...this.entries].find(match);
33
+ if (!oldest)
34
+ return;
35
+ this.entries.delete(oldest);
36
+ evicted.push(oldest.socket);
37
+ };
38
+ while ([...this.entries].filter(e => e.identity === identity && e.kind === kind).length > this.limits.kind)
39
+ drop(e => e.identity === identity && e.kind === kind);
40
+ while ([...this.entries].filter(e => e.identity === identity).length > this.limits.identity)
41
+ drop(e => e.identity === identity);
42
+ while (this.entries.size > this.limits.total) {
43
+ const counts = new Map();
44
+ for (const e of this.entries)
45
+ counts.set(e.identity, (counts.get(e.identity) ?? 0) + 1);
46
+ // Ties go against a peer identity, so forged peer budgets never push out the owner's own devices first.
47
+ const [heaviest] = [...counts].sort((a, b) => b[1] - a[1] || Number(a[0] === "owner") - Number(b[0] === "owner"))[0];
48
+ drop(e => e.identity === heaviest);
49
+ }
50
+ return evicted;
51
+ }
52
+ remove(socket) {
53
+ for (const e of this.entries)
54
+ if (e.socket === socket) {
55
+ this.entries.delete(e);
56
+ return;
57
+ }
58
+ }
59
+ count(identity) {
60
+ return identity === undefined ? this.entries.size : [...this.entries].filter(e => e.identity === identity).length;
61
+ }
62
+ }
@@ -27118,12 +27118,17 @@ async function listenersFromSs(ports) {
27118
27118
  async function webServers() {
27119
27119
  const servers2 = await serversCache.get("listeners", scanWebServers);
27120
27120
  if (!servers2.some((server) => server.pid !== void 0) || Date.now() - (scanStarted.get(servers2) ?? 0) < LISTENER_TRUST_MS) return servers2;
27121
- const live = await readListeners().catch(() => void 0);
27121
+ const live = await sharedListeners();
27122
27122
  if (!live) return servers2.map(({ pid: _pid, ...server }) => ({ ...server, unverified: true }));
27123
27123
  const kept = servers2.filter((server) => server.pid === void 0 || live.get(listenerKey(server))?.pid === server.pid);
27124
27124
  if (kept.length !== servers2.length) serversCache.invalidate(() => true);
27125
27125
  return kept;
27126
27126
  }
27127
+ function sharedListeners() {
27128
+ return listenersInFlight ??= readListeners().catch(() => void 0).finally(() => {
27129
+ listenersInFlight = void 0;
27130
+ });
27131
+ }
27127
27132
  function listenerKey(server) {
27128
27133
  return `${server.origin.includes("[::1]") ? "[::1]" : "127.0.0.1"}:${server.port}`;
27129
27134
  }
@@ -27148,12 +27153,10 @@ async function scanWebServers() {
27148
27153
  const ports = await readListeners();
27149
27154
  const candidates = [...ports.values()].sort((a, b) => Number(a.port >= EPHEMERAL_PORT) - Number(b.port >= EPHEMERAL_PORT) || a.port - b.port).slice(0, 64);
27150
27155
  const found = [];
27151
- for (let i = 0; i < candidates.length; i += 8) {
27152
- await Promise.all(candidates.slice(i, i + 8).map(async (server) => {
27153
- const name = await probe(server.port, server.origin.includes("[::1]") ? "::1" : "127.0.0.1");
27154
- if (name !== null) found.push({ ...server, name });
27155
- }));
27156
- }
27156
+ await Promise.all(candidates.map(async (server) => {
27157
+ const name = await probe(server.port, server.origin.includes("[::1]") ? "::1" : "127.0.0.1");
27158
+ if (name !== null) found.push({ ...server, name });
27159
+ }));
27157
27160
  const listing = found.sort((a, b) => a.port - b.port);
27158
27161
  scanStarted.set(listing, started);
27159
27162
  return listing;
@@ -27181,7 +27184,7 @@ async function launchDirectory(raw, activity = [], located = []) {
27181
27184
  }
27182
27185
  throw new BridgeError(403, "Workspace directory must be under home or a located project.");
27183
27186
  }
27184
- var exec, gitReadBudget, GIT_READ_MS, gitTimeout, BRANCH_FRESH_MS, BRANCH_MAX_MS, branches, ENTITIES, LISTEN_HOST, EPHEMERAL_PORT, serversCache, scanStarted, LISTENER_TRUST_MS;
27187
+ var exec, gitReadBudget, GIT_READ_MS, gitTimeout, BRANCH_FRESH_MS, BRANCH_MAX_MS, branches, ENTITIES, LISTEN_HOST, EPHEMERAL_PORT, serversCache, scanStarted, LISTENER_TRUST_MS, listenersInFlight;
27185
27188
  var init_projects = __esm({
27186
27189
  "src/bridge/projects.ts"() {
27187
27190
  "use strict";
@@ -37100,7 +37103,7 @@ var init_package_metadata = __esm({
37100
37103
  __dirname = path35.dirname(fileURLToPath2(import.meta.url));
37101
37104
  ROOT = path35.join(__dirname, "..");
37102
37105
  PACKAGE_JSON_PATH = path35.join(ROOT, "package.json");
37103
- BUNDLED_VERSION = true ? "0.3.54" : "0.0.0";
37106
+ BUNDLED_VERSION = true ? "0.3.55" : "0.0.0";
37104
37107
  PACKAGE_JSON = readPackageJson();
37105
37108
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
37106
37109
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -56218,7 +56221,8 @@ var init_git_host_auth = __esm({
56218
56221
 
56219
56222
  // src/bridge/git.ts
56220
56223
  import { createHash as createHash28 } from "node:crypto";
56221
- import { readFileSync as readFileSync44, realpathSync as realpathSync3 } from "node:fs";
56224
+ import { readFileSync as readFileSync44, realpathSync as realpathSync3, statSync as statSync22 } from "node:fs";
56225
+ import { homedir as homedir15 } from "node:os";
56222
56226
  import { lstat as lstat23, open as open16, readdir as readdir14, realpath as realpath13 } from "node:fs/promises";
56223
56227
  import path96 from "node:path";
56224
56228
  function statusLetter(code) {
@@ -56485,15 +56489,76 @@ function invalidatePullsForDomain(domain2) {
56485
56489
  const normalized = domain2.trim().toLowerCase().replace(/\.$/, "");
56486
56490
  for (const key4 of credentialReads.keys()) if (JSON.parse(key4)[1] === normalized) credentialReads.delete(key4);
56487
56491
  pullsCache.invalidate((key4) => key4.split("\0")[1] === normalized);
56492
+ pullsTargets.clear();
56493
+ }
56494
+ function fileStamp(file4) {
56495
+ try {
56496
+ const info = statSync22(file4);
56497
+ return `${info.mtimeMs}:${info.size}:${info.ino}`;
56498
+ } catch {
56499
+ return "-";
56500
+ }
56501
+ }
56502
+ function pullsSignature(root) {
56503
+ const parts = [];
56504
+ const dotGit = path96.join(root, ".git");
56505
+ let gitDir2 = dotGit;
56506
+ try {
56507
+ const link = /^gitdir:\s*(.+)$/m.exec(readFileSync44(dotGit, "utf8"));
56508
+ if (link) gitDir2 = path96.resolve(root, link[1].trim());
56509
+ } catch {
56510
+ }
56511
+ let common = gitDir2;
56512
+ try {
56513
+ common = path96.resolve(gitDir2, readFileSync44(path96.join(gitDir2, "commondir"), "utf8").trim());
56514
+ } catch {
56515
+ }
56516
+ let head;
56517
+ try {
56518
+ head = readFileSync44(path96.join(gitDir2, "HEAD"), "utf8");
56519
+ } catch {
56520
+ head = "?";
56521
+ }
56522
+ const home = homedir15();
56523
+ parts.push(
56524
+ head,
56525
+ fileStamp(path96.join(common, "config")),
56526
+ fileStamp(path96.join(gitDir2, "config.worktree")),
56527
+ fileStamp(process.env.GIT_CONFIG_GLOBAL || path96.join(home, ".gitconfig")),
56528
+ fileStamp(path96.join(process.env.XDG_CONFIG_HOME || path96.join(home, ".config"), "git", "config"))
56529
+ );
56530
+ return parts.join("\0");
56531
+ }
56532
+ async function pullsTarget(cwd) {
56533
+ const hit = pullsTargets.get(cwd);
56534
+ if (hit && Date.now() - hit.at < PULLS_TARGET_TTL_MS) {
56535
+ try {
56536
+ const { target: target2, signature } = await hit.value;
56537
+ if (pullsSignature(target2.root) === signature) return target2;
56538
+ } catch (error62) {
56539
+ if (pullsTargets.get(cwd) === hit) pullsTargets.delete(cwd);
56540
+ throw error62;
56541
+ }
56542
+ }
56543
+ const entry2 = { at: Date.now(), value: withIndependentGitReadDeadline(async () => {
56544
+ const root = await repository(cwd);
56545
+ const signature = pullsSignature(root);
56546
+ const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
56547
+ const host = await detectHost(root, branch);
56548
+ const { apiHost } = await tokenDestination(root, host);
56549
+ return { target: { root, branch, host: { ...host, apiHost } }, signature };
56550
+ }) };
56551
+ pullsTargets.set(cwd, entry2);
56552
+ if (pullsTargets.size > 64) pullsTargets.delete(pullsTargets.keys().next().value);
56553
+ try {
56554
+ return (await entry2.value).target;
56555
+ } catch (error62) {
56556
+ if (pullsTargets.get(cwd) === entry2) pullsTargets.delete(cwd);
56557
+ throw error62;
56558
+ }
56488
56559
  }
56489
56560
  async function gitPulls(cwd, retried = false) {
56490
- const { root, branch, host } = await withIndependentGitReadDeadline(async () => {
56491
- const root2 = await repository(cwd);
56492
- const branch2 = (await git(root2, "branch", "--show-current").catch(() => "")).trim();
56493
- const host2 = await detectHost(root2, branch2);
56494
- const { apiHost } = await tokenDestination(root2, host2);
56495
- return { root: root2, branch: branch2, host: { ...host2, apiHost } };
56496
- });
56561
+ const { root, branch, host } = await pullsTarget(cwd);
56497
56562
  const provider2 = providerFor(host);
56498
56563
  const credential = await credentialIdentity(host);
56499
56564
  const key4 = repositoryId(root) + "\0" + (host.domain ?? "").toLowerCase().replace(/\.$/, "") + "\0" + JSON.stringify([branch, host, credential]);
@@ -56818,7 +56883,7 @@ async function readGitShow(cwd, sha) {
56818
56883
  truncated
56819
56884
  };
56820
56885
  }
56821
- var UNKNOWN_COUNTS, NO_DIFF2, MAX_STATUS_ROWS, REVOKING, pullsCache, credentialReads, CREDENTIAL_TTL_MS, CredentialsChanged, treeCache, TREE_TTL_MS, MAX_IGNORED_ENTRIES, ignoredCache, MAX_SHOW_FILES, MAX_SHOW_PATCH, MAX_FILE_PATCH;
56886
+ var UNKNOWN_COUNTS, NO_DIFF2, MAX_STATUS_ROWS, REVOKING, pullsCache, credentialReads, CREDENTIAL_TTL_MS, CredentialsChanged, PULLS_TARGET_TTL_MS, pullsTargets, treeCache, TREE_TTL_MS, MAX_IGNORED_ENTRIES, ignoredCache, MAX_SHOW_FILES, MAX_SHOW_PATCH, MAX_FILE_PATCH;
56822
56887
  var init_git = __esm({
56823
56888
  "src/bridge/git.ts"() {
56824
56889
  "use strict";
@@ -56845,6 +56910,8 @@ var init_git = __esm({
56845
56910
  CREDENTIAL_TTL_MS = 5e3;
56846
56911
  CredentialsChanged = class extends Error {
56847
56912
  };
56913
+ PULLS_TARGET_TTL_MS = 1e4;
56914
+ pullsTargets = /* @__PURE__ */ new Map();
56848
56915
  treeCache = /* @__PURE__ */ new Map();
56849
56916
  TREE_TTL_MS = 2e3;
56850
56917
  MAX_IGNORED_ENTRIES = 1e3;
@@ -58793,7 +58860,7 @@ var init_git_write_policy = __esm({
58793
58860
  // src/bridge/git-worktrees.ts
58794
58861
  import { createHash as createHash31 } from "node:crypto";
58795
58862
  import { realpath as realpath14, stat as stat20 } from "node:fs/promises";
58796
- import { homedir as homedir15 } from "node:os";
58863
+ import { homedir as homedir16 } from "node:os";
58797
58864
  import path101 from "node:path";
58798
58865
  function worktreeId(abs) {
58799
58866
  return createHash31("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
@@ -58834,7 +58901,7 @@ function displayPath(abs, roots) {
58834
58901
  const rel = path101.relative(root, abs);
58835
58902
  if (rel && !rel.startsWith("..") && !path101.isAbsolute(rel)) return rel.split(path101.sep).join("/");
58836
58903
  }
58837
- const home = homedir15();
58904
+ const home = homedir16();
58838
58905
  return abs === home ? "~" : abs.startsWith(home + path101.sep) ? "~/" + path101.relative(home, abs).split(path101.sep).join("/") : abs;
58839
58906
  }
58840
58907
  function uncommitted(status) {
@@ -60109,7 +60176,7 @@ var init_scoped_gateway = __esm({
60109
60176
 
60110
60177
  // src/bridge/pair.ts
60111
60178
  import { execFile as execFile23 } from "node:child_process";
60112
- import { homedir as homedir16, hostname as hostname9, networkInterfaces, userInfo as userInfo5 } from "node:os";
60179
+ import { homedir as homedir17, hostname as hostname9, networkInterfaces, userInfo as userInfo5 } from "node:os";
60113
60180
  import { promisify as promisify21 } from "node:util";
60114
60181
  async function computerDisplayName() {
60115
60182
  if (process.platform === "darwin") {
@@ -63146,11 +63213,11 @@ ${await conductorBrief()}` : context3 } : {}));
63146
63213
  // src/bridge/models.ts
63147
63214
  import { spawn as spawn11 } from "node:child_process";
63148
63215
  import { readdir as readdir16, readFile as readFile48, stat as stat22 } from "node:fs/promises";
63149
- import { homedir as homedir17 } from "node:os";
63216
+ import { homedir as homedir18 } from "node:os";
63150
63217
  import path112 from "node:path";
63151
63218
  function readCodexModels(executable2 = codexExecutable()) {
63152
63219
  return new Promise((resolve17) => {
63153
- const child = spawn11(executable2, ["app-server"], { cwd: homedir17(), stdio: ["pipe", "pipe", "ignore"] });
63220
+ const child = spawn11(executable2, ["app-server"], { cwd: homedir18(), stdio: ["pipe", "pipe", "ignore"] });
63154
63221
  let pending3 = "", bytes = 0, initialized = false, done = false;
63155
63222
  const finish = (result = []) => {
63156
63223
  if (done) return;
@@ -63280,7 +63347,7 @@ function olderVersion(installed, required2) {
63280
63347
  }
63281
63348
  function claudeVersion(executable2 = "claude") {
63282
63349
  return new Promise((resolve17) => {
63283
- const child = spawn11(executable2, ["--version"], { cwd: homedir17(), stdio: ["ignore", "pipe", "ignore"] });
63350
+ const child = spawn11(executable2, ["--version"], { cwd: homedir18(), stdio: ["ignore", "pipe", "ignore"] });
63284
63351
  let out = "";
63285
63352
  const timer = setTimeout(() => {
63286
63353
  child.kill("SIGKILL");
@@ -63305,9 +63372,9 @@ async function readClaudeModels(configDir2, installed) {
63305
63372
  const live = await readClaudeCatalog(configDir2, version2).catch(() => []);
63306
63373
  return live.length ? live : CLAUDE_MENU.map((model) => ({ ...model }));
63307
63374
  }
63308
- async function readOpenCodeModels(executable2 = "opencode", configDir2 = path112.join(homedir17(), ".config/opencode")) {
63375
+ async function readOpenCodeModels(executable2 = "opencode", configDir2 = path112.join(homedir18(), ".config/opencode")) {
63309
63376
  const listed4 = await new Promise((resolve17) => {
63310
- const child = spawn11(executable2, ["models"], { cwd: homedir17(), stdio: ["ignore", "pipe", "ignore"] });
63377
+ const child = spawn11(executable2, ["models"], { cwd: homedir18(), stdio: ["ignore", "pipe", "ignore"] });
63311
63378
  let out = "", done = false;
63312
63379
  const finish = () => {
63313
63380
  if (!done) {
@@ -63352,7 +63419,7 @@ async function readPhrenModels(command) {
63352
63419
  const found = command ? void 0 : (await Promise.resolve().then(() => (init_agent_package(), agent_package_exports))).findAgentPackage({ global: false });
63353
63420
  const run4 = command ?? (found ? { file: process.execPath, args: [found.bin, "models", "--json"] } : { file: "phren-agent", args: ["models", "--json"] });
63354
63421
  const listed4 = await new Promise((resolve17) => {
63355
- const child = spawn11(run4.file, run4.args, { cwd: homedir17(), stdio: ["ignore", "pipe", "ignore"] });
63422
+ const child = spawn11(run4.file, run4.args, { cwd: homedir18(), stdio: ["ignore", "pipe", "ignore"] });
63356
63423
  let out = "", done = false;
63357
63424
  const finish = () => {
63358
63425
  if (!done) {
@@ -66675,14 +66742,14 @@ var init_activity2 = __esm({
66675
66742
  // src/modules/code-package.ts
66676
66743
  import { execFileSync as execFileSync7 } from "node:child_process";
66677
66744
  import * as fs46 from "node:fs";
66678
- import { homedir as homedir18 } from "node:os";
66745
+ import { homedir as homedir19 } from "node:os";
66679
66746
  import * as path122 from "node:path";
66680
66747
  import { fileURLToPath as fileURLToPath5, pathToFileURL } from "node:url";
66681
66748
  function loadedFrom() {
66682
66749
  return resolvedFrom;
66683
66750
  }
66684
66751
  function bridgeRoot2() {
66685
- return process.env.PHREN_BRIDGE_HOME || path122.join(homedir18(), ".local/share/phren/bridge");
66752
+ return process.env.PHREN_BRIDGE_HOME || path122.join(homedir19(), ".local/share/phren/bridge");
66686
66753
  }
66687
66754
  function npmPath() {
66688
66755
  const entries2 = (process.env.PATH ?? "").split(path122.delimiter).filter(Boolean);
@@ -66788,7 +66855,7 @@ var init_code_package = __esm({
66788
66855
  "src/modules/code-package.ts"() {
66789
66856
  "use strict";
66790
66857
  CODE_PACKAGE_HINT = "phren code needs @phren/code: run phren modules enable code";
66791
- EXTRA_PATH = [path122.join(homedir18(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
66858
+ EXTRA_PATH = [path122.join(homedir19(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
66792
66859
  }
66793
66860
  });
66794
66861
 
@@ -70452,7 +70519,7 @@ import { execFile as execFile29 } from "node:child_process";
70452
70519
  import { promisify as promisify27 } from "node:util";
70453
70520
  import { realpathSync as realpathSync6 } from "node:fs";
70454
70521
  import { readdir as readdir20, readFile as readFile55, stat as stat30, mkdir as mkdir33 } from "node:fs/promises";
70455
- import { homedir as homedir19 } from "node:os";
70522
+ import { homedir as homedir20 } from "node:os";
70456
70523
  import path136 from "node:path";
70457
70524
  function repoName(url2) {
70458
70525
  const last = url2.replace(/\/+$/, "").split(/[/:]/).pop() ?? "";
@@ -70548,7 +70615,7 @@ async function candidateRepos(activity, env = process.env) {
70548
70615
  }
70549
70616
  } catch {
70550
70617
  }
70551
- const home = homedir19();
70618
+ const home = homedir20();
70552
70619
  for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path136.join(home, r))]) {
70553
70620
  let children = [];
70554
70621
  try {
@@ -70561,7 +70628,7 @@ async function candidateRepos(activity, env = process.env) {
70561
70628
  return found.slice(0, 64);
70562
70629
  }
70563
70630
  async function cloneRoot(env) {
70564
- const home = homedir19();
70631
+ const home = homedir20();
70565
70632
  for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path136.join(home, r))]) {
70566
70633
  try {
70567
70634
  if ((await stat30(root)).isDirectory()) return root;
@@ -70763,7 +70830,7 @@ var init_file_resolve = __esm({
70763
70830
 
70764
70831
  // src/content/citation-freshness.ts
70765
70832
  import { execFileSync as execFileSync9 } from "node:child_process";
70766
- import { readFileSync as readFileSync54, realpathSync as realpathSync7, renameSync as renameSync17, statSync as statSync26, unlinkSync as unlinkSync8, writeFileSync as writeFileSync23 } from "node:fs";
70833
+ import { readFileSync as readFileSync54, realpathSync as realpathSync7, renameSync as renameSync17, statSync as statSync27, unlinkSync as unlinkSync8, writeFileSync as writeFileSync23 } from "node:fs";
70767
70834
  import path139 from "node:path";
70768
70835
  import { randomUUID as randomUUID29 } from "node:crypto";
70769
70836
  function git8(root, timeoutMs, ...args) {
@@ -70839,7 +70906,7 @@ function cacheFile(opts) {
70839
70906
  function readCache(file4) {
70840
70907
  if (!file4) return {};
70841
70908
  try {
70842
- const info = statSync26(file4);
70909
+ const info = statSync27(file4);
70843
70910
  const memo2 = cacheMemo.get(file4);
70844
70911
  if (memo2 && memo2.mtimeMs === info.mtimeMs && memo2.size === info.size) return memo2.entries;
70845
70912
  const raw = JSON.parse(readFileSync54(file4, "utf8"));
@@ -70851,7 +70918,7 @@ function readCache(file4) {
70851
70918
  return {};
70852
70919
  }
70853
70920
  }
70854
- function rememberCache(file4, entries2, info = statSync26(file4)) {
70921
+ function rememberCache(file4, entries2, info = statSync27(file4)) {
70855
70922
  const { mtimeMs, size } = info;
70856
70923
  if (cacheMemo.size >= 64) cacheMemo.delete(cacheMemo.keys().next().value);
70857
70924
  cacheMemo.set(file4, { mtimeMs, size, entries: entries2 });
@@ -76410,7 +76477,7 @@ var init_simulators = __esm({
76410
76477
  });
76411
76478
 
76412
76479
  // src/bridge/steps.ts
76413
- import { homedir as homedir20, tmpdir as tmpdir8 } from "node:os";
76480
+ import { homedir as homedir21, tmpdir as tmpdir8 } from "node:os";
76414
76481
  import path145 from "node:path";
76415
76482
  async function currentStep(source, session) {
76416
76483
  let file4;
@@ -76543,7 +76610,7 @@ function describe4(tool, args) {
76543
76610
  const name = tool.toLowerCase();
76544
76611
  let value2;
76545
76612
  if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
76546
- const command = collapseTemp(firstLine2(text5("command", "cmd")).replace(/^(?:\/\S*\/)?(?:bash|sh|zsh)\s+-l?c\s+/, "").replace(/^(['"])(.*)\1$/, "$2").replace(SHELL_ASSIGNMENTS, "").replace(/^cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/, "").replace(SHELL_ASSIGNMENTS, "").split(homedir20()).join("~"));
76613
+ const command = collapseTemp(firstLine2(text5("command", "cmd")).replace(/^(?:\/\S*\/)?(?:bash|sh|zsh)\s+-l?c\s+/, "").replace(/^(['"])(.*)\1$/, "$2").replace(SHELL_ASSIGNMENTS, "").replace(/^cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/, "").replace(SHELL_ASSIGNMENTS, "").split(homedir21()).join("~"));
76547
76614
  value2 = command ? `${tool}: ${command}` : tool;
76548
76615
  } else if (["edit", "multiedit", "write", "notebookedit", "patch", "apply_patch", "str_replace_editor", "str_replace"].includes(name)) {
76549
76616
  const patchTarget = /\*\*\* (?:Update|Add|Delete) File: (.+)/.exec(text5("input", "patch"))?.[1];
@@ -76823,7 +76890,7 @@ var init_session_rename = __esm({
76823
76890
  // src/bridge/link.ts
76824
76891
  import { execFile as execFile31 } from "node:child_process";
76825
76892
  import { readFile as readFile57 } from "node:fs/promises";
76826
- import { homedir as homedir21, hostname as hostname12, userInfo as userInfo6 } from "node:os";
76893
+ import { homedir as homedir22, hostname as hostname12, userInfo as userInfo6 } from "node:os";
76827
76894
  import path148 from "node:path";
76828
76895
  import { promisify as promisify29 } from "node:util";
76829
76896
  function sshConfigHosts(text5) {
@@ -76867,7 +76934,7 @@ async function probe2(host) {
76867
76934
  return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
76868
76935
  }
76869
76936
  async function discoverComputers(options = {}) {
76870
- const config4 = options.sshConfig ?? await readFile57(path148.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
76937
+ const config4 = options.sshConfig ?? await readFile57(path148.join(homedir22(), ".ssh", "config"), "utf8").catch(() => "");
76871
76938
  const store = options.store !== void 0 ? options.store : findPhrenPath();
76872
76939
  const machines = store ? listMachines(store) : void 0;
76873
76940
  const { peers } = await optionalHookPeers();
@@ -79053,6 +79120,60 @@ var init_codex_auth_refresh = __esm({
79053
79120
  }
79054
79121
  });
79055
79122
 
79123
+ // src/bridge/socket-budget.ts
79124
+ function socketIdentity(request10) {
79125
+ const peer = requestPeer(request10);
79126
+ return peer ? `peer:${peer.fingerprint}` : "owner";
79127
+ }
79128
+ var SOCKETS_PER_KIND, SOCKETS_PER_IDENTITY, SOCKETS_TOTAL, socketKind, SocketBudget;
79129
+ var init_socket_budget = __esm({
79130
+ "src/bridge/socket-budget.ts"() {
79131
+ "use strict";
79132
+ init_request_origin();
79133
+ SOCKETS_PER_KIND = 16;
79134
+ SOCKETS_PER_IDENTITY = 32;
79135
+ SOCKETS_TOTAL = 128;
79136
+ socketKind = (request10) => request10.headers["x-phren-client"] === "desktop" ? "desktop" : "default";
79137
+ SocketBudget = class {
79138
+ constructor(limits = { kind: SOCKETS_PER_KIND, identity: SOCKETS_PER_IDENTITY, total: SOCKETS_TOTAL }) {
79139
+ this.limits = limits;
79140
+ }
79141
+ limits;
79142
+ entries = /* @__PURE__ */ new Set();
79143
+ /** Register a socket; returns the sockets to close to stay inside the caps. */
79144
+ add(socket, identity, kind) {
79145
+ const entry2 = { socket, identity, kind };
79146
+ this.entries.add(entry2);
79147
+ const evicted = [];
79148
+ const drop = (match) => {
79149
+ const oldest = [...this.entries].find(match);
79150
+ if (!oldest) return;
79151
+ this.entries.delete(oldest);
79152
+ evicted.push(oldest.socket);
79153
+ };
79154
+ while ([...this.entries].filter((e) => e.identity === identity && e.kind === kind).length > this.limits.kind) drop((e) => e.identity === identity && e.kind === kind);
79155
+ while ([...this.entries].filter((e) => e.identity === identity).length > this.limits.identity) drop((e) => e.identity === identity);
79156
+ while (this.entries.size > this.limits.total) {
79157
+ const counts = /* @__PURE__ */ new Map();
79158
+ for (const e of this.entries) counts.set(e.identity, (counts.get(e.identity) ?? 0) + 1);
79159
+ const [heaviest] = [...counts].sort((a, b) => b[1] - a[1] || Number(a[0] === "owner") - Number(b[0] === "owner"))[0];
79160
+ drop((e) => e.identity === heaviest);
79161
+ }
79162
+ return evicted;
79163
+ }
79164
+ remove(socket) {
79165
+ for (const e of this.entries) if (e.socket === socket) {
79166
+ this.entries.delete(e);
79167
+ return;
79168
+ }
79169
+ }
79170
+ count(identity) {
79171
+ return identity === void 0 ? this.entries.size : [...this.entries].filter((e) => e.identity === identity).length;
79172
+ }
79173
+ };
79174
+ }
79175
+ });
79176
+
79056
79177
  // src/bridge/server.ts
79057
79178
  import { randomUUID as randomUUID32 } from "node:crypto";
79058
79179
  import { chmod as chmod6, lstat as lstat37, mkdir as mkdir35, readFile as readFile59, rm as rm17, unlink as unlink10, writeFile as writeFile12 } from "node:fs/promises";
@@ -79315,7 +79436,7 @@ async function serve(version2, options = {}) {
79315
79436
  http.headersTimeout = 1e4;
79316
79437
  http.maxHeadersCount = 32;
79317
79438
  const ws2 = new import_websocket_server.default({ noServer: true, maxPayload: 65536, perMessageDeflate: false });
79318
- const socketPools = /* @__PURE__ */ new Map();
79439
+ const socketPools = new SocketBudget();
79319
79440
  http.on("upgrade", (request10, socket, head) => {
79320
79441
  try {
79321
79442
  const url2 = new URL(request10.url || "/", "http://phren.local");
@@ -79325,17 +79446,12 @@ async function serve(version2, options = {}) {
79325
79446
  }
79326
79447
  requireRoute(modules, "WS", url2.pathname);
79327
79448
  const overviewServer = url2.pathname === "/v1/overview" ? selectedServer(url2) : void 0;
79328
- const pool2 = request10.headers["x-phren-client"] === "desktop" ? "desktop" : "default";
79449
+ const identity = socketIdentity(request10), kind = socketKind(request10);
79329
79450
  ws2.handleUpgrade(request10, socket, head, (client) => {
79330
- const members2 = socketPools.get(pool2) ?? /* @__PURE__ */ new Set();
79331
- socketPools.set(pool2, members2);
79332
- members2.add(client);
79333
- client.once("close", () => members2.delete(client));
79334
- while (members2.size > 16) {
79335
- const oldest = members2.values().next().value;
79451
+ client.once("close", () => socketPools.remove(client));
79452
+ for (const oldest of socketPools.add(client, identity, kind)) {
79336
79453
  oldest.close(1008, "Too many connections; reconnect");
79337
79454
  oldest.terminate();
79338
- members2.delete(oldest);
79339
79455
  ws2.clients.delete(oldest);
79340
79456
  }
79341
79457
  if (overviewServer !== void 0) {
@@ -79535,6 +79651,7 @@ var init_server = __esm({
79535
79651
  init_codex_auth_refresh();
79536
79652
  init_computer_names();
79537
79653
  init_store_sync();
79654
+ init_socket_budget();
79538
79655
  init_server_routes();
79539
79656
  init_server_stream();
79540
79657
  init_server_launch();
@@ -79549,7 +79666,7 @@ __export(device_enroll_exports, {
79549
79666
  runEnrollDevice: () => runEnrollDevice
79550
79667
  });
79551
79668
  import { readFile as readFile60 } from "node:fs/promises";
79552
- import { homedir as homedir22, userInfo as userInfo7 } from "node:os";
79669
+ import { homedir as homedir23, userInfo as userInfo7 } from "node:os";
79553
79670
  import path152 from "node:path";
79554
79671
  async function enrollDevice(input2, options) {
79555
79672
  try {
@@ -79557,7 +79674,7 @@ async function enrollDevice(input2, options) {
79557
79674
  const comment = options.device === "android" ? "phren-android" : "phren-iphone";
79558
79675
  const line = `restrict,pty,${forcedCommand} ${publicKey} ${comment}`;
79559
79676
  const encoded = publicKey.split(" ")[1];
79560
- const file4 = path152.join(options.sshDirectory ?? path152.join(homedir22(), ".ssh"), "authorized_keys");
79677
+ const file4 = path152.join(options.sshDirectory ?? path152.join(homedir23(), ".ssh"), "authorized_keys");
79561
79678
  const before = await readFile60(file4, "utf8").catch(() => "");
79562
79679
  await appendAuthorizedKey(
79563
79680
  line,
@@ -79955,7 +80072,7 @@ async function main() {
79955
80072
  return askpass2(args[1]);
79956
80073
  }
79957
80074
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
79958
- return runBridge2(args, "0.3.54");
80075
+ return runBridge2(args, "0.3.55");
79959
80076
  }
79960
80077
  main().then((code) => {
79961
80078
  process.exitCode = code;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.54",
3
+ "version": "0.3.55",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {