@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.
Files changed (51) hide show
  1. package/backend/engine/adapters/opencode/server.ts +72 -33
  2. package/backend/snapshot/helpers.ts +8 -0
  3. package/backend/tunnel/cloudflared/binary.ts +153 -0
  4. package/backend/tunnel/cloudflared/index.ts +21 -0
  5. package/backend/tunnel/cloudflared/tunnel.ts +389 -0
  6. package/backend/tunnel/global-tunnel-manager.ts +538 -152
  7. package/backend/tunnel/project-tunnel-manager.ts +6 -14
  8. package/backend/tunnel/tunnel-config.ts +234 -0
  9. package/backend/ws/tunnel/config.ts +108 -0
  10. package/backend/ws/tunnel/index.ts +3 -1
  11. package/backend/ws/tunnel/operations.ts +290 -43
  12. package/bin/clopen.ts +1 -1
  13. package/bun.lock +0 -4
  14. package/frontend/App.svelte +2 -1
  15. package/frontend/components/chat/ChatInterface.svelte +6 -1
  16. package/frontend/components/chat/formatters/Tools.svelte +3 -1
  17. package/frontend/components/chat/input/components/EngineModelPicker.svelte +12 -1
  18. package/frontend/components/chat/message/ChatMessage.svelte +0 -29
  19. package/frontend/components/chat/message/ChatMessages.svelte +2 -2
  20. package/frontend/components/chat/message/MessageBubble.svelte +0 -6
  21. package/frontend/components/chat/message/MessageHeader.svelte +0 -16
  22. package/frontend/components/chat/tools/SkillTool.svelte +21 -0
  23. package/frontend/components/chat/tools/index.ts +1 -0
  24. package/frontend/components/chat/widgets/ContextIndicator.svelte +186 -0
  25. package/frontend/components/history/HistoryModal.svelte +3 -3
  26. package/frontend/components/settings/SettingsModal.svelte +5 -0
  27. package/frontend/components/settings/SettingsView.svelte +4 -0
  28. package/frontend/components/settings/model/EngineModelPicker.svelte +9 -0
  29. package/frontend/components/settings/tunnel/TunnelSettings.svelte +1060 -0
  30. package/frontend/components/tunnel/TunnelActive.svelte +132 -71
  31. package/frontend/components/tunnel/TunnelButton.svelte +4 -4
  32. package/frontend/components/tunnel/TunnelInactive.svelte +38 -65
  33. package/frontend/components/tunnel/TunnelModal.svelte +55 -2
  34. package/frontend/components/workspace/PanelHeader.svelte +4 -0
  35. package/frontend/components/workspace/WorkspaceLayout.svelte +31 -1
  36. package/frontend/components/workspace/panels/ChatPanel.svelte +6 -0
  37. package/frontend/services/favicon.service.ts +103 -0
  38. package/frontend/services/terminal/project.service.ts +52 -0
  39. package/frontend/stores/features/tunnel-config.svelte.ts +205 -0
  40. package/frontend/stores/features/tunnel.svelte.ts +194 -80
  41. package/frontend/stores/ui/settings-modal.svelte.ts +7 -0
  42. package/frontend/utils/chat/message-grouper.ts +33 -5
  43. package/frontend/utils/chat/message-processor.ts +2 -1
  44. package/frontend/utils/chat/tool-handler.ts +38 -3
  45. package/frontend/utils/context-manager.ts +35 -237
  46. package/package.json +1 -2
  47. package/shared/types/messaging/index.ts +1 -0
  48. package/shared/types/messaging/tool.ts +24 -1
  49. package/shared/utils/ws-client.ts +23 -1
  50. package/frontend/components/chat/modal/TokenUsageModal.svelte +0 -124
  51. package/frontend/components/chat/widgets/TokenUsage.svelte +0 -78
@@ -0,0 +1,389 @@
1
+ /**
2
+ * Cloudflared Tunnel
3
+ *
4
+ * EventEmitter wrapper around cloudflared child process.
5
+ * Replaces the `Tunnel` class from the `cloudflared` npm package.
6
+ *
7
+ * Events:
8
+ * - 'url' (url: string) - TryCloudflare URL generated
9
+ * - 'connected' (info: ConnectionInfo) - Tunnel connection established
10
+ * - 'disconnected'(info: ConnectionInfo) - Tunnel connection lost
11
+ * - 'config' (data: { config: any; version: number }) - Config update (remote tunnels)
12
+ * - 'error' (error: Error) - Error occurred
13
+ * - 'exit' (code: number | null, signal: string | null) - Process exited
14
+ * - 'stdout' (data: string) - Raw stdout output
15
+ * - 'stderr' (data: string) - Raw stderr output
16
+ */
17
+
18
+ import { spawn, type ChildProcess } from 'child_process';
19
+ import { EventEmitter } from 'events';
20
+ import { existsSync, mkdirSync, writeFileSync, chmodSync } from 'fs';
21
+ import { tmpdir, platform } from 'os';
22
+ import { join } from 'path';
23
+ import { getBinaryPath } from './binary';
24
+
25
+ // --- Output parsing regexes (from cloudflared npm package) ---
26
+
27
+ const CONN_REGEX = /connection[= ]([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12})/i;
28
+ const IP_REGEX = /ip=([0-9.]+)/;
29
+ const LOCATION_REGEX = /location=([A-Za-z0-9]+)/;
30
+ const INDEX_REGEX = /connIndex=(\d)/;
31
+ const TRYCLOUDFLARE_REGEX = /https:\/\/([a-z0-9-]+)\.trycloudflare\.com/;
32
+ const CONFIG_REGEX = /\bconfig="(.+?)" version=(\d+)/;
33
+
34
+ export interface ConnectionInfo {
35
+ id: string;
36
+ ip: string;
37
+ location: string;
38
+ }
39
+
40
+ export interface LoginHandle {
41
+ process: ChildProcess;
42
+ cancel: () => void;
43
+ }
44
+
45
+ export interface LoginCallbacks {
46
+ onUrl: (url: string) => void;
47
+ onComplete: () => void;
48
+ onError: (message: string) => void;
49
+ }
50
+
51
+ export interface LoginOptions {
52
+ /** Prevent cloudflared from auto-opening a browser. Default: `true` */
53
+ preventBrowserOpen?: boolean;
54
+ }
55
+
56
+ export interface CreateTunnelOptions {
57
+ /** Custom path for the credentials file output */
58
+ credentialsFile?: string;
59
+ /** Base64-encoded tunnel secret (must decode to >= 32 bytes) */
60
+ secret?: string;
61
+ /** Custom path for the origin certificate */
62
+ origincert?: string;
63
+ }
64
+
65
+ export interface CreateTunnelResult {
66
+ tunnelId: string;
67
+ credentialsFile: string;
68
+ output: string;
69
+ }
70
+
71
+ export interface DeleteTunnelOptions {
72
+ /** Force delete even if tunnel has active connections. Default: `false` */
73
+ force?: boolean;
74
+ /** Custom path for the credentials file */
75
+ credentialsFile?: string;
76
+ /** Custom path for the origin certificate */
77
+ origincert?: string;
78
+ }
79
+
80
+ export interface DeleteTunnelResult {
81
+ output: string;
82
+ }
83
+
84
+ export interface RouteDnsOptions {
85
+ /** Overwrite existing DNS record for this hostname. Default: `false` */
86
+ overwriteDns?: boolean;
87
+ /** Custom path for the origin certificate */
88
+ origincert?: string;
89
+ }
90
+
91
+ export interface RouteDnsResult {
92
+ alreadyExists: boolean;
93
+ output: string;
94
+ }
95
+
96
+ type OutputHandler = (output: string, tunnel: CloudflaredTunnel) => void;
97
+
98
+ export class CloudflaredTunnel extends EventEmitter {
99
+ private _process: ChildProcess;
100
+ private outputHandlers: OutputHandler[] = [];
101
+ private connections: (ConnectionInfo | undefined)[] = [];
102
+
103
+ constructor(args: string[]) {
104
+ super();
105
+ this.setupDefaultHandlers();
106
+ this._process = this.createProcess(args);
107
+ this.setupEventRouting();
108
+ }
109
+
110
+ get process(): ChildProcess {
111
+ return this._process;
112
+ }
113
+
114
+ /** Stop the tunnel process */
115
+ stop(): boolean {
116
+ return this._process.kill('SIGINT');
117
+ }
118
+
119
+ /** Add a custom output handler */
120
+ addHandler(handler: OutputHandler): void {
121
+ this.outputHandlers.push(handler);
122
+ }
123
+
124
+ // --- Static factory methods ---
125
+
126
+ /** Create a quick tunnel (TryCloudflare, no account needed) */
127
+ static quick(url?: string): CloudflaredTunnel {
128
+ const args = url
129
+ ? ['tunnel', '--url', url]
130
+ : ['tunnel', '--hello-world'];
131
+ return new CloudflaredTunnel(args);
132
+ }
133
+
134
+ /** Create a tunnel with a Cloudflare token (dashboard-managed) */
135
+ static withToken(token: string): CloudflaredTunnel {
136
+ return new CloudflaredTunnel(['tunnel', 'run', '--token', token]);
137
+ }
138
+
139
+ /** Create a tunnel with a local config file */
140
+ static withConfig(configPath: string): CloudflaredTunnel {
141
+ return new CloudflaredTunnel(['tunnel', '--config', configPath, 'run']);
142
+ }
143
+
144
+ // --- Static commands ---
145
+
146
+ /**
147
+ * Start `cloudflared tunnel login`.
148
+ * Returns a handle with `.cancel()` to abort the process.
149
+ */
150
+ static login(callbacks: LoginCallbacks, options?: LoginOptions): LoginHandle {
151
+ const preventBrowserOpen = options?.preventBrowserOpen ?? true;
152
+
153
+ let env = process.env;
154
+
155
+ if (preventBrowserOpen) {
156
+ const fakeOpenDir = join(tmpdir(), 'cloudflared-noop-open');
157
+ if (!existsSync(fakeOpenDir)) mkdirSync(fakeOpenDir, { recursive: true });
158
+ const fakeScript = '#!/bin/sh\nexit 0\n';
159
+ const cmds = platform() === 'darwin' ? ['open'] : ['xdg-open', 'sensible-browser', 'x-www-browser'];
160
+ for (const cmd of cmds) {
161
+ const p = join(fakeOpenDir, cmd);
162
+ if (!existsSync(p)) {
163
+ writeFileSync(p, fakeScript, { mode: 0o755 });
164
+ chmodSync(p, 0o755);
165
+ }
166
+ }
167
+ env = { ...process.env, BROWSER: 'false', PATH: `${fakeOpenDir}:${process.env.PATH ?? ''}` };
168
+ }
169
+
170
+ const proc = spawn(getBinaryPath(), ['tunnel', 'login'], {
171
+ stdio: ['ignore', 'pipe', 'pipe'],
172
+ env
173
+ });
174
+
175
+ let urlSent = false;
176
+ let cancelled = false;
177
+
178
+ const handleOutput = (data: Buffer) => {
179
+ if (cancelled) return;
180
+ const output = data.toString();
181
+ if (!urlSent) {
182
+ const urlMatch = output.match(/https:\/\/dash\.cloudflare\.com\/argotunnel\S+/);
183
+ if (urlMatch) {
184
+ urlSent = true;
185
+ callbacks.onUrl(urlMatch[0]);
186
+ }
187
+ }
188
+ };
189
+
190
+ proc.stdout?.on('data', handleOutput);
191
+ proc.stderr?.on('data', handleOutput);
192
+
193
+ proc.on('exit', (code) => {
194
+ if (cancelled) return;
195
+ if (code === 0) callbacks.onComplete();
196
+ else callbacks.onError(`Login failed (exit code ${code})`);
197
+ });
198
+
199
+ proc.on('error', (error) => {
200
+ if (cancelled) return;
201
+ callbacks.onError(error.message);
202
+ });
203
+
204
+ return {
205
+ process: proc,
206
+ cancel() {
207
+ cancelled = true;
208
+ proc.kill('SIGTERM');
209
+ }
210
+ };
211
+ }
212
+
213
+ /** Create a named tunnel. Returns tunnel UUID and credentials file path. */
214
+ static async createTunnel(name: string, options?: CreateTunnelOptions): Promise<CreateTunnelResult> {
215
+ const args = ['tunnel'];
216
+ if (options?.origincert) args.push('--origincert', options.origincert);
217
+ args.push('create');
218
+ if (options?.credentialsFile) args.push('--credentials-file', options.credentialsFile);
219
+ if (options?.secret) args.push('--secret', options.secret);
220
+ args.push(name);
221
+
222
+ const { output, exitCode } = await CloudflaredTunnel.run(args);
223
+
224
+ if (exitCode !== 0) {
225
+ throw new Error(`Failed to create tunnel (exit code ${exitCode}): ${output.trim()}`);
226
+ }
227
+
228
+ const idMatch = output.match(/with id ([a-f0-9-]+)/);
229
+ const credMatch = output.match(/credentials written to (.+\.json)/);
230
+
231
+ if (!idMatch || !credMatch) {
232
+ throw new Error(`Could not parse tunnel creation output: ${output}`);
233
+ }
234
+
235
+ return { tunnelId: idMatch[1], credentialsFile: credMatch[1].trim(), output };
236
+ }
237
+
238
+ /** Delete a tunnel by UUID or name. */
239
+ static async deleteTunnel(tunnel: string, options?: DeleteTunnelOptions): Promise<DeleteTunnelResult> {
240
+ const args = ['tunnel'];
241
+ if (options?.origincert) args.push('--origincert', options.origincert);
242
+ args.push('delete');
243
+ if (options?.force) args.push('--force');
244
+ if (options?.credentialsFile) args.push('--credentials-file', options.credentialsFile);
245
+ args.push(tunnel);
246
+
247
+ const { output, exitCode } = await CloudflaredTunnel.run(args);
248
+
249
+ if (exitCode !== 0) {
250
+ throw new Error(`Failed to delete tunnel: ${output.trim()}`);
251
+ }
252
+
253
+ return { output };
254
+ }
255
+
256
+ /** Create a CNAME DNS record pointing hostname to a tunnel. */
257
+ static async routeDns(tunnel: string, hostname: string, options?: RouteDnsOptions): Promise<RouteDnsResult> {
258
+ const args = ['tunnel'];
259
+ if (options?.origincert) args.push('--origincert', options.origincert);
260
+ args.push('route', 'dns');
261
+ if (options?.overwriteDns) args.push('--overwrite-dns');
262
+ args.push(tunnel, hostname);
263
+
264
+ const { output, exitCode } = await CloudflaredTunnel.run(args);
265
+
266
+ if (exitCode === 0) {
267
+ return { alreadyExists: /already exists|updated/i.test(output), output };
268
+ }
269
+
270
+ // DNS already points to this tunnel — treat as success
271
+ if (/already exists|CNAME.*already/i.test(output)) {
272
+ return { alreadyExists: true, output };
273
+ }
274
+
275
+ throw new Error(`Failed to route DNS: ${output.trim()}`);
276
+ }
277
+
278
+ // --- Private helpers ---
279
+
280
+ /** Run a one-shot cloudflared command and collect all output. */
281
+ private static run(args: string[]): Promise<{ output: string; exitCode: number }> {
282
+ return new Promise((resolve, reject) => {
283
+ const proc = spawn(getBinaryPath(), args, {
284
+ stdio: ['ignore', 'pipe', 'pipe']
285
+ });
286
+
287
+ let output = '';
288
+ proc.stdout?.on('data', (data: Buffer) => { output += data.toString(); });
289
+ proc.stderr?.on('data', (data: Buffer) => { output += data.toString(); });
290
+
291
+ proc.on('exit', (code) => resolve({ output, exitCode: code ?? 1 }));
292
+ proc.on('error', (error) => reject(error));
293
+ });
294
+ }
295
+
296
+ // --- Internal ---
297
+
298
+ private setupDefaultHandlers(): void {
299
+ // Connection handler
300
+ this.addHandler((output, tunnel) => {
301
+ const connMatch = output.match(CONN_REGEX);
302
+ const ipMatch = output.match(IP_REGEX);
303
+ const locationMatch = output.match(LOCATION_REGEX);
304
+ const indexMatch = output.match(INDEX_REGEX);
305
+
306
+ if (connMatch && ipMatch && locationMatch && indexMatch) {
307
+ const info: ConnectionInfo = {
308
+ id: connMatch[1],
309
+ ip: ipMatch[1],
310
+ location: locationMatch[1]
311
+ };
312
+ this.connections[Number(indexMatch[1])] = info;
313
+ tunnel.emit('connected', info);
314
+ }
315
+
316
+ // Disconnection
317
+ if (output.includes('terminated')) {
318
+ const idxMatch = output.match(INDEX_REGEX);
319
+ if (idxMatch) {
320
+ const idx = Number(idxMatch[1]);
321
+ if (this.connections[idx]) {
322
+ tunnel.emit('disconnected', this.connections[idx]);
323
+ this.connections[idx] = undefined;
324
+ }
325
+ }
326
+ }
327
+ });
328
+
329
+ // TryCloudflare URL handler
330
+ this.addHandler((output, tunnel) => {
331
+ const urlMatch = output.match(TRYCLOUDFLARE_REGEX);
332
+ if (urlMatch) {
333
+ tunnel.emit('url', urlMatch[0]);
334
+ }
335
+ });
336
+
337
+ // Config handler (for remote/token-based tunnels)
338
+ this.addHandler((output, tunnel) => {
339
+ const configMatch = output.match(CONFIG_REGEX);
340
+ if (configMatch) {
341
+ try {
342
+ const configStr = configMatch[1].replace(/\\"/g, '"');
343
+ const config = JSON.parse(configStr);
344
+ const version = parseInt(configMatch[2], 10);
345
+ tunnel.emit('config', { config, version });
346
+
347
+ // Also emit URL for each ingress hostname
348
+ if (config?.ingress && Array.isArray(config.ingress)) {
349
+ for (const ingress of config.ingress) {
350
+ if (ingress.hostname) {
351
+ tunnel.emit('url', ingress.hostname);
352
+ }
353
+ }
354
+ }
355
+ } catch {
356
+ // Ignore parse errors
357
+ }
358
+ }
359
+ });
360
+ }
361
+
362
+ private createProcess(args: string[]): ChildProcess {
363
+ const binPath = getBinaryPath();
364
+ const child = spawn(binPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });
365
+
366
+ child.on('error', (error) => this.emit('error', error));
367
+ child.on('exit', (code, signal) => this.emit('exit', code, signal));
368
+
369
+ child.stdout?.on('data', (data: Buffer) => this.emit('stdout', data.toString()));
370
+ child.stderr?.on('data', (data: Buffer) => this.emit('stderr', data.toString()));
371
+
372
+ return child;
373
+ }
374
+
375
+ private setupEventRouting(): void {
376
+ const processOutput = (output: string) => {
377
+ for (const handler of this.outputHandlers) {
378
+ try {
379
+ handler(output, this);
380
+ } catch (error) {
381
+ this.emit('error', error instanceof Error ? error : new Error(String(error)));
382
+ }
383
+ }
384
+ };
385
+
386
+ this.on('stdout', processOutput);
387
+ this.on('stderr', processOutput);
388
+ }
389
+ }