@myrialabs/clopen 0.3.2 → 0.3.4

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,362 @@
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-enrich';
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
+ function finalizeSession(session: Session, preferredStatus: SessionStatus, exitCode: number): void {
161
+ // `cancelled` (set preemptively by cancelInstall) or earlier failure paths
162
+ // must not be overwritten by the caller's preferred status.
163
+ if (session.status === 'running') {
164
+ session.status = preferredStatus;
165
+ }
166
+ session.exitCode = exitCode;
167
+ session.endedAt = Date.now();
168
+ session.proc = null;
169
+
170
+ debug.log('path', `[install:${session.id}] Finished status=${session.status} exit=${exitCode}`);
171
+
172
+ ws.emit.user(session.startedBy, 'system-tools:install-finished', {
173
+ sessionId: session.id,
174
+ tool: session.tool,
175
+ status: session.status,
176
+ exitCode: exitCode ?? -1,
177
+ endedAt: session.endedAt
178
+ });
179
+
180
+ scheduleRetention(session);
181
+ }
182
+
183
+ async function runStreamedProcess(session: Session, proc: ReturnType<typeof Bun.spawn>): Promise<number> {
184
+ const [, , exitCode] = await Promise.all([
185
+ pipeStream(session, proc.stdout as ReadableStream<Uint8Array>, 'stdout'),
186
+ pipeStream(session, proc.stderr as ReadableStream<Uint8Array>, 'stderr'),
187
+ proc.exited
188
+ ]);
189
+ flushPending(session);
190
+ return exitCode;
191
+ }
192
+
193
+ async function runInstall(session: Session, env: Record<string, string>): Promise<void> {
194
+ const { recipe } = session;
195
+ let proc: ReturnType<typeof Bun.spawn>;
196
+
197
+ if (recipe.fetchAndPipe) {
198
+ const { url, interpreter } = recipe.fetchAndPipe;
199
+ emitStream(session, 'stdout', `» fetching ${url}\n`);
200
+
201
+ let body: string;
202
+ try {
203
+ const response = await fetch(url, { redirect: 'follow' });
204
+ if (!response.ok) {
205
+ emitStream(session, 'stderr', `fetch failed: HTTP ${response.status} ${response.statusText}\n`);
206
+ finalizeSession(session, 'failed', -1);
207
+ return;
208
+ }
209
+ body = await response.text();
210
+ } catch (err) {
211
+ emitStream(session, 'stderr', `fetch error: ${err instanceof Error ? err.message : String(err)}\n`);
212
+ finalizeSession(session, 'failed', -1);
213
+ return;
214
+ }
215
+
216
+ // Cancel may have fired while the fetch was in flight.
217
+ if (session.status !== 'running') {
218
+ finalizeSession(session, session.status, -1);
219
+ return;
220
+ }
221
+
222
+ emitStream(session, 'stdout', `» piping ${body.length} bytes to ${interpreter.join(' ')}\n`);
223
+
224
+ try {
225
+ proc = Bun.spawn(interpreter, {
226
+ stdout: 'pipe',
227
+ stderr: 'pipe',
228
+ stdin: 'pipe',
229
+ env
230
+ });
231
+ } catch (err) {
232
+ emitStream(session, 'stderr', `spawn failed: ${err instanceof Error ? err.message : String(err)}\n`);
233
+ finalizeSession(session, 'failed', -1);
234
+ return;
235
+ }
236
+
237
+ session.proc = proc;
238
+
239
+ try {
240
+ const stdin = proc.stdin as import('bun').FileSink;
241
+ stdin.write(body);
242
+ stdin.end();
243
+ } catch (err) {
244
+ debug.warn('path', `[install:${session.id}] stdin write error:`, err);
245
+ }
246
+ } else {
247
+ const spawnArgs = recipe.shell
248
+ ? [recipe.shell.program, ...recipe.shell.args, ...recipe.command!]
249
+ : recipe.command!;
250
+
251
+ debug.log('path', `[install:${session.id}] Spawning: ${spawnArgs.join(' ')}`);
252
+
253
+ try {
254
+ proc = Bun.spawn(spawnArgs, {
255
+ stdout: 'pipe',
256
+ stderr: 'pipe',
257
+ stdin: 'ignore',
258
+ env
259
+ });
260
+ } catch (err) {
261
+ emitStream(session, 'stderr', `spawn failed: ${err instanceof Error ? err.message : String(err)}\n`);
262
+ finalizeSession(session, 'failed', -1);
263
+ return;
264
+ }
265
+
266
+ session.proc = proc;
267
+ }
268
+
269
+ const exitCode = await runStreamedProcess(session, proc);
270
+ finalizeSession(session, exitCode === 0 ? 'success' : 'failed', exitCode);
271
+ }
272
+
273
+ export async function startInstall(tool: ToolId, userId: string): Promise<Session> {
274
+ await refreshProcessPath();
275
+
276
+ const existing = activeByTool.get(tool);
277
+ if (existing) {
278
+ const session = sessions.get(existing);
279
+ if (session && session.status === 'running') {
280
+ throw new InstallAlreadyRunningError(existing, tool);
281
+ }
282
+ }
283
+
284
+ const recipe = await resolveRecipe(tool);
285
+ const hasExecutable = recipe.autoInstallable && (recipe.command || recipe.fetchAndPipe);
286
+ if (!hasExecutable) {
287
+ throw new InstallNotAutoInstallableError(tool, recipe.unavailableReason ?? 'Not auto-installable on this platform');
288
+ }
289
+
290
+ const id = crypto.randomUUID();
291
+ const env = { ...getCleanSpawnEnv(), ...(recipe.env ?? {}) };
292
+
293
+ const session: Session = {
294
+ id,
295
+ tool,
296
+ recipe,
297
+ proc: null,
298
+ status: 'running',
299
+ exitCode: null,
300
+ startedAt: Date.now(),
301
+ endedAt: null,
302
+ buffer: newRingBuffer(),
303
+ retentionTimer: null,
304
+ startedBy: userId,
305
+ pending: { stdout: '', stderr: '' }
306
+ };
307
+
308
+ sessions.set(id, session);
309
+ activeByTool.set(tool, id);
310
+
311
+ // Initial marker line so clients see something immediately.
312
+ const banner = `$ ${recipe.displayCommand ?? ''}`;
313
+ emitStream(session, 'stdout', banner + '\n');
314
+
315
+ // Broadcast the session-started event so clients that subscribe mid-run can attach.
316
+ ws.emit.user(userId, 'system-tools:install-started', {
317
+ sessionId: id,
318
+ tool,
319
+ displayCommand: recipe.displayCommand ?? '',
320
+ startedAt: session.startedAt
321
+ });
322
+
323
+ runInstall(session, env).catch((err) => {
324
+ debug.error('path', `[install:${id}] runner crash:`, err);
325
+ emitStream(session, 'stderr', `runner crash: ${err instanceof Error ? err.message : String(err)}\n`);
326
+ finalizeSession(session, 'failed', -1);
327
+ });
328
+
329
+ return session;
330
+ }
331
+
332
+ export function cancelInstall(sessionId: string): boolean {
333
+ const session = sessions.get(sessionId);
334
+ if (!session || session.status !== 'running') return false;
335
+ session.status = 'cancelled';
336
+ // `proc` may be null during the fetchAndPipe fetch phase; runInstall
337
+ // re-checks status after fetch and finalizes accordingly.
338
+ if (session.proc) {
339
+ try {
340
+ session.proc.kill();
341
+ } catch {
342
+ // Already dead — the exited promise will resolve regardless.
343
+ }
344
+ }
345
+ return true;
346
+ }
347
+
348
+ export function getSession(sessionId: string) {
349
+ const session = sessions.get(sessionId);
350
+ return session ? sessionSnapshot(session) : null;
351
+ }
352
+
353
+ export function getActiveSessionForTool(tool: ToolId) {
354
+ const id = activeByTool.get(tool);
355
+ if (!id) return null;
356
+ const session = sessions.get(id);
357
+ return session ? sessionSnapshot(session) : null;
358
+ }
359
+
360
+ export function listActiveSessions() {
361
+ return Array.from(sessions.values()).map(sessionSnapshot);
362
+ }
@@ -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-enrich';
22
23
  import { debug } from '$shared/utils/logger';
23
24
  import { networkInterfaces } from 'os';
24
25
  import { resolve } from 'node:path';
@@ -127,6 +128,15 @@ 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
+ // Enrich process.env.PATH with known install directories so Bun.which /
132
+ // Bun.spawn / bun-pty discover CLI binaries regardless of how clopen was
133
+ // launched (GUI, service, container, login shell). See path-enrich.ts.
134
+ try {
135
+ await refreshProcessPath();
136
+ } catch (error) {
137
+ debug.warn('path', '⚠️ Initial PATH enrichment failed:', error);
138
+ }
139
+
130
140
  // Initialize database first before accepting connections
131
141
  try {
132
142
  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,38 @@
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. Enrich process.env.PATH with known install directories (and, on Unix
8
+ * desktops, the user's interactive-shell PATH) so binaries installed
9
+ * via our System Tools installer, nvm/fnm/volta/asdf/bun/homebrew, or
10
+ * by the user become visible without a clopen restart.
11
+ * 2. Call `Bun.which(binary, { PATH: process.env.PATH })` — the explicit
12
+ * PATH option is critical: without it, Bun.which uses a cached startup
13
+ * PATH and ignores runtime updates, so newly-installed binaries remain
14
+ * invisible even though process.env.PATH has been refreshed.
7
15
  */
8
16
 
17
+ import { refreshProcessPath } from './path-enrich';
18
+
9
19
  export type CLIStatus = { installed: boolean; version: string | null };
10
20
 
21
+ export function resolveBinary(binary: string): string | null {
22
+ return Bun.which(binary, { PATH: process.env.PATH }) ?? null;
23
+ }
24
+
25
+ /**
26
+ * Refresh $PATH from the user's shell, then resolve. Use at any spawn site
27
+ * that may run after a fresh install (e.g. models:list, setup-token).
28
+ */
29
+ export async function resolveBinaryWithRefresh(binary: string): Promise<string | null> {
30
+ await refreshProcessPath();
31
+ return resolveBinary(binary);
32
+ }
33
+
11
34
  export async function getStatus(command: string): Promise<CLIStatus> {
12
- const resolved = Bun.which(command);
35
+ const resolved = await resolveBinaryWithRefresh(command);
13
36
  if (!resolved) return { installed: false, version: null };
14
37
 
15
38
  try {
@@ -24,4 +47,4 @@ export async function getStatus(command: string): Promise<CLIStatus> {
24
47
  } catch {
25
48
  return { installed: false, version: null };
26
49
  }
27
- }
50
+ }