@myrialabs/clopen 0.3.2 → 0.3.3

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.
@@ -0,0 +1,298 @@
1
+ /**
2
+ * System Tool Install Runner
3
+ *
4
+ * Spawns install recipes via Bun.spawn (non-interactive), streams stdout
5
+ * and stderr to subscribed WebSocket clients, buffers recent output in a
6
+ * bounded ring buffer so late subscribers (or re-connecting clients) can
7
+ * catch up, and supports cancellation.
8
+ *
9
+ * Session model:
10
+ * - One active session per ToolId (prevents duplicate installs).
11
+ * - A session survives client navigation: output continues to accumulate
12
+ * in the ring buffer and the run completes regardless of who is listening.
13
+ * - After exit, the session remains in memory for RETENTION_MS so the
14
+ * frontend can retrieve final state (exit code + log), then GC'd.
15
+ *
16
+ * Security: install recipes are constructed server-side only. The client
17
+ * may only pick a tool id; it cannot supply arbitrary command strings.
18
+ */
19
+
20
+ import { debug } from '$shared/utils/logger';
21
+ import { ws } from '$backend/utils/ws';
22
+ import { getCleanSpawnEnv } from '$backend/utils/env';
23
+ import { refreshProcessPath } from '$backend/utils/path-harvest';
24
+ import type { Recipe, ToolId } from './install-recipes';
25
+ import { resolveRecipe } from './install-recipes';
26
+
27
+ const RING_BUFFER_LINES = 10_000;
28
+ const RETENTION_MS = 5 * 60 * 1000;
29
+
30
+ export type SessionStatus = 'running' | 'success' | 'failed' | 'cancelled';
31
+
32
+ interface RingBuffer {
33
+ lines: string[];
34
+ total: number;
35
+ }
36
+
37
+ interface Session {
38
+ id: string;
39
+ tool: ToolId;
40
+ recipe: Recipe;
41
+ proc: ReturnType<typeof Bun.spawn> | null;
42
+ status: SessionStatus;
43
+ exitCode: number | null;
44
+ startedAt: number;
45
+ endedAt: number | null;
46
+ buffer: RingBuffer;
47
+ retentionTimer: ReturnType<typeof setTimeout> | null;
48
+ startedBy: string;
49
+ /** Current partial line per stream (for line-based chunking). */
50
+ pending: { stdout: string; stderr: string };
51
+ }
52
+
53
+ const sessions = new Map<string, Session>();
54
+ const activeByTool = new Map<ToolId, string>();
55
+
56
+ function newRingBuffer(): RingBuffer {
57
+ return { lines: [], total: 0 };
58
+ }
59
+
60
+ function pushLine(buf: RingBuffer, line: string): void {
61
+ buf.lines.push(line);
62
+ buf.total += 1;
63
+ if (buf.lines.length > RING_BUFFER_LINES) {
64
+ buf.lines.splice(0, buf.lines.length - RING_BUFFER_LINES);
65
+ }
66
+ }
67
+
68
+ function scheduleRetention(session: Session): void {
69
+ if (session.retentionTimer) clearTimeout(session.retentionTimer);
70
+ session.retentionTimer = setTimeout(() => {
71
+ sessions.delete(session.id);
72
+ if (activeByTool.get(session.tool) === session.id) {
73
+ activeByTool.delete(session.tool);
74
+ }
75
+ }, RETENTION_MS);
76
+ }
77
+
78
+ function sessionSnapshot(session: Session) {
79
+ return {
80
+ sessionId: session.id,
81
+ tool: session.tool,
82
+ status: session.status,
83
+ exitCode: session.exitCode,
84
+ startedAt: session.startedAt,
85
+ endedAt: session.endedAt,
86
+ totalLines: session.buffer.total,
87
+ recentLines: session.buffer.lines.slice(),
88
+ displayCommand: session.recipe.displayCommand ?? ''
89
+ };
90
+ }
91
+
92
+ function emitStream(session: Session, stream: 'stdout' | 'stderr', chunk: string): void {
93
+ // Buffer partial lines so subscribers receive whole lines at a time.
94
+ const prev = session.pending[stream] + chunk;
95
+ const parts = prev.split(/\r?\n/);
96
+ session.pending[stream] = parts.pop() ?? '';
97
+ for (const line of parts) {
98
+ pushLine(session.buffer, line);
99
+ ws.emit.user(session.startedBy, 'system-tools:install-stream', {
100
+ sessionId: session.id,
101
+ tool: session.tool,
102
+ type: stream,
103
+ line
104
+ });
105
+ }
106
+ }
107
+
108
+ function flushPending(session: Session): void {
109
+ for (const stream of ['stdout', 'stderr'] as const) {
110
+ const remaining = session.pending[stream];
111
+ if (remaining) {
112
+ pushLine(session.buffer, remaining);
113
+ ws.emit.user(session.startedBy, 'system-tools:install-stream', {
114
+ sessionId: session.id,
115
+ tool: session.tool,
116
+ type: stream,
117
+ line: remaining
118
+ });
119
+ session.pending[stream] = '';
120
+ }
121
+ }
122
+ }
123
+
124
+ async function pipeStream(
125
+ session: Session,
126
+ stream: ReadableStream<Uint8Array> | null,
127
+ kind: 'stdout' | 'stderr'
128
+ ): Promise<void> {
129
+ if (!stream) return;
130
+ const decoder = new TextDecoder();
131
+ const reader = stream.getReader();
132
+ try {
133
+ while (true) {
134
+ const { done, value } = await reader.read();
135
+ if (done) break;
136
+ const chunk = decoder.decode(value, { stream: true });
137
+ emitStream(session, kind, chunk);
138
+ }
139
+ const tail = decoder.decode();
140
+ if (tail) emitStream(session, kind, tail);
141
+ } catch (err) {
142
+ debug.warn('path', `[install:${session.id}] stream read error (${kind}):`, err);
143
+ } finally {
144
+ try { reader.releaseLock(); } catch { /* ignore */ }
145
+ }
146
+ }
147
+
148
+ export class InstallAlreadyRunningError extends Error {
149
+ constructor(public sessionId: string, public tool: ToolId) {
150
+ super(`Install already running for ${tool}`);
151
+ }
152
+ }
153
+
154
+ export class InstallNotAutoInstallableError extends Error {
155
+ constructor(public tool: ToolId, public reason: string) {
156
+ super(`Cannot auto-install ${tool}: ${reason}`);
157
+ }
158
+ }
159
+
160
+ export async function startInstall(tool: ToolId, userId: string): Promise<Session> {
161
+ await refreshProcessPath();
162
+
163
+ const existing = activeByTool.get(tool);
164
+ if (existing) {
165
+ const session = sessions.get(existing);
166
+ if (session && session.status === 'running') {
167
+ throw new InstallAlreadyRunningError(existing, tool);
168
+ }
169
+ }
170
+
171
+ const recipe = await resolveRecipe(tool);
172
+ if (!recipe.autoInstallable || !recipe.command) {
173
+ throw new InstallNotAutoInstallableError(tool, recipe.unavailableReason ?? 'Not auto-installable on this platform');
174
+ }
175
+
176
+ const id = crypto.randomUUID();
177
+ const spawnArgs = recipe.shell
178
+ ? [recipe.shell.program, ...recipe.shell.args, ...recipe.command]
179
+ : recipe.command;
180
+
181
+ const env = { ...getCleanSpawnEnv(), ...(recipe.env ?? {}) };
182
+
183
+ debug.log('path', `[install:${id}] Spawning: ${spawnArgs.join(' ')}`);
184
+
185
+ let proc: ReturnType<typeof Bun.spawn>;
186
+ try {
187
+ proc = Bun.spawn(spawnArgs, {
188
+ stdout: 'pipe',
189
+ stderr: 'pipe',
190
+ stdin: 'ignore',
191
+ env
192
+ });
193
+ } catch (err) {
194
+ throw new Error(`Failed to spawn: ${err instanceof Error ? err.message : String(err)}`);
195
+ }
196
+
197
+ const session: Session = {
198
+ id,
199
+ tool,
200
+ recipe,
201
+ proc,
202
+ status: 'running',
203
+ exitCode: null,
204
+ startedAt: Date.now(),
205
+ endedAt: null,
206
+ buffer: newRingBuffer(),
207
+ retentionTimer: null,
208
+ startedBy: userId,
209
+ pending: { stdout: '', stderr: '' }
210
+ };
211
+
212
+ sessions.set(id, session);
213
+ activeByTool.set(tool, id);
214
+
215
+ // Initial marker line so clients see something immediately.
216
+ const banner = `$ ${recipe.displayCommand ?? spawnArgs.join(' ')}`;
217
+ emitStream(session, 'stdout', banner + '\n');
218
+
219
+ // Broadcast the session-started event so clients that subscribe mid-run can attach.
220
+ ws.emit.user(userId, 'system-tools:install-started', {
221
+ sessionId: id,
222
+ tool,
223
+ displayCommand: recipe.displayCommand ?? '',
224
+ startedAt: session.startedAt
225
+ });
226
+
227
+ (async () => {
228
+ const [, , exitCode] = await Promise.all([
229
+ pipeStream(session, proc.stdout as ReadableStream<Uint8Array>, 'stdout'),
230
+ pipeStream(session, proc.stderr as ReadableStream<Uint8Array>, 'stderr'),
231
+ proc.exited
232
+ ]);
233
+ flushPending(session);
234
+
235
+ // `cancelled` is set preemptively by cancelInstall(); don't overwrite.
236
+ if (session.status === 'running') {
237
+ session.status = exitCode === 0 ? 'success' : 'failed';
238
+ }
239
+ session.exitCode = exitCode;
240
+ session.endedAt = Date.now();
241
+ session.proc = null;
242
+
243
+ debug.log('path', `[install:${id}] Finished status=${session.status} exit=${exitCode}`);
244
+
245
+ ws.emit.user(userId, 'system-tools:install-finished', {
246
+ sessionId: id,
247
+ tool,
248
+ status: session.status,
249
+ exitCode: exitCode ?? -1,
250
+ endedAt: session.endedAt
251
+ });
252
+
253
+ scheduleRetention(session);
254
+ })().catch((err) => {
255
+ debug.error('path', `[install:${id}] runner crash:`, err);
256
+ session.status = 'failed';
257
+ session.endedAt = Date.now();
258
+ session.exitCode = -1;
259
+ ws.emit.user(userId, 'system-tools:install-finished', {
260
+ sessionId: id,
261
+ tool,
262
+ status: session.status,
263
+ exitCode: -1,
264
+ endedAt: session.endedAt
265
+ });
266
+ scheduleRetention(session);
267
+ });
268
+
269
+ return session;
270
+ }
271
+
272
+ export function cancelInstall(sessionId: string): boolean {
273
+ const session = sessions.get(sessionId);
274
+ if (!session || session.status !== 'running' || !session.proc) return false;
275
+ session.status = 'cancelled';
276
+ try {
277
+ session.proc.kill();
278
+ } catch {
279
+ // Already dead — the exited promise will resolve regardless.
280
+ }
281
+ return true;
282
+ }
283
+
284
+ export function getSession(sessionId: string) {
285
+ const session = sessions.get(sessionId);
286
+ return session ? sessionSnapshot(session) : null;
287
+ }
288
+
289
+ export function getActiveSessionForTool(tool: ToolId) {
290
+ const id = activeByTool.get(tool);
291
+ if (!id) return null;
292
+ const session = sessions.get(id);
293
+ return session ? sessionSnapshot(session) : null;
294
+ }
295
+
296
+ export function listActiveSessions() {
297
+ return Array.from(sessions.values()).map(sessionSnapshot);
298
+ }
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { debug } from '$shared/utils/logger';
7
7
  import { getCleanSpawnEnv } from '../utils/env';
8
+ import { resolveBinary } from '../utils/cli';
8
9
 
9
10
  export interface GitExecResult {
10
11
  stdout: string;
@@ -22,7 +23,7 @@ export async function execGit(
22
23
  ): Promise<GitExecResult> {
23
24
  debug.log('git', `Executing: git ${args.join(' ')} in ${cwd}`);
24
25
 
25
- const gitPath = Bun.which('git');
26
+ const gitPath = resolveBinary('git');
26
27
  if (!gitPath) throw new Error('git binary not found on PATH');
27
28
 
28
29
  const safeCwd = cwd.replace(/\\/g, '/');
package/backend/index.ts CHANGED
@@ -19,6 +19,7 @@ import { loggerMiddleware } from './middleware/logger';
19
19
  // Database initialization
20
20
  import { initializeDatabase, closeDatabase } from './database';
21
21
  import { disposeAllEngines } from './engine';
22
+ import { refreshProcessPath } from './utils/path-harvest';
22
23
  import { debug } from '$shared/utils/logger';
23
24
  import { networkInterfaces } from 'os';
24
25
  import { resolve } from 'node:path';
@@ -127,6 +128,16 @@ async function startServer() {
127
128
  // This avoids double port-check race conditions (e.g. zombie processes on
128
129
  // Windows causing silent desync between Vite proxy and backend).
129
130
 
131
+ // Harvest user's interactive-shell PATH into process.env (Unix only).
132
+ // Ensures Bun.which / Bun.spawn / bun-pty see the same PATH as the user's
133
+ // terminal, so CLI binaries installed via nvm/fnm/volta/asdf/bun/homebrew
134
+ // are discoverable even when clopen is launched from a minimal environment.
135
+ try {
136
+ await refreshProcessPath();
137
+ } catch (error) {
138
+ debug.warn('path', '⚠️ Initial PATH harvest failed:', error);
139
+ }
140
+
130
141
  // Initialize database first before accepting connections
131
142
  try {
132
143
  await initializeDatabase();
@@ -19,6 +19,7 @@ import type { Browser, BrowserContext, Page } from 'puppeteer';
19
19
  import { debug } from '$shared/utils/logger';
20
20
  import puppeteer from 'puppeteer-extra';
21
21
  import StealthPlugin from 'puppeteer-extra-plugin-stealth';
22
+ import { getChromeExecutablePath } from '$backend/engine/install-recipes';
22
23
 
23
24
  puppeteer.use(StealthPlugin());
24
25
 
@@ -98,11 +99,18 @@ class BrowserPool {
98
99
  private async launchBrowser(): Promise<Browser> {
99
100
  debug.log('preview', '🚀 Launching browser with puppeteer-extra + StealthPlugin...');
100
101
 
101
- const browser = await puppeteer.launch({
102
- headless: true,
103
- channel: 'chrome',
104
- args: CHROMIUM_ARGS
105
- }) as unknown as Browser;
102
+ // Prefer the clopen-managed Chrome under ~/.clopen/bin, then system Chrome.
103
+ // Fall back to puppeteer's `channel: 'chrome'` discovery only if neither exists.
104
+ const executablePath = getChromeExecutablePath();
105
+ const launchOptions: Parameters<typeof puppeteer.launch>[0] = executablePath
106
+ ? { headless: true, executablePath, args: CHROMIUM_ARGS }
107
+ : { headless: true, channel: 'chrome', args: CHROMIUM_ARGS };
108
+
109
+ if (executablePath) {
110
+ debug.log('preview', ` using Chrome at: ${executablePath}`);
111
+ }
112
+
113
+ const browser = await puppeteer.launch(launchOptions) as unknown as Browser;
106
114
 
107
115
  debug.log('preview', '✅ Browser launched successfully');
108
116
 
@@ -1,15 +1,37 @@
1
1
  /**
2
2
  * CLI Binary Resolution & Status
3
3
  *
4
- * Uses Bun.which() for cross-platform PATH resolution.
5
- * Bun.which() returns absolute paths and handles PATHEXT
6
- * extensions (.exe, .cmd) on Windows automatically.
4
+ * Single source of truth for detecting tools like `opencode`, `claude`, `git`.
5
+ *
6
+ * Resolution strategy:
7
+ * 1. Refresh process.env.PATH from the user's interactive shell (Unix only)
8
+ * so binaries installed via nvm/fnm/volta/asdf/bun/homebrew (and our own
9
+ * System Tools installer) become visible without a clopen restart.
10
+ * 2. Call `Bun.which(binary, { PATH: process.env.PATH })` — the explicit
11
+ * PATH option is critical: without it, Bun.which uses a cached startup
12
+ * PATH and ignores runtime updates, so newly-installed binaries remain
13
+ * invisible even though process.env.PATH has been refreshed.
7
14
  */
8
15
 
16
+ import { refreshProcessPath } from './path-harvest';
17
+
9
18
  export type CLIStatus = { installed: boolean; version: string | null };
10
19
 
20
+ export function resolveBinary(binary: string): string | null {
21
+ return Bun.which(binary, { PATH: process.env.PATH }) ?? null;
22
+ }
23
+
24
+ /**
25
+ * Refresh $PATH from the user's shell, then resolve. Use at any spawn site
26
+ * that may run after a fresh install (e.g. models:list, setup-token).
27
+ */
28
+ export async function resolveBinaryWithRefresh(binary: string): Promise<string | null> {
29
+ await refreshProcessPath();
30
+ return resolveBinary(binary);
31
+ }
32
+
11
33
  export async function getStatus(command: string): Promise<CLIStatus> {
12
- const resolved = Bun.which(command);
34
+ const resolved = await resolveBinaryWithRefresh(command);
13
35
  if (!resolved) return { installed: false, version: null };
14
36
 
15
37
  try {
@@ -24,4 +46,4 @@ export async function getStatus(command: string): Promise<CLIStatus> {
24
46
  } catch {
25
47
  return { installed: false, version: null };
26
48
  }
27
- }
49
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * User PATH Harvesting
3
+ *
4
+ * On Unix, clopen may be launched from an environment whose PATH differs
5
+ * from the user's interactive shell — e.g. systemd, launchd, non-interactive
6
+ * parent processes. Binaries installed via nvm/fnm/volta/asdf/bun/homebrew
7
+ * live in paths added by `.zshrc`/`.bashrc`/`.profile`, which those minimal
8
+ * environments do not source. This makes `Bun.which('claude')` return null
9
+ * even though `claude -v` works in the user's terminal.
10
+ *
11
+ * Fix: spawn the user's login+interactive shell, read its PATH, and merge
12
+ * back into `process.env.PATH`. All downstream consumers (`Bun.which`,
13
+ * `Bun.spawn`, `getCleanSpawnEnv`, bun-pty) then see the correct PATH.
14
+ *
15
+ * Windows is a no-op — PATH on Windows is set via System/User Env Variables
16
+ * and inherited correctly by child processes, and `Bun.which` already handles
17
+ * PATHEXT resolution (.exe/.cmd/.bat).
18
+ *
19
+ * Concurrency: refreshProcessPath() dedups via an in-flight promise, so
20
+ * parallel callers share a single shell spawn. No TTL — once resolved, the
21
+ * next call performs a fresh harvest. This keeps "Recheck Installation"
22
+ * live: install a CLI in terminal, click the button, harvest runs again.
23
+ */
24
+
25
+ import { userInfo } from 'node:os';
26
+ import { debug } from '$shared/utils/logger';
27
+
28
+ const HARVEST_TIMEOUT_MS = 2000;
29
+
30
+ let harvestInFlight: Promise<string | null> | null = null;
31
+
32
+ function resolveUserShell(): string | null {
33
+ if (process.env.SHELL) return process.env.SHELL;
34
+ try {
35
+ const info = userInfo();
36
+ if (info.shell) return info.shell;
37
+ } catch {
38
+ // userInfo() can throw on some platforms — fall through
39
+ }
40
+ return null;
41
+ }
42
+
43
+ /**
44
+ * Spawn the user's login+interactive shell and capture its PATH.
45
+ * Returns null on Windows, on failure, or when no shell is available.
46
+ */
47
+ async function harvestUserPath(): Promise<string | null> {
48
+ if (process.platform === 'win32') return null;
49
+ if (process.env.CLOPEN_SKIP_PATH_HARVEST === '1') {
50
+ debug.log('path', 'PATH harvest skipped via CLOPEN_SKIP_PATH_HARVEST');
51
+ return null;
52
+ }
53
+
54
+ const shell = resolveUserShell();
55
+ if (!shell) {
56
+ debug.warn('path', 'No $SHELL or user shell available — skipping PATH harvest');
57
+ return null;
58
+ }
59
+
60
+ const controller = new AbortController();
61
+ const timer = setTimeout(() => controller.abort(), HARVEST_TIMEOUT_MS);
62
+
63
+ try {
64
+ // -i makes the shell source rc files (.bashrc/.zshrc).
65
+ // -l makes it source login files (.profile/.zprofile/.bash_profile).
66
+ // printf %s (no newline) yields PATH cleanly; rc banners go to stderr
67
+ // or are discarded if they go to stdout before our printf.
68
+ const proc = Bun.spawn([shell, '-ilc', 'printf %s "$PATH"'], {
69
+ stdout: 'pipe',
70
+ stderr: 'ignore',
71
+ signal: controller.signal
72
+ });
73
+
74
+ const [stdout, exitCode] = await Promise.all([
75
+ new Response(proc.stdout).text(),
76
+ proc.exited
77
+ ]);
78
+
79
+ if (exitCode !== 0) {
80
+ debug.warn('path', `Shell exited ${exitCode} during PATH harvest`);
81
+ return null;
82
+ }
83
+
84
+ // Some rc files echo banners before our printf runs. The last line of
85
+ // stdout is PATH (our printf). Trim, then take the last non-empty line.
86
+ const lines = stdout.split('\n').map(l => l.trim()).filter(Boolean);
87
+ const path = lines[lines.length - 1] ?? '';
88
+ if (!path.includes('/')) {
89
+ debug.warn('path', 'Harvested PATH looks invalid, skipping');
90
+ return null;
91
+ }
92
+ return path;
93
+ } catch (err) {
94
+ debug.warn('path', 'PATH harvest failed:', err instanceof Error ? err.message : err);
95
+ return null;
96
+ } finally {
97
+ clearTimeout(timer);
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Merge harvested PATH into process.env.PATH, preserving existing entries
103
+ * as a fallback and deduplicating. Harvested entries are prepended so user
104
+ * shell preferences win over whatever the parent process supplied.
105
+ */
106
+ function applyHarvestedPath(harvested: string): void {
107
+ const existing = process.env.PATH ?? '';
108
+ const seen = new Set<string>();
109
+ const merged: string[] = [];
110
+
111
+ for (const entry of [...harvested.split(':'), ...existing.split(':')]) {
112
+ const trimmed = entry.trim();
113
+ if (!trimmed) continue;
114
+ if (seen.has(trimmed)) continue;
115
+ seen.add(trimmed);
116
+ merged.push(trimmed);
117
+ }
118
+
119
+ const next = merged.join(':');
120
+ if (next !== existing) {
121
+ process.env.PATH = next;
122
+ debug.log('path', `PATH refreshed (${merged.length} entries)`);
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Ensure process.env.PATH reflects the user's interactive shell PATH.
128
+ * - Windows: no-op.
129
+ * - Unix: spawns the user's shell to harvest PATH, merges into process.env.
130
+ * - Concurrent callers share a single in-flight harvest (promise dedup).
131
+ * - No TTL: once the promise resolves, the next call starts a fresh harvest,
132
+ * so users can install a CLI in their terminal and re-check without restart.
133
+ */
134
+ export async function refreshProcessPath(): Promise<void> {
135
+ if (process.platform === 'win32') return;
136
+
137
+ if (!harvestInFlight) {
138
+ harvestInFlight = harvestUserPath();
139
+ // Clear the slot once settled so the next call performs a fresh harvest.
140
+ harvestInFlight.finally(() => {
141
+ harvestInFlight = null;
142
+ });
143
+ }
144
+
145
+ const harvested = await harvestInFlight;
146
+ if (harvested) applyHarvestedPath(harvested);
147
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Privilege Detection
3
+ *
4
+ * Determines whether the clopen server process is running with elevated
5
+ * privileges (root on Unix, Administrator on Windows). Used by the
6
+ * install-runner to decide whether a package manager invocation that
7
+ * requires privilege (apt, choco) can realistically succeed in the
8
+ * current non-interactive spawn mode.
9
+ *
10
+ * Cached for the process lifetime — elevation status does not change
11
+ * while the process is running.
12
+ */
13
+
14
+ import { debug } from '$shared/utils/logger';
15
+
16
+ let cached: boolean | null = null;
17
+
18
+ async function detectElevatedWindows(): Promise<boolean> {
19
+ try {
20
+ const proc = Bun.spawn(['net', 'session'], {
21
+ stdout: 'ignore',
22
+ stderr: 'ignore'
23
+ });
24
+ const exitCode = await proc.exited;
25
+ return exitCode === 0;
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
30
+
31
+ function detectElevatedUnix(): boolean {
32
+ try {
33
+ const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
34
+ return typeof getuid === 'function' && getuid.call(process) === 0;
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Returns true when the process is running elevated (root/Administrator).
42
+ * First call performs detection; subsequent calls return the cached value.
43
+ */
44
+ export async function isElevated(): Promise<boolean> {
45
+ if (cached !== null) return cached;
46
+ cached = process.platform === 'win32'
47
+ ? await detectElevatedWindows()
48
+ : detectElevatedUnix();
49
+ debug.log('path', `Privilege detection: ${cached ? 'elevated' : 'non-elevated'}`);
50
+ return cached;
51
+ }
@@ -19,6 +19,7 @@ import { createRouter } from '$shared/utils/ws-server';
19
19
  import { ws } from '$backend/utils/ws';
20
20
  import { engineQueries } from '../../../database/queries';
21
21
  import { resetEnvironment, getClaudeUserConfigDir } from '../../../engine/adapters/claude/environment';
22
+ import { resolveBinaryWithRefresh } from '../../../utils/cli';
22
23
  import { debug } from '$shared/utils/logger';
23
24
  import { getCleanSpawnEnv } from '../../../utils/env';
24
25
 
@@ -190,7 +191,7 @@ export const accountsHandler = createRouter()
190
191
  ptyEnv['CLAUDE_CONFIG_DIR'] = getClaudeUserConfigDir();
191
192
  ptyEnv['BROWSER'] = 'false';
192
193
 
193
- const claudeCmd = Bun.which('claude');
194
+ const claudeCmd = await resolveBinaryWithRefresh('claude');
194
195
  if (!claudeCmd) throw new Error('claude binary not found on PATH');
195
196
  let pty: ReturnType<typeof spawn>;
196
197
  try {
@@ -28,6 +28,7 @@ import { systemRouter } from './system';
28
28
  import { tunnelRouter } from './tunnel';
29
29
  import { gitRouter } from './git';
30
30
  import { engineRouter } from './engine';
31
+ import { systemToolsRouter } from './system-tools';
31
32
 
32
33
  // ============================================
33
34
  // Main App Router - Merge All Module Routers
@@ -63,7 +64,10 @@ export const wsRouter = createRouter()
63
64
  .merge(gitRouter)
64
65
 
65
66
  // AI Engine Management
66
- .merge(engineRouter);
67
+ .merge(engineRouter)
68
+
69
+ // System Tools (install Git, Claude Code, OpenCode, Chrome binaries)
70
+ .merge(systemToolsRouter);
67
71
 
68
72
  // Export API type for frontend type-safe access
69
73
  export type WSAPI = typeof wsRouter['$api'];
@@ -0,0 +1,16 @@
1
+ /**
2
+ * System Tools Router
3
+ *
4
+ * Entry point for install-related WebSocket handlers:
5
+ * - system-tools:status / status-all — detection + recipe
6
+ * - system-tools:install-start / install-cancel / install-session
7
+ * - Server → client stream events
8
+ */
9
+
10
+ import { createRouter } from '$shared/utils/ws-server';
11
+ import { systemToolsStatusHandler } from './status';
12
+ import { systemToolsInstallHandler } from './install';
13
+
14
+ export const systemToolsRouter = createRouter()
15
+ .merge(systemToolsStatusHandler)
16
+ .merge(systemToolsInstallHandler);