-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathserver.js
More file actions
5243 lines (4797 loc) · 200 KB
/
server.js
File metadata and controls
5243 lines (4797 loc) · 200 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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require('dotenv').config();
const https = require('https');
const express = require('express');
const helmet = require('helmet');
const fs = require('fs');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const { execFile, spawn } = require('child_process');
const pty = require('node-pty');
const { WebSocketServer } = require('ws');
const rateLimit = require('express-rate-limit');
const yaml = require('js-yaml');
const Database = require('better-sqlite3');
const { getConfig } = require('./lib/hci-config');
const {
mergeSessionsFromSources,
parseHermesSessionsList,
} = require('./lib/session-list');
// ── TUI Gateway Bridge ──
const { getBridge, killAllBridges } = require('./lib/tui-gateway-bridge');
// ── LLM Pricing (via @pydantic/genai-prices) ──
const { calcPrice } = require('@pydantic/genai-prices');
// Free models (no cost regardless of pricing data)
const FREE_MODELS = new Set([
'xiaomi/mimo-v2-pro',
'mimo-v2-pro',
]);
// Hermes billing_provider → genai-prices providerId mapping
const PROVIDER_MAP = {
'openrouter': 'openrouter',
'openai-codex': 'openai',
'opencode-go': 'openrouter', // minimax available via OpenRouter pricing
};
// Custom pricing for models not in genai-prices (per million tokens)
const CUSTOM_PRICING = {
'minimax-m2': { input_mtok: 0.30, output_mtok: 1.20, cache_read_mtok: 0.03 },
'minimax-m2.7': { input_mtok: 0.30, output_mtok: 1.20, cache_read_mtok: 0.03 },
};
// Calculate cost in USD from token counts
function calculateCost(model, inputTokens, outputTokens, cacheReadTokens = 0, billingProvider) {
if (!model || FREE_MODELS.has(model)) return 0;
// genai-prices expects input_tokens = total input (including cache)
// Our DB stores input and cache separately, so combine them
const usage = {
input_tokens: inputTokens + cacheReadTokens,
output_tokens: outputTokens,
cache_read_tokens: cacheReadTokens,
};
// 1. Try with provider hint
const providerId = PROVIDER_MAP[billingProvider];
if (providerId) {
try {
const r = calcPrice(usage, model, { providerId });
if (r) return r.total_price;
} catch (_) { /* fallback to next */ }
}
// 2. Try without provider (match across all providers)
try {
const r = calcPrice(usage, model);
if (r) return r.total_price;
} catch (_) { /* fallback to custom pricing */ }
// 3. Custom pricing fallback
const custom = CUSTOM_PRICING[model];
if (custom) {
return (inputTokens / 1e6) * custom.input_mtok
+ (outputTokens / 1e6) * custom.output_mtok
+ (cacheReadTokens / 1e6) * (custom.cache_read_mtok || custom.input_mtok * 0.1);
}
return 0;
}
// Async shell execution utility (non-blocking)
function parseShellTimeout(value) {
if (typeof value === 'number' && Number.isFinite(value)) return value;
const raw = String(value || '8s').trim();
const match = raw.match(/^(\d+)(ms|s|m)?$/i);
if (!match) return 8000;
const amount = Number(match[1]);
const unit = (match[2] || 'ms').toLowerCase();
if (unit === 'm') return amount * 60_000;
if (unit === 's') return amount * 1_000;
return amount;
}
function shell(cmd, timeout = '8s') {
return new Promise((resolve) => {
execFile('bash', ['-lc', `${cmd} 2>&1`], {
encoding: 'utf8',
maxBuffer: 64 * 1024,
timeout: parseShellTimeout(timeout),
}, (err, stdout, stderr) => {
resolve((stdout || stderr || '').trim());
});
});
}
// Safer execution — no bash interpretation, direct args
// Optional stdin: pipe data to the process (e.g. 'y' for confirmation prompts)
function execHermes(args, timeout = 30000, stdin = null) {
return new Promise((resolve) => {
const proc = execFile('hermes', args, {
encoding: 'utf8',
maxBuffer: 64 * 1024,
timeout,
}, (err, stdout, stderr) => {
// stderr often contains real error messages hermes doesn't write to stdout
const output = err ? (stdout + '\n' + stderr) : stdout;
resolve(output);
});
if (stdin && proc.stdin) {
proc.stdin.write(stdin);
proc.stdin.end();
}
});
}
// ── Load HCI config (hci.config.yaml + env overrides) ──
const cfg = getConfig();
const PORT = cfg.port;
const CONTROL_PASSWORD = cfg.password;
const CONTROL_SECRET = cfg.secret;
const AUTH_COOKIE = cfg.session.cookieName;
const PROJECT_ROOT = __dirname;
const PROJECTS_ROOT = cfg.projectsRoot;
// Dynamic identity — works for root and non-root users
const HCI_USER = os.userInfo().username;
const HCI_HOST = os.hostname();
const HCI_IDENTITY = `${HCI_USER}@${HCI_HOST}`;
const IS_ROOT = process.getuid() === 0;
// systemctl/journalctl: add --user flag for non-root
const SYSTEMD_USER_FLAG = IS_ROOT ? '' : '--user';
// XDG_RUNTIME_DIR: required for systemctl --user to work
// Auto-detect if not set (e.g. running via sudo -u without login session)
if (!IS_ROOT && !process.env.XDG_RUNTIME_DIR) {
const uid = process.getuid();
const runtimeDir = `/run/user/${uid}`;
if (fs.existsSync(runtimeDir)) {
process.env.XDG_RUNTIME_DIR = runtimeDir;
}
}
// Cookie helper — conditionally adds Secure flag for HTTPS
function setAuthCookie(res, token, maxAge = cfg.session.cookieMaxAge) {
const secure = cfg.session.secure !== null
? cfg.session.secure
: res.req?.secure || res.req?.get('X-Forwarded-Proto') === 'https';
res.setHeader('Set-Cookie', `${AUTH_COOKIE}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${maxAge}${secure ? '; Secure' : ''}`);
}
function clearAuthCookie(res) {
res.setHeader('Set-Cookie', `${AUTH_COOKIE}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`);
}
const CONTROL_HOME = cfg.hermesHome;
const CONTROL_STATE_DIR = path.join(CONTROL_HOME, 'control-interface');
const AVATAR_OVERRIDE_PATH = path.join(CONTROL_STATE_DIR, 'avatar.dataurl');
const STATE_DB_PATH = path.join(CONTROL_HOME, 'state.db');
// Explorer roots — already parsed by hci-config.js
const ROOTS = cfg.roots;
const IGNORED_DIRS = new Set([
'node_modules', '.git', 'cache', 'document_cache', 'audio_cache', 'checkpoints', 'logs', 'tmp', '.next', '.turbo', '.cache',
]);
if (!CONTROL_PASSWORD || !CONTROL_SECRET) {
throw new Error('Missing HERMES_CONTROL_PASSWORD or HERMES_CONTROL_SECRET environment variables');
}
const app = express();
// Security headers — safe config (no HSTS, CSP allows Google Fonts)
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net"],
scriptSrcAttr: ["'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://cdn.jsdelivr.net"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
imgSrc: ["'self'", "data:", "blob:", "https://portal.nousresearch.com"],
connectSrc: ["'self'", "ws:", "wss:"],
upgradeInsecureRequests: null,
},
},
hsts: false,
}));
app.use(express.json({ limit: '1mb' }));
// Vite-built assets have content hashes — safe to cache aggressively
app.use(express.static(path.join(__dirname, 'dist'), {
maxAge: '365d',
immutable: true,
setHeaders: (res, filePath) => {
// HTML files should NEVER be cached (they reference hashed assets)
if (filePath.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
}
},
}));
// API responses should NEVER be cached
app.use('/api', (req, res, next) => {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
next();
});
app.use('/vendor/xterm', express.static(path.join(__dirname, 'node_modules/@xterm/xterm'), { maxAge: '30d' }));
app.use('/vendor/xterm-addon-fit', express.static(path.join(__dirname, 'node_modules/@xterm/addon-fit'), { maxAge: '30d' }));
// ── Plugin System ──
// Scan ~/.hermes/skills/*/ui/manifest.json for plugin registrations
function findPluginManifests() {
const skillsDir = path.join(os.homedir(), '.hermes', 'skills');
const manifests = [];
if (!fs.existsSync(skillsDir)) return manifests;
try {
const categories = fs.readdirSync(skillsDir);
for (const cat of categories) {
const catDir = path.join(skillsDir, cat);
if (!fs.statSync(catDir).isDirectory()) continue;
try {
const skills = fs.readdirSync(catDir);
for (const skill of skills) {
const manifestPath = path.join(catDir, skill, 'ui', 'manifest.json');
if (fs.existsSync(manifestPath)) {
try {
const plugin = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
plugin.path = path.join(catDir, skill);
plugin.uiPath = path.join(catDir, skill, 'ui');
plugin.status = plugin.premium ? 'locked' : 'active';
manifests.push(plugin);
} catch (e) { log('plugin.parse', `Failed to parse ${manifestPath}: ${e.message}`); }
}
}
} catch {}
}
} catch {}
return manifests;
}
// List plugins API
app.get('/api/plugins', requireRole('admin'), (req, res) => {
const plugins = findPluginManifests().map(p => ({
id: p.id,
name: p.name,
version: p.version,
description: p.description,
icon: p.icon || '📦',
pages: p.pages || [],
status: p.status,
premium: p.premium || false,
price: p.price || null,
}));
res.json({ ok: true, plugins });
});
// Serve plugin static files (UI assets)
app.use('/plugins/:id', (req, res, next) => {
const plugins = findPluginManifests();
const plugin = plugins.find(p => p.id === req.params.id);
if (!plugin) return res.status(404).json({ error: 'plugin not found' });
if (plugin.status === 'locked') return res.status(402).json({ error: 'premium required', price: plugin.price });
express.static(plugin.uiPath, { maxAge: '1h' })(req, res, next);
});
const events = [];
// ── Chat System — uses real hermes sessions from state.db ──
// No in-memory chat sessions — sidebar shows actual hermes sessions
// Sending a message uses --resume with the real hermes session ID
// ── Gateway API Proxy (fast, structured events) ────────────────────
// Gateway API key: explicit config → auto-discover from hermes config.yaml
const GATEWAY_API_KEY = cfg.gatewayApiKey || loadGatewayApiKey();
const HERMES_HOME = process.env.HERMES_HOME || path.join(os.homedir(), '.hermes');
// Load gateway API key from default profile config.yaml
function loadGatewayApiKey() {
try {
const yaml = require('js-yaml');
const configPath = path.join(os.homedir(), '.hermes', 'config.yaml');
if (fs.existsSync(configPath)) {
const cfg = yaml.load(fs.readFileSync(configPath, 'utf8'));
return cfg?.platforms?.api_server?.extra?.key || '';
}
} catch {}
return '';
}
// Resolve CORS origins for gateway config injection
// Priority: explicit config → HCI_CORS_ORIGINS env var → auto-detect from request
function resolveCorsOrigins(req) {
// If loaded from config/env, use it directly (already comma-separated string)
if (cfg.corsOrigins) return cfg.corsOrigins;
// If env var set, use it directly (comma-separated)
if (process.env.HCI_CORS_ORIGINS) return process.env.HCI_CORS_ORIGINS;
// Auto-detect from the incoming request origin
const origin = req?.headers?.origin || req?.get?.('origin') || '';
if (origin) return origin;
// Defaults: localhost common dev ports
return 'http://localhost:3000,http://localhost:5173,http://localhost:10272,http://127.0.0.1:3000,http://127.0.0.1:5173,http://127.0.0.1:10272';
}
// Dynamic profile → Gateway API port discovery
// Scans ~/.hermes/config.yaml (default) + ~/.hermes/profiles/*/config.yaml
function discoverGatewayPorts() {
const ports = {};
const baseHermesHome = path.join(os.homedir(), '.hermes');
try {
// Default profile: ~/.hermes/config.yaml (base, not HERMES_HOME which may be profile-specific)
const defaultConf = fs.readFileSync(path.join(baseHermesHome, 'config.yaml'), 'utf8');
const defaultCfg = yaml.load(defaultConf);
// Check both platforms.api_server (injected) and top-level api_server (legacy)
const ds = defaultCfg.platforms?.api_server || defaultCfg.api_server;
if (ds?.enabled && ds?.extra?.port) {
ports['default'] = ds.extra.port;
}
} catch (_) { /* no default config */ }
// Other profiles: ~/.hermes/profiles/<name>/config.yaml
const profilesDir = path.join(baseHermesHome, 'profiles');
try {
for (const name of fs.readdirSync(profilesDir)) {
try {
const confPath = path.join(profilesDir, name, 'config.yaml');
const raw = fs.readFileSync(confPath, 'utf8');
const cfg = yaml.load(raw);
const apiSrv = cfg.platforms?.api_server || cfg.api_server;
if (apiSrv?.enabled && apiSrv?.extra?.port) {
ports[name] = apiSrv.extra.port;
}
} catch (_) { /* skip broken config */ }
}
} catch (_) { /* no profiles dir */ }
return ports;
}
let gatewayPorts = discoverGatewayPorts();
console.log('[Gateway] Discovered ports:', gatewayPorts);
// Refresh on config changes (watch profiles dir)
try {
fs.watch(path.join(HERMES_HOME, 'profiles'), { recursive: true }, (event, filename) => {
if (filename?.endsWith('config.yaml')) {
gatewayPorts = discoverGatewayPorts();
console.log('[Gateway] Ports refreshed:', gatewayPorts);
}
});
} catch (_) { /* fs.watch not supported */ }
function getGatewayBase(profile) {
const port = gatewayPorts[profile] || gatewayPorts['default'];
if (!port) return null; // no gateway api available
return `http://127.0.0.1:${port}`;
}
// Probe gateway health endpoint directly (works without systemd)
// Returns { ok: boolean, managedBy: 'api' | 'systemd' | 'unknown' }
async function probeGatewayHealth(profile) {
const base = getGatewayBase(profile);
if (base) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 3000);
const res = await fetch(`${base}/health`, { signal: controller.signal });
clearTimeout(timeout);
if (res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: data.status === 'ok' || res.status === 200, managedBy: 'api', port: gatewayPorts[profile] || gatewayPorts['default'] };
}
} catch {}
}
// Fallback: check systemctl
try {
const SYSTEMD_USER_FLAG = process.getuid?.() === 0 ? '' : '--user ';
const svc = `hermes-gateway${profile !== 'default' ? `-${profile}` : ''}`;
const check = await shell(`systemctl ${SYSTEMD_USER_FLAG} is-active ${svc} 2>/dev/null || echo inactive`);
if (check.trim() === 'active') return { ok: true, managedBy: 'systemd' };
} catch {}
return { ok: false, managedBy: base ? 'api' : 'unknown' };
}
// Read default model from profile config.yaml
function getDefaultModel(profile) {
const baseHermesHome = path.join(os.homedir(), '.hermes');
try {
const configPath = profile === 'default'
? path.join(baseHermesHome, 'config.yaml')
: path.join(baseHermesHome, 'profiles', profile, 'config.yaml');
if (fs.existsSync(configPath)) {
const cfg = yaml.load(fs.readFileSync(configPath, 'utf8'));
return cfg?.model?.default || cfg?.model || 'moonshotai/kimi-k2.6';
}
} catch (_) { /* fallback */ }
return 'moonshotai/kimi-k2.6';
}
// GET /api/gateway/ports — discovered gateway API ports per profile
app.get('/api/gateway/ports', requireAuth, (req, res) => {
res.json({ ports: gatewayPorts, profiles: Object.keys(gatewayPorts) });
});
// POST /api/gateway/responses — start a new agent run via Gateway API
app.post('/api/gateway/responses', requireAuth, requirePerm('chat.use'), async (req, res) => {
const { message, profile, session_id, model, stream = true } = req.body || {};
if (!message || typeof message !== 'string') return res.status(400).json({ error: 'message required' });
console.log(`[GatewayChat] profile="${profile || 'default'}", available ports:`, gatewayPorts);
try {
const gatewayBase = getGatewayBase(profile || 'default');
if (!gatewayBase) {
console.log(`[GatewayChat] No gateway for profile "${profile || 'default'}", falling back`);
return res.status(503).json({ error: 'Gateway API not available for profile: ' + (profile || 'default') });
}
console.log(`[GatewayChat] Routing to ${gatewayBase}/v1/responses`);
const gatewayBody = {
model: model || getDefaultModel(profile || 'default'),
input: message,
stream,
};
// Use X-Hermes-Session-Id header for conversation continuity
const gwHeaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${GATEWAY_API_KEY}`,
};
if (session_id) {
gwHeaders['X-Hermes-Session-Id'] = session_id;
}
const gatewayRes = await fetch(`${gatewayBase}/v1/responses`, {
method: 'POST',
headers: gwHeaders,
body: JSON.stringify(gatewayBody),
});
console.log(`[GatewayChat] Response status: ${gatewayRes.status}`);
if (!gatewayRes.ok) {
const errText = await gatewayRes.text();
console.log(`[GatewayChat] Gateway error: ${errText}`);
return res.status(gatewayRes.status).json({ error: `Gateway error: ${errText}` });
}
// Extract Hermes session ID from Gateway response headers
const hermesSessionId = gatewayRes.headers.get('x-hermes-session-id') || '';
if (!stream) {
const data = await gatewayRes.json();
if (hermesSessionId) data._hermes_session_id = hermesSessionId;
return res.json(data);
}
// Streaming: proxy SSE events to client using Web ReadableStream API
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no',
...(hermesSessionId ? { 'X-Hermes-Session-Id': hermesSessionId } : {}),
});
// Inject session ID as first SSE event so frontend can pick it up
if (hermesSessionId) {
res.write(`event: hci.session\ndata: ${JSON.stringify({ type: 'hci.session', session_id: hermesSessionId })}\n\n`);
}
const webReader = gatewayRes.body.getReader();
const decoder = new TextDecoder();
let aborted = false;
// Client abort → cancel gateway stream
req.on('close', () => {
aborted = true;
webReader.cancel().catch(() => {});
});
// Pipe chunks from Gateway to client
(async () => {
try {
while (!aborted) {
const { done, value } = await webReader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
res.write(chunk);
}
} catch (pipeErr) {
console.error('[Gateway proxy] pipe error:', pipeErr.message);
} finally {
res.end();
}
})();
} catch (e) {
console.error('[Gateway proxy] error:', e.message);
if (!res.headersSent) {
return res.status(502).json({ error: `Gateway unavailable: ${e.message}` });
}
res.end();
}
});
app.post('/api/chat/send', requireAuth, requirePerm('chat.use'), async (req, res) => {
const { message, profile, sessionId, model } = req.body || {};
if (!message || typeof message !== 'string') return res.status(400).json({ error: 'message required' });
const prof = sanitizeProfileName(profile) || 'default';
// Build hermes command
const escapedMsg = "'" + message.replace(/'/g, "'\\''") + "'";
const profileFlag = prof !== 'default' ? `-p ${prof}` : '';
const modelFlag = model ? `-m ${model}` : '';
// Resume existing session, or create new with empty --continue flag
const resumeFlag = sessionId ? `--resume ${sessionId}` : '--continue ""';
const fullCmd = `hermes chat -Q -q ${escapedMsg} ${profileFlag} ${modelFlag} ${resumeFlag} 2>&1`;
// SSE response
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
const startTime = Date.now();
let fullResponse = '';
try {
const proc = spawn('bash', ['-lc', fullCmd], {
stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, HERMES_HOME: path.join(os.homedir(), '.hermes') },
});
proc.stdout.on('data', (chunk) => {
const text = chunk.toString();
fullResponse += text;
// With -Q flag, output is clean — stream directly
const cleaned = text
.replace(/╭[═─╮][\s\S]*?╰[═─╯][^\n]*\n?/g, '') // safety: strip any remaining banners
.replace(/^Session:\s+\d+.*$/gm, '')
.replace(/^Resume this session with:.*$/gm, '')
.replace(/^Duration:.*$/gm, '')
.replace(/^Messages:.*$/gm, '')
.replace(/^Query:.*$/gm, '')
.replace(/^-{10,}$/gm, '')
.replace(/^Initializing agent.*$/gm, '');
if (cleaned.trim()) {
res.write(`data: ${JSON.stringify({ type: 'token', content: cleaned })}\n\n`);
}
});
proc.stderr.on('data', (chunk) => {
res.write(`data: ${JSON.stringify({ type: 'error', content: chunk.toString() })}\n\n`);
});
proc.on('close', () => {
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
// Extract real hermes session ID from output
const sidMatch = fullResponse.match(/session_id:\s*([0-9]{8}_[0-9]{6}_[a-f0-9]+)/i)
|| fullResponse.match(/Session:\s+([0-9]{8}_[0-9]{6}_[a-f0-9]+)/i);
const newSessionId = sidMatch ? sidMatch[1] : sessionId || '';
res.write(`data: ${JSON.stringify({ type: 'done', sessionId: newSessionId, elapsed: parseFloat(elapsed) })}\n\n`);
res.end();
});
} catch (e) {
res.write(`data: ${JSON.stringify({ type: 'error', content: e.message })}\n\n`);
res.end();
}
});
// POST /api/chat/fork — create a new session forked from a source session up to message_index
app.post('/api/chat/fork', requireAuth, requireCsrf, requirePerm('chat.use'), (req, res) => {
const { sessionId, messageIndex, profile } = req.body || {};
if (!sessionId || typeof sessionId !== 'string') {
return res.status(400).json({ error: 'sessionId required' });
}
if (messageIndex == null || typeof messageIndex !== 'number' || messageIndex < 0) {
return res.status(400).json({ error: 'messageIndex must be a non-negative number' });
}
const prof = sanitizeProfileName(profile) || 'default';
const stateDbPath = getStateDbPath(prof);
if (!fs.existsSync(stateDbPath)) {
return res.status(404).json({ error: 'session store not found for profile: ' + prof });
}
let db;
try {
db = new Database(stateDbPath, { readonly: false });
// Verify source session exists
const sourceSession = db.prepare('SELECT * FROM sessions WHERE id = ?').get(sessionId);
if (!sourceSession) {
return res.status(404).json({ error: 'source session not found' });
}
// Get messages for the source session, ordered by id, up to message_index (inclusive, 0-based)
// We use id <= (SELECT MIN(id) FROM messages WHERE session_id = ? AND rowid > ...) approach
// Simpler: grab all messages for this session sorted by id, slice to messageIndex + 1
const messages = db.prepare(`
SELECT * FROM messages WHERE session_id = ? ORDER BY id ASC
`).all(sessionId);
if (messageIndex >= messages.length) {
return res.status(400).json({ error: 'messageIndex out of range for this session' });
}
const messagesToFork = messages.slice(0, messageIndex + 1);
// Generate new session ID: YYYYMMDD_HHMMSS_randomHex
const now = new Date();
const ts = now.toISOString().replace(/[-:T]/g, '').slice(0, 14).replace(/^(\d{8})(\d{6})$/, '$1_$2_');
const rand = crypto.randomBytes(4).toString('hex');
const newSessionId = ts + rand;
// Calculate message_count for forked session
const forkedMessageCount = messagesToFork.length;
// Copy the source session, but give it a new id and set parent_session_id
db.prepare(`
INSERT INTO sessions (
id, source, user_id, model, model_config, system_prompt,
parent_session_id, started_at, ended_at, end_reason,
message_count, tool_call_count, input_tokens, output_tokens,
cache_read_tokens, cache_write_tokens, reasoning_tokens,
billing_provider, billing_base_url, billing_mode,
estimated_cost_usd, actual_cost_usd, cost_status, cost_source,
pricing_version, title, api_call_count
) VALUES (
@id, @source, @user_id, @model, @model_config, @system_prompt,
@parent_session_id, @started_at, @ended_at, @end_reason,
@message_count, @tool_call_count, @input_tokens, @output_tokens,
@cache_read_tokens, @cache_write_tokens, @reasoning_tokens,
@billing_provider, @billing_base_url, @billing_mode,
@estimated_cost_usd, @actual_cost_usd, @cost_status, @cost_source,
@pricing_version, @title, @api_call_count
)
`).run({
id: newSessionId,
source: sourceSession.source,
user_id: sourceSession.user_id,
model: sourceSession.model,
model_config: sourceSession.model_config,
system_prompt: sourceSession.system_prompt,
parent_session_id: sessionId,
started_at: Date.now() / 1000,
ended_at: null,
end_reason: null,
message_count: forkedMessageCount,
tool_call_count: 0,
input_tokens: 0,
output_tokens: 0,
cache_read_tokens: 0,
cache_write_tokens: 0,
reasoning_tokens: 0,
billing_provider: sourceSession.billing_provider,
billing_base_url: sourceSession.billing_base_url,
billing_mode: sourceSession.billing_mode,
estimated_cost_usd: null,
actual_cost_usd: null,
cost_status: null,
cost_source: null,
pricing_version: sourceSession.pricing_version,
title: sourceSession.title ? (sourceSession.title + ' (fork)') : null,
api_call_count: 0,
});
// Copy messages to the new session
const insertMsg = db.prepare(`
INSERT INTO messages (
session_id, role, content, tool_call_id, tool_calls, tool_name,
timestamp, token_count, finish_reason, reasoning, reasoning_details,
codex_reasoning_items, reasoning_content, codex_message_items
) VALUES (
@session_id, @role, @content, @tool_call_id, @tool_calls, @tool_name,
@timestamp, @token_count, @finish_reason, @reasoning, @reasoning_details,
@codex_reasoning_items, @reasoning_content, @codex_message_items
)
`);
for (const msg of messagesToFork) {
insertMsg.run({
session_id: newSessionId,
role: msg.role,
content: msg.content,
tool_call_id: msg.tool_call_id,
tool_calls: msg.tool_calls,
tool_name: msg.tool_name,
timestamp: msg.timestamp,
token_count: msg.token_count,
finish_reason: msg.finish_reason,
reasoning: msg.reasoning,
reasoning_details: msg.reasoning_details,
codex_reasoning_items: msg.codex_reasoning_items,
reasoning_content: msg.reasoning_content,
codex_message_items: msg.codex_message_items,
});
}
// Invalidate sessions caches so the new session appears
hermesSidebarSessionsCache = { at: 0, data: [] };
hermesAllSessionsCache = { at: 0, data: [] };
res.json({
ok: true,
newSessionId,
forkedSession: {
id: newSessionId,
title: sourceSession.title ? (sourceSession.title + ' (fork)') : null,
parent_session_id: sessionId,
message_count: forkedMessageCount,
model: sourceSession.model,
started_at: Date.now() / 1000,
},
});
} catch (e) {
console.error('[chat.fork] error:', e.message);
res.status(500).json({ error: 'failed to fork session: ' + e.message });
} finally {
if (db) db.close();
}
});
// ── Model Info — read from config.yaml ──
app.get('/api/models', requireAuth, async (req, res) => {
try {
const configPath = path.join(os.homedir(), '.hermes', 'config.yaml');
const configContent = await fs.promises.readFile(configPath, 'utf-8');
const config = yaml.load(configContent) || {};
const modelConfig = config.model || {};
const defaultModel = modelConfig.default || 'unknown';
const provider = modelConfig.provider || 'unknown';
// Return single model info (hermes doesn't expose full model list via CLI)
res.json({
ok: true,
default: defaultModel,
provider: provider,
groups: [{
provider: provider,
models: [defaultModel]
}]
});
} catch (e) {
res.json({ ok: false, error: e.message, groups: [], default: 'auto' });
}
});
// Log streaming state
let logStream = { proc: null, type: null, level: null, clients: new Set() };
let hermesSidebarSessionsCache = { at: 0, data: [] };
const cronJobs = [];
const quickActions = [
{ cmd: 'hermes status', desc: 'Show Hermes health and session status' },
{ cmd: 'hermes skills', desc: 'Inspect installed skills' },
{ cmd: 'hermes cron list', desc: 'List cron jobs' },
{ cmd: 'hermes model', desc: 'Inspect the active model' },
{ cmd: 'hermes config', desc: 'Show Hermes config' },
];
const layoutStorePath = path.join(CONTROL_HOME, 'control-interface-layout.json');
const officeDepartmentsPath = path.join(CONTROL_HOME, 'office-departments.json');
const spriteState = {
state: 'idle',
label: 'ready',
details: 'standing by',
since: Date.now(),
frame: 0,
};
const terminalSession = {
proc: null,
startedAt: null,
buffer: '',
prompt: `${HCI_IDENTITY}:${PROJECT_ROOT}# `,
cwd: PROJECT_ROOT,
ready: false,
lastError: null,
cols: 120,
rows: 32,
};
const AVATAR_IMAGE_PATH = path.join(CONTROL_STATE_DIR, 'default-avatar.jpg');
const DEFAULT_AVATAR_FALLBACK = AVATAR_IMAGE_PATH;
let avatarDataUrlCache = null;
function ensureControlStateDir() {
fs.mkdirSync(CONTROL_STATE_DIR, { recursive: true });
}
function readAvatarOverride() {
try {
return fs.readFileSync(AVATAR_OVERRIDE_PATH, 'utf8').trim();
} catch {
return '';
}
}
function writeAvatarOverride(dataUrl) {
ensureControlStateDir();
fs.writeFileSync(AVATAR_OVERRIDE_PATH, String(dataUrl || ''), 'utf8');
avatarDataUrlCache = String(dataUrl || '');
}
function clearAvatarOverride() {
avatarDataUrlCache = null;
try { fs.unlinkSync(AVATAR_OVERRIDE_PATH); } catch {}
}
function getAvatarDataUrl() {
if (avatarDataUrlCache) return avatarDataUrlCache;
const override = readAvatarOverride();
if (override) {
avatarDataUrlCache = override;
return avatarDataUrlCache;
}
try {
const buf = fs.readFileSync(DEFAULT_AVATAR_FALLBACK);
avatarDataUrlCache = `data:image/jpeg;base64,${buf.toString('base64')}`;
} catch (error) {
log('avatar.missing', error.message || 'avatar image not found');
avatarDataUrlCache = '';
}
return avatarDataUrlCache;
}
function log(kind, message, extra = {}) {
events.push({
id: `${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,
ts: new Date().toISOString(),
kind,
message,
...extra,
});
if (events.length > 100) events.splice(0, events.length - 100);
}
function hmac(value) {
return crypto.createHmac('sha256', CONTROL_SECRET).update(value).digest('hex');
}
function deriveCsrfToken(authToken) {
return hmac('csrf:' + authToken);
}
function verifyCsrfToken(req) {
const headerToken = req.headers['x-csrf-token'];
if (!headerToken) return false;
const cookies = parseCookies(req);
const authToken = cookies[AUTH_COOKIE];
if (!authToken) return false;
const expected = deriveCsrfToken(authToken);
return safeTimingEqual(headerToken, expected);
}
function safeTimingEqual(a, b) {
const ab = Buffer.from(String(a));
const bb = Buffer.from(String(b));
if (ab.length !== bb.length) return false;
return crypto.timingSafeEqual(ab, bb);
}
function verifyAuthToken(token) {
if (!token || typeof token !== 'string') return false;
const [ts, sig] = token.split('.');
if (!ts || !sig) return false;
if (Date.now() - Number(ts) > 24 * 60 * 60 * 1000) return false;
return safeTimingEqual(sig, hmac(ts));
}
function parseCookies(req) {
const raw = req.headers.cookie || '';
return raw.split(';').reduce((acc, pair) => {
const idx = pair.indexOf('=');
if (idx === -1) return acc;
const key = pair.slice(0, idx).trim();
const value = decodeURIComponent(pair.slice(idx + 1).trim());
acc[key] = value;
return acc;
}, {});
}
function isAuthed(req) {
return getCurrentUser(req) !== null;
}
function requireAuth(req, res, next) {
if (isAuthed(req)) return next();
return res.status(401).json({ error: 'authentication required' });
}
function requireCsrf(req, res, next) {
if (!isAuthed(req)) return res.status(401).json({ error: 'authentication required' });
const headerToken = req.headers['x-csrf-token'];
if (!headerToken) return res.status(403).json({ error: 'invalid CSRF token' });
const cookies = parseCookies(req);
const authToken = cookies[AUTH_COOKIE];
if (!authToken) return res.status(403).json({ error: 'invalid CSRF token' });
const expected = deriveCsrfToken(authToken);
if (!safeTimingEqual(headerToken, expected)) return res.status(403).json({ error: 'invalid CSRF token' });
return next();
}
// (setAuthCookie and clearAuthCookie defined above at L37/L40)
function getClientIp(req) {
const fw = req.headers['x-forwarded-for'];
if (fw) return String(fw.split(',')[0]).trim();
return req.socket.remoteAddress || req.ip || 'unknown';
}
// Rate limiter: block an IP after 5 failed login attempts within 15 minutes
// Each failed password check also increments the counter via the handler below
const loginRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 attempts per window
keyGenerator: (req) => getClientIp(req),
handler: (req, res) => {
log('auth.rate_limited', `ip ${getClientIp(req)}`);
res.status(429).json({
ok: false,
error: 'too many failed attempts, try again in 15 minutes',
});
},
standardHeaders: true, // Return rate limit info in `RateLimit-*` headers
legacyHeaders: false,
});
// Terminal exec rate limiter — 30 commands/minute per IP
const terminalRateLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 30, // 30 commands per minute per IP
keyGenerator: (req) => getClientIp(req),
handler: (req, res) => {
log('terminal.rate_limited', `ip ${getClientIp(req)}`);
res.status(429).json({ ok: false, error: 'too many terminal commands, slow down' });
},
standardHeaders: true,
legacyHeaders: false,
});
function trimTerminalBuffer(text, limit = 50000) {
const raw = String(text || '');
return raw.length > limit ? raw.slice(raw.length - limit) : raw;
}
function broadcastToClients(message) {
const payload = JSON.stringify(message);
for (const client of wss?.clients || []) {
if (client.readyState === 1 && client.authed) client.send(payload);
}
}
function startLogStream(logType, level, socket) {
// Kill existing stream
stopLogStream();
const args = ['logs', logType || 'agent', '-f', '-n', '200'];
if (level) args.push('--level', level);
logStream.proc = spawn('hermes', args, { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PYTHONUNBUFFERED: '1' } });
logStream.type = logType || 'agent';
logStream.level = level || 'all';
logStream.clients.add(socket);
let buffer = '';
let flushTimer = null;
const flush = () => {
if (buffer && socket.readyState === 1) {
socket.send(JSON.stringify({ type: 'log-stream', logType: logStream.type, data: buffer }));
buffer = '';
}
flushTimer = null;
};
logStream.proc.stdout.on('data', (chunk) => {
buffer += chunk.toString();
if (!flushTimer) flushTimer = setTimeout(flush, 200);
});
logStream.proc.stderr.on('data', (chunk) => {
buffer += chunk.toString();
if (!flushTimer) flushTimer = setTimeout(flush, 200);
});
logStream.proc.on('close', () => {
if (flushTimer) clearTimeout(flushTimer);
flush();
logStream.proc = null;
});
// Send initial confirmation