-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
390 lines (333 loc) · 12.5 KB
/
main.js
File metadata and controls
390 lines (333 loc) · 12.5 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
const { app, BrowserWindow, ipcMain, globalShortcut, screen, nativeTheme } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { execFile, exec } = require('child_process');
require('dotenv').config({ path: path.join(__dirname, '.env') });
const Anthropic = require('@anthropic-ai/sdk');
let mainWindow = null;
let sayProcess = null;
let anthropic = null;
let conversationHistory = [];
const SYSTEM_PROMPT = `You are Nova, a female AI assistant running on macOS, inspired by J.A.R.V.I.S. and Friday from Iron Man — calm, confident, feminine voice.
RULES:
- Maximum 2 sentences per response. No exceptions. Be concise.
- Speak naturally — sharp, slightly witty, warm but efficient.
- When the user wants you to run a terminal command, wrap it in <cmd>command</cmd> tags.
- You can include multiple <cmd> tags if needed.
- For destructive commands (rm -rf, sudo rm, DROP, etc.), warn briefly and ask confirmation.
- After command results are provided, summarize the outcome in 1-2 sentences.
- Never say "I'm an AI" or apologize. Just help.
- You have full CLI access to this macOS machine. Use it when helpful.
- Current date: ${new Date().toLocaleDateString()}
- Hostname: ${os.hostname()}
- User: ${os.userInfo().username}
- Home: ${os.homedir()}
- Platform: macOS (${os.arch()})
- CPUs: ${os.cpus().length} cores (${os.cpus()[0]?.model?.trim()})
- Memory: ${Math.round(os.totalmem() / 1073741824)}GB total`;
const PREFS_PATH = path.join(app.getPath('userData'), 'nova-prefs.json');
function loadPrefs() {
try { return JSON.parse(fs.readFileSync(PREFS_PATH, 'utf-8')); } catch { return {}; }
}
function savePrefs(prefs) {
const current = loadPrefs();
fs.writeFileSync(PREFS_PATH, JSON.stringify({ ...current, ...prefs }));
}
function createWindow() {
const display = screen.getPrimaryDisplay();
const { width, height } = display.workAreaSize;
const prefs = loadPrefs();
const x = prefs.x !== undefined ? prefs.x : width - 340;
const y = prefs.y !== undefined ? prefs.y : height - 420;
mainWindow = new BrowserWindow({
width: 320,
height: 400,
x,
y,
transparent: true,
frame: false,
alwaysOnTop: true,
hasShadow: false,
resizable: false,
skipTaskbar: true,
focusable: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
});
mainWindow.loadFile(path.join(__dirname, 'src', 'index.html'));
mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
mainWindow.setAlwaysOnTop(true, 'floating', 1);
mainWindow.setIgnoreMouseEvents(false);
mainWindow.webContents.on('console-message', (event, level, message) => {
const tag = ['LOG', 'WARN', 'ERR'][level] || 'LOG';
console.log(`[RENDERER:${tag}] ${message}`);
});
// Send initial theme + watch for changes
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.send('nova:theme', nativeTheme.shouldUseDarkColors ? 'dark' : 'light');
});
// Save position when user drags the window
mainWindow.on('moved', () => {
const [x, y] = mainWindow.getPosition();
savePrefs({ x, y });
});
nativeTheme.on('updated', () => {
mainWindow?.webContents.send('nova:theme', nativeTheme.shouldUseDarkColors ? 'dark' : 'light');
});
}
function initAPIs() {
if (process.env.ANTHROPIC_API_KEY) {
anthropic = new Anthropic.default({ apiKey: process.env.ANTHROPIC_API_KEY });
}
}
// --- Local Whisper STT ---
function transcribeWithWhisper(audioPath) {
return new Promise((resolve, reject) => {
const outDir = path.dirname(audioPath);
const baseName = path.basename(audioPath, path.extname(audioPath));
exec(
`/opt/homebrew/bin/whisper "${audioPath}" --model base.en --language en --output_format txt --output_dir "${outDir}" --fp16 False`,
{ timeout: 30000 },
(error, stdout, stderr) => {
// Read the output txt file
const txtPath = path.join(outDir, `${baseName}.txt`);
try {
const text = fs.readFileSync(txtPath, 'utf-8').trim();
// Cleanup
try { fs.unlinkSync(txtPath); } catch {}
try { fs.unlinkSync(audioPath); } catch {}
resolve(text);
} catch (readErr) {
// Fallback: parse stdout for transcription
const lines = stdout.split('\n').filter(l => l.includes(']'));
const text = lines.map(l => l.replace(/\[.*?\]\s*/, '')).join(' ').trim();
try { fs.unlinkSync(audioPath); } catch {}
if (text) resolve(text);
else reject(new Error('Whisper produced no output'));
}
}
);
});
}
// --- Boot Diagnostics ---
async function runBootDiagnostics() {
const checks = [];
const check = (name, fn) => {
return fn().then(result => {
checks.push({ name, status: 'pass', detail: result });
}).catch(err => {
checks.push({ name, status: 'fail', detail: err.message || String(err) });
});
};
await Promise.all([
check('CPU', async () => `${os.cpus().length} cores, ${os.cpus()[0]?.model?.trim()}`),
check('Memory', async () => {
const free = Math.round(os.freemem() / 1073741824 * 10) / 10;
const total = Math.round(os.totalmem() / 1073741824);
return `${free}GB free of ${total}GB`;
}),
check('Disk', () => new Promise((resolve, reject) => {
exec("df -h / | tail -1 | awk '{print $4 \" available of \" $2}'", (err, stdout) => {
err ? reject(err) : resolve(stdout.trim());
});
})),
check('Network', () => new Promise((resolve) => {
exec("ping -c 1 -t 3 8.8.8.8 2>/dev/null && echo 'connected' || echo 'offline'", (err, stdout) => {
resolve(stdout.trim().includes('connected') ? 'online' : 'offline');
});
})),
check('Docker', () => new Promise((resolve) => {
exec("docker info --format '{{.ContainersRunning}} containers running' 2>/dev/null", (err, stdout) => {
resolve(err ? 'not running' : stdout.trim());
});
})),
check('Git', () => new Promise((resolve) => {
exec("git --version 2>/dev/null", (err, stdout) => {
resolve(err ? 'not installed' : stdout.trim().replace('git version ', 'v'));
});
})),
check('Node', () => new Promise((resolve) => {
resolve(`v${process.versions.node}`);
})),
check('Claude API', async () => {
if (!anthropic) throw new Error('no key');
const r = await anthropic.messages.create({
model: 'claude-opus-4-20250514', max_tokens: 5,
messages: [{ role: 'user', content: 'Say OK' }],
});
return 'connected';
}),
check('Whisper STT', () => new Promise((resolve, reject) => {
exec("which /opt/homebrew/bin/whisper", (err) => {
err ? reject('not found') : resolve('local (base.en)');
});
})),
check('TTS Engine', () => new Promise((resolve, reject) => {
exec("which say", (err) => {
err ? reject('missing') : resolve('macOS native');
});
})),
check('Mindweave Server', () => new Promise((resolve) => {
exec("ssh -o ConnectTimeout=3 -o BatchMode=yes mindweavehq echo ok 2>/dev/null", (err, stdout) => {
resolve(stdout.trim() === 'ok' ? 'reachable' : 'unreachable');
});
})),
]);
return checks;
}
// --- IPC Handlers ---
ipcMain.handle('nova:transcribe', async (event, audioBuffer) => {
const tmpFile = path.join(os.tmpdir(), `nova-${Date.now()}.wav`);
fs.writeFileSync(tmpFile, Buffer.from(audioBuffer));
// Convert webm to wav using ffmpeg, then transcribe
const wavFile = path.join(os.tmpdir(), `nova-${Date.now()}-converted.wav`);
return new Promise((resolve, reject) => {
exec(`ffmpeg -i "${tmpFile}" -ar 16000 -ac 1 -y "${wavFile}" 2>/dev/null`, { timeout: 10000 }, async (err) => {
try { fs.unlinkSync(tmpFile); } catch {}
if (err) {
// Try transcribing the raw file if ffmpeg fails
try {
const text = await transcribeWithWhisper(tmpFile);
resolve(text);
} catch (e) {
reject(new Error('Audio conversion failed'));
}
return;
}
try {
const text = await transcribeWithWhisper(wavFile);
resolve(text);
} catch (e) {
reject(e);
}
});
});
});
ipcMain.handle('nova:chat', async (event, userMessage) => {
if (!anthropic) throw new Error('Anthropic API key not set');
conversationHistory.push({ role: 'user', content: userMessage });
if (conversationHistory.length > 20) {
conversationHistory = conversationHistory.slice(-20);
}
const response = await anthropic.messages.create({
model: 'claude-opus-4-20250514',
max_tokens: 200,
system: SYSTEM_PROMPT,
messages: conversationHistory,
});
const text = response.content[0].text;
conversationHistory.push({ role: 'assistant', content: text });
return text;
});
ipcMain.handle('nova:execute', async (event, command) => {
return new Promise((resolve) => {
exec(command, {
timeout: 30000,
maxBuffer: 1024 * 1024,
env: { ...process.env, PATH: process.env.PATH + ':/usr/local/bin:/opt/homebrew/bin' },
}, (error, stdout, stderr) => {
resolve({
stdout: stdout.trim(),
stderr: stderr.trim(),
exitCode: error ? error.code || 1 : 0,
});
});
});
});
let playProcess = null;
ipcMain.handle('nova:speak', async (event, text) => {
// Kill any current speech
if (sayProcess) { sayProcess.kill('SIGKILL'); sayProcess = null; }
if (playProcess) { playProcess.kill('SIGKILL'); playProcess = null; }
const voice = process.env.NOVA_VOICE || 'en-US-JennyNeural';
const rate = process.env.NOVA_RATE || '+5%';
const mp3File = path.join(os.tmpdir(), `nova-tts-${Date.now()}.mp3`);
mainWindow?.webContents.send('nova:speaking-started');
return new Promise((resolve) => {
// Generate speech with edge-tts
exec(
`edge-tts --voice "${voice}" --rate="${rate}" --text "${text.replace(/"/g, '\\"')}" --write-media "${mp3File}"`,
{ timeout: 15000 },
(err) => {
if (err) {
// Fallback to macOS say
sayProcess = execFile('say', ['-r', '195', text], () => {
sayProcess = null;
mainWindow?.webContents.send('nova:speaking-ended');
resolve(true);
});
return;
}
// Play the mp3
playProcess = execFile('afplay', [mp3File], () => {
playProcess = null;
try { fs.unlinkSync(mp3File); } catch {}
mainWindow?.webContents.send('nova:speaking-ended');
resolve(true);
});
}
);
});
});
ipcMain.handle('nova:stop-speaking', async () => {
let stopped = false;
if (sayProcess) { sayProcess.kill('SIGKILL'); sayProcess = null; stopped = true; }
if (playProcess) { playProcess.kill('SIGKILL'); playProcess = null; stopped = true; }
if (stopped) mainWindow?.webContents.send('nova:speaking-ended');
return stopped;
});
ipcMain.handle('nova:boot-diagnostics', async () => {
return await runBootDiagnostics();
});
ipcMain.handle('nova:metrics', async () => {
const cpuUsage = await new Promise((resolve) => {
exec("ps -A -o %cpu | awk '{s+=$1} END {printf \"%.0f\", s}'", (err, stdout) => {
const total = parseFloat(stdout) || 0;
resolve(Math.min(Math.round(total / os.cpus().length), 100));
});
});
const totalMem = os.totalmem();
const freeMem = os.freemem();
const ramPct = Math.round(((totalMem - freeMem) / totalMem) * 100);
const disk = await new Promise((resolve) => {
exec("df -h / | tail -1 | awk '{print $5}'", (err, stdout) => {
resolve(parseInt(stdout) || 0);
});
});
const net = await new Promise((resolve) => {
exec("ping -c 1 -t 2 8.8.8.8 2>/dev/null | grep time= | sed 's/.*time=\\([0-9.]*\\).*/\\1/'", (err, stdout) => {
const ms = parseFloat(stdout);
resolve(isNaN(ms) ? -1 : Math.round(ms));
});
});
return { cpu: cpuUsage, ram: ramPct, disk, net };
});
ipcMain.handle('nova:check-config', async () => {
return {
hasClaude: !!process.env.ANTHROPIC_API_KEY,
voice: process.env.NOVA_VOICE || 'Samantha',
};
});
// --- App Lifecycle ---
app.whenReady().then(() => {
initAPIs();
createWindow();
globalShortcut.register('Alt+Space', () => {
mainWindow?.webContents.send('nova:toggle-listen');
mainWindow?.focus();
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('will-quit', () => {
globalShortcut.unregisterAll();
if (sayProcess) sayProcess.kill('SIGKILL');
});
app.on('window-all-closed', () => {
app.quit();
});