@myrialabs/clopen 0.2.14 → 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.
- package/backend/engine/adapters/opencode/server.ts +72 -33
- package/backend/snapshot/helpers.ts +8 -0
- package/backend/tunnel/cloudflared/binary.ts +153 -0
- package/backend/tunnel/cloudflared/index.ts +21 -0
- package/backend/tunnel/cloudflared/tunnel.ts +389 -0
- package/backend/tunnel/global-tunnel-manager.ts +538 -152
- package/backend/tunnel/project-tunnel-manager.ts +6 -14
- package/backend/tunnel/tunnel-config.ts +234 -0
- package/backend/ws/tunnel/config.ts +108 -0
- package/backend/ws/tunnel/index.ts +3 -1
- package/backend/ws/tunnel/operations.ts +290 -43
- package/bin/clopen.ts +1 -1
- package/bun.lock +0 -4
- package/frontend/App.svelte +2 -1
- package/frontend/components/chat/ChatInterface.svelte +6 -1
- package/frontend/components/chat/formatters/Tools.svelte +3 -1
- package/frontend/components/chat/input/components/EngineModelPicker.svelte +12 -1
- package/frontend/components/chat/message/ChatMessage.svelte +0 -29
- package/frontend/components/chat/message/ChatMessages.svelte +2 -2
- package/frontend/components/chat/message/MessageBubble.svelte +0 -6
- package/frontend/components/chat/message/MessageHeader.svelte +0 -16
- package/frontend/components/chat/tools/SkillTool.svelte +21 -0
- package/frontend/components/chat/tools/index.ts +1 -0
- package/frontend/components/chat/widgets/ContextIndicator.svelte +186 -0
- package/frontend/components/history/HistoryModal.svelte +3 -3
- package/frontend/components/settings/SettingsModal.svelte +5 -0
- package/frontend/components/settings/SettingsView.svelte +4 -0
- package/frontend/components/settings/model/EngineModelPicker.svelte +9 -0
- package/frontend/components/settings/tunnel/TunnelSettings.svelte +1060 -0
- package/frontend/components/tunnel/TunnelActive.svelte +132 -71
- package/frontend/components/tunnel/TunnelButton.svelte +4 -4
- package/frontend/components/tunnel/TunnelInactive.svelte +38 -65
- package/frontend/components/tunnel/TunnelModal.svelte +55 -2
- package/frontend/components/workspace/PanelHeader.svelte +4 -0
- package/frontend/components/workspace/WorkspaceLayout.svelte +31 -1
- package/frontend/components/workspace/panels/ChatPanel.svelte +6 -0
- package/frontend/services/favicon.service.ts +103 -0
- package/frontend/services/terminal/project.service.ts +52 -0
- package/frontend/stores/features/tunnel-config.svelte.ts +205 -0
- package/frontend/stores/features/tunnel.svelte.ts +194 -80
- package/frontend/stores/ui/settings-modal.svelte.ts +7 -0
- package/frontend/utils/chat/message-grouper.ts +33 -5
- package/frontend/utils/chat/message-processor.ts +2 -1
- package/frontend/utils/chat/tool-handler.ts +38 -3
- package/frontend/utils/context-manager.ts +35 -237
- package/package.json +1 -2
- package/shared/types/messaging/index.ts +1 -0
- package/shared/types/messaging/tool.ts +24 -1
- package/shared/utils/ws-client.ts +23 -1
- package/frontend/components/chat/modal/TokenUsageModal.svelte +0 -124
- package/frontend/components/chat/widgets/TokenUsage.svelte +0 -78
|
@@ -1,34 +1,66 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Open Code Server & Client Manager
|
|
3
3
|
*
|
|
4
|
-
* Manages the
|
|
5
|
-
*
|
|
4
|
+
* Manages the `opencode serve` child process and provides an OpencodeClient
|
|
5
|
+
* singleton for all engine instances.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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
|
-
*
|
|
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)
|
|
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
|
|
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:
|
|
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
|
-
*
|
|
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', `
|
|
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
|
|
151
|
+
debug.error('engine', 'Error stopping Open Code server:', error);
|
|
110
152
|
}
|
|
111
|
-
serverHandle = null;
|
|
112
153
|
}
|
|
113
154
|
|
|
114
|
-
|
|
115
|
-
ready = false;
|
|
116
|
-
initPromise = null;
|
|
155
|
+
resetState();
|
|
117
156
|
debug.log('engine', 'Open Code client disposed');
|
|
118
157
|
}
|
|
@@ -275,6 +275,11 @@ function findSessionEndByParent(
|
|
|
275
275
|
sessionContinuation = child;
|
|
276
276
|
break;
|
|
277
277
|
}
|
|
278
|
+
// System messages (e.g. compact_boundary) are part of session continuation
|
|
279
|
+
if (sdk.type === 'system') {
|
|
280
|
+
sessionContinuation = child;
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
278
283
|
} catch {
|
|
279
284
|
continue;
|
|
280
285
|
}
|
|
@@ -314,6 +319,9 @@ function findSessionEndByTimestamp(
|
|
|
314
319
|
lastValidEnd = msg;
|
|
315
320
|
} else if (sdk.type === 'user' && isInternalToolMessage(sdk)) {
|
|
316
321
|
lastValidEnd = msg;
|
|
322
|
+
} else if (sdk.type === 'system') {
|
|
323
|
+
// System messages (e.g. compact_boundary) are part of session continuation
|
|
324
|
+
lastValidEnd = msg;
|
|
317
325
|
} else if (sdk.type === 'user' && !isInternalToolMessage(sdk)) {
|
|
318
326
|
// Hit the next real user message (checkpoint) - stop
|
|
319
327
|
break;
|
|
@@ -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';
|