-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathchat-server.mjs
More file actions
80 lines (72 loc) · 2.27 KB
/
chat-server.mjs
File metadata and controls
80 lines (72 loc) · 2.27 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
#!/usr/bin/env node
import { join } from 'path';
const http = await import('http');
const [
{ CHAT_PORT, CHAT_BIND_HOST, SECURE_COOKIES, MEMORY_DIR },
{ handleRequest },
apiRequestLog,
usageLedger,
ws,
sessionManager,
triggers,
tools,
{ ensureDir },
embeddedMailWorker,
] = await Promise.all([
import('./lib/config.mjs'),
import('./chat/router.mjs'),
import('./chat/api-request-log.mjs'),
import('./chat/usage-ledger.mjs'),
import('./chat/ws.mjs'),
import('./chat/session-manager.mjs'),
import('./chat/triggers.mjs'),
import('./lib/tools.mjs'),
import('./chat/fs-utils.mjs'),
import('./lib/embedded-mail-worker.mjs'),
]);
for (const dir of [MEMORY_DIR, join(MEMORY_DIR, 'tasks')]) {
await ensureDir(dir);
}
await apiRequestLog.initApiRequestLog();
await usageLedger.initUsageLedger();
await tools.ensureDefaultMicroAgentToolRegistrationAsync();
const server = http.createServer((req, res) => {
const requestLog = apiRequestLog.startApiRequestLog(req, res);
handleRequest(req, res).catch(err => {
requestLog.markError(err);
console.error('Unhandled request error:', err);
if (!res.headersSent) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
}
});
});
ws.attachWebSocket(server);
triggers.startTriggerScheduler();
void (async () => {
try {
await sessionManager.startDetachedRunObservers();
} catch (error) {
console.error('Failed to rehydrate detached runs on startup:', error);
}
})();
const mailWorker = await embeddedMailWorker.startEmbeddedMailWorker({
createSession: sessionManager.createSession,
submitHttpMessage: sessionManager.submitHttpMessage,
saveAttachments: sessionManager.saveAttachments,
});
async function shutdown() {
console.log('Shutting down chat server...');
if (mailWorker) mailWorker.stop();
await apiRequestLog.closeApiRequestLog();
await usageLedger.closeUsageLedger();
triggers.stopTriggerScheduler();
sessionManager.killAll();
process.exit(0);
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
server.listen(CHAT_PORT, CHAT_BIND_HOST, () => {
console.log(`Chat server listening on http://${CHAT_BIND_HOST}:${CHAT_PORT}`);
console.log(`Cookie mode: ${SECURE_COOKIES ? 'Secure (HTTPS)' : 'Non-secure (localhost)'}`);
});