@myrialabs/clopen 0.2.19 → 0.2.21

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.
@@ -6,31 +6,35 @@
6
6
  *
7
7
  * Strategy:
8
8
  * 1. Check DB for previously stored server URL → health-check → reuse if alive
9
- * 2. Otherwise spawn `opencode serve` with port 0 (OS-assigned) and persist URL
9
+ * 2. Otherwise spawn `opencode serve` via Bun.spawn (port 0, OS-assigned) and persist URL
10
10
  * 3. On every ensureClient() call, verify the server is still alive.
11
11
  * If it died mid-session, automatically recover through the same flow.
12
12
  */
13
13
 
14
14
  import type { OpencodeClient } from '@opencode-ai/sdk';
15
+ import type { Subprocess } from 'bun';
15
16
  import { getOpenCodeMcpConfig } from '../../../mcp';
16
17
  import { settingsQueries } from '../../../database/queries';
18
+ import { resolveCommand } from '../../../ws/engine/utils';
17
19
  import { debug } from '$shared/utils/logger';
18
20
 
19
21
  const OPENCODE_HOST = '127.0.0.1';
20
22
  const DB_KEY = 'opencode.server.url';
21
23
  const HEALTH_TIMEOUT = 1500;
24
+ const SERVER_START_TIMEOUT = 30_000; // 30s — generous for slow devices
22
25
 
26
+ let serverProc: Subprocess | null = null;
23
27
  let serverHandle: { url: string; close(): void } | null = null;
24
28
  let client: OpencodeClient | null = null;
25
29
  let initPromise: Promise<void> | null = null;
26
30
  let ready = false;
27
31
  let ownsProcess = false;
28
32
 
29
- function resetState(): void {
33
+ function clearClientState(): void {
30
34
  client = null;
31
35
  ready = false;
32
- initPromise = null;
33
36
  serverHandle = null;
37
+ serverProc = null;
34
38
  ownsProcess = false;
35
39
  }
36
40
 
@@ -51,22 +55,36 @@ async function isServerAlive(url: string): Promise<boolean> {
51
55
  * If the server died (bun --watch restart, crash, etc.), state is reset and
52
56
  * init() is re-invoked — the same DB-check → reuse-or-spawn flow handles
53
57
  * recovery automatically.
58
+ *
59
+ * Race-condition guard: after any `await` (health check), we re-check
60
+ * `initPromise` before starting a new init — another caller may have
61
+ * already kicked one off during our async gap.
54
62
  */
55
63
  export async function ensureClient(): Promise<OpencodeClient> {
64
+ // Wait for any in-progress init first
65
+ if (initPromise) {
66
+ try { await initPromise; } catch { /* handled below */ }
67
+ if (client && ready) return client;
68
+ }
69
+
70
+ // Fast path: server is up and healthy
56
71
  if (client && ready && serverHandle) {
57
72
  if (await isServerAlive(serverHandle.url)) return client;
58
73
 
59
- // Server disconnected — purge stale DB entry and re-init
74
+ // Server disconnected — purge stale DB entry
75
+ // Do NOT clear initPromise — another caller may have started one
60
76
  debug.log('engine', 'Open Code server disconnected, recovering...');
61
77
  settingsQueries.delete(DB_KEY);
62
- resetState();
78
+ clearClientState();
63
79
  }
64
80
 
81
+ // Re-check after async gap — another caller may have started init
65
82
  if (initPromise) {
66
- await initPromise;
67
- return client!;
83
+ try { await initPromise; } catch { /* handled below */ }
84
+ if (client && ready) return client;
68
85
  }
69
86
 
87
+ // Start init — no other caller is initializing at this point
70
88
  initPromise = init();
71
89
  try {
72
90
  await initPromise;
@@ -99,32 +117,106 @@ async function init(): Promise<void> {
99
117
  settingsQueries.delete(DB_KEY);
100
118
  }
101
119
 
102
- // 2. Spawn a new server — port 0 lets opencode pick an OS-assigned port
103
- const { createOpencode } = await import('@opencode-ai/sdk');
120
+ // 2. Spawn a new server via Bun.spawn — uses same binary resolution as detectCLI
121
+ const command = await resolveCommand('opencode');
122
+ const args = [command, 'serve', `--hostname=${OPENCODE_HOST}`, '--port=0'];
104
123
 
105
- const mcpConfig = getOpenCodeMcpConfig();
124
+ // Build MCP config — but only inject if the MCP endpoint is actually reachable.
125
+ // The opencode binary may initialize MCP connections synchronously before printing
126
+ // "opencode server listening", so an unreachable/slow MCP endpoint can stall startup.
127
+ let mcpConfig = getOpenCodeMcpConfig();
106
128
  if (Object.keys(mcpConfig).length > 0) {
107
- debug.log('engine', `Open Code server: injecting ${Object.keys(mcpConfig).length} MCP server(s)`);
108
- for (const [name, config] of Object.entries(mcpConfig)) {
109
- debug.log('engine', ` → ${name}: ${config.type} (${(config as any).url || (config as any).command?.join(' ')})`);
129
+ const mcpUrls = Object.values(mcpConfig).map(c => (c as any).url).filter(Boolean);
130
+ const reachable = await Promise.all(
131
+ mcpUrls.map(url => isServerAlive(url))
132
+ );
133
+
134
+ if (reachable.every(Boolean)) {
135
+ debug.log('engine', `Open Code server: injecting ${Object.keys(mcpConfig).length} MCP server(s)`);
136
+ for (const [name, config] of Object.entries(mcpConfig)) {
137
+ debug.log('engine', ` → ${name}: ${config.type} (${(config as any).url || (config as any).command?.join(' ')})`);
138
+ }
139
+ } else {
140
+ debug.warn('engine', 'Open Code server: MCP endpoint not reachable, starting without MCP');
141
+ mcpConfig = {};
110
142
  }
111
143
  }
112
144
 
113
- const result = await createOpencode({
114
- hostname: OPENCODE_HOST,
115
- port: 0,
116
- ...(Object.keys(mcpConfig).length > 0 && {
117
- config: { mcp: mcpConfig },
118
- }),
145
+ const configContent = Object.keys(mcpConfig).length > 0
146
+ ? JSON.stringify({ mcp: mcpConfig })
147
+ : '{}';
148
+
149
+ debug.log('engine', `Spawning: ${args.join(' ')}`);
150
+
151
+ const proc = Bun.spawn(args, {
152
+ stdout: 'pipe',
153
+ stderr: 'pipe',
154
+ env: {
155
+ ...process.env,
156
+ OPENCODE_CONFIG_CONTENT: configContent,
157
+ },
119
158
  });
120
159
 
121
- serverHandle = result.server;
122
- client = result.client;
160
+ // Parse server URL from stdout — opencode prints "opencode server listening on <url>"
161
+ const url = await new Promise<string>((resolve, reject) => {
162
+ const timeout = setTimeout(() => {
163
+ proc.kill();
164
+ reject(new Error(`Timeout waiting for opencode server to start after ${SERVER_START_TIMEOUT}ms`));
165
+ }, SERVER_START_TIMEOUT);
166
+
167
+ let output = '';
168
+
169
+ const readStream = async (stream: ReadableStream<Uint8Array>, label: string) => {
170
+ const reader = stream.getReader();
171
+ const decoder = new TextDecoder();
172
+ try {
173
+ while (true) {
174
+ const { done, value } = await reader.read();
175
+ if (done) break;
176
+ const chunk = decoder.decode(value, { stream: true });
177
+ output += chunk;
178
+
179
+ if (label === 'stdout') {
180
+ for (const line of output.split('\n')) {
181
+ if (line.startsWith('opencode server listening')) {
182
+ const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
183
+ if (match) {
184
+ clearTimeout(timeout);
185
+ resolve(match[1]);
186
+ return;
187
+ }
188
+ }
189
+ }
190
+ }
191
+ }
192
+ } catch {
193
+ // stream closed
194
+ }
195
+ };
196
+
197
+ readStream(proc.stdout as ReadableStream<Uint8Array>, 'stdout');
198
+ readStream(proc.stderr as ReadableStream<Uint8Array>, 'stderr');
199
+
200
+ proc.exited.then((code) => {
201
+ clearTimeout(timeout);
202
+ let msg = `opencode server exited with code ${code}`;
203
+ if (output.trim()) msg += `\nServer output: ${output}`;
204
+ reject(new Error(msg));
205
+ });
206
+ });
207
+
208
+ serverProc = proc;
209
+ const { createOpencodeClient } = await import('@opencode-ai/sdk');
210
+ client = createOpencodeClient({ baseUrl: url });
211
+ serverHandle = {
212
+ url,
213
+ close() { proc.kill(); },
214
+ };
123
215
  ownsProcess = true;
124
216
  ready = true;
125
217
 
126
- settingsQueries.set(DB_KEY, result.server.url);
127
- debug.log('engine', `Open Code client ready (server: ${result.server.url})`);
218
+ settingsQueries.set(DB_KEY, url);
219
+ debug.log('engine', `Open Code client ready (server: ${url})`);
128
220
  }
129
221
 
130
222
  export function getClient(): OpencodeClient | null {
@@ -152,6 +244,7 @@ export async function disposeOpenCodeClient(): Promise<void> {
152
244
  }
153
245
  }
154
246
 
155
- resetState();
247
+ clearClientState();
248
+ initPromise = null;
156
249
  debug.log('engine', 'Open Code client disposed');
157
250
  }
@@ -5,7 +5,7 @@
5
5
  * Converts Open Code messages/events → SDKMessage (Claude format)
6
6
  * so stream-manager and frontend remain unchanged.
7
7
  *
8
- * Server lifecycle is managed by ./server.ts (bun-pty spawn).
8
+ * Server lifecycle is managed by ./server.ts (Bun.spawn).
9
9
  * This file only contains the OpenCodeEngine class (per-project instance).
10
10
  */
11
11
 
package/bin/clopen.ts CHANGED
@@ -359,10 +359,8 @@ async function clearAllData() {
359
359
  // ============================================================
360
360
 
361
361
  async function setupEnvironment() {
362
- if (!existsSync(ENV_FILE)) {
363
- if (existsSync(ENV_EXAMPLE)) {
364
- copyFileSync(ENV_EXAMPLE, ENV_FILE);
365
- }
362
+ if (existsSync(ENV_EXAMPLE)) {
363
+ copyFileSync(ENV_EXAMPLE, ENV_FILE);
366
364
  }
367
365
  }
368
366
 
@@ -383,15 +381,43 @@ async function startServer(options: CLIOptions) {
383
381
  if (options.host) env.CLOPEN_HOST = options.host;
384
382
  if (options.log) env.CLOPEN_DEBUG = 'true';
385
383
 
384
+ startSpinner('Starting server...');
385
+
386
386
  const serverProc = Bun.spawn(['bun', startScript], {
387
387
  cwd: __dirname,
388
- stdout: 'inherit',
389
- stderr: 'inherit',
388
+ stdout: 'pipe',
389
+ stderr: 'pipe',
390
390
  stdin: 'inherit',
391
391
  env,
392
392
  });
393
393
 
394
- await serverProc.exited;
394
+ // Forward subprocess output, stopping spinner on first chunk
395
+ let spinnerActive = true;
396
+
397
+ async function pipeStream(stream: ReadableStream<Uint8Array>, target: NodeJS.WriteStream) {
398
+ const reader = stream.getReader();
399
+ try {
400
+ while (true) {
401
+ const { done, value } = await reader.read();
402
+ if (done) break;
403
+ if (spinnerActive) {
404
+ stopSpinner();
405
+ spinnerActive = false;
406
+ }
407
+ target.write(value);
408
+ }
409
+ } finally {
410
+ reader.releaseLock();
411
+ }
412
+ }
413
+
414
+ await Promise.all([
415
+ pipeStream(serverProc.stdout, process.stdout),
416
+ pipeStream(serverProc.stderr, process.stderr),
417
+ serverProc.exited,
418
+ ]);
419
+
420
+ if (spinnerActive) stopSpinner();
395
421
  }
396
422
 
397
423
  // ============================================================
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myrialabs/clopen",
3
- "version": "0.2.19",
3
+ "version": "0.2.21",
4
4
  "description": "All-in-one web workspace for Claude Code & OpenCode — chat, terminal, git, browser preview, checkpoints, and real-time collaboration",
5
5
  "author": "Myria Labs",
6
6
  "license": "MIT",