-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathmain.ts
More file actions
630 lines (558 loc) · 17.4 KB
/
Copy pathmain.ts
File metadata and controls
630 lines (558 loc) · 17.4 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/**
* Dorothy - Main Electron Entry Point
*
* This file initializes and wires together all the modular components:
* - Window management and protocol handling
* - Agent state and PTY management
* - IPC handlers for renderer communication
* - External services (Telegram, Slack, HTTP API)
* - MCP orchestrator integration
* - Scheduler for automated tasks
*/
import { app, BrowserWindow } from 'electron';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
// Types
import type { AppSettings, AgentStatus } from './types';
// Constants
import { APP_SETTINGS_FILE } from './constants';
// Core modules
import {
createWindow,
registerProtocolSchemes,
setupProtocolHandler,
getMainWindow,
} from './core/window-manager';
import {
agents,
loadAgents,
saveAgents,
initAgentPty,
handleStatusChangeNotification,
getSuperAgentOutputBuffer,
clearSuperAgentOutputBuffer,
} from './core/agent-manager';
import {
ptyProcesses,
quickPtyProcesses,
skillPtyProcesses,
pluginPtyProcesses,
killAllPty,
writeProgrammaticInput,
} from './core/pty-manager';
import { initTray, destroyTray } from './core/tray-manager';
import { broadcastToAllWindows } from './utils/broadcast';
import { extractStatusLine } from './utils/ansi';
import { scheduleTick } from './utils/agents-tick';
// Services
import { startApiServer } from './services/api-server';
import {
initTelegramBotService,
initTelegramBot as initTelegramBotHandlers,
getTelegramBot,
sendTelegramMessage,
sendSuperAgentResponseToTelegram,
} from './services/telegram-bot';
import {
initSlackBot,
getSlackApp,
getSlackResponseChannel,
getSlackResponseThreadTs,
} from './services/slack-bot';
import {
getClaudeSettings,
getClaudeStats,
getClaudeProjects,
getClaudePlugins,
getClaudeSkills,
getClaudeHistory,
} from './services/claude-service';
import { configureStatusHooks } from './services/hooks-manager';
import {
setupMcpOrchestrator,
registerMcpOrchestratorHandlers,
getMcpOrchestratorPath,
} from './services/mcp-orchestrator';
// Handlers
import { registerIpcHandlers, IpcHandlerDependencies } from './handlers/ipc-handlers';
import { registerSchedulerHandlers } from './handlers/scheduler-handlers';
import { registerAutomationHandlers } from './handlers/automation-handlers';
import { registerCLIPathsHandlers } from './handlers/cli-paths-handlers';
import { registerKanbanHandlers } from './handlers/kanban-handlers';
import { registerVaultHandlers } from './handlers/vault-handlers';
import { registerWorldHandlers } from './handlers/world-handlers';
import { initVaultDb, closeVaultDb } from './services/vault-db';
import { initAutoUpdater, checkForUpdates, setMainWindowGetter } from './services/update-checker';
import { initKanbanAutomation, findMatchingAgent, createAgentForTask, startAgentForTask } from './services/kanban-automation';
// Utils
import {
setMainWindow as setUtilsMainWindow,
sendNotification,
isSuperAgent,
getSuperAgent,
ensureDataDir,
ensureDorothyClaudeMd,
migrateFromClaudeManager,
} from './utils';
// ============== App Settings Management ==============
let appSettings: AppSettings = loadAppSettings();
function loadAppSettings(): AppSettings {
const defaults: AppSettings = {
notificationsEnabled: true,
notifyOnWaiting: true,
notifyOnComplete: true,
notifyOnStop: true,
notifyOnError: true,
telegramEnabled: false,
telegramBotToken: '',
telegramChatId: '',
telegramAuthToken: '',
telegramAuthorizedChatIds: [],
telegramRequireMention: false,
slackEnabled: false,
slackBotToken: '',
slackAppToken: '',
slackSigningSecret: '',
slackChannelId: '',
jiraEnabled: false,
jiraDomain: '',
jiraEmail: '',
jiraApiToken: '',
socialDataEnabled: false,
socialDataApiKey: '',
xPostingEnabled: false,
xApiKey: '',
xApiSecret: '',
xAccessToken: '',
xAccessTokenSecret: '',
tasmaniaEnabled: false,
tasmaniaServerPath: '',
gwsEnabled: false,
gwsSkillsInstalled: false,
verboseModeEnabled: false,
autoCheckUpdates: true,
opencodeEnabled: false,
opencodeDefaultModel: '',
defaultProvider: 'claude',
cliPaths: {
claude: '',
codex: '',
gemini: '',
opencode: '',
pi: '',
gws: '',
gcloud: '',
gh: '',
node: '',
additionalPaths: [],
},
};
try {
if (fs.existsSync(APP_SETTINGS_FILE)) {
const saved = JSON.parse(fs.readFileSync(APP_SETTINGS_FILE, 'utf-8'));
return { ...defaults, ...saved };
}
} catch (err) {
console.error('Failed to load app settings:', err);
}
return defaults;
}
function saveAppSettingsToFile(settings: AppSettings) {
try {
ensureDataDir();
fs.writeFileSync(APP_SETTINGS_FILE, JSON.stringify(settings, null, 2));
} catch (err) {
console.error('Failed to save app settings:', err);
}
}
// ============== Telegram Bot Initialization ==============
function initTelegramBot() {
// First inject dependencies into the Telegram bot service
initTelegramBotService(
agents,
ptyProcesses,
appSettings,
getMainWindow(),
() => getSuperAgent(agents),
saveAgents,
getClaudeStats,
(agent: AgentStatus) => initAgentPty(
agent,
getMainWindow(),
handleStatusChangeNotificationWrapper,
saveAgents
),
saveAppSettingsToFile
);
// Then initialize the bot with handlers
initTelegramBotHandlers();
}
// ============== Notification Handler Wrapper ==============
function handleStatusChangeNotificationWrapper(agent: AgentStatus, newStatus: string) {
handleStatusChangeNotification(
agent,
newStatus,
appSettings,
sendNotification,
(text: string) => sendTelegramMessage(text),
sendSuperAgentResponseToTelegram
);
}
// ============== IPC Handler Dependencies ==============
function createIpcDependencies(): IpcHandlerDependencies {
return {
// State
ptyProcesses,
agents,
skillPtyProcesses,
quickPtyProcesses,
pluginPtyProcesses,
// Functions
getMainWindow,
getAppSettings: () => appSettings,
setAppSettings: (settings: AppSettings) => { appSettings = settings; },
saveAppSettings: saveAppSettingsToFile,
saveAgents,
initAgentPty: (agent: AgentStatus) => initAgentPty(
agent,
getMainWindow(),
handleStatusChangeNotificationWrapper,
saveAgents
),
handleStatusChangeNotification: handleStatusChangeNotificationWrapper,
isSuperAgent,
getMcpOrchestratorPath,
initTelegramBot,
initSlackBot: () => initSlackBot(appSettings, (settings) => {
appSettings = settings;
saveAppSettingsToFile(settings);
}, getMainWindow()),
getTelegramBot,
getSlackApp,
getSuperAgentTelegramTask: () => {
// Import from agent-manager state
const { superAgentTelegramTask } = require('./core/agent-manager');
return superAgentTelegramTask;
},
getSuperAgentOutputBuffer,
setSuperAgentOutputBuffer: (buffer: string[]) => {
// This is handled internally by agent-manager
clearSuperAgentOutputBuffer();
buffer.forEach(item => getSuperAgentOutputBuffer().push(item));
},
// Claude data functions
getClaudeSettings,
getClaudeStats,
getClaudeProjects,
getClaudePlugins,
getClaudeSkills,
getClaudeHistory,
};
}
// ============== API Server Initialization ==============
function initApiServer() {
startApiServer(
getMainWindow(),
appSettings,
getTelegramBot,
getSlackApp,
getSlackResponseChannel(),
getSlackResponseThreadTs(),
handleStatusChangeNotificationWrapper,
sendNotification,
(agent: AgentStatus) => initAgentPty(
agent,
getMainWindow(),
handleStatusChangeNotificationWrapper,
saveAgents
),
() => appSettings
);
}
// ============== App Initialization ==============
// Register protocol schemes before app is ready
registerProtocolSchemes();
app.whenReady().then(async () => {
console.log('App ready, initializing...');
// Ensure data directory exists
ensureDataDir();
// Write Dorothy's CLAUDE.md to ~/.dorothy/ so all spawned agents can load it
ensureDorothyClaudeMd();
// Migrate data from ~/.claude-manager if it exists (rebrand migration)
migrateFromClaudeManager();
// Load agents from disk
loadAgents();
// Setup protocol handler for production
setupProtocolHandler();
// Create the main window
createWindow();
// Set the main window reference in utils
setUtilsMainWindow(getMainWindow());
// Initialize macOS menu bar tray with custom popup panel
initTray();
// Register all IPC handlers
const deps = createIpcDependencies();
registerIpcHandlers(deps);
registerSchedulerHandlers({
agents,
getAppSettings: () => appSettings,
});
registerAutomationHandlers();
registerMcpOrchestratorHandlers();
registerCLIPathsHandlers({
getAppSettings: () => appSettings,
setAppSettings: (settings) => { appSettings = settings; },
saveAppSettings: saveAppSettingsToFile,
});
// Register kanban handlers
registerKanbanHandlers({
getMainWindow,
findMatchingAgent,
createAgentForTask,
startAgent: startAgentForTask,
stopAgent: async (agentId: string) => {
const agent = agents.get(agentId);
if (agent?.ptyId) {
const ptyProcess = ptyProcesses.get(agent.ptyId);
if (ptyProcess) {
// Send Ctrl+C to interrupt
ptyProcess.write('\x03');
}
agent.status = 'idle';
agent.currentTask = undefined;
agent.lastActivity = new Date().toISOString();
saveAgents();
broadcastToAllWindows('agent:status', {
type: 'status',
agentId,
status: 'idle',
timestamp: new Date().toISOString(),
});
}
},
deleteAgent: async (agentId: string) => {
const agent = agents.get(agentId);
if (agent) {
// Stop PTY if running
if (agent.ptyId) {
const ptyProcess = ptyProcesses.get(agent.ptyId);
if (ptyProcess) {
ptyProcess.kill();
}
ptyProcesses.delete(agent.ptyId);
}
// Remove agent
agents.delete(agentId);
saveAgents();
console.log(`Agent ${agentId} deleted`);
}
},
getAgentOutput: (agentId: string) => {
const agent = agents.get(agentId);
return agent?.output || [];
},
});
// Initialize vault database
try {
initVaultDb();
console.log('[Dorothy] Vault database initialized successfully');
} catch (err) {
console.error('[Dorothy] Failed to initialize vault database:', err);
}
// Register vault handlers
try {
registerVaultHandlers({ getMainWindow });
console.log('[Dorothy] Vault handlers registered successfully');
} catch (err) {
console.error('[Dorothy] Failed to register vault handlers:', err);
}
// Register world (generative zone) handlers
registerWorldHandlers({ getMainWindow });
// Initialize kanban automation service
initKanbanAutomation({
agents,
createAgent: async (config) => {
// Create agent directly - similar to agent:create handler
const { v4: uuidv4 } = await import('uuid');
const pty = await import('node-pty');
const id = uuidv4();
const shell = process.env.SHELL || '/bin/zsh';
let cwd = config.projectPath;
if (!fs.existsSync(cwd)) {
cwd = os.homedir();
}
// Always include world-builder skill
const allSkills = [...new Set([...config.skills, 'world-builder'])];
const ptyProcess = pty.spawn(shell, ['-l'], {
name: 'xterm-256color',
cols: 120,
rows: 30,
cwd,
env: {
...process.env as { [key: string]: string },
CLAUDE_SKILLS: allSkills.join(','),
CLAUDE_AGENT_ID: id,
CLAUDE_PROJECT_PATH: config.projectPath,
},
});
const ptyId = uuidv4();
ptyProcesses.set(ptyId, ptyProcess);
const status: AgentStatus = {
id,
status: 'idle',
projectPath: config.projectPath,
skills: allSkills,
output: [],
lastActivity: new Date().toISOString(),
ptyId,
character: config.character || 'robot',
name: config.name || `Agent ${id.slice(0, 4)}`,
skipPermissions: config.skipPermissions || false,
};
agents.set(id, status);
saveAgents();
// Setup PTY event handlers
ptyProcess.onData((data) => {
const agent = agents.get(id);
if (agent) {
agent.output.push(data);
agent.lastActivity = new Date().toISOString();
agent.statusLine = extractStatusLine(agent.output);
}
broadcastToAllWindows('agent:output', {
type: 'output',
agentId: id,
ptyId,
data,
timestamp: new Date().toISOString(),
});
scheduleTick();
});
ptyProcess.onExit(({ exitCode }) => {
const agent = agents.get(id);
if (agent) {
const newStatus = exitCode === 0 ? 'completed' : 'error';
agent.status = newStatus;
agent.lastActivity = new Date().toISOString();
handleStatusChangeNotificationWrapper(agent, newStatus);
}
ptyProcesses.delete(ptyId);
// Emit status event so kanban sync can detect completion
broadcastToAllWindows('agent:status', {
type: 'status',
agentId: id,
status: exitCode === 0 ? 'completed' : 'error',
timestamp: new Date().toISOString(),
});
broadcastToAllWindows('agent:complete', {
type: 'complete',
agentId: id,
ptyId,
exitCode,
timestamp: new Date().toISOString(),
});
scheduleTick();
});
return status;
},
startAgent: async (agentId, prompt) => {
const agent = agents.get(agentId);
if (!agent) throw new Error('Agent not found');
// Initialize PTY if needed
if (!agent.ptyId || !ptyProcesses.has(agent.ptyId)) {
const ptyId = await initAgentPty(
agent,
getMainWindow(),
handleStatusChangeNotificationWrapper,
saveAgents
);
agent.ptyId = ptyId;
}
const ptyProcess = ptyProcesses.get(agent.ptyId);
if (!ptyProcess) throw new Error('PTY not found');
// Build Claude command - always use dangerous mode for kanban tasks
let command = 'claude --dangerously-skip-permissions';
if (appSettings.verboseModeEnabled) {
command += ' --verbose';
}
// Build final prompt with skills
let finalPrompt = prompt;
if (agent.skills && agent.skills.length > 0) {
const skillsList = agent.skills.join(', ');
finalPrompt = `[IMPORTANT: Use these skills for this session: ${skillsList}. Invoke them with /<skill-name> when relevant to the task.] ${prompt}`;
}
const escapedPrompt = finalPrompt.replace(/'/g, "'\\''");
command += ` '${escapedPrompt}'`;
// Update status
agent.status = 'running';
agent.currentTask = prompt.slice(0, 100);
agent.lastActivity = new Date().toISOString();
const workingPath = (agent.worktreePath || agent.projectPath).replace(/'/g, "'\\''");
const fullCommand = `cd '${workingPath}' && ${command}`;
// For long commands, write to a temp script to avoid PTY line-wrapping mangling
if (fullCommand.length > 100) {
const tmpScript = path.join(os.tmpdir(), `claude-agent-${agentId}.sh`);
fs.writeFileSync(tmpScript, `#!/bin/bash\n${fullCommand}\n`, { mode: 0o755 });
writeProgrammaticInput(ptyProcess, `bash '${tmpScript}'`);
} else {
writeProgrammaticInput(ptyProcess, fullCommand);
}
saveAgents();
},
saveAgents,
});
// Initialize services
initTelegramBot();
initSlackBot(appSettings, (settings) => {
appSettings = settings;
saveAppSettingsToFile(settings);
}, getMainWindow());
initApiServer();
// Setup MCP orchestrator and hooks
await setupMcpOrchestrator(appSettings);
await configureStatusHooks();
// Initialize electron-updater (wires up IPC events for progress, downloaded, error)
initAutoUpdater(getMainWindow);
setMainWindowGetter(getMainWindow);
// Auto-check for updates on startup (electron-updater sends 'app:update-available' automatically)
if (appSettings.autoCheckUpdates !== false) {
setTimeout(() => {
checkForUpdates().catch((err) => {
console.error('Auto-update check failed:', err);
});
}, 5000);
}
console.log('App initialization complete');
});
// Quit when all windows are closed (except on macOS)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// Re-create window on macOS when dock icon is clicked
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
setUtilsMainWindow(getMainWindow());
}
});
// Save agents and kill all PTY processes before quitting
app.on('before-quit', () => {
console.log('App quitting, saving agents and killing all PTY processes...');
destroyTray();
saveAgents();
killAllPty();
closeVaultDb();
});
// Handle certificate errors in development
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
if (url.startsWith('https://localhost')) {
event.preventDefault();
callback(true);
} else {
callback(false);
}
});
export { appSettings, getTelegramBot };