File size: 11,593 Bytes
b9a3ef2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// ---------------------------------------------------------------------------
// Bridge -- Real persistent Antigravity CLI session management
// ---------------------------------------------------------------------------
// Spawns the Antigravity CLI as a persistent interactive subprocess.
// Relays stdin/stdout/stderr over WebSocket so the webapp mirrors the CLI.
// ---------------------------------------------------------------------------

import { Server, Socket } from 'socket.io';
import { spawn, ChildProcess } from 'child_process';
import { ToolRegistry, ToolResult } from './toolRegistry';
import { CLIDetectionResult, detectCLI } from './cliDetector';
import fs from 'fs';
import path from 'path';

const SETTINGS_FILE = path.join(__dirname, '..', 'settings.json');

interface Settings {
    cliPath: string;
    autoConnect: boolean;
}

interface CLISession {
    process: ChildProcess;
    logs: string[];
    started: number;
}

// Persistent state
let currentSession: CLISession | null = null;
let settings: Settings = loadSettings();
let latestCliStatus: CLIDetectionResult | null = null;

function loadSettings(): Settings {
    try {
        if (fs.existsSync(SETTINGS_FILE)) {
            return JSON.parse(fs.readFileSync(SETTINGS_FILE, 'utf-8'));
        }
    } catch { }
    return { cliPath: '', autoConnect: false };
}

function saveSettings(s: Settings): void {
    settings = s;
    fs.writeFileSync(SETTINGS_FILE, JSON.stringify(s, null, 2), 'utf-8');
}

export function getSettings(): Settings {
    return settings;
}

export function updateSettings(partial: Partial<Settings>): Settings {
    settings = { ...settings, ...partial };
    saveSettings(settings);
    return settings;
}

export async function redetectCLI(): Promise<CLIDetectionResult> {
    // Override detection with user-configured path
    if (settings.cliPath) {
        process.env.ANTIGRAVITY_CLI_PATH = settings.cliPath;
    }
    latestCliStatus = await detectCLI();
    return latestCliStatus;
}

export function setupBridge(

    io: Server,

    toolRegistry: ToolRegistry,

    cliStatus: CLIDetectionResult

): void {
    latestCliStatus = cliStatus;

    io.on('connection', (socket: Socket) => {
        console.log(`  [Bridge] Client connected: ${socket.id}`);

        // Send initial state
        socket.emit('bridge:init', {
            tools: toolRegistry.listTools(),
            cli: {
                detected: latestCliStatus!.detected,
                version: latestCliStatus!.version,
                method: latestCliStatus!.method,
                path: latestCliStatus!.path,
            },
            settings: settings,
            sessionActive: currentSession !== null,
            serverTime: new Date().toISOString(),
        });

        // ------------------------------------------------------------------
        // Settings management (from UI)
        // ------------------------------------------------------------------
        socket.on('settings:get', (callback: Function) => {
            if (typeof callback === 'function') {
                callback({ settings, cli: latestCliStatus });
            }
        });

        socket.on('settings:update', async (data: Partial<Settings>, callback: Function) => {
            const updated = updateSettings(data);
            console.log(`  [Bridge] Settings updated:`, updated);

            // Re-detect with new path
            const newStatus = await redetectCLI();
            latestCliStatus = newStatus;

            // Notify all clients
            io.emit('settings:changed', { settings: updated, cli: newStatus });

            if (typeof callback === 'function') {
                callback({ settings: updated, cli: newStatus });
            }
        });

        // ------------------------------------------------------------------
        // CLI Session management
        // ------------------------------------------------------------------
        socket.on('cli:start', async (data: { cliPath?: string }) => {
            const cliPath = data?.cliPath || settings.cliPath || latestCliStatus?.path;

            if (!cliPath) {
                socket.emit('cli:error', {
                    message: 'No CLI path configured. Go to Settings and set the path to your Antigravity CLI executable.',
                });
                return;
            }

            // Kill existing session
            if (currentSession) {
                try { currentSession.process.kill('SIGTERM'); } catch { }
                currentSession = null;
            }

            console.log(`  [Bridge] Starting CLI session: ${cliPath}`);
            io.emit('cli:starting', { path: cliPath });

            try {
                const child = spawn(cliPath, [], {
                    shell: true,
                    cwd: process.cwd(),
                    env: { ...process.env, TERM: 'dumb', NO_COLOR: '1' },
                    stdio: ['pipe', 'pipe', 'pipe'],
                });

                currentSession = {
                    process: child,
                    logs: [],
                    started: Date.now(),
                };

                child.stdout?.on('data', (chunk: Buffer) => {
                    const text = chunk.toString();
                    currentSession?.logs.push(text);
                    io.emit('cli:stdout', { data: text, timestamp: Date.now() });
                });

                child.stderr?.on('data', (chunk: Buffer) => {
                    const text = chunk.toString();
                    currentSession?.logs.push(`[stderr] ${text}`);
                    io.emit('cli:stderr', { data: text, timestamp: Date.now() });
                });

                child.on('close', (code: number | null) => {
                    console.log(`  [Bridge] CLI session ended: exit code ${code}`);
                    io.emit('cli:ended', { exitCode: code });
                    currentSession = null;
                });

                child.on('error', (err: Error) => {
                    console.error(`  [Bridge] CLI error: ${err.message}`);
                    io.emit('cli:error', { message: `Failed to start CLI: ${err.message}` });
                    currentSession = null;
                });

                io.emit('cli:started', { path: cliPath, timestamp: Date.now() });
            } catch (err: any) {
                io.emit('cli:error', { message: `Failed to spawn CLI: ${err.message}` });
            }
        });

        socket.on('cli:stop', () => {
            if (currentSession) {
                try { currentSession.process.kill('SIGTERM'); } catch { }
                currentSession = null;
                io.emit('cli:ended', { exitCode: null, reason: 'user-stopped' });
            }
        });

        socket.on('cli:status', (callback: Function) => {
            if (typeof callback === 'function') {
                callback({
                    active: currentSession !== null,
                    uptime: currentSession ? Date.now() - currentSession.started : 0,
                    logLength: currentSession?.logs.length || 0,
                });
            }
        });

        // ------------------------------------------------------------------
        // Prompt handling -- relay to CLI or match tools
        // ------------------------------------------------------------------
        socket.on('prompt:send', async (data: { message: string; id: string }) => {
            const { message, id } = data;
            console.log(`  [Bridge] Prompt: ${message}`);

            // Broadcast to all clients
            io.emit('prompt:received', {
                message, id, from: 'human',
                timestamp: new Date().toISOString(),
            });

            // Check for tool match first
            const match = toolRegistry.matchTool(message);

            if (match) {
                const { tool, params } = match;
                console.log(`  [Bridge] Tool matched: ${tool.name}`);

                io.emit('tool:started', { id, toolName: tool.name, params, timestamp: new Date().toISOString() });

                try {
                    const result: ToolResult = await tool.execute(params, (progress: string) => {
                        io.emit('tool:progress', { id, toolName: tool.name, progress, timestamp: new Date().toISOString() });
                    });

                    io.emit('tool:completed', { id, toolName: tool.name, result, timestamp: new Date().toISOString() });
                } catch (err: any) {
                    io.emit('tool:error', { id, toolName: tool.name, error: err.message, timestamp: new Date().toISOString() });
                }
            } else if (currentSession?.process?.stdin) {
                // Send prompt to the running CLI process
                try {
                    currentSession.process.stdin.write(message + '\n');
                    console.log(`  [Bridge] Sent to CLI stdin: ${message}`);
                } catch (err: any) {
                    io.emit('cli:error', { message: `Failed to write to CLI: ${err.message}` });
                }
            } else {
                // No tool match, no CLI session
                io.emit('agent:message', {
                    id, from: 'system',
                    message: currentSession
                        ? 'CLI session is active but stdin is unavailable.'
                        : 'No CLI session is running. Click "Connect" in Settings to start the Antigravity CLI, or configure the path first.',
                    timestamp: new Date().toISOString(),
                });
            }
        });

        // ------------------------------------------------------------------
        // MCP tool discovery & invocation
        // ------------------------------------------------------------------
        socket.on('tool:list', (callback: Function) => {
            if (typeof callback === 'function') {
                callback({ status: 'success', tools: toolRegistry.listTools() });
            }
        });

        socket.on('tool:invoke', async (data: { toolName: string; params: any }, callback: Function) => {
            const tool = toolRegistry.getTool(data.toolName);
            if (!tool) {
                if (typeof callback === 'function') callback({ status: 'error', message: `Tool "${data.toolName}" not found.` });
                return;
            }

            try {
                const result = await tool.execute(data.params, (progress: string) => {
                    io.emit('tool:progress', { toolName: data.toolName, progress, timestamp: new Date().toISOString() });
                });
                if (typeof callback === 'function') callback({ status: 'success', result });
            } catch (err: any) {
                if (typeof callback === 'function') callback({ status: 'error', message: err.message });
            }
        });

        socket.on('agent:response', (data: any) => {
            io.emit('agent:message', { ...data, from: 'agent', timestamp: new Date().toISOString() });
        });

        socket.on('disconnect', () => {
            console.log(`  [Bridge] Client disconnected: ${socket.id}`);
            // Don't kill CLI session on disconnect -- it persists
        });
    });
}