@tiens.nguyen/gu-cli 1.0.944 → 1.0.945

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.
@@ -19,7 +19,7 @@
19
19
  */
20
20
  import { createRequire } from "node:module";
21
21
  import { createHash, randomBytes, randomUUID } from "node:crypto";
22
- import { spawnSurviving, pidOnPort } from "./platform-tools.mjs";
22
+ import { spawnSurviving, pidOnPort, portOwnerUid } from "./platform-tools.mjs";
23
23
  import { procCommand, procStart, sameProcess } from "./proc-identity.mjs";
24
24
  import { DEFAULT_API_BASE as HOSTED_API_BASE } from "./device-login.mjs";
25
25
  import { spawn } from "node:child_process";
@@ -486,17 +486,32 @@ export async function seedDatabase({
486
486
  * port that accepts a connection and is not that: someone else's server. Only "other" is a
487
487
  * reason to move.
488
488
  */
489
- export async function whoHoldsPort(port, { fetchImpl = fetch, connects = tcpConnects } = {}) {
489
+ export async function whoHoldsPort(port, { fetchImpl = fetch, connects = tcpConnects, account = portAccount } = {}) {
490
490
  try {
491
491
  const res = await fetchImpl(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(2500) });
492
492
  const body = await res.json().catch(() => null);
493
- if (body && typeof body === "object" && ("dataBackend" in body || "persistence" in body)) return "gu";
493
+ if (body && typeof body === "object" && ("dataBackend" in body || "persistence" in body)) {
494
+ // GH #618: gu's API — but ANOTHER ACCOUNT's on this computer serves that account's
495
+ // database, and this account's worker key is refused there. Not ours to reuse.
496
+ return (await account(port).catch(() => "unknown")) === "other" ? "other-account" : "gu";
497
+ }
494
498
  return "other";
495
499
  } catch {
496
500
  return (await connects(port)) ? "other" : "free";
497
501
  }
498
502
  }
499
503
 
504
+ /**
505
+ * Whose is the program listening on `port` → "mine" | "other" (another account on this computer)
506
+ * | "unknown" (Windows, or the system would not say). Only "other" changes anything (GH #618).
507
+ */
508
+ export async function portAccount(port, { ownerUid = portOwnerUid, myUid = process.getuid?.() } = {}) {
509
+ if (!Number.isInteger(myUid)) return "unknown";
510
+ const uid = await ownerUid(port).catch(() => null);
511
+ if (!Number.isInteger(uid)) return "unknown";
512
+ return uid === myUid ? "mine" : "other";
513
+ }
514
+
500
515
  /** Does anything accept a TCP connection on 127.0.0.1:port? */
501
516
  async function tcpConnects(port, timeoutMs = 1500) {
502
517
  const net = await import("node:net");
@@ -553,7 +568,7 @@ async function systemFreePort() {
553
568
  * an explicit choice is not overridden, it is reported.
554
569
  */
555
570
  export function portDecision({ holder, source }) {
556
- if (holder !== "other") return "use";
571
+ if (holder !== "other" && holder !== "other-account") return "use";
557
572
  return source === "env" ? "refuse" : "move";
558
573
  }
559
574
 
@@ -582,8 +597,9 @@ export async function settleApiPort({
582
597
  if (action === "use") return { moved: false, port: from };
583
598
  // The program's name when the system gives it; on Windows it often does not (seen live),
584
599
  // and "another program (another program)" is not a sentence.
585
- const name = (await (nameOf ?? (await import("./mongo-native.mjs")).portHolder)(from).catch(() => null)) || "";
586
- const who = name || "another program";
600
+ const otherAccount = holder === "other-account";
601
+ const name = otherAccount ? "" : (await (nameOf ?? (await import("./mongo-native.mjs")).portHolder)(from).catch(() => null)) || "";
602
+ const who = otherAccount ? "another account's gu" : name || "another program";
587
603
  if (action === "refuse") {
588
604
  log(` Port ${from} (set by GONEXT_LOCAL_API_PORT) is in use by ${who}.`);
589
605
  log(" Stop that program, or choose another port, then run gu again.");
@@ -591,7 +607,11 @@ export async function settleApiPort({
591
607
  }
592
608
  const to = await freePort(from);
593
609
  await useApiPort(to);
594
- log(` Port ${from} is used by another program${name ? ` (${name})` : ""} — gu's API uses ${to}.`);
610
+ log(
611
+ otherAccount
612
+ ? ` Port ${from} is another account's gu — this account's API uses ${to}.`
613
+ : ` Port ${from} is used by another program${name ? ` (${name})` : ""} — gu's API uses ${to}.`
614
+ );
595
615
  // An install that was already working: its terminal and its worker read worker.env. The
596
616
  // worker read it ONCE, at start, so it is restarted — or it would poll the old port forever.
597
617
  if (await repointWorkerEnv(from, to)) {
@@ -711,7 +731,7 @@ export async function waitForApi({ port = LOCAL_API_PORT, timeoutMs = 45000, now
711
731
  export async function waitForApiDown({ port = LOCAL_API_PORT, timeoutMs = 20000, now = Date.now } = {}) {
712
732
  const deadline = now() + timeoutMs;
713
733
  while (now() < deadline) {
714
- if (!(await probeLocalApi(port)).reachable) return { down: true, why: "" };
734
+ if (!(await probeLocalApi(port, { account: async () => "unknown" })).reachable) return { down: true, why: "" };
715
735
  await new Promise((r) => setTimeout(r, 200));
716
736
  }
717
737
  // Reported rather than thrown: a caller that is about to start a fresh server may still want to
@@ -720,12 +740,17 @@ export async function waitForApiDown({ port = LOCAL_API_PORT, timeoutMs = 20000,
720
740
  }
721
741
 
722
742
  /** Is a previously started API still answering? Used by status/doctor and by resume. */
723
- export async function probeLocalApi(port = LOCAL_API_PORT) {
743
+ export async function probeLocalApi(port = LOCAL_API_PORT, { account = portAccount } = {}) {
724
744
  try {
725
745
  const res = await fetch(`http://127.0.0.1:${port}/api/health`, {
726
746
  signal: AbortSignal.timeout(3000),
727
747
  });
728
748
  const body = await res.json();
749
+ // GH #618: another account's API on this computer answers here too. It is not this account's —
750
+ // its database does not know this worker key — so it is not usable, and its version is not ours.
751
+ if ((await account(port).catch(() => "unknown")) === "other") {
752
+ return { reachable: true, ok: false, otherAccount: true, why: `port ${port} is another account's gu API on this computer`, body: null };
753
+ }
729
754
  return { reachable: true, ...apiIsUsable(body), body };
730
755
  } catch {
731
756
  return { reachable: false, ok: false, why: "no API on the port", body: null };
package/gu-repl.mjs CHANGED
@@ -12097,7 +12097,7 @@ async function fetchCodingChoice(folderHash) {
12097
12097
  headers: { "X-Worker-Key": workerKey },
12098
12098
  signal: AbortSignal.timeout(API_CALL_TIMEOUT_MS),
12099
12099
  });
12100
- if (!r.ok) throw new Error(`coding-choice GET failed: HTTP ${r.status}`);
12100
+ if (!r.ok) throw Object.assign(new Error(`coding-choice GET failed: HTTP ${r.status}`), { status: r.status });
12101
12101
  const j = await r.json().catch(() => ({}));
12102
12102
  const c = j?.choice;
12103
12103
  if (!c || typeof c !== "object") return null;
@@ -15806,7 +15806,10 @@ async function main() {
15806
15806
  // local mongodb is unreachable. Cloud mode failing to reach the hosted API means the
15807
15807
  // computer has lost its internet connection. Two different messages, one per mode.
15808
15808
  dbUnreachable = true;
15809
- if (isLocalApiBase(apiBase) && (isNetworkError(err) || isTimeout(err))) {
15809
+ if (err?.status === 401 || err?.status === 403) {
15810
+ // GH #618: the API answered and refused the KEY — the database was fine. The key message
15811
+ // that follows says what to do; "cannot access local mongodb" sent the reader the wrong way.
15812
+ } else if (isLocalApiBase(apiBase) && (isNetworkError(err) || isTimeout(err))) {
15810
15813
  // THE API ITSELF IS NOT ANSWERING (GH #397) — MongoDB was not even asked. Blaming the
15811
15814
  // database here sent the reader to check mongod while it was fine; the message right after
15812
15815
  // this one names the API and starts it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.944",
3
+ "version": "1.0.945",
4
4
  "description": "gu: the coding agent in your terminal. It reads your repo, makes the change and runs the tests, with your own models (Ollama or any OpenAI-compatible provider). Free installs keep the agent, its API and its database on your machine. macOS, Linux and Windows.",
5
5
  "keywords": [
6
6
  "ai",
@@ -660,6 +660,53 @@ export async function pidOnPort(port) {
660
660
  return Number.isFinite(pid) && pid > 0 ? pid : null;
661
661
  }
662
662
 
663
+ /**
664
+ * WHICH ACCOUNT LISTENS ON `port` → its uid, or null when that can't be told (GH #618).
665
+ *
666
+ * Two accounts on one computer share 127.0.0.1: the second account's gu found the first
667
+ * account's API on 4100, took it for its own, and every turn was refused ("your worker key was
668
+ * rejected"), because that API serves the other account's database. lsof can't tell: without
669
+ * root it does not list another account's sockets at all (checked on macOS). These can:
670
+ * macOS — `netstat -anv` names the pid of every listener, and `ps` gives its uid;
671
+ * Linux — `ss -e` prints the socket's uid (left out when it is 0, root).
672
+ * Windows: null — not told, so nothing changes there.
673
+ */
674
+ export async function portOwnerUid(port, { platform = process.platform, exec = run } = {}) {
675
+ const p = Number(port);
676
+ if (!Number.isInteger(p) || p <= 0) return null;
677
+ if (platform === "darwin") {
678
+ const pid = darwinListenerPid(await exec("netstat", ["-anv", "-p", "tcp"]), p);
679
+ if (!pid) return null;
680
+ const uid = Number(String((await exec("ps", ["-o", "uid=", "-p", String(pid)])) ?? "").trim());
681
+ return Number.isInteger(uid) && String(uid) !== "" && uid >= 0 ? uid : null;
682
+ }
683
+ if (platform === "linux") return linuxListenerUid(await exec("ss", ["-ltnHe", `sport = :${p}`]), p);
684
+ return null;
685
+ }
686
+
687
+ /** macOS `netstat -anv -p tcp` → the pid listening on `port` (the "process:pid" column), or null. */
688
+ export function darwinListenerPid(out, port) {
689
+ for (const line of String(out ?? "").split("\n")) {
690
+ if (!/\bLISTEN\b/.test(line)) continue;
691
+ const cols = line.trim().split(/\s+/);
692
+ if (!new RegExp(`[.:]${port}$`).test(cols[3] ?? "")) continue;
693
+ const m = line.match(/\S+:(\d+)\s+[0-9a-f]{5}\s/);
694
+ if (m) return Number(m[1]);
695
+ }
696
+ return null;
697
+ }
698
+
699
+ /** Linux `ss -ltnHe` → the uid listening on `port`; no uid field on a matching line = root (0). */
700
+ export function linuxListenerUid(out, port) {
701
+ for (const line of String(out ?? "").split("\n")) {
702
+ const cols = line.trim().split(/\s+/);
703
+ if (!/^LISTEN$/.test(cols[0] ?? "") || !new RegExp(`:${port}$`).test(cols[3] ?? "")) continue;
704
+ const m = line.match(/\buid:(\d+)/);
705
+ return m ? Number(m[1]) : 0;
706
+ }
707
+ return null;
708
+ }
709
+
663
710
  /* ------------------------------------------------------- "View logs" (task #166) ---------- */
664
711
 
665
712
  /**