@myrialabs/clopen 0.2.15 → 0.2.16

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.
@@ -1,34 +1,66 @@
1
1
  /**
2
2
  * Open Code Server & Client Manager
3
3
  *
4
- * Manages the Open Code server lifecycle via `createOpencode()` from the SDK
5
- * and provides an OpencodeClient singleton for all engine instances.
4
+ * Manages the `opencode serve` child process and provides an OpencodeClient
5
+ * singleton for all engine instances.
6
6
  *
7
- * Uses `createOpencode()` which starts the server in-process and returns
8
- * both the server handle and a connected client.
7
+ * Strategy:
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
10
+ * 3. On every ensureClient() call, verify the server is still alive.
11
+ * If it died mid-session, automatically recover through the same flow.
9
12
  */
10
13
 
11
14
  import type { OpencodeClient } from '@opencode-ai/sdk';
12
15
  import { getOpenCodeMcpConfig } from '../../../mcp';
16
+ import { settingsQueries } from '../../../database/queries';
13
17
  import { debug } from '$shared/utils/logger';
14
- import { findAvailablePort } from '../../../utils/port-utils';
15
18
 
16
- const OPENCODE_PORT = 4096;
17
19
  const OPENCODE_HOST = '127.0.0.1';
20
+ const DB_KEY = 'opencode.server.url';
21
+ const HEALTH_TIMEOUT = 1500;
18
22
 
19
23
  let serverHandle: { url: string; close(): void } | null = null;
20
24
  let client: OpencodeClient | null = null;
21
25
  let initPromise: Promise<void> | null = null;
22
26
  let ready = false;
27
+ let ownsProcess = false;
28
+
29
+ function resetState(): void {
30
+ client = null;
31
+ ready = false;
32
+ initPromise = null;
33
+ serverHandle = null;
34
+ ownsProcess = false;
35
+ }
36
+
37
+ async function isServerAlive(url: string): Promise<boolean> {
38
+ try {
39
+ await fetch(url, { signal: AbortSignal.timeout(HEALTH_TIMEOUT) });
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
23
45
 
24
46
  /**
25
47
  * Get (or create) the OpenCode client.
26
48
  * Concurrency-safe: multiple callers share a single init promise.
27
49
  *
28
- * Uses `createOpencode()` from the SDK to start the server and create a client.
50
+ * When the server is already initialized, a lightweight health check runs.
51
+ * If the server died (bun --watch restart, crash, etc.), state is reset and
52
+ * init() is re-invoked — the same DB-check → reuse-or-spawn flow handles
53
+ * recovery automatically.
29
54
  */
30
55
  export async function ensureClient(): Promise<OpencodeClient> {
31
- if (client && ready) return client;
56
+ if (client && ready && serverHandle) {
57
+ if (await isServerAlive(serverHandle.url)) return client;
58
+
59
+ // Server disconnected — purge stale DB entry and re-init
60
+ debug.log('engine', 'Open Code server disconnected, recovering...');
61
+ settingsQueries.delete(DB_KEY);
62
+ resetState();
63
+ }
32
64
 
33
65
  if (initPromise) {
34
66
  await initPromise;
@@ -46,11 +78,30 @@ export async function ensureClient(): Promise<OpencodeClient> {
46
78
  }
47
79
 
48
80
  async function init(): Promise<void> {
49
- debug.log('engine', 'Initializing Open Code client via createOpencode()...');
81
+ debug.log('engine', 'Initializing Open Code client...');
82
+
83
+ // 1. Try to reuse an existing server persisted in DB
84
+ const stored = settingsQueries.get(DB_KEY);
85
+ if (stored?.value) {
86
+ debug.log('engine', `Found stored Open Code server: ${stored.value}, checking...`);
87
+
88
+ if (await isServerAlive(stored.value)) {
89
+ const { createOpencodeClient } = await import('@opencode-ai/sdk');
90
+ client = createOpencodeClient({ baseUrl: stored.value });
91
+ serverHandle = { url: stored.value, close() {} };
92
+ ownsProcess = false;
93
+ ready = true;
94
+ debug.log('engine', `Reusing existing Open Code server at ${stored.value}`);
95
+ return;
96
+ }
50
97
 
98
+ debug.log('engine', 'Stored server not responding, spawning new one...');
99
+ settingsQueries.delete(DB_KEY);
100
+ }
101
+
102
+ // 2. Spawn a new server — port 0 lets opencode pick an OS-assigned port
51
103
  const { createOpencode } = await import('@opencode-ai/sdk');
52
104
 
53
- // Build MCP config from enabled servers
54
105
  const mcpConfig = getOpenCodeMcpConfig();
55
106
  if (Object.keys(mcpConfig).length > 0) {
56
107
  debug.log('engine', `Open Code server: injecting ${Object.keys(mcpConfig).length} MCP server(s)`);
@@ -59,14 +110,9 @@ async function init(): Promise<void> {
59
110
  }
60
111
  }
61
112
 
62
- const actualPort = await findAvailablePort(OPENCODE_PORT);
63
- if (actualPort !== OPENCODE_PORT) {
64
- debug.log('engine', `Open Code port ${OPENCODE_PORT} in use, using ${actualPort} instead`);
65
- }
66
-
67
113
  const result = await createOpencode({
68
114
  hostname: OPENCODE_HOST,
69
- port: actualPort,
115
+ port: 0,
70
116
  ...(Object.keys(mcpConfig).length > 0 && {
71
117
  config: { mcp: mcpConfig },
72
118
  }),
@@ -74,45 +120,38 @@ async function init(): Promise<void> {
74
120
 
75
121
  serverHandle = result.server;
76
122
  client = result.client;
123
+ ownsProcess = true;
77
124
  ready = true;
78
125
 
126
+ settingsQueries.set(DB_KEY, result.server.url);
79
127
  debug.log('engine', `Open Code client ready (server: ${result.server.url})`);
80
128
  }
81
129
 
82
- /**
83
- * Get the current client (if initialized).
84
- * Returns null if not yet initialized. Use ensureClient() for guaranteed access.
85
- */
86
130
  export function getClient(): OpencodeClient | null {
87
131
  return ready ? client : null;
88
132
  }
89
133
 
90
- /**
91
- * Get the OpenCode server base URL (e.g. "http://127.0.0.1:4096").
92
- * Used for direct HTTP calls to v2 endpoints not available on the v1 client.
93
- */
94
134
  export function getServerUrl(): string | null {
95
135
  return serverHandle?.url ?? null;
96
136
  }
97
137
 
98
138
  /**
99
139
  * Dispose the OpenCode client and stop the server.
100
- * Called during full server shutdown (disposeAllEngines).
140
+ *
141
+ * Only kills the child process when we spawned it. Reused servers stay alive
142
+ * so the next session can pick them up without spawning a new process.
101
143
  */
102
144
  export async function disposeOpenCodeClient(): Promise<void> {
103
- if (serverHandle) {
145
+ if (serverHandle && ownsProcess) {
104
146
  try {
105
- debug.log('engine', `Closing Open Code server (${serverHandle.url})...`);
106
- ready = false;
147
+ debug.log('engine', `Stopping Open Code server (${serverHandle.url})...`);
107
148
  serverHandle.close();
149
+ settingsQueries.delete(DB_KEY);
108
150
  } catch (error) {
109
- debug.error('engine', 'Error closing Open Code server:', error);
151
+ debug.error('engine', 'Error stopping Open Code server:', error);
110
152
  }
111
- serverHandle = null;
112
153
  }
113
154
 
114
- client = null;
115
- ready = false;
116
- initPromise = null;
155
+ resetState();
117
156
  debug.log('engine', 'Open Code client disposed');
118
157
  }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Cloudflared Binary Manager
3
+ *
4
+ * Handles downloading and managing the cloudflared binary.
5
+ * Replaces the `cloudflared` npm package for binary management.
6
+ *
7
+ * Binary is stored in ~/.clopen/bin/cloudflared (or .clopen-dev for dev)
8
+ * Downloads from GitHub releases: https://github.com/cloudflare/cloudflared/releases
9
+ */
10
+
11
+ import { existsSync, mkdirSync, createWriteStream, chmodSync, unlinkSync, renameSync } from 'fs';
12
+ import { join, dirname } from 'path';
13
+ import { platform, arch } from 'os';
14
+ import { execSync } from 'child_process';
15
+ import { getClopenDir } from '../../utils/paths';
16
+ import { debug } from '$shared/utils/logger';
17
+
18
+ const RELEASE_BASE = 'https://github.com/cloudflare/cloudflared/releases/';
19
+
20
+ /** Platform-specific download filenames */
21
+ const LINUX_FILES: Record<string, string> = {
22
+ arm64: 'cloudflared-linux-arm64',
23
+ arm: 'cloudflared-linux-arm',
24
+ x64: 'cloudflared-linux-amd64',
25
+ ia32: 'cloudflared-linux-386'
26
+ };
27
+
28
+ const MACOS_FILES: Record<string, string> = {
29
+ arm64: 'cloudflared-darwin-arm64.tgz',
30
+ x64: 'cloudflared-darwin-amd64.tgz'
31
+ };
32
+
33
+ const WINDOWS_FILES: Record<string, string> = {
34
+ x64: 'cloudflared-windows-amd64.exe',
35
+ ia32: 'cloudflared-windows-386.exe'
36
+ };
37
+
38
+ /** Get the path where the cloudflared binary should be stored */
39
+ export function getBinaryPath(): string {
40
+ const binDir = join(getClopenDir(), 'bin');
41
+ const name = platform() === 'win32' ? 'cloudflared.exe' : 'cloudflared';
42
+ return join(binDir, name);
43
+ }
44
+
45
+ /** Check if binary exists */
46
+ export function isBinaryInstalled(): boolean {
47
+ return existsSync(getBinaryPath());
48
+ }
49
+
50
+ /** Download a file via HTTPS, following redirects */
51
+ function download(url: string, to: string, redirect = 0): Promise<string> {
52
+ if (redirect > 10) {
53
+ return Promise.reject(new Error('Too many redirects'));
54
+ }
55
+
56
+ const dir = dirname(to);
57
+ if (!existsSync(dir)) {
58
+ mkdirSync(dir, { recursive: true });
59
+ }
60
+
61
+ return new Promise((resolve, reject) => {
62
+ const protocol = url.startsWith('https') ? require('https') : require('http');
63
+
64
+ const request = protocol.get(url, (res: any) => {
65
+ const redirectCodes = [301, 302, 303, 307, 308];
66
+ if (redirectCodes.includes(res.statusCode) && res.headers.location) {
67
+ request.destroy();
68
+ resolve(download(res.headers.location, to, redirect + 1));
69
+ return;
70
+ }
71
+
72
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
73
+ const file = createWriteStream(to);
74
+ file.on('finish', () => file.close(() => resolve(to)));
75
+ file.on('error', (err: Error) => {
76
+ try { unlinkSync(to); } catch { /* ignore */ }
77
+ reject(err);
78
+ });
79
+ res.pipe(file);
80
+ } else {
81
+ request.destroy();
82
+ reject(new Error(`HTTP ${res.statusCode} downloading cloudflared`));
83
+ }
84
+ });
85
+
86
+ request.on('error', (err: Error) => reject(err));
87
+ request.end();
88
+ });
89
+ }
90
+
91
+ /** Get the download URL for current platform/arch */
92
+ function getDownloadUrl(version = 'latest'): string {
93
+ const base = version === 'latest'
94
+ ? `${RELEASE_BASE}latest/download/`
95
+ : `${RELEASE_BASE}download/${version}/`;
96
+
97
+ const os = platform();
98
+ const a = arch();
99
+
100
+ if (os === 'linux') {
101
+ const file = LINUX_FILES[a];
102
+ if (!file) throw new Error(`Unsupported Linux architecture: ${a}`);
103
+ return base + file;
104
+ }
105
+
106
+ if (os === 'darwin') {
107
+ const file = MACOS_FILES[a];
108
+ if (!file) throw new Error(`Unsupported macOS architecture: ${a}`);
109
+ return base + file;
110
+ }
111
+
112
+ if (os === 'win32') {
113
+ const file = WINDOWS_FILES[a];
114
+ if (!file) throw new Error(`Unsupported Windows architecture: ${a}`);
115
+ return base + file;
116
+ }
117
+
118
+ throw new Error(`Unsupported platform: ${os}`);
119
+ }
120
+
121
+ /** Install cloudflared binary for the current platform */
122
+ export async function installBinary(version = 'latest'): Promise<string> {
123
+ const binPath = getBinaryPath();
124
+ const url = getDownloadUrl(version);
125
+ const os = platform();
126
+
127
+ debug.log('tunnel', `Downloading cloudflared from ${url}`);
128
+
129
+ if (os === 'darwin') {
130
+ // macOS: download .tgz, extract, rename
131
+ const tgzPath = `${binPath}.tgz`;
132
+ await download(url, tgzPath);
133
+ execSync(`tar -xzf ${tgzPath}`, { cwd: dirname(binPath) });
134
+ unlinkSync(tgzPath);
135
+ // tar extracts as "cloudflared" in the same directory
136
+ const extractedPath = join(dirname(binPath), 'cloudflared');
137
+ if (extractedPath !== binPath && existsSync(extractedPath)) {
138
+ renameSync(extractedPath, binPath);
139
+ }
140
+ } else if (os === 'linux') {
141
+ await download(url, binPath);
142
+ chmodSync(binPath, '755');
143
+ } else if (os === 'win32') {
144
+ await download(url, binPath);
145
+ }
146
+
147
+ if (!existsSync(binPath)) {
148
+ throw new Error('Binary was not created after installation');
149
+ }
150
+
151
+ debug.log('tunnel', `Cloudflared binary installed at: ${binPath}`);
152
+ return binPath;
153
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Cloudflared Module
3
+ *
4
+ * Custom replacement for the `cloudflared` npm package.
5
+ * Provides binary management and tunnel process control.
6
+ */
7
+
8
+ export { getBinaryPath, isBinaryInstalled, installBinary } from './binary';
9
+ export {
10
+ CloudflaredTunnel,
11
+ type ConnectionInfo,
12
+ type LoginHandle,
13
+ type LoginCallbacks,
14
+ type LoginOptions,
15
+ type CreateTunnelOptions,
16
+ type CreateTunnelResult,
17
+ type DeleteTunnelOptions,
18
+ type DeleteTunnelResult,
19
+ type RouteDnsOptions,
20
+ type RouteDnsResult
21
+ } from './tunnel';