-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathserver.js
More file actions
2545 lines (2243 loc) Β· 81.4 KB
/
server.js
File metadata and controls
2545 lines (2243 loc) Β· 81.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
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
#!/usr/bin/env node
/**
* OpenClaw Command Center Dashboard Server
* Serves the dashboard UI and provides API endpoints for status data
*/
const http = require("http");
const fs = require("fs");
const path = require("path");
const { execSync, exec } = require("child_process");
const { handleJobsRequest, isJobsRoute } = require("./jobs");
const { CONFIG } = require("./config");
const PORT = CONFIG.server.port;
const DASHBOARD_DIR = path.join(__dirname, "../public");
// ============================================================================
// AUTH CONFIGURATION (from config.js)
// ============================================================================
const AUTH_CONFIG = {
mode: CONFIG.auth.mode,
token: CONFIG.auth.token,
allowedUsers: CONFIG.auth.allowedUsers,
allowedIPs: CONFIG.auth.allowedIPs,
publicPaths: CONFIG.auth.publicPaths,
};
// Auth header names
const AUTH_HEADERS = {
tailscale: {
login: "tailscale-user-login",
name: "tailscale-user-name",
pic: "tailscale-user-profile-pic",
},
cloudflare: {
email: "cf-access-authenticated-user-email",
},
};
// ============================================================================
// PATHS CONFIGURATION (from config.js with auto-detection)
// ============================================================================
const PATHS = CONFIG.paths;
// SSE clients for real-time updates
const sseClients = new Set();
function sendSSE(res, event, data) {
try {
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
} catch (e) {
// Client disconnected
}
}
function broadcastSSE(event, data) {
for (const client of sseClients) {
sendSSE(client, event, data);
}
}
const DATA_DIR = path.join(DASHBOARD_DIR, "data");
// ============================================================================
// OPERATORS DATA
// ============================================================================
const OPERATORS_FILE = path.join(DATA_DIR, "operators.json");
function loadOperators() {
try {
if (fs.existsSync(OPERATORS_FILE)) {
return JSON.parse(fs.readFileSync(OPERATORS_FILE, "utf8"));
}
} catch (e) {
console.error("Failed to load operators:", e.message);
}
return { version: 1, operators: [], roles: {} };
}
function saveOperators(data) {
try {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
fs.writeFileSync(OPERATORS_FILE, JSON.stringify(data, null, 2));
return true;
} catch (e) {
console.error("Failed to save operators:", e.message);
return false;
}
}
function getOperatorBySlackId(slackId) {
const data = loadOperators();
return data.operators.find((op) => op.id === slackId || op.metadata?.slackId === slackId);
}
// Extract session originator from transcript
function getSessionOriginator(sessionId) {
try {
if (!sessionId) return null;
const transcriptPath = path.join(
process.env.HOME,
".openclaw",
"agents",
"main",
"sessions",
`${sessionId}.jsonl`,
);
if (!fs.existsSync(transcriptPath)) return null;
const content = fs.readFileSync(transcriptPath, "utf8");
const lines = content.trim().split("\n");
// Find the first user message to extract originator
for (let i = 0; i < Math.min(lines.length, 10); i++) {
try {
const entry = JSON.parse(lines[i]);
if (entry.type !== "message" || !entry.message) continue;
const msg = entry.message;
if (msg.role !== "user") continue;
let text = "";
if (typeof msg.content === "string") {
text = msg.content;
} else if (Array.isArray(msg.content)) {
const textPart = msg.content.find((c) => c.type === "text");
if (textPart) text = textPart.text || "";
}
if (!text) continue;
// Extract Slack user from message patterns:
// Example: "[Slack #channel +6m 2026-01-27 15:31 PST] username (USERID): message"
// Pattern: "username (USERID):" where USERID is the sender's Slack ID
const slackUserMatch = text.match(/\]\s*([\w.-]+)\s*\(([A-Z0-9]+)\):/);
if (slackUserMatch) {
const username = slackUserMatch[1];
const userId = slackUserMatch[2];
const operator = getOperatorBySlackId(userId);
return {
userId,
username,
displayName: operator?.name || username,
role: operator?.role || "user",
avatar: operator?.avatar || null,
};
}
} catch (e) {}
}
return null;
} catch (e) {
return null;
}
}
// Utility functions
function formatBytes(bytes) {
if (bytes >= 1099511627776) return (bytes / 1099511627776).toFixed(1) + " TB";
if (bytes >= 1073741824) return (bytes / 1073741824).toFixed(1) + " GB";
if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + " MB";
if (bytes >= 1024) return (bytes / 1024).toFixed(1) + " KB";
return bytes + " B";
}
function formatTimeAgo(date) {
const now = new Date();
const diffMs = now - date;
const diffMins = Math.round(diffMs / 60000);
if (diffMins < 1) return "just now";
if (diffMins < 60) return `${diffMins}m ago`;
if (diffMins < 1440) return `${Math.round(diffMins / 60)}h ago`;
return `${Math.round(diffMins / 1440)}d ago`;
}
// ============================================================================
// AUTHENTICATION
// ============================================================================
// Check if user is authorized
function checkAuth(req) {
const mode = AUTH_CONFIG.mode;
// Always allow localhost access (for direct physical machine access)
const remoteAddr = req.socket?.remoteAddress || "";
const isLocalhost =
remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1";
if (isLocalhost) {
return { authorized: true, user: { type: "localhost", login: "localhost" } };
}
// No auth mode - allow all
if (mode === "none") {
return { authorized: true, user: null };
}
// Token mode - check Bearer token
if (mode === "token") {
const authHeader = req.headers["authorization"] || "";
const token = authHeader.replace(/^Bearer\s+/i, "");
if (token && token === AUTH_CONFIG.token) {
return { authorized: true, user: { type: "token" } };
}
return { authorized: false, reason: "Invalid or missing token" };
}
// Tailscale mode - check Tailscale-User-Login header
if (mode === "tailscale") {
const login = (req.headers[AUTH_HEADERS.tailscale.login] || "").toLowerCase();
const name = req.headers[AUTH_HEADERS.tailscale.name] || "";
const pic = req.headers[AUTH_HEADERS.tailscale.pic] || "";
if (!login) {
return { authorized: false, reason: "Not accessed via Tailscale Serve" };
}
// Check if user is in allowlist
const isAllowed = AUTH_CONFIG.allowedUsers.some((allowed) => {
if (allowed === "*") return true;
if (allowed === login) return true;
// Support wildcards like *@github
if (allowed.startsWith("*@")) {
const domain = allowed.slice(2);
return login.endsWith("@" + domain);
}
return false;
});
if (isAllowed) {
return { authorized: true, user: { type: "tailscale", login, name, pic } };
}
return { authorized: false, reason: `User ${login} not in allowlist`, user: { login } };
}
// Cloudflare mode - check Cf-Access-Authenticated-User-Email header
if (mode === "cloudflare") {
const email = (req.headers[AUTH_HEADERS.cloudflare.email] || "").toLowerCase();
if (!email) {
return { authorized: false, reason: "Not accessed via Cloudflare Access" };
}
const isAllowed = AUTH_CONFIG.allowedUsers.some((allowed) => {
if (allowed === "*") return true;
if (allowed === email) return true;
if (allowed.startsWith("*@")) {
const domain = allowed.slice(2);
return email.endsWith("@" + domain);
}
return false;
});
if (isAllowed) {
return { authorized: true, user: { type: "cloudflare", email } };
}
return { authorized: false, reason: `User ${email} not in allowlist`, user: { email } };
}
// IP allowlist mode
if (mode === "allowlist") {
const clientIP =
req.headers["x-forwarded-for"]?.split(",")[0]?.trim() || req.socket?.remoteAddress || "";
const isAllowed = AUTH_CONFIG.allowedIPs.some((allowed) => {
if (allowed === clientIP) return true;
// Simple CIDR check for /24
if (allowed.endsWith("/24")) {
const prefix = allowed.slice(0, -3).split(".").slice(0, 3).join(".");
return clientIP.startsWith(prefix + ".");
}
return false;
});
if (isAllowed) {
return { authorized: true, user: { type: "ip", ip: clientIP } };
}
return { authorized: false, reason: `IP ${clientIP} not in allowlist` };
}
return { authorized: false, reason: "Unknown auth mode" };
}
// Generate login/unauthorized page
function getUnauthorizedPage(reason, user) {
const userInfo = user
? `<p class="user-info">Detected: ${user.login || user.email || user.ip || "unknown"}</p>`
: "";
return `<!DOCTYPE html>
<html>
<head>
<title>Access Denied - Command Center</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: #e8e8e8;
}
.container {
text-align: center;
padding: 3rem;
background: rgba(255,255,255,0.05);
border-radius: 16px;
border: 1px solid rgba(255,255,255,0.1);
max-width: 500px;
}
.icon { font-size: 4rem; margin-bottom: 1rem; }
h1 { font-size: 1.8rem; margin-bottom: 1rem; color: #ff6b6b; }
.reason { color: #aaa; margin-bottom: 1.5rem; font-size: 0.95rem; }
.user-info { color: #ffeb3b; margin: 1rem 0; font-size: 0.9rem; }
.instructions { color: #ccc; font-size: 0.85rem; line-height: 1.5; }
.auth-mode { margin-top: 2rem; padding-top: 1rem; border-top: 1px solid rgba(255,255,255,0.1); color: #888; font-size: 0.75rem; }
code { background: rgba(255,255,255,0.1); padding: 2px 6px; border-radius: 4px; }
</style>
</head>
<body>
<div class="container">
<div class="icon">π</div>
<h1>Access Denied</h1>
<div class="reason">${reason}</div>
${userInfo}
<div class="instructions">
<p>This dashboard requires authentication via <strong>${AUTH_CONFIG.mode}</strong>.</p>
${AUTH_CONFIG.mode === "tailscale" ? '<p style="margin-top:1rem">Make sure you\'re accessing via your Tailscale URL and your account is in the allowlist.</p>' : ""}
${AUTH_CONFIG.mode === "cloudflare" ? '<p style="margin-top:1rem">Make sure you\'re accessing via Cloudflare Access and your email is in the allowlist.</p>' : ""}
</div>
<div class="auth-mode">Auth mode: <code>${AUTH_CONFIG.mode}</code></div>
</div>
</body>
</html>`;
}
// Get detailed system vitals (iStatMenus-style)
function getSystemVitals() {
const vitals = {
hostname: "",
uptime: "",
disk: { used: 0, free: 0, total: 0, percent: 0 },
cpu: { loadAvg: [0, 0, 0], cores: 0, usage: 0 },
memory: { used: 0, free: 0, total: 0, percent: 0, pressure: "normal" },
temperature: null,
};
try {
// Hostname
vitals.hostname = execSync("hostname", { encoding: "utf8" }).trim();
// Uptime
const uptimeRaw = execSync("uptime", { encoding: "utf8" });
const uptimeMatch = uptimeRaw.match(/up\s+([^,]+)/);
if (uptimeMatch) vitals.uptime = uptimeMatch[1].trim();
// Load averages from uptime
const loadMatch = uptimeRaw.match(/load averages?:\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/);
if (loadMatch) {
vitals.cpu.loadAvg = [
parseFloat(loadMatch[1]),
parseFloat(loadMatch[2]),
parseFloat(loadMatch[3]),
];
}
// CPU cores and topology
try {
const coresRaw = execSync("sysctl -n hw.ncpu", { encoding: "utf8" });
vitals.cpu.cores = parseInt(coresRaw.trim(), 10);
// Calculate usage as percentage of max load (cores * 1.0)
vitals.cpu.usage = Math.min(
100,
Math.round((vitals.cpu.loadAvg[0] / vitals.cpu.cores) * 100),
);
// Get P-core and E-core counts (Apple Silicon)
try {
const perfCores = execSync("sysctl -n hw.perflevel0.logicalcpu 2>/dev/null || echo 0", {
encoding: "utf8",
});
const effCores = execSync("sysctl -n hw.perflevel1.logicalcpu 2>/dev/null || echo 0", {
encoding: "utf8",
});
vitals.cpu.pCores = parseInt(perfCores.trim(), 10) || null;
vitals.cpu.eCores = parseInt(effCores.trim(), 10) || null;
} catch (e) {}
// Get CPU brand
try {
const brand = execSync('sysctl -n machdep.cpu.brand_string 2>/dev/null || echo ""', {
encoding: "utf8",
}).trim();
if (brand) vitals.cpu.brand = brand;
} catch (e) {}
// Get chip name for Apple Silicon
try {
const chip = execSync(
'system_profiler SPHardwareDataType 2>/dev/null | grep "Chip:" | cut -d: -f2',
{ encoding: "utf8" },
).trim();
if (chip) vitals.cpu.chip = chip;
} catch (e) {}
} catch (e) {}
// Get CPU usage breakdown (user/sys/idle) from top
try {
const topOutput = execSync('top -l 1 -n 0 2>/dev/null | grep "CPU usage"', {
encoding: "utf8",
});
const userMatch = topOutput.match(/([\d.]+)%\s*user/);
const sysMatch = topOutput.match(/([\d.]+)%\s*sys/);
const idleMatch = topOutput.match(/([\d.]+)%\s*idle/);
vitals.cpu.userPercent = userMatch ? parseFloat(userMatch[1]) : null;
vitals.cpu.sysPercent = sysMatch ? parseFloat(sysMatch[1]) : null;
vitals.cpu.idlePercent = idleMatch ? parseFloat(idleMatch[1]) : null;
// Calculate actual usage from user + sys
if (vitals.cpu.userPercent !== null && vitals.cpu.sysPercent !== null) {
vitals.cpu.usage = Math.round(vitals.cpu.userPercent + vitals.cpu.sysPercent);
}
} catch (e) {}
// Disk usage (macOS df - use ~ to get Data volume, not read-only system volume)
try {
const dfRaw = execSync("df -k ~ | tail -1", { encoding: "utf8" });
const dfParts = dfRaw.trim().split(/\s+/);
if (dfParts.length >= 4) {
const totalKb = parseInt(dfParts[1], 10);
const usedKb = parseInt(dfParts[2], 10);
const freeKb = parseInt(dfParts[3], 10);
vitals.disk.total = totalKb * 1024;
vitals.disk.used = usedKb * 1024;
vitals.disk.free = freeKb * 1024;
vitals.disk.percent = Math.round((usedKb / totalKb) * 100);
}
} catch (e) {}
// Disk I/O stats (macOS iostat) - IOPS, throughput, transfer size
try {
// Get 1-second sample from iostat (2 iterations, take the last one for current activity)
const iostatRaw = execSync("iostat -d -c 2 2>/dev/null | tail -1", { encoding: "utf8" });
const iostatParts = iostatRaw.trim().split(/\s+/);
// iostat output: KB/t tps MB/s (repeated for each disk)
// We take the first disk's stats (primary disk)
if (iostatParts.length >= 3) {
vitals.disk.kbPerTransfer = parseFloat(iostatParts[0]) || 0;
vitals.disk.iops = parseFloat(iostatParts[1]) || 0;
vitals.disk.throughputMBps = parseFloat(iostatParts[2]) || 0;
}
} catch (e) {
// iostat may not be available or may fail
vitals.disk.kbPerTransfer = 0;
vitals.disk.iops = 0;
vitals.disk.throughputMBps = 0;
}
// Memory (macOS vm_stat + sysctl)
try {
const memTotalRaw = execSync("sysctl -n hw.memsize", { encoding: "utf8" });
vitals.memory.total = parseInt(memTotalRaw.trim(), 10);
const vmStatRaw = execSync("vm_stat", { encoding: "utf8" });
const pageSize = 16384; // Default macOS page size
// Parse vm_stat
const freeMatch = vmStatRaw.match(/Pages free:\s+(\d+)/);
const activeMatch = vmStatRaw.match(/Pages active:\s+(\d+)/);
const inactiveMatch = vmStatRaw.match(/Pages inactive:\s+(\d+)/);
const wiredMatch = vmStatRaw.match(/Pages wired down:\s+(\d+)/);
const compressedMatch = vmStatRaw.match(/Pages occupied by compressor:\s+(\d+)/);
const freePages = freeMatch ? parseInt(freeMatch[1], 10) : 0;
const activePages = activeMatch ? parseInt(activeMatch[1], 10) : 0;
const inactivePages = inactiveMatch ? parseInt(inactiveMatch[1], 10) : 0;
const wiredPages = wiredMatch ? parseInt(wiredMatch[1], 10) : 0;
const compressedPages = compressedMatch ? parseInt(compressedMatch[1], 10) : 0;
// Used = active + wired + compressed
const usedPages = activePages + wiredPages + compressedPages;
vitals.memory.used = usedPages * pageSize;
vitals.memory.free = vitals.memory.total - vitals.memory.used;
vitals.memory.percent = Math.round((vitals.memory.used / vitals.memory.total) * 100);
// Expose detailed breakdown
vitals.memory.active = activePages * pageSize;
vitals.memory.wired = wiredPages * pageSize;
vitals.memory.compressed = compressedPages * pageSize;
vitals.memory.cached = inactivePages * pageSize;
vitals.memory.pageSize = pageSize;
// Memory pressure (simplified)
const pressureRatio = vitals.memory.used / vitals.memory.total;
if (pressureRatio > 0.9) vitals.memory.pressure = "critical";
else if (pressureRatio > 0.75) vitals.memory.pressure = "warning";
else vitals.memory.pressure = "normal";
} catch (e) {}
// Temperature (macOS - detect Apple Silicon vs Intel)
vitals.temperature = null;
vitals.temperatureNote = null;
// Check if Apple Silicon
const isAppleSilicon = vitals.cpu.chip || vitals.cpu.pCores;
if (isAppleSilicon) {
// Apple Silicon: temperature requires sudo powermetrics
vitals.temperatureNote = "Apple Silicon (requires elevated access)";
// Try to read from powermetrics if available (won't work without sudo)
try {
const pmOutput = execSync(
'timeout 2 sudo -n powermetrics --samplers smc -i 1 -n 1 2>/dev/null | grep -i "die temp" | head -1 || echo ""',
{ encoding: "utf8" },
).trim();
const tempMatch = pmOutput.match(/([\d.]+)/);
if (tempMatch) {
vitals.temperature = parseFloat(tempMatch[1]);
vitals.temperatureNote = null;
}
} catch (e) {}
} else {
// Intel Mac: try osx-cpu-temp
try {
const temp = execSync('osx-cpu-temp 2>/dev/null || echo ""', { encoding: "utf8" }).trim();
if (temp && temp.includes("Β°")) {
const tempMatch = temp.match(/([\d.]+)/);
if (tempMatch && parseFloat(tempMatch[1]) > 0) {
vitals.temperature = parseFloat(tempMatch[1]);
}
}
} catch (e) {}
// Fallback: try ioreg for battery temp
if (!vitals.temperature) {
try {
const ioregRaw = execSync(
'ioreg -r -n AppleSmartBattery 2>/dev/null | grep Temperature || echo ""',
{ encoding: "utf8" },
);
const tempMatch = ioregRaw.match(/"Temperature"\s*=\s*(\d+)/);
if (tempMatch) {
vitals.temperature = Math.round(parseInt(tempMatch[1], 10) / 100);
}
} catch (e) {}
}
}
} catch (e) {
console.error("Failed to get system vitals:", e.message);
}
// Add formatted versions for display
vitals.memory.usedFormatted = formatBytes(vitals.memory.used);
vitals.memory.totalFormatted = formatBytes(vitals.memory.total);
vitals.memory.freeFormatted = formatBytes(vitals.memory.free);
vitals.disk.usedFormatted = formatBytes(vitals.disk.used);
vitals.disk.totalFormatted = formatBytes(vitals.disk.total);
vitals.disk.freeFormatted = formatBytes(vitals.disk.free);
return vitals;
}
// Helper to run openclaw commands
function runOpenClaw(args) {
const profile = process.env.OPENCLAW_PROFILE || "";
const profileFlag = profile ? ` --profile ${profile}` : "";
try {
const result = execSync(`openclaw${profileFlag} ${args}`, {
encoding: "utf8",
timeout: 10000,
env: { ...process.env, NO_COLOR: "1" },
});
return result;
} catch (e) {
console.error(`openclaw${profileFlag} ${args} failed:`, e.message);
return null;
}
}
// Topic patterns for session classification
// Each topic maps to an array of keywords - more specific keywords = higher relevance
const TOPIC_PATTERNS = {
// Core system topics
dashboard: ["dashboard", "command center", "ui", "interface", "status page"],
scheduling: ["cron", "schedule", "timer", "reminder", "alarm", "periodic", "interval"],
heartbeat: [
"heartbeat",
"heartbeat_ok",
"poll",
"health check",
"ping",
"keepalive",
"monitoring",
],
memory: ["memory", "remember", "recall", "notes", "journal", "log", "context"],
// Communication channels
Slack: ["slack", "channel", "#cc-", "thread", "mention", "dm", "workspace"],
email: ["email", "mail", "inbox", "gmail", "send email", "unread", "compose"],
calendar: ["calendar", "event", "meeting", "appointment", "schedule", "gcal"],
// Development topics
coding: [
"code",
"script",
"function",
"debug",
"error",
"bug",
"implement",
"refactor",
"programming",
],
git: [
"git",
"commit",
"branch",
"merge",
"push",
"pull",
"repository",
"pr",
"pull request",
"github",
],
"file editing": ["file", "edit", "write", "read", "create", "delete", "modify", "save"],
API: ["api", "endpoint", "request", "response", "webhook", "integration", "rest", "graphql"],
// Research & web
research: ["search", "research", "lookup", "find", "investigate", "learn", "study"],
browser: ["browser", "webpage", "website", "url", "click", "navigate", "screenshot", "web_fetch"],
"Quip export": ["quip", "export", "document", "spreadsheet"],
// Domain-specific
finance: ["finance", "investment", "stock", "money", "budget", "bank", "trading", "portfolio"],
home: ["home", "automation", "lights", "thermostat", "smart home", "iot", "homekit"],
health: ["health", "fitness", "workout", "exercise", "weight", "sleep", "nutrition"],
travel: ["travel", "flight", "hotel", "trip", "vacation", "booking", "airport"],
food: ["food", "recipe", "restaurant", "cooking", "meal", "order", "delivery"],
// Agent operations
subagent: ["subagent", "spawn", "sub-agent", "delegate", "worker", "parallel"],
tools: ["tool", "exec", "shell", "command", "terminal", "bash", "run"],
};
/**
* Detect topics from text content
* @param {string} text - Text to analyze
* @returns {string[]} - Array of detected topics (may be empty)
*/
function detectTopics(text) {
if (!text) return [];
const lowerText = text.toLowerCase();
// Score each topic based on keyword matches
const scores = {};
for (const [topic, keywords] of Object.entries(TOPIC_PATTERNS)) {
let score = 0;
for (const keyword of keywords) {
// Check for keyword presence (word boundary aware for short keywords)
if (keyword.length <= 3) {
// Short keywords need word boundaries to avoid false positives
const regex = new RegExp(`\\b${keyword}\\b`, "i");
if (regex.test(lowerText)) score++;
} else if (lowerText.includes(keyword)) {
score++;
}
}
if (score > 0) {
scores[topic] = score;
}
}
// No matches
if (Object.keys(scores).length === 0) return [];
// Find best score
const bestScore = Math.max(...Object.values(scores));
// Include all topics with score >= 2 OR >= 50% of best score
const threshold = Math.max(2, bestScore * 0.5);
return Object.entries(scores)
.filter(([_, score]) => score >= threshold || (score >= 1 && bestScore <= 2))
.sort((a, b) => b[1] - a[1])
.map(([topic, _]) => topic);
}
// Channel ID to name mapping (auto-populated from Slack)
const CHANNEL_MAP = {
c0aax7y80np: "#cc-meta",
c0ab9f8sdfe: "#cc-research",
c0aan4rq7v5: "#cc-finance",
c0abxulk1qq: "#cc-properties",
c0ab5nz8mkl: "#cc-ai",
c0aan38tzv5: "#cc-dev",
c0ab7wwhqvc: "#cc-home",
c0ab1pjhxef: "#cc-health",
c0ab7txvcqd: "#cc-legal",
c0aay2g3n3r: "#cc-social",
c0aaxrw2wqp: "#cc-business",
c0ab19f3lae: "#cc-random",
c0ab0r74y33: "#cc-food",
c0ab0qrq3r9: "#cc-travel",
c0ab0sbqqlg: "#cc-family",
c0ab0slqdba: "#cc-games",
c0ab1ps7ef2: "#cc-music",
c0absbnrsbe: "#cc-dashboard",
};
// Parse session key into readable label
function parseSessionLabel(key) {
// Pattern: agent:main:slack:channel:CHANNEL_ID:thread:TIMESTAMP
// or: agent:main:slack:channel:CHANNEL_ID
// or: agent:main:main (telegram main)
const parts = key.split(":");
if (parts.includes("slack")) {
const channelIdx = parts.indexOf("channel");
if (channelIdx >= 0 && parts[channelIdx + 1]) {
const channelId = parts[channelIdx + 1].toLowerCase();
const channelName = CHANNEL_MAP[channelId] || `#${channelId}`;
// Check if it's a thread
if (parts.includes("thread")) {
const threadTs = parts[parts.indexOf("thread") + 1];
// Convert timestamp to rough time
const ts = parseFloat(threadTs);
const date = new Date(ts * 1000);
const timeStr = date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
return `${channelName} thread @ ${timeStr}`;
}
return channelName;
}
}
if (key.includes("telegram")) {
return "π± Telegram";
}
if (key === "agent:main:main") {
return "π Main Session";
}
// Fallback: truncate key
return key.length > 40 ? key.slice(0, 37) + "..." : key;
}
// Get sessions data
/**
* Get quick topic for a session by reading first portion of transcript
* @param {string} sessionId - Session ID
* @returns {string|null} - Primary topic or null
*/
function getSessionTopic(sessionId) {
if (!sessionId) return null;
try {
const transcriptPath = path.join(
process.env.HOME,
".openclaw",
"agents",
"main",
"sessions",
`${sessionId}.jsonl`,
);
if (!fs.existsSync(transcriptPath)) return null;
// Read first 50KB of transcript (enough for topic detection, fast)
const fd = fs.openSync(transcriptPath, "r");
const buffer = Buffer.alloc(50000);
const bytesRead = fs.readSync(fd, buffer, 0, 50000, 0);
fs.closeSync(fd);
if (bytesRead === 0) return null;
const content = buffer.toString("utf8", 0, bytesRead);
const lines = content.split("\n").filter((l) => l.trim());
// Extract text from messages
// Transcript format: {type: "message", message: {role: "user"|"assistant", content: [...]}}
let textSamples = [];
for (const line of lines.slice(0, 30)) {
// First 30 entries
try {
const entry = JSON.parse(line);
if (entry.type === "message" && entry.message?.content) {
const msgContent = entry.message.content;
if (Array.isArray(msgContent)) {
msgContent.forEach((c) => {
if (c.type === "text" && c.text) {
textSamples.push(c.text.slice(0, 500));
}
});
} else if (typeof msgContent === "string") {
textSamples.push(msgContent.slice(0, 500));
}
}
} catch (e) {
/* skip malformed lines */
}
}
if (textSamples.length === 0) return null;
const topics = detectTopics(textSamples.join(" "));
return topics.length > 0 ? topics.slice(0, 2).join(", ") : null;
} catch (e) {
return null;
}
}
function getSessions(options = {}) {
const limit = Object.prototype.hasOwnProperty.call(options, "limit") ? options.limit : 20;
try {
const output = runOpenClaw("sessions list --json 2>/dev/null");
if (output) {
const data = JSON.parse(output);
let sessions = data.sessions || [];
if (limit != null) {
sessions = sessions.slice(0, limit);
}
return sessions.map((s) => {
// Calculate active status from ageMs
const minutesAgo = s.ageMs ? s.ageMs / 60000 : Infinity;
// Determine channel type from key
let channel = "other";
if (s.key.includes("slack")) channel = "slack";
else if (s.key.includes("telegram")) channel = "telegram";
const originator = getSessionOriginator(s.sessionId);
// Use groupChannel if available, otherwise parse from key
const label = s.groupChannel || s.displayName || parseSessionLabel(s.key);
// Get topic for session (lightweight detection)
const topic = getSessionTopic(s.sessionId);
return {
sessionKey: s.key,
sessionId: s.sessionId,
label: label,
groupChannel: s.groupChannel || null,
displayName: s.displayName || null,
kind: s.kind,
channel: channel,
active: minutesAgo < 15,
recentlyActive: minutesAgo < 60,
minutesAgo: Math.round(minutesAgo),
tokens: s.totalTokens || 0,
model: s.model,
originator: originator,
topic: topic,
};
});
}
} catch (e) {
console.error("Failed to get sessions:", e.message);
}
return [];
}
// Get cron jobs
// Convert cron expression to human-readable text
function cronToHuman(expr) {
if (!expr || expr === "β") return null;
const parts = expr.split(" ");
if (parts.length < 5) return null;
const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;
const dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// Helper to format time
function formatTime(h, m) {
const hNum = parseInt(h, 10);
const mNum = parseInt(m, 10);
if (isNaN(hNum)) return null;
const ampm = hNum >= 12 ? "pm" : "am";
const h12 = hNum === 0 ? 12 : hNum > 12 ? hNum - 12 : hNum;
return mNum === 0 ? `${h12}${ampm}` : `${h12}:${mNum.toString().padStart(2, "0")}${ampm}`;
}
// Every minute
if (minute === "*" && hour === "*" && dayOfMonth === "*" && month === "*" && dayOfWeek === "*") {
return "Every minute";
}
// Every X minutes
if (minute.startsWith("*/")) {
const interval = minute.slice(2);
return `Every ${interval} minutes`;
}
// Every X hours (*/N in hour field)
if (hour.startsWith("*/")) {
const interval = hour.slice(2);
const minStr = minute === "0" ? "" : `:${minute.padStart(2, "0")}`;
return `Every ${interval} hours${minStr ? " at " + minStr : ""}`;
}
// Every hour at specific minute
if (minute !== "*" && hour === "*" && dayOfMonth === "*" && month === "*" && dayOfWeek === "*") {
return `Hourly at :${minute.padStart(2, "0")}`;
}
// Build time string for specific hour
let timeStr = "";
if (minute !== "*" && hour !== "*" && !hour.startsWith("*/")) {
timeStr = formatTime(hour, minute);
}
// Daily at specific time
if (timeStr && dayOfMonth === "*" && month === "*" && dayOfWeek === "*") {
return `Daily at ${timeStr}`;
}
// Weekdays (Mon-Fri) - check before generic day of week
if ((dayOfWeek === "1-5" || dayOfWeek === "MON-FRI") && dayOfMonth === "*" && month === "*") {
return timeStr ? `Weekdays at ${timeStr}` : "Weekdays";
}
// Weekends - check before generic day of week
if ((dayOfWeek === "0,6" || dayOfWeek === "6,0") && dayOfMonth === "*" && month === "*") {
return timeStr ? `Weekends at ${timeStr}` : "Weekends";
}
// Specific day of week
if (dayOfMonth === "*" && month === "*" && dayOfWeek !== "*") {
const days = dayOfWeek.split(",").map((d) => {
const num = parseInt(d, 10);
return dayNames[num] || d;
});
const dayStr = days.length === 1 ? days[0] : days.join(", ");
return timeStr ? `${dayStr} at ${timeStr}` : `Every ${dayStr}`;
}
// Specific day of month
if (dayOfMonth !== "*" && month === "*" && dayOfWeek === "*") {
const day = parseInt(dayOfMonth, 10);
const suffix =
day === 1 || day === 21 || day === 31
? "st"
: day === 2 || day === 22
? "nd"
: day === 3 || day === 23
? "rd"
: "th";
return timeStr ? `${day}${suffix} of month at ${timeStr}` : `${day}${suffix} of every month`;
}
// Fallback: just show the time if we have it
if (timeStr) {
return `At ${timeStr}`;
}
return expr; // Return original as fallback
}
// Get cron jobs - reads directly from file for speed (CLI takes 11s+)
function getCronJobs() {
try {
const cronPath = path.join(process.env.HOME, ".openclaw", "cron", "jobs.json");
if (fs.existsSync(cronPath)) {
const data = JSON.parse(fs.readFileSync(cronPath, "utf8"));
return (data.jobs || []).map((j) => {
// Parse schedule
let scheduleStr = "β";
let scheduleHuman = null;
if (j.schedule) {
if (j.schedule.kind === "cron" && j.schedule.expr) {
scheduleStr = j.schedule.expr;
scheduleHuman = cronToHuman(j.schedule.expr);
} else if (j.schedule.kind === "once") {
scheduleStr = "once";
scheduleHuman = "One-time";
}
}
// Format next run
let nextRunStr = "β";
if (j.state?.nextRunAtMs) {
const next = new Date(j.state.nextRunAtMs);
const now = new Date();
const diffMs = next - now;
const diffMins = Math.round(diffMs / 60000);
if (diffMins < 0) {
nextRunStr = "overdue";