send-to-paseo 1.3.0

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.
package/server/deps.ts ADDED
@@ -0,0 +1,432 @@
1
+ import { execFile } from "node:child_process";
2
+ import { access } from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ import { homedir, platform } from "node:os";
5
+ import { delimiter, isAbsolute, join } from "node:path";
6
+
7
+ /**
8
+ * Every external command the plugin depends on, where it lives, and whether it
9
+ * works. One module so the answer to "what does this need installed?" is in one
10
+ * place, and so the startup self-check and the Paseo surface report the same
11
+ * thing.
12
+ *
13
+ * WHY THE WELL-KNOWN DIRECTORY LIST EXISTS — this is the bug that motivated
14
+ * this module. A Paseo plugin runs inside a daemon subprocess, and that daemon
15
+ * is normally launched by launchd / the desktop app, not from an interactive
16
+ * shell, so it inherits a *login-less* PATH.
17
+ *
18
+ * Be precise about what was actually measured (VERIFICATION.md 16.2), because
19
+ * this was latent rather than biting during the original macOS 26.6 / Paseo 0.7.0 measurement:
20
+ * the plugin subprocess got the user's FULL interactive PATH — the host enriches
21
+ * it. One process up, `Paseo.app` itself had
22
+ *
23
+ * /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
24
+ *
25
+ * with no `/opt/homebrew/bin`, which is the PATH a plugin would inherit on any
26
+ * host that does not enrich it (an older or newer Paseo, a systemd unit, a
27
+ * launchctl-managed daemon).
28
+ * A `gh` installed by Homebrew — the way almost every macOS user installs it —
29
+ * is invisible to a bare `$PATH` scan even though `gh --version` works fine in
30
+ * the user's terminal. So each lookup probes a short list of well-known install
31
+ * locations *in addition* to PATH, and PATH is consulted first so an explicit
32
+ * user PATH always wins.
33
+ *
34
+ * Nothing here ever runs through a shell. `gh` is a shell *function* in some
35
+ * users' zsh, so a shell spawn would run the function instead of the program;
36
+ * resolving the executable ourselves and calling `execFile` with an argv array
37
+ * guarantees we get the real binary and that no input can become shell syntax.
38
+ */
39
+
40
+ /** Version/auth probes are cheap; nothing here may hang the bridge. */
41
+ const PROBE_TIMEOUT_MS = 5_000;
42
+ /** `gh auth status` talks to github.com, so it gets a longer, still bounded leash. */
43
+ const AUTH_TIMEOUT_MS = 8_000;
44
+ /** Long enough that repeated surface refreshes are free, short enough that
45
+ * installing gh and reopening the surface shows the new state. */
46
+ const SNAPSHOT_TTL_MS = 60_000;
47
+ const EXEC_TIMEOUT_MS = 5_000;
48
+
49
+ /**
50
+ * Directories searched after `$PATH`. Deliberately short and boring: package
51
+ * managers, not personal conventions.
52
+ *
53
+ * /opt/homebrew/bin Homebrew, Apple silicon
54
+ * /usr/local/bin Homebrew on Intel, and most `make install`
55
+ * /usr/bin, /bin system packages, Xcode git
56
+ * /opt/local/bin MacPorts
57
+ * ~/.local/bin pip/pipx and the XDG user convention
58
+ * /home/linuxbrew/.linuxbrew/bin Homebrew on Linux
59
+ * /snap/bin Ubuntu snaps (`snap install gh`)
60
+ * /usr/local/git/bin the standalone macOS git installer
61
+ */
62
+ function wellKnownBinDirs(): string[] {
63
+ // Escape hatch, and the only way to switch the probe off. A user whose tools
64
+ // live somewhere exotic (`~/bin`, a Nix profile) can point the plugin at it
65
+ // without editing PATH for the whole Paseo app; the plugin's own test suite
66
+ // uses it to simulate a machine with nothing installed. Replaces the list
67
+ // below rather than adding to it, so it can express "nowhere".
68
+ const override = process.env.SEND_TO_PASEO_BIN_DIRS;
69
+ if (override !== undefined && override !== "") return override.split(delimiter);
70
+ return [
71
+ "/opt/homebrew/bin",
72
+ "/usr/local/bin",
73
+ "/usr/bin",
74
+ "/bin",
75
+ "/opt/local/bin",
76
+ join(homedir(), ".local", "bin"),
77
+ "/home/linuxbrew/.linuxbrew/bin",
78
+ "/snap/bin",
79
+ "/usr/local/git/bin",
80
+ ];
81
+ }
82
+
83
+ async function isExecutable(candidate: string): Promise<boolean> {
84
+ try {
85
+ await access(candidate, constants.X_OK);
86
+ return true;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Finds a real binary without a shell: an explicit override, then `$PATH`, then
94
+ * the well-known install locations the daemon's PATH probably omits.
95
+ *
96
+ * `delimiter` rather than a literal ":" so the PATH split is correct on every
97
+ * platform Node runs on.
98
+ */
99
+ export async function resolveBinary(
100
+ name: string,
101
+ preferred: readonly string[],
102
+ ): Promise<string | null> {
103
+ for (const candidate of preferred) {
104
+ if (candidate !== "" && (await isExecutable(candidate))) return candidate;
105
+ }
106
+ const searched = [
107
+ ...(process.env.PATH ?? "").split(delimiter),
108
+ // Only after PATH: an explicit user PATH must always win over our guesses.
109
+ ...wellKnownBinDirs(),
110
+ ];
111
+ const seen = new Set<string>();
112
+ for (const dir of searched) {
113
+ if (dir === "" || !isAbsolute(dir) || seen.has(dir)) continue;
114
+ seen.add(dir);
115
+ const candidate = join(dir, name);
116
+ if (await isExecutable(candidate)) return candidate;
117
+ }
118
+ return null;
119
+ }
120
+
121
+ /** Releases the event-loop refs a child holds, handles and pipes alike. */
122
+ function unrefChild(child: {
123
+ unref(): void;
124
+ stdout: unknown;
125
+ stderr: unknown;
126
+ stdin: unknown;
127
+ }): void {
128
+ child.unref();
129
+ for (const stream of [child.stdout, child.stderr, child.stdin]) {
130
+ (stream as { unref?: () => void } | null)?.unref?.();
131
+ }
132
+ }
133
+
134
+ export function runProcess(
135
+ file: string,
136
+ args: readonly string[],
137
+ options: {
138
+ cwd?: string;
139
+ timeoutMs?: number;
140
+ env?: NodeJS.ProcessEnv;
141
+ /**
142
+ * Detach from the event loop. Used by the startup self-check only: it is
143
+ * fire-and-forget, and a probe still in flight when Paseo says "Stopping
144
+ * plugin" must not hold the subprocess open — that is the failure that
145
+ * wedges `paseo plugin reload`.
146
+ *
147
+ * Measured, because it is not obvious: unref does NOT defeat the timeout.
148
+ * While something else holds the loop open — the bridge's listening socket,
149
+ * always, in the real plugin — a hung child is still killed at `timeoutMs`
150
+ * and the promise still rejects (SIGTERM at 3004ms for a 3000ms timeout).
151
+ * Only once nothing else keeps the process alive does the promise simply
152
+ * never settle, which during teardown is exactly what we want.
153
+ */
154
+ unref?: boolean;
155
+ } = {},
156
+ ): Promise<{ stdout: string; stderr: string }> {
157
+ return new Promise((resolvePromise, reject) => {
158
+ const child = execFile(
159
+ file,
160
+ [...args],
161
+ {
162
+ // No `shell`, so argv is passed straight to execve.
163
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
164
+ // Every spawn in this plugin is bounded: a hung `gh` must never hold an
165
+ // HTTP request, and through it the bridge, open forever.
166
+ timeout: options.timeoutMs ?? EXEC_TIMEOUT_MS,
167
+ maxBuffer: 4 * 1024 * 1024,
168
+ windowsHide: true,
169
+ encoding: "utf8",
170
+ ...(options.env === undefined ? {} : { env: options.env }),
171
+ },
172
+ (error, stdout, stderr) => {
173
+ if (error !== null) {
174
+ reject(Object.assign(error, { stdout, stderr }));
175
+ return;
176
+ }
177
+ resolvePromise({ stdout, stderr });
178
+ },
179
+ );
180
+ if (options.unref === true) unrefChild(child);
181
+ });
182
+ }
183
+
184
+ // ---------------------------------------------------------------------------
185
+ // Lookups
186
+ // ---------------------------------------------------------------------------
187
+
188
+ const binaryCache = new Map<string, string | null>();
189
+
190
+ async function findBinary(name: string, override: string | undefined): Promise<string | null> {
191
+ const cached = binaryCache.get(name);
192
+ if (cached !== undefined) return cached;
193
+ const found = await resolveBinary(name, [override ?? ""]);
194
+ binaryCache.set(name, found);
195
+ return found;
196
+ }
197
+
198
+ /** Absolute path to `git`, or null when it is not installed. Never throws. */
199
+ export function findGit(): Promise<string | null> {
200
+ return findBinary("git", process.env.SEND_TO_PASEO_GIT_PATH);
201
+ }
202
+
203
+ /** Absolute path to `gh`, or null when it is not installed. Never throws. */
204
+ export function findGh(): Promise<string | null> {
205
+ return findBinary("gh", process.env.SEND_TO_PASEO_GH_PATH);
206
+ }
207
+
208
+ /** Keeps `gh` non-interactive and machine-readable regardless of user config. */
209
+ export function ghEnv(): NodeJS.ProcessEnv {
210
+ return {
211
+ ...process.env,
212
+ GH_PAGER: "cat",
213
+ PAGER: "cat",
214
+ GH_NO_UPDATE_NOTIFIER: "1",
215
+ GH_PROMPT_DISABLED: "1",
216
+ CLICOLOR: "0",
217
+ NO_COLOR: "1",
218
+ };
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // Install advice
223
+ // ---------------------------------------------------------------------------
224
+
225
+ const isMac = platform() === "darwin";
226
+
227
+ /** Bare commands, per CONTRACT.md: `hint` carries shell commands unquoted. */
228
+ export const INSTALL_HINT = {
229
+ git: isMac
230
+ ? "Install git: xcode-select --install"
231
+ : "Install git: sudo apt install git (or your distribution's package manager)",
232
+ gh: isMac
233
+ ? "Install the GitHub CLI: brew install gh"
234
+ : "Install the GitHub CLI: sudo apt install gh (see cli.github.com for other distributions)",
235
+ } as const;
236
+
237
+ // ---------------------------------------------------------------------------
238
+ // Snapshot
239
+ // ---------------------------------------------------------------------------
240
+
241
+ export type DependencyName = "git" | "gh";
242
+ export type DependencyState = "ok" | "degraded" | "missing";
243
+
244
+ export interface DependencyReport {
245
+ name: DependencyName;
246
+ /** False means the plugin still works without it, with reduced information. */
247
+ required: boolean;
248
+ state: DependencyState;
249
+ path: string | null;
250
+ version: string | null;
251
+ /** One sentence: what is wrong, or what is lost. Empty when state is "ok". */
252
+ detail: string;
253
+ /** What the user should run. Empty when there is nothing to do. */
254
+ hint: string;
255
+ }
256
+
257
+ export interface DependencySnapshot {
258
+ at: number;
259
+ /** The PATH this subprocess actually inherited. Logged once; it is the single
260
+ * most useful line when someone reports "but gh works in my terminal". */
261
+ path: string;
262
+ dependencies: DependencyReport[];
263
+ }
264
+
265
+ let snapshotCache: DependencySnapshot | null = null;
266
+ let snapshotInFlight: Promise<DependencySnapshot> | null = null;
267
+
268
+ /** First line of `--version` output, trimmed. */
269
+ function firstLine(text: string): string {
270
+ return text.split("\n", 1)[0]?.trim() ?? "";
271
+ }
272
+
273
+ async function probeVersion(bin: string, args: readonly string[]): Promise<string | null> {
274
+ try {
275
+ const { stdout } = await runProcess(bin, args, { timeoutMs: PROBE_TIMEOUT_MS, unref: true });
276
+ const line = firstLine(stdout);
277
+ return line === "" ? null : line;
278
+ } catch {
279
+ return null;
280
+ }
281
+ }
282
+
283
+ async function reportGit(): Promise<DependencyReport> {
284
+ const path = await findGit();
285
+ if (path === null) {
286
+ return {
287
+ name: "git",
288
+ required: true,
289
+ state: "missing",
290
+ path: null,
291
+ version: null,
292
+ detail:
293
+ "git was not found. Paseo cannot create a worktree for a pull request without it, and workspace branches cannot be read.",
294
+ hint: INSTALL_HINT.git,
295
+ };
296
+ }
297
+ const version = await probeVersion(path, ["--version"]);
298
+ if (version === null) {
299
+ return {
300
+ name: "git",
301
+ required: true,
302
+ state: "degraded",
303
+ path,
304
+ version: null,
305
+ detail: `git was found at ${path} but did not run.`,
306
+ hint: INSTALL_HINT.git,
307
+ };
308
+ }
309
+ return { name: "git", required: true, state: "ok", path, version, detail: "", hint: "" };
310
+ }
311
+
312
+ /**
313
+ * `gh auth status` exits non-zero when no account is logged in. It prints to
314
+ * stderr, and it must never be logged verbatim — under some configurations it
315
+ * echoes the token. Only the exit status is used here.
316
+ */
317
+ async function ghAuthState(bin: string): Promise<"ok" | "unauthenticated"> {
318
+ try {
319
+ await runProcess(bin, ["auth", "status"], {
320
+ timeoutMs: AUTH_TIMEOUT_MS,
321
+ env: ghEnv(),
322
+ unref: true,
323
+ });
324
+ return "ok";
325
+ } catch {
326
+ return "unauthenticated";
327
+ }
328
+ }
329
+
330
+ async function reportGh(): Promise<DependencyReport> {
331
+ const path = await findGh();
332
+ if (path === null) {
333
+ return {
334
+ name: "gh",
335
+ required: false,
336
+ state: "missing",
337
+ path: null,
338
+ version: null,
339
+ detail:
340
+ "The GitHub CLI (gh) was not found. Sending still works: Paseo checks the PR out itself. Only the PR title, branch names and stack detection are unavailable.",
341
+ hint: INSTALL_HINT.gh,
342
+ };
343
+ }
344
+ const version = await probeVersion(path, ["--version"]);
345
+ if (version === null) {
346
+ return {
347
+ name: "gh",
348
+ required: false,
349
+ state: "degraded",
350
+ path,
351
+ version: null,
352
+ detail: `gh was found at ${path} but did not run. PR titles, branch names and stack detection are unavailable.`,
353
+ hint: INSTALL_HINT.gh,
354
+ };
355
+ }
356
+ const auth = await ghAuthState(path);
357
+ if (auth === "unauthenticated") {
358
+ return {
359
+ name: "gh",
360
+ required: false,
361
+ state: "degraded",
362
+ path,
363
+ version,
364
+ detail:
365
+ "gh is installed but not signed in to GitHub. Sending still works; PR titles, branch names and stack detection are unavailable until it is.",
366
+ hint: "Run: gh auth login",
367
+ };
368
+ }
369
+ return { name: "gh", required: false, state: "ok", path, version, detail: "", hint: "" };
370
+ }
371
+
372
+ /**
373
+ * Current dependency state, cached briefly. Safe to call from a request path:
374
+ * a warm cache costs nothing and a cold one costs two `--version` calls and one
375
+ * `gh auth status`, each with its own timeout.
376
+ */
377
+ export async function dependencySnapshot(): Promise<DependencySnapshot> {
378
+ const now = Date.now();
379
+ if (snapshotCache !== null && now - snapshotCache.at < SNAPSHOT_TTL_MS) return snapshotCache;
380
+ if (snapshotInFlight !== null) return snapshotInFlight;
381
+ snapshotInFlight = (async () => {
382
+ const dependencies = await Promise.all([reportGit(), reportGh()]);
383
+ const snapshot: DependencySnapshot = {
384
+ at: Date.now(),
385
+ path: process.env.PATH ?? "",
386
+ dependencies,
387
+ };
388
+ snapshotCache = snapshot;
389
+ snapshotInFlight = null;
390
+ return snapshot;
391
+ })();
392
+ return snapshotInFlight;
393
+ }
394
+
395
+ function describe(report: DependencyReport): string {
396
+ if (report.state === "ok") {
397
+ return `${report.name}: ok — ${report.version ?? "unknown version"} at ${report.path}`;
398
+ }
399
+ const role = report.required ? "REQUIRED" : "optional";
400
+ const hint = report.hint === "" ? "" : ` ${report.hint}`;
401
+ return `${report.name}: ${report.state} (${role}) — ${report.detail}${hint}`;
402
+ }
403
+
404
+ let selfCheckDone = false;
405
+
406
+ /**
407
+ * Four lines at most, once per plugin start, to
408
+ * `paseo plugin logs send-to-paseo` — the first place anyone debugging looks.
409
+ * The PATH line is there because "gh works in my terminal but the plugin says
410
+ * it is missing" is otherwise unanswerable.
411
+ */
412
+ export async function logDependencySelfCheck(): Promise<void> {
413
+ if (selfCheckDone) return;
414
+ selfCheckDone = true;
415
+ try {
416
+ const snapshot = await dependencySnapshot();
417
+ for (const report of snapshot.dependencies) {
418
+ console.log(`[send-to-paseo] dependency ${describe(report)}`);
419
+ }
420
+ // Always logged, not only on failure: "but gh works in my terminal" is the
421
+ // most likely support question, and this line and the resolved paths above
422
+ // are the whole answer.
423
+ console.log(`[send-to-paseo] plugin subprocess PATH=${snapshot.path}`);
424
+ } catch (error) {
425
+ console.error("[send-to-paseo] dependency self-check failed", String(error));
426
+ }
427
+ }
428
+
429
+ export function clearDependencyCaches(): void {
430
+ binaryCache.clear();
431
+ snapshotCache = null;
432
+ }