@myrialabs/clopen 0.3.3 → 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.
@@ -41,6 +41,7 @@ import type {
41
41
  ListMcpResourcesInput,
42
42
  ReadMcpResourceInput,
43
43
  TodoWriteInput,
44
+ PatchInput,
44
45
  } from '$shared/types/unified';
45
46
 
46
47
  // ============================================================
@@ -86,6 +87,7 @@ type NormalizedToolInput =
86
87
  | GlobInput | GrepInput | WebFetchInput | WebSearchInput
87
88
  | AskUserQuestionInput | TodoWriteInput
88
89
  | ListMcpResourcesInput | ReadMcpResourceInput
90
+ | PatchInput
89
91
  | Record<string, unknown>;
90
92
 
91
93
  // ============================================================
@@ -109,6 +111,9 @@ const TOOL_NAME_MAP: Record<string, string> = {
109
111
  'write': 'Write',
110
112
  'edit': 'Edit',
111
113
  'patch': 'Patch',
114
+ // OpenAI GPT-5 family emits `apply_patch` with a V4A-format `patch_text`
115
+ // payload. Normalize to canonical `Patch` so PatchTool.svelte renders it.
116
+ 'apply_patch': 'Patch',
112
117
  // Search & discovery
113
118
  'glob': 'Glob',
114
119
  'grep': 'Grep',
@@ -315,6 +320,26 @@ function normalizeTodoWriteInput(raw: OCToolInput): TodoWriteInput {
315
320
  };
316
321
  }
317
322
 
323
+ /**
324
+ * Handle both OpenCode's `patch` tool (`{ file_path, patch }`) and OpenAI
325
+ * GPT-5's `apply_patch` (`{ patch_text }`). For apply_patch we extract the
326
+ * first file path from the V4A header so the Patch tool header has something
327
+ * meaningful; the full patch body still shows every file.
328
+ */
329
+ function normalizePatchInput(raw: OCToolInput): PatchInput {
330
+ const patchText = str(raw, 'patch_text', 'patchText');
331
+ const patchBody = patchText || str(raw, 'patch', 'patch');
332
+ const explicitPath = str(raw, 'file_path', 'filePath');
333
+
334
+ let filePath = explicitPath;
335
+ if (!filePath && patchBody) {
336
+ const match = patchBody.match(/^\*\*\*\s+(?:Add|Update|Delete)\s+File:\s*(.+)$/m);
337
+ if (match) filePath = match[1].trim();
338
+ }
339
+
340
+ return { filePath, patch: patchBody };
341
+ }
342
+
318
343
  // ============================================================
319
344
  // Normalizer Dispatcher
320
345
  // ============================================================
@@ -342,6 +367,7 @@ function normalizeToolInput(claudeToolName: string, raw: OCToolInput): Normalize
342
367
  case 'ListMcpResources': return normalizeListMcpResourcesInput(raw);
343
368
  case 'ReadMcpResource': return normalizeReadMcpResourceInput(raw);
344
369
  case 'TodoWrite': return normalizeTodoWriteInput(raw);
370
+ case 'Patch': return normalizePatchInput(raw);
345
371
  default: {
346
372
  // Unknown tool: generic camelCase → snake_case key normalization
347
373
  const normalized: Record<string, string | number | boolean> = {};
@@ -20,7 +20,7 @@ import { isElevated } from '$backend/utils/privilege';
20
20
  import { getClopenDir } from '$backend/utils/paths';
21
21
  import { resolveBinary, resolveBinaryWithRefresh } from '$backend/utils/cli';
22
22
 
23
- export type ToolId = 'git' | 'claude' | 'opencode' | 'chrome' | 'curl';
23
+ export type ToolId = 'git' | 'claude' | 'opencode' | 'chrome';
24
24
 
25
25
  export interface ManualInstruction {
26
26
  label: string;
@@ -37,6 +37,13 @@ export interface Recipe {
37
37
  command?: string[];
38
38
  /** Optional shell to wrap command (e.g. sh -c for pipe chains). */
39
39
  shell?: { program: string; args: string[] };
40
+ /**
41
+ * Fetch a remote script via Bun.fetch and pipe its body to the
42
+ * interpreter's stdin. Used in place of `curl | bash` so clopen can
43
+ * install tools like Claude/OpenCode without requiring curl to be
44
+ * present on the system. Exclusive with `command`/`shell`.
45
+ */
46
+ fetchAndPipe?: { url: string; interpreter: string[] };
40
47
  /** Human-readable command string for confirmation dialog preview. */
41
48
  displayCommand?: string;
42
49
  /** Extra env vars for the install subprocess. */
@@ -194,10 +201,6 @@ export async function getToolStatus(tool: ToolId): Promise<ToolStatus> {
194
201
  // Recipe resolution
195
202
  // ─────────────────────────────────────────────────────────────────────────────
196
203
 
197
- function needsCurl(): boolean {
198
- return !resolveBinary('curl');
199
- }
200
-
201
204
  async function resolveGitRecipe(): Promise<Recipe> {
202
205
  const base: Recipe = {
203
206
  tool: 'git',
@@ -301,54 +304,6 @@ async function resolveGitRecipe(): Promise<Recipe> {
301
304
  return base;
302
305
  }
303
306
 
304
- async function resolveCurlRecipe(): Promise<Recipe> {
305
- const base: Recipe = {
306
- tool: 'curl',
307
- autoInstallable: false,
308
- missingPrereqs: [],
309
- manualInstructions: [
310
- { label: 'apt (Debian/Ubuntu)', command: 'sudo apt update && sudo apt install -y curl' },
311
- { label: 'dnf (Fedora/RHEL)', command: 'sudo dnf install -y curl' },
312
- { label: 'pacman (Arch)', command: 'sudo pacman -S --noconfirm curl' },
313
- { label: 'apk (Alpine)', command: 'sudo apk add curl' }
314
- ]
315
- };
316
- if (process.platform === 'win32' || process.platform === 'darwin') {
317
- // curl ships with both — if it's missing, defer to manual.
318
- base.unavailableReason = 'curl is expected to be available on this platform.';
319
- return base;
320
- }
321
- const mgr = detectLinuxPkgMgr();
322
- if (!mgr) {
323
- base.unavailableReason = 'No supported Linux package manager found.';
324
- return base;
325
- }
326
- const elevated = await isElevated();
327
- if (!elevated) {
328
- base.unavailableReason = 'Linux package install requires root. Run the command manually with sudo.';
329
- return base;
330
- }
331
- base.autoInstallable = true;
332
- if (mgr === 'apt') {
333
- base.shell = { program: 'sh', args: ['-c'] };
334
- base.command = ['apt-get update && apt-get install -y curl'];
335
- base.displayCommand = 'apt-get update && apt-get install -y curl';
336
- } else if (mgr === 'dnf') {
337
- base.command = ['dnf', 'install', '-y', 'curl'];
338
- base.displayCommand = 'dnf install -y curl';
339
- } else if (mgr === 'pacman') {
340
- base.command = ['pacman', '-S', '--noconfirm', 'curl'];
341
- base.displayCommand = 'pacman -S --noconfirm curl';
342
- } else if (mgr === 'apk') {
343
- base.command = ['apk', 'add', 'curl'];
344
- base.displayCommand = 'apk add curl';
345
- } else if (mgr === 'zypper') {
346
- base.command = ['zypper', '--non-interactive', 'install', 'curl'];
347
- base.displayCommand = 'zypper --non-interactive install curl';
348
- }
349
- return base;
350
- }
351
-
352
307
  async function resolveClaudeRecipe(): Promise<Recipe> {
353
308
  const base: Recipe = {
354
309
  tool: 'claude',
@@ -370,20 +325,15 @@ async function resolveClaudeRecipe(): Promise<Recipe> {
370
325
  return base;
371
326
  }
372
327
 
373
- // macOS / Linux
328
+ // macOS / Linux — fetch the script via Bun.fetch and pipe it to bash
329
+ // so curl does not need to be installed.
374
330
  base.manualInstructions.push({
375
331
  label: 'curl + bash',
376
332
  command: 'curl -fsSL https://claude.ai/install.sh | bash',
377
333
  docs: 'https://docs.claude.com/en/docs/claude-code/overview'
378
334
  });
379
- if (needsCurl()) {
380
- base.missingPrereqs.push('curl');
381
- base.unavailableReason = 'curl is required to run the install script.';
382
- return base;
383
- }
384
335
  base.autoInstallable = true;
385
- base.shell = { program: 'bash', args: ['-c'] };
386
- base.command = ['curl -fsSL https://claude.ai/install.sh | bash'];
336
+ base.fetchAndPipe = { url: 'https://claude.ai/install.sh', interpreter: ['bash'] };
387
337
  base.displayCommand = 'curl -fsSL https://claude.ai/install.sh | bash';
388
338
  return base;
389
339
  }
@@ -405,14 +355,8 @@ async function resolveOpenCodeRecipe(): Promise<Recipe> {
405
355
  return base;
406
356
  }
407
357
 
408
- if (needsCurl()) {
409
- base.missingPrereqs.push('curl');
410
- base.unavailableReason = 'curl is required to run the install script.';
411
- return base;
412
- }
413
358
  base.autoInstallable = true;
414
- base.shell = { program: 'bash', args: ['-c'] };
415
- base.command = ['curl -fsSL https://opencode.ai/install | bash'];
359
+ base.fetchAndPipe = { url: 'https://opencode.ai/install', interpreter: ['bash'] };
416
360
  base.displayCommand = 'curl -fsSL https://opencode.ai/install | bash';
417
361
  return base;
418
362
  }
@@ -442,7 +386,6 @@ async function resolveChromeRecipe(): Promise<Recipe> {
442
386
  export async function resolveRecipe(tool: ToolId): Promise<Recipe> {
443
387
  switch (tool) {
444
388
  case 'git': return resolveGitRecipe();
445
- case 'curl': return resolveCurlRecipe();
446
389
  case 'claude': return resolveClaudeRecipe();
447
390
  case 'opencode': return resolveOpenCodeRecipe();
448
391
  case 'chrome': return resolveChromeRecipe();
@@ -20,7 +20,7 @@
20
20
  import { debug } from '$shared/utils/logger';
21
21
  import { ws } from '$backend/utils/ws';
22
22
  import { getCleanSpawnEnv } from '$backend/utils/env';
23
- import { refreshProcessPath } from '$backend/utils/path-harvest';
23
+ import { refreshProcessPath } from '$backend/utils/path-enrich';
24
24
  import type { Recipe, ToolId } from './install-recipes';
25
25
  import { resolveRecipe } from './install-recipes';
26
26
 
@@ -157,6 +157,119 @@ export class InstallNotAutoInstallableError extends Error {
157
157
  }
158
158
  }
159
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
+
160
273
  export async function startInstall(tool: ToolId, userId: string): Promise<Session> {
161
274
  await refreshProcessPath();
162
275
 
@@ -169,36 +282,19 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
169
282
  }
170
283
 
171
284
  const recipe = await resolveRecipe(tool);
172
- if (!recipe.autoInstallable || !recipe.command) {
285
+ const hasExecutable = recipe.autoInstallable && (recipe.command || recipe.fetchAndPipe);
286
+ if (!hasExecutable) {
173
287
  throw new InstallNotAutoInstallableError(tool, recipe.unavailableReason ?? 'Not auto-installable on this platform');
174
288
  }
175
289
 
176
290
  const id = crypto.randomUUID();
177
- const spawnArgs = recipe.shell
178
- ? [recipe.shell.program, ...recipe.shell.args, ...recipe.command]
179
- : recipe.command;
180
-
181
291
  const env = { ...getCleanSpawnEnv(), ...(recipe.env ?? {}) };
182
292
 
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
293
  const session: Session = {
198
294
  id,
199
295
  tool,
200
296
  recipe,
201
- proc,
297
+ proc: null,
202
298
  status: 'running',
203
299
  exitCode: null,
204
300
  startedAt: Date.now(),
@@ -213,7 +309,7 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
213
309
  activeByTool.set(tool, id);
214
310
 
215
311
  // Initial marker line so clients see something immediately.
216
- const banner = `$ ${recipe.displayCommand ?? spawnArgs.join(' ')}`;
312
+ const banner = `$ ${recipe.displayCommand ?? ''}`;
217
313
  emitStream(session, 'stdout', banner + '\n');
218
314
 
219
315
  // Broadcast the session-started event so clients that subscribe mid-run can attach.
@@ -224,46 +320,10 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
224
320
  startedAt: session.startedAt
225
321
  });
226
322
 
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) => {
323
+ runInstall(session, env).catch((err) => {
255
324
  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);
325
+ emitStream(session, 'stderr', `runner crash: ${err instanceof Error ? err.message : String(err)}\n`);
326
+ finalizeSession(session, 'failed', -1);
267
327
  });
268
328
 
269
329
  return session;
@@ -271,12 +331,16 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
271
331
 
272
332
  export function cancelInstall(sessionId: string): boolean {
273
333
  const session = sessions.get(sessionId);
274
- if (!session || session.status !== 'running' || !session.proc) return false;
334
+ if (!session || session.status !== 'running') return false;
275
335
  session.status = 'cancelled';
276
- try {
277
- session.proc.kill();
278
- } catch {
279
- // Already dead — the exited promise will resolve regardless.
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
+ }
280
344
  }
281
345
  return true;
282
346
  }
package/backend/index.ts CHANGED
@@ -19,7 +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
+ import { refreshProcessPath } from './utils/path-enrich';
23
23
  import { debug } from '$shared/utils/logger';
24
24
  import { networkInterfaces } from 'os';
25
25
  import { resolve } from 'node:path';
@@ -128,14 +128,13 @@ async function startServer() {
128
128
  // This avoids double port-check race conditions (e.g. zombie processes on
129
129
  // Windows causing silent desync between Vite proxy and backend).
130
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.
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.
135
134
  try {
136
135
  await refreshProcessPath();
137
136
  } catch (error) {
138
- debug.warn('path', '⚠️ Initial PATH harvest failed:', error);
137
+ debug.warn('path', '⚠️ Initial PATH enrichment failed:', error);
139
138
  }
140
139
 
141
140
  // Initialize database first before accepting connections
@@ -4,16 +4,17 @@
4
4
  * Single source of truth for detecting tools like `opencode`, `claude`, `git`.
5
5
  *
6
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.
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.
10
11
  * 2. Call `Bun.which(binary, { PATH: process.env.PATH })` — the explicit
11
12
  * PATH option is critical: without it, Bun.which uses a cached startup
12
13
  * PATH and ignores runtime updates, so newly-installed binaries remain
13
14
  * invisible even though process.env.PATH has been refreshed.
14
15
  */
15
16
 
16
- import { refreshProcessPath } from './path-harvest';
17
+ import { refreshProcessPath } from './path-enrich';
17
18
 
18
19
  export type CLIStatus = { installed: boolean; version: string | null };
19
20