@myrialabs/clopen 0.3.3 → 0.3.5

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> = {};
@@ -19,8 +19,9 @@ import { join } from 'node:path';
19
19
  import { isElevated } from '$backend/utils/privilege';
20
20
  import { getClopenDir } from '$backend/utils/paths';
21
21
  import { resolveBinary, resolveBinaryWithRefresh } from '$backend/utils/cli';
22
+ import { resolveStaticCurlAsset } from '$backend/utils/static-curl';
22
23
 
23
- export type ToolId = 'git' | 'claude' | 'opencode' | 'chrome' | 'curl';
24
+ export type ToolId = 'git' | 'claude' | 'opencode' | 'chrome';
24
25
 
25
26
  export interface ManualInstruction {
26
27
  label: string;
@@ -37,6 +38,21 @@ export interface Recipe {
37
38
  command?: string[];
38
39
  /** Optional shell to wrap command (e.g. sh -c for pipe chains). */
39
40
  shell?: { program: string; args: string[] };
41
+ /**
42
+ * True when the install command (or script it downloads) shells out
43
+ * to `curl`. When set, the runner ensures curl is on PATH —
44
+ * downloading a SHA-pinned static curl from stunnel/static-curl if
45
+ * the system lacks one.
46
+ */
47
+ requiresCurl?: boolean;
48
+ /**
49
+ * When requiresCurl is true and the system has no curl, this carries
50
+ * the pinned asset metadata so the frontend can surface URL + SHA256
51
+ * in the install confirmation dialog for explicit user consent.
52
+ * Undefined when system curl is already present or no asset covers
53
+ * the current platform/arch.
54
+ */
55
+ pendingCurlDownload?: { version: string; url: string; sha256: string; archKey: string };
40
56
  /** Human-readable command string for confirmation dialog preview. */
41
57
  displayCommand?: string;
42
58
  /** Extra env vars for the install subprocess. */
@@ -194,10 +210,6 @@ export async function getToolStatus(tool: ToolId): Promise<ToolStatus> {
194
210
  // Recipe resolution
195
211
  // ─────────────────────────────────────────────────────────────────────────────
196
212
 
197
- function needsCurl(): boolean {
198
- return !resolveBinary('curl');
199
- }
200
-
201
213
  async function resolveGitRecipe(): Promise<Recipe> {
202
214
  const base: Recipe = {
203
215
  tool: 'git',
@@ -301,52 +313,27 @@ async function resolveGitRecipe(): Promise<Recipe> {
301
313
  return base;
302
314
  }
303
315
 
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';
316
+ /**
317
+ * Populate `requiresCurl` and (when the system lacks curl) the pending
318
+ * static-curl download metadata. Returns false when this platform/arch
319
+ * has no pinned asset — caller should mark the recipe unavailable.
320
+ */
321
+ function attachCurlRequirement(base: Recipe, toolLabel: string): boolean {
322
+ base.requiresCurl = true;
323
+ if (resolveBinary('curl')) return true;
324
+
325
+ const asset = resolveStaticCurlAsset();
326
+ if (!asset) {
327
+ base.unavailableReason = `curl is required by the ${toolLabel} installer, and no static curl is available for ${process.platform}/${process.arch}.`;
328
+ return false;
348
329
  }
349
- return base;
330
+ base.pendingCurlDownload = {
331
+ version: asset.version,
332
+ url: asset.url,
333
+ sha256: asset.sha256,
334
+ archKey: asset.archKey
335
+ };
336
+ return true;
350
337
  }
351
338
 
352
339
  async function resolveClaudeRecipe(): Promise<Recipe> {
@@ -376,11 +363,8 @@ async function resolveClaudeRecipe(): Promise<Recipe> {
376
363
  command: 'curl -fsSL https://claude.ai/install.sh | bash',
377
364
  docs: 'https://docs.claude.com/en/docs/claude-code/overview'
378
365
  });
379
- if (needsCurl()) {
380
- base.missingPrereqs.push('curl');
381
- base.unavailableReason = 'curl is required to run the install script.';
382
- return base;
383
- }
366
+ if (!attachCurlRequirement(base, 'Claude Code')) return base;
367
+
384
368
  base.autoInstallable = true;
385
369
  base.shell = { program: 'bash', args: ['-c'] };
386
370
  base.command = ['curl -fsSL https://claude.ai/install.sh | bash'];
@@ -405,11 +389,8 @@ async function resolveOpenCodeRecipe(): Promise<Recipe> {
405
389
  return base;
406
390
  }
407
391
 
408
- if (needsCurl()) {
409
- base.missingPrereqs.push('curl');
410
- base.unavailableReason = 'curl is required to run the install script.';
411
- return base;
412
- }
392
+ if (!attachCurlRequirement(base, 'OpenCode')) return base;
393
+
413
394
  base.autoInstallable = true;
414
395
  base.shell = { program: 'bash', args: ['-c'] };
415
396
  base.command = ['curl -fsSL https://opencode.ai/install | bash'];
@@ -442,7 +423,6 @@ async function resolveChromeRecipe(): Promise<Recipe> {
442
423
  export async function resolveRecipe(tool: ToolId): Promise<Recipe> {
443
424
  switch (tool) {
444
425
  case 'git': return resolveGitRecipe();
445
- case 'curl': return resolveCurlRecipe();
446
426
  case 'claude': return resolveClaudeRecipe();
447
427
  case 'opencode': return resolveOpenCodeRecipe();
448
428
  case 'chrome': return resolveChromeRecipe();
@@ -20,7 +20,8 @@
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
+ import { ensureCurlAvailable } from '$backend/utils/static-curl';
24
25
  import type { Recipe, ToolId } from './install-recipes';
25
26
  import { resolveRecipe } from './install-recipes';
26
27
 
@@ -157,6 +158,91 @@ export class InstallNotAutoInstallableError extends Error {
157
158
  }
158
159
  }
159
160
 
161
+ function finalizeSession(session: Session, preferredStatus: SessionStatus, exitCode: number): void {
162
+ // `cancelled` (set preemptively by cancelInstall) or earlier failure paths
163
+ // must not be overwritten by the caller's preferred status.
164
+ if (session.status === 'running') {
165
+ session.status = preferredStatus;
166
+ }
167
+ session.exitCode = exitCode;
168
+ session.endedAt = Date.now();
169
+ session.proc = null;
170
+
171
+ debug.log('path', `[install:${session.id}] Finished status=${session.status} exit=${exitCode}`);
172
+
173
+ ws.emit.user(session.startedBy, 'system-tools:install-finished', {
174
+ sessionId: session.id,
175
+ tool: session.tool,
176
+ status: session.status,
177
+ exitCode: exitCode ?? -1,
178
+ endedAt: session.endedAt
179
+ });
180
+
181
+ scheduleRetention(session);
182
+ }
183
+
184
+ async function runStreamedProcess(session: Session, proc: ReturnType<typeof Bun.spawn>): Promise<number> {
185
+ const [, , exitCode] = await Promise.all([
186
+ pipeStream(session, proc.stdout as ReadableStream<Uint8Array>, 'stdout'),
187
+ pipeStream(session, proc.stderr as ReadableStream<Uint8Array>, 'stderr'),
188
+ proc.exited
189
+ ]);
190
+ flushPending(session);
191
+ return exitCode;
192
+ }
193
+
194
+ async function runInstall(session: Session, env: Record<string, string>): Promise<void> {
195
+ const { recipe } = session;
196
+ let proc: ReturnType<typeof Bun.spawn>;
197
+
198
+ // Ensure curl is available when the recipe shells out to it. Prepends
199
+ // the static-curl directory to PATH when a managed binary is staged.
200
+ if (recipe.requiresCurl) {
201
+ try {
202
+ const curlDir = await ensureCurlAvailable((event) => {
203
+ emitStream(session, 'stdout', `» curl: ${event.message}\n`);
204
+ });
205
+ if (curlDir) {
206
+ env.PATH = `${curlDir}${process.platform === 'win32' ? ';' : ':'}${env.PATH ?? ''}`;
207
+ }
208
+ } catch (err) {
209
+ emitStream(session, 'stderr', `curl setup failed: ${err instanceof Error ? err.message : String(err)}\n`);
210
+ finalizeSession(session, 'failed', -1);
211
+ return;
212
+ }
213
+
214
+ // Cancel may have fired while curl was being staged.
215
+ if (session.status !== 'running') {
216
+ finalizeSession(session, session.status, -1);
217
+ return;
218
+ }
219
+ }
220
+
221
+ const spawnArgs = recipe.shell
222
+ ? [recipe.shell.program, ...recipe.shell.args, ...recipe.command!]
223
+ : recipe.command!;
224
+
225
+ debug.log('path', `[install:${session.id}] Spawning: ${spawnArgs.join(' ')}`);
226
+
227
+ try {
228
+ proc = Bun.spawn(spawnArgs, {
229
+ stdout: 'pipe',
230
+ stderr: 'pipe',
231
+ stdin: 'ignore',
232
+ env
233
+ });
234
+ } catch (err) {
235
+ emitStream(session, 'stderr', `spawn failed: ${err instanceof Error ? err.message : String(err)}\n`);
236
+ finalizeSession(session, 'failed', -1);
237
+ return;
238
+ }
239
+
240
+ session.proc = proc;
241
+
242
+ const exitCode = await runStreamedProcess(session, proc);
243
+ finalizeSession(session, exitCode === 0 ? 'success' : 'failed', exitCode);
244
+ }
245
+
160
246
  export async function startInstall(tool: ToolId, userId: string): Promise<Session> {
161
247
  await refreshProcessPath();
162
248
 
@@ -174,31 +260,13 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
174
260
  }
175
261
 
176
262
  const id = crypto.randomUUID();
177
- const spawnArgs = recipe.shell
178
- ? [recipe.shell.program, ...recipe.shell.args, ...recipe.command]
179
- : recipe.command;
180
-
181
263
  const env = { ...getCleanSpawnEnv(), ...(recipe.env ?? {}) };
182
264
 
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
265
  const session: Session = {
198
266
  id,
199
267
  tool,
200
268
  recipe,
201
- proc,
269
+ proc: null,
202
270
  status: 'running',
203
271
  exitCode: null,
204
272
  startedAt: Date.now(),
@@ -213,7 +281,7 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
213
281
  activeByTool.set(tool, id);
214
282
 
215
283
  // Initial marker line so clients see something immediately.
216
- const banner = `$ ${recipe.displayCommand ?? spawnArgs.join(' ')}`;
284
+ const banner = `$ ${recipe.displayCommand ?? ''}`;
217
285
  emitStream(session, 'stdout', banner + '\n');
218
286
 
219
287
  // Broadcast the session-started event so clients that subscribe mid-run can attach.
@@ -224,46 +292,10 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
224
292
  startedAt: session.startedAt
225
293
  });
226
294
 
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) => {
295
+ runInstall(session, env).catch((err) => {
255
296
  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);
297
+ emitStream(session, 'stderr', `runner crash: ${err instanceof Error ? err.message : String(err)}\n`);
298
+ finalizeSession(session, 'failed', -1);
267
299
  });
268
300
 
269
301
  return session;
@@ -271,12 +303,16 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
271
303
 
272
304
  export function cancelInstall(sessionId: string): boolean {
273
305
  const session = sessions.get(sessionId);
274
- if (!session || session.status !== 'running' || !session.proc) return false;
306
+ if (!session || session.status !== 'running') return false;
275
307
  session.status = 'cancelled';
276
- try {
277
- session.proc.kill();
278
- } catch {
279
- // Already dead — the exited promise will resolve regardless.
308
+ // `proc` may be null during the static-curl download phase; runInstall
309
+ // re-checks status after each await and finalizes accordingly.
310
+ if (session.proc) {
311
+ try {
312
+ session.proc.kill();
313
+ } catch {
314
+ // Already dead — the exited promise will resolve regardless.
315
+ }
280
316
  }
281
317
  return true;
282
318
  }
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