forked from mudrii/openclaw-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefresh.sh
More file actions
executable file
·1517 lines (1395 loc) · 66.9 KB
/
Copy pathrefresh.sh
File metadata and controls
executable file
·1517 lines (1395 loc) · 66.9 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
#!/bin/bash
# OpenClaw Dashboard — Data Refresh Script
# Generates data.json with all dashboard data
set -euo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
OPENCLAW_PATH="${OPENCLAW_HOME:-$HOME/.openclaw}"
OPENCLAW_PATH="${OPENCLAW_PATH/#\~/$HOME}"
echo "Dashboard dir: $DIR"
echo "OpenClaw path: $OPENCLAW_PATH"
if [ ! -d "$OPENCLAW_PATH" ]; then
echo "❌ OpenClaw not found at $OPENCLAW_PATH"
exit 1
fi
PYTHON=$(command -v python3 || command -v python)
if [ -z "$PYTHON" ]; then
echo "❌ Python not found"
exit 1
fi
"$PYTHON" - "$DIR" "$OPENCLAW_PATH" << 'PYEOF' > "$DIR/data.json.tmp"
import json, glob, os, sys, subprocess, time
import re as _re
from collections import defaultdict
from datetime import datetime, timezone, timedelta
try:
from zoneinfo import ZoneInfo
local_tz = ZoneInfo('Europe/London')
except ImportError:
local_tz = timezone(timedelta(hours=0))
dashboard_dir = sys.argv[1]
openclaw_path = sys.argv[2]
now = datetime.now(local_tz)
today_str = now.strftime('%Y-%m-%d')
base = os.path.join(openclaw_path, "agents")
config_path = os.path.join(openclaw_path, "openclaw.json")
cron_path = os.path.join(openclaw_path, "cron/jobs.json")
# ── Bot config ──
bot_name = "OpenClaw Dashboard"
bot_emoji = "⚡"
dc_path = os.path.join(dashboard_dir, "config.json")
if os.path.exists(dc_path):
try:
with open(dc_path) as _f:
dc = json.load(_f)
bot_name = dc.get('bot', {}).get('name', bot_name)
bot_emoji = dc.get('bot', {}).get('emoji', bot_emoji)
except Exception as _e:
import sys; print(f"[dashboard warn] {_e}", file=sys.stderr)
dc = {}
else:
dc = {}
# ── Alert thresholds (configurable via config.json) ──
alert_cfg = dc.get('alerts', {})
COST_THRESHOLD_HIGH = alert_cfg.get('dailyCostHigh', 50)
COST_THRESHOLD_WARN = alert_cfg.get('dailyCostWarn', 20)
CONTEXT_THRESHOLD = alert_cfg.get('contextPct', 80)
MEMORY_THRESHOLD_KB = alert_cfg.get('memoryMb', 640) * 1024
# ── Gateway health ──
gateway = {"status": "offline", "pid": None, "uptime": "", "memory": "", "rss": 0}
try:
result = subprocess.run(["pgrep", "-f", "openclaw-gateway"],
capture_output=True, text=True)
pids = [p for p in result.stdout.strip().split('\n') if p and p != str(os.getpid())]
if pids and pids[0]:
pid = pids[0]
gateway["pid"] = int(pid)
gateway["status"] = "online"
ps = subprocess.run(['ps', '-p', pid, '-o', 'etime=,rss='], capture_output=True, text=True)
parts = ps.stdout.strip().split()
if len(parts) >= 2:
gateway["uptime"] = parts[0].strip()
rss_kb = int(parts[1])
gateway["rss"] = rss_kb
if rss_kb > 1048576: gateway["memory"] = f"{rss_kb/1048576:.1f} GB"
elif rss_kb > 1024: gateway["memory"] = f"{rss_kb/1024:.0f} MB"
else: gateway["memory"] = f"{rss_kb} KB"
except Exception as _e:
import sys; print(f"[dashboard warn] {_e}", file=sys.stderr)
# ── Provider status (from auth-profiles.json across all agents) ──
provider_agg = {} # provider_id -> {errorCount, rate_limit, lastFailureAt, cooldownUntil, lastUsed}
for ap_file in glob.glob(os.path.join(base, '*/agent/auth-profiles.json')):
try:
with open(ap_file) as _f:
ap = json.load(_f)
for profile_key, stats in ap.get('usageStats', {}).items():
provider_id = profile_key.split(':')[0]
if provider_id not in provider_agg:
provider_agg[provider_id] = {
'errorCount': 0, 'rate_limit': 0,
'lastFailureAt': 0, 'cooldownUntil': 0, 'lastUsed': 0,
}
agg = provider_agg[provider_id]
agg['errorCount'] += stats.get('errorCount', 0)
agg['rate_limit'] += stats.get('failureCounts', {}).get('rate_limit', 0)
agg['lastFailureAt'] = max(agg['lastFailureAt'], stats.get('lastFailureAt', 0))
agg['cooldownUntil'] = max(agg['cooldownUntil'], stats.get('cooldownUntil', 0))
agg['lastUsed'] = max(agg['lastUsed'], stats.get('lastUsed', 0))
except Exception as _e:
import sys; print(f"[dashboard warn] auth-profiles: {_e}", file=sys.stderr)
# GitHub Copilot token expiry
copilot_token_info = {}
copilot_token_path = os.path.join(openclaw_path, 'credentials', 'github-copilot.token.json')
if os.path.exists(copilot_token_path):
try:
with open(copilot_token_path) as _f:
ct = json.load(_f)
copilot_token_info = {
'expiresAt': ct.get('expiresAt', 0),
'updatedAt': ct.get('updatedAt', 0),
}
except Exception as _e:
import sys; print(f"[dashboard warn] copilot token: {_e}", file=sys.stderr)
# Determine provider status
now_ms = int(now.timestamp() * 1000)
twenty_four_hours_ms = 24 * 60 * 60 * 1000
provider_status = {}
for pid, agg in provider_agg.items():
recent_failure = (now_ms - agg['lastFailureAt']) < twenty_four_hours_ms if agg['lastFailureAt'] else False
if agg['cooldownUntil'] > now_ms:
status = 'cooldown'
elif agg['errorCount'] >= 5 and recent_failure:
status = 'down'
elif agg['errorCount'] >= 1 and recent_failure:
status = 'degraded'
else:
status = 'ok'
provider_status[pid] = {
'status': status,
'errorCount': agg['errorCount'],
'rateLimitCount': agg['rate_limit'],
'lastFailureAt': agg['lastFailureAt'],
'cooldownUntil': agg['cooldownUntil'],
'lastUsed': agg['lastUsed'],
}
# Merge github-copilot auth-profiles data with token file
if copilot_token_info:
existing = provider_status.get('github-copilot', {})
token_expires = copilot_token_info.get('expiresAt', 0)
# Token refreshes every ~30min; only flag "down" if not refreshed in >2h
stale_token = (now_ms - copilot_token_info.get('updatedAt', 0)) > 7200000 and token_expires < now_ms
provider_status['github-copilot'] = {
'status': 'down' if stale_token else existing.get('status', 'ok'),
'errorCount': existing.get('errorCount', 0),
'rateLimitCount': existing.get('rateLimitCount', 0),
'lastFailureAt': existing.get('lastFailureAt', 0),
'cooldownUntil': existing.get('cooldownUntil', 0),
'lastUsed': max(copilot_token_info.get('updatedAt', 0), existing.get('lastUsed', 0)),
}
# Provider metadata — descriptions, types, and quota info
PROVIDER_META = {
'github-copilot': {
'providerType': 'subscription',
'plan': 'Copilot Pro',
'monthlyPremiumLimit': 300,
'description': 'GitHub Copilot Pro subscription',
},
'openai-codex': {
'providerType': 'subscription',
'plan': 'ChatGPT OWALF',
'description': 'ChatGPT OAuth subscription (OWALF)',
},
'kimi-coding': {
'providerType': 'subscription',
'plan': 'Kimi Code',
'description': 'Kimi Code subscription (Moonshot AI)',
},
'openrouter': {
'providerType': 'api_key',
'plan': 'API Key',
'description': 'OpenRouter API (pay-per-use)',
},
'anthropic': {
'providerType': 'subscription',
'plan': 'API Subscription',
'description': 'Anthropic API subscription',
},
}
# GitHub Copilot premium request multipliers
COPILOT_MULTIPLIERS = {
'opus-4.6': 3, 'opus-4.5': 3,
'sonnet-4': 1, 'sonnet-4.5': 1, 'sonnet-4.6': 1,
'haiku-4.5': 0.33,
'gpt-5.1': 1, 'gpt-5.1-codex': 1, 'gpt-5.1-codex-mini': 0.33,
'gpt-5.2': 1, 'gpt-5.2-codex': 1, 'gpt-5.3-codex': 1,
'gemini-2.5-pro': 1, 'gemini-flash-3': 0.33, 'gemini-3-flash': 0.33,
'gemini-3-pro': 1, 'gemini-3.1-pro': 1,
'gpt-4.1': 0, 'gpt-4o': 0, 'gpt-5-mini': 0,
}
# Calculate Copilot premium requests consumed this month
month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0).strftime('%Y-%m-%dT00:00:00')
copilot_premium_used = 0
copilot_model_calls = {} # model -> {calls, premium}
for _f in glob.glob(os.path.join(base, '*/sessions/*.jsonl')):
_sess_provider = 'unknown'
try:
with open(_f) as _fh:
for _line in _fh:
try:
_obj = json.loads(_line)
if _obj.get('type') == 'model_change' and _obj.get('provider'):
_sess_provider = _obj['provider']
_msg = _obj.get('message', {})
if _msg.get('role') != 'assistant': continue
if _msg.get('usage', {}).get('totalTokens', 0) == 0: continue
if _sess_provider != 'github-copilot': continue
_ts = _obj.get('timestamp', '')
if _ts < month_start: continue
_model = _msg.get('model', 'unknown')
_mult = COPILOT_MULTIPLIERS.get(_model, 1)
copilot_premium_used += _mult
if _model not in copilot_model_calls:
copilot_model_calls[_model] = {'calls': 0, 'premium': 0}
copilot_model_calls[_model]['calls'] += 1
copilot_model_calls[_model]['premium'] += _mult
except (json.JSONDecodeError, ValueError):
continue
except (FileNotFoundError, PermissionError, OSError):
pass
# Determine each provider's role from openclaw.json
provider_roles = {} # pid -> 'primary' | 'fallback' | 'inactive'
try:
with open(config_path) as _cf:
_oc_roles = json.load(_cf)
_def_primary = _oc_roles.get('agents', {}).get('defaults', {}).get('model', {}).get('primary', '')
_def_primary_pid = _def_primary.split('/')[0] if '/' in _def_primary else ''
if _def_primary_pid:
provider_roles[_def_primary_pid] = 'primary'
_def_fbs = _oc_roles.get('agents', {}).get('defaults', {}).get('model', {}).get('fallbacks', [])
for _fb in (_def_fbs if isinstance(_def_fbs, list) else []):
_fb_str = _fb.get('model', '') if isinstance(_fb, dict) else str(_fb)
_fb_pid = _fb_str.split('/')[0] if '/' in _fb_str else ''
if _fb_pid and _fb_pid not in provider_roles:
provider_roles[_fb_pid] = 'fallback'
# Check agent-specific overrides
for _aname, _acfg in _oc_roles.get('agents', {}).items():
if _aname == 'defaults' or not isinstance(_acfg, dict): continue
_ap = _acfg.get('model', {}).get('primary', '')
_ap_pid = _ap.split('/')[0] if '/' in _ap else ''
if _ap_pid and _ap_pid not in provider_roles:
provider_roles[_ap_pid] = 'primary'
except Exception:
pass
# Add computed fields to all providers
for pid, pdata in provider_status.items():
meta = PROVIDER_META.get(pid, {})
pdata['providerType'] = meta.get('providerType', 'unknown')
pdata['plan'] = meta.get('plan', '')
pdata['description'] = meta.get('description', '')
pdata['role'] = provider_roles.get(pid, 'configured')
# Cooldown remaining vs expired
cd = pdata.get('cooldownUntil', 0)
if cd > now_ms:
pdata['cooldownRemainingMs'] = cd - now_ms
elif cd > 0:
pdata['cooldownExpired'] = True # Cooldown has expired, provider ready
# Copilot premium requests
if pid == 'github-copilot':
limit = meta.get('monthlyPremiumLimit', 300)
pdata['premiumUsed'] = int(copilot_premium_used)
pdata['premiumLimit'] = limit
pdata['premiumRemaining'] = max(0, limit - int(copilot_premium_used))
pdata['premiumModels'] = copilot_model_calls
# OpenRouter live usage from API (JSONL doesn't track OR costs)
try:
env_path = os.path.expanduser('~/.openclaw/.env')
or_key = ''
if os.path.exists(env_path):
for _line in open(env_path):
if _line.startswith('OPENROUTER_API_KEY='):
or_key = _line.split('=', 1)[1].strip().strip('"').strip("'")
break
if or_key:
import urllib.request
_req = urllib.request.Request('https://openrouter.ai/api/v1/auth/key',
headers={'Authorization': f'Bearer {or_key}'})
with urllib.request.urlopen(_req, timeout=5) as _resp:
_or = json.loads(_resp.read()).get('data', {})
or_status = provider_status.get('openrouter', {})
or_status['apiUsageTotal'] = round(_or.get('usage', 0), 4)
or_status['apiUsageDaily'] = round(_or.get('usage_daily', 0), 4)
or_status['apiUsageWeekly'] = round(_or.get('usage_weekly', 0), 4)
or_status['apiUsageMonthly'] = round(_or.get('usage_monthly', 0), 4)
or_status['dailyLimit'] = _or.get('limit', 0)
or_status['dailyRemaining'] = _or.get('limit_remaining', 0)
except Exception as _e:
import sys; print(f"[dashboard warn] openrouter api: {_e}", file=sys.stderr)
# ── MCP Servers ──
mcp_servers = []
try:
mcporter_path = os.path.expanduser('~/.mcporter/mcporter.json')
if os.path.exists(mcporter_path):
with open(mcporter_path) as _f:
mcporter = json.load(_f)
servers_cfg = mcporter.get('mcpServers', {})
# Parse smoke test log for latest failures
# Format: "2026-03-03 06:00:15 | Failures: librecrawl-mcp"
smoke_failures = set()
smoke_log = os.path.expanduser('~/logs/mcp-smoke-test.log')
if os.path.exists(smoke_log):
with open(smoke_log) as _f:
for _line in _f:
_line = _line.strip()
if 'passed' in _line and 'failed' in _line:
smoke_failures = set() # Reset on new run summary
elif '| Failures:' in _line:
names = _line.split('| Failures:')[1].strip()
for n in names.split(','):
n = n.strip().replace('-mcp', '') # Normalize to mcporter names
if n: smoke_failures.add(n)
# Check persistent SSE services
persistent_status = {}
for svc_name in ['fantasy-pl-mcp', 'google-analytics-mcp']:
try:
_r = subprocess.run(['systemctl', '--user', 'is-active', svc_name],
capture_output=True, text=True, timeout=3)
is_active = _r.stdout.strip() == 'active'
persistent_status[svc_name] = 'ok' if is_active else 'down'
except Exception:
persistent_status[svc_name] = 'unknown'
for name, cfg in sorted(servers_cfg.items()):
srv = {'name': name}
# Determine type: SSE vs stdio
if cfg.get('baseUrl'):
srv['type'] = 'sse'
srv['url'] = cfg['baseUrl']
elif cfg.get('command'):
cmd = cfg['command']
if 'containers/' in cmd or 'run.sh' in cmd:
srv['type'] = 'container'
elif 'npx' in cmd or 'node' in cmd:
srv['type'] = 'node'
elif 'python' in cmd or 'uvx' in cmd:
srv['type'] = 'python'
else:
srv['type'] = 'stdio'
else:
srv['type'] = 'unknown'
# Status: persistent services get systemd check, containers get smoke test
if name in persistent_status:
srv['status'] = persistent_status[name]
elif name in smoke_failures:
srv['status'] = 'error'
else:
srv['status'] = 'ok' # Assume ok if no negative signal
mcp_servers.append(srv)
except Exception as _e:
import sys; print(f"[dashboard warn] mcp servers: {_e}", file=sys.stderr)
# ── OpenClaw config ──
skills = []
available_models = []
compaction_mode = "unknown"
agent_config = {'primaryModel':'','primaryModelId':'','imageModel':'','imageModelId':'','fallbacks':[],'streamMode':'off','telegramDmPolicy':'—','telegramGroups':0,'channels':[],'channelStatus':{},'compaction':{},'agents':[],'search':{},'gateway':{},'hooks':[],'plugins':[],'skills':[],'bindings':[],'crons':[],'tts':False,'diagnostics':False}
if os.path.exists(config_path):
try:
with open(config_path) as cf:
oc = json.load(cf)
# Compaction
compaction_mode = oc.get('agents', {}).get('defaults', {}).get('compaction', {}).get('mode', 'auto')
# Skills — scan filesystem (skills are file-based, not in openclaw.json)
_skill_dirs = [
(os.path.join(openclaw_path, 'workspace', 'skills'), 'main'),
]
for _ws_agent_dir in glob.glob(os.path.join(openclaw_path, 'workspaces', '*', 'skills')):
_agent_id = os.path.basename(os.path.dirname(_ws_agent_dir))
_skill_dirs.append((_ws_agent_dir, _agent_id))
for _sdir, _agent_id in _skill_dirs:
if not os.path.isdir(_sdir):
continue
for _entry in os.listdir(_sdir):
_skill_md = os.path.join(_sdir, _entry, 'SKILL.md')
if os.path.isfile(_skill_md):
skills.append({'name': _entry, 'agent': _agent_id, 'active': True})
# Models
primary = oc.get('agents', {}).get('defaults', {}).get('model', {}).get('primary', '')
fallbacks = oc.get('agents', {}).get('defaults', {}).get('model', {}).get('fallbacks', [])
image_model = oc.get('agents', {}).get('defaults', {}).get('imageModel', {}).get('primary', '')
model_aliases = {mid: mconf.get('alias', mid) for mid, mconf in oc.get('agents', {}).get('defaults', {}).get('models', {}).items()}
for mid, mconf in oc.get('agents', {}).get('defaults', {}).get('models', {}).items():
provider = mid.split('/')[0] if '/' in mid else 'unknown'
available_models.append({
'provider': provider.title(),
'name': mconf.get('alias', mid),
'id': mid,
'status': 'active' if mid == primary else 'available'
})
# Agent config
defs = oc.get('agents', {}).get('defaults', {})
agent_list = oc.get('agents', {}).get('list', [])
compaction_cfg = defs.get('compaction', {})
model_params = {mid: mconf.get('params', {}) for mid, mconf in oc.get('agents', {}).get('defaults', {}).get('models', {}).items()}
channels_cfg = oc.get('channels', {})
tg_cfg = channels_cfg.get('telegram', {})
channels_enabled = [ch for ch, conf in channels_cfg.items() if isinstance(conf, dict) and conf.get('enabled', True)]
channel_status = {}
for ch_name, conf in channels_cfg.items():
if not isinstance(conf, dict):
continue
enabled = bool(conf.get('enabled', True))
configured = conf.get('configured')
if configured is None:
configured = any(k not in ('enabled', 'configured', 'connected', 'health', 'error', 'lastError') for k in conf.keys())
health = conf.get('health')
connected = conf.get('connected')
error = conf.get('error') or conf.get('lastError')
if isinstance(health, dict):
connected = health.get('connected', connected)
error = health.get('error') or health.get('lastError') or error
elif isinstance(health, str) and connected is None:
health_s = health.lower()
if health_s in ('connected', 'ok', 'healthy', 'online'):
connected = True
elif health_s in ('disconnected', 'offline', 'error', 'unhealthy'):
connected = False
channel_status[ch_name] = {
'enabled': enabled,
'configured': bool(configured),
'connected': connected,
'health': health,
'error': error,
}
# Search / web tools
web_cfg = oc.get('tools', {}).get('web', {}).get('search', {})
# Gateway
gw_cfg = oc.get('gateway', {})
# Hooks
hook_entries = oc.get('hooks', {}).get('internal', {}).get('entries', {})
hooks_list = [{'name': n, 'enabled': v.get('enabled', True) if isinstance(v, dict) else True} for n, v in hook_entries.items()]
# Plugins
plugin_entries = oc.get('plugins', {}).get('entries', {})
plugins_list = list(plugin_entries.keys()) if isinstance(plugin_entries, dict) else []
# Skills
skill_entries = oc.get('skills', {}).get('entries', {})
skills_cfg = [{'name': n, 'enabled': v.get('enabled', True) if isinstance(v, dict) else True} for n, v in skill_entries.items()]
# Bindings
# Build group ID → friendly name map from session data
group_names = {}
for store_file2 in glob.glob(os.path.join(base, '*/sessions/sessions.json')):
try:
with open(store_file2) as _f:
store2 = json.load(_f)
for key2, val2 in store2.items():
if 'group:' not in key2 or 'topic' in key2 or 'run:' in key2 or 'subagent' in key2: continue
gid2 = key2.split('group:')[-1].split(':')[0]
name2 = val2.get('subject','') or val2.get('displayName','') or ''
# strip raw telegram paths
if name2 and not name2.startswith('telegram:'):
group_names[gid2] = name2
except Exception as _e:
import sys; print(f"[dashboard warn] {_e}", file=sys.stderr)
bindings = oc.get('bindings', [])
bindings_list = [{'agentId': b.get('agentId',''), 'channel': b.get('match',{}).get('channel',''), 'kind': b.get('match',{}).get('peer',{}).get('kind',''), 'id': b.get('match',{}).get('peer',{}).get('id',''), 'name': group_names.get(b.get('match',{}).get('peer',{}).get('id',''), '')} for b in bindings]
# Add synthetic entry for the default (main) agent — catches everything not explicitly bound
default_agent = next((a.get('id') for a in agent_list if a.get('default')), 'main')
bindings_list.append({'agentId': default_agent, 'channel': 'all', 'kind': 'default', 'id': '', 'name': 'All unmatched channels'})
# TTS
has_tts = bool(oc.get('talk', {}).get('apiKey'))
# Diagnostics
diag_enabled = oc.get('diagnostics', {}).get('enabled', False)
agent_config = {
'primaryModel': model_aliases.get(primary, primary),
'primaryModelId': primary,
'imageModel': model_aliases.get(image_model, image_model),
'imageModelId': image_model,
'fallbacks': [model_aliases.get(f, f) for f in fallbacks[:3]],
'streamMode': tg_cfg.get('streamMode', 'off'),
'telegramDmPolicy': tg_cfg.get('dmPolicy', '—'),
'telegramGroups': len(tg_cfg.get('groups', {})),
'channels': channels_enabled,
'channelStatus': channel_status,
'compaction': {
'mode': compaction_cfg.get('mode', 'auto'),
'reserveTokensFloor': compaction_cfg.get('reserveTokensFloor', 0),
'memoryFlush': compaction_cfg.get('memoryFlush', {}),
'softThresholdTokens': compaction_cfg.get('memoryFlush', {}).get('softThresholdTokens', 0),
},
'search': {
'provider': web_cfg.get('provider', '—'),
'maxResults': web_cfg.get('maxResults', '—'),
'cacheTtlMinutes': web_cfg.get('cacheTtlMinutes', '—'),
},
'gateway': {
'port': gw_cfg.get('port', '—'),
'mode': gw_cfg.get('mode', '—'),
'bind': gw_cfg.get('bind', '—'),
'authMode': gw_cfg.get('auth', {}).get('mode', '—'),
'tailscale': gw_cfg.get('tailscale', {}).get('mode', 'off'),
},
'hooks': hooks_list,
'plugins': plugins_list,
'skills': skills_cfg,
'bindings': bindings_list,
'tts': has_tts,
'diagnostics': diag_enabled,
'agents': [],
'availableModels': [
{'id': mid, 'alias': mconf.get('alias', mid), 'provider': mid.split('/')[0] if '/' in mid else '—'}
for mid, mconf in oc.get('agents', {}).get('defaults', {}).get('models', {}).items()
],
'subagentConfig': {
'maxConcurrent': defs.get('subagents', {}).get('maxConcurrent', '—'),
'maxSpawnDepth': defs.get('subagents', {}).get('maxSpawnDepth', '—'),
'maxChildrenPerAgent': defs.get('subagents', {}).get('maxChildrenPerAgent', '—'),
},
}
# Build agent entries; if no agent list, synthesize a single default entry
if agent_list:
for i, ag in enumerate(agent_list):
aid = ag.get('id', f'agent-{i}')
model_cfg = ag.get('model', primary)
if isinstance(model_cfg, dict):
amodel = model_cfg.get('primary', primary)
agent_fallbacks = model_cfg.get('fallbacks', fallbacks)
else:
amodel = model_cfg
agent_fallbacks = ag.get('fallbacks', fallbacks)
params = model_params.get(amodel, {})
is_default = ag.get('default', False)
# Derive a human role: prefer explicit 'role' field, else capitalise id
role = ag.get('role', 'Default' if is_default else aid.replace('-',' ').title())
# Per-agent fallbacks now handled above (supports dict-style model config)
agent_config['agents'].append({
'id': aid,
'role': role,
'model': model_aliases.get(amodel, amodel),
'modelId': amodel,
'workspace': ag.get('workspace', '~/.openclaw/workspace'),
'isDefault': is_default,
'context1m': params.get('context1m', None),
'fallbacks': [model_aliases.get(f, f) for f in agent_fallbacks[:3]],
})
else:
# Single-model / minimal config — synthesise one default entry
params = model_params.get(primary, {})
agent_config['agents'].append({
'id': 'default',
'role': 'Default',
'model': model_aliases.get(primary, primary),
'modelId': primary,
'workspace': '~/.openclaw/workspace',
'isDefault': True,
'context1m': params.get('context1m', None),
})
except Exception as _e:
import sys; print(f"[dashboard warn] {_e}", file=sys.stderr)
# ── Session model resolution from JSONL ──
def _load_agent_default_models():
try:
with open(os.path.join(base, '..', 'openclaw.json')) as _cf:
_cfg = json.load(_cf)
_primary = _cfg.get('agents', {}).get('defaults', {}).get('model', {}).get('primary', 'unknown')
_defaults = {}
for _n, _v in _cfg.get('agents', {}).items():
if _n == 'defaults' or not isinstance(_v, dict): continue
_defaults[_n] = _v.get('model', {}).get('primary', _primary)
for _a in ('main', 'work', 'group'):
if _a not in _defaults: _defaults[_a] = _primary
return _defaults
except Exception:
return {'main': 'unknown', 'work': 'unknown', 'group': 'unknown'}
AGENT_DEFAULT_MODELS = _load_agent_default_models()
def get_session_model(session_key, agent_name, session_id):
"""Read first 10 lines of session JSONL to find model_change event."""
if session_id:
jsonl_path = os.path.join(base, agent_name, 'sessions', f'{session_id}.jsonl')
try:
with open(jsonl_path, 'r') as fh:
for i, line in enumerate(fh):
if i >= 10: break
try:
obj = json.loads(line)
if obj.get('type') == 'model_change':
provider = obj.get('provider', '')
model_id = obj.get('modelId', '')
if provider and model_id:
return f'{provider}/{model_id}'
except (json.JSONDecodeError, ValueError):
continue
except (FileNotFoundError, PermissionError, OSError):
pass
return AGENT_DEFAULT_MODELS.get(agent_name, 'unknown')
# ── Gateway API query for live session model info ──
gateway_model_map = {}
try:
result = subprocess.run(
['openclaw', 'sessions', '--json'],
capture_output=True, text=True, timeout=10
)
if result.returncode == 0 and result.stdout.strip():
gateway_sessions = json.loads(result.stdout)
if isinstance(gateway_sessions, list):
for gs in gateway_sessions:
key = gs.get('key', '')
model = gs.get('model', '')
if key and model:
gateway_model_map[key] = model
elif isinstance(gateway_sessions, dict):
# Handle {sessions: [...]} wrapper format
for gs in gateway_sessions.get('sessions', []):
key = gs.get('key', '')
model = gs.get('model', '')
if key and model:
gateway_model_map[key] = model
except Exception as _e:
import sys; print(f"[dashboard info] Gateway session query unavailable: {_e}", file=sys.stderr)
gateway_model_map = {}
# ── System vitals ──
system_vitals = {'cpuTemp': None, 'diskUsedPct': None, 'diskFreeGb': None, 'loadAvg': None}
# CPU temp
try:
result = subprocess.run(['sensors', '-j'], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
sensors = json.loads(result.stdout)
for chip, data in sensors.items():
if 'coretemp' in chip.lower() or 'k10temp' in chip.lower():
for key, val in data.items():
if isinstance(val, dict) and ('Package' in key or 'Tctl' in key or 'Tdie' in key):
for subkey, subval in val.items():
if subkey.endswith('_input'):
system_vitals['cpuTemp'] = round(subval, 1)
break
if system_vitals['cpuTemp'] is not None:
break
if system_vitals['cpuTemp'] is not None:
break
except Exception as _e:
import sys; print(f"[dashboard warn] sensors: {_e}", file=sys.stderr)
# Disk usage
try:
result = subprocess.run(['df', '--output=pcent,avail', '/'], capture_output=True, text=True, timeout=5)
lines = result.stdout.strip().split('\n')
if len(lines) >= 2:
parts = lines[1].split()
system_vitals['diskUsedPct'] = int(parts[0].replace('%', ''))
avail_kb = int(parts[1])
system_vitals['diskFreeGb'] = round(avail_kb / 1048576, 1)
except Exception as _e:
import sys; print(f"[dashboard warn] df: {_e}", file=sys.stderr)
# Load average
try:
with open('/proc/loadavg') as _f:
system_vitals['loadAvg'] = float(_f.read().split()[0])
except Exception as _e:
import sys; print(f"[dashboard warn] loadavg: {_e}", file=sys.stderr)
# ── Activity feed ──
activity_feed = []
# Agent ID → display name
AGENT_NAMES = {
'main': 'Holly', 'researcher': 'Archie', 'automator': 'Gears',
'scribe': 'Ink', 'coder': 'Forge', 'housekeeper': 'Tidy',
'steward': 'Steward', 'seo': 'Scout', 'ads': 'Adsmith',
'pm': 'Taskmaster', 'fpl': 'Gaffer',
}
# Brief descriptions for cron jobs (matched by substring in name)
CRON_DESCRIPTIONS = {
'Morning briefing': 'Daily summary of overnight events and priorities',
'Weekly review': 'Review the week and plan ahead',
'Daily housekeeping': 'Clean workspace, prune logs, tidy configs',
'Weekly trend analysis': 'Analyse trends across systems and usage',
'Monthly reflection': 'Monthly retrospective and goal check',
'Weekly security audit': 'Scan for misconfigs, expired certs, permissions',
'YouTube feed sync': 'Sync YouTube subscriptions and new videos',
'Weekly software updater': 'Check for OS and package updates',
'Memory Consolidation': 'Compress and organise agent memory files',
'Workflow Health Check': 'Verify n8n workflows are active and healthy',
'Workflow Audit': 'Full audit of n8n workflow configs',
'Documentation Coverage': 'Find undocumented code and APIs',
'SEO Summary': 'Weekly SEO performance across all sites',
'Daily database sync': 'Sync all databases (FPL, GA4, Ads, etc.)',
'Hourly Sweep': 'Check tasks, update statuses, chase stale items',
'Email Triage': 'Triage inbox and create tasks from emails',
'Evening Review': 'End-of-day task review and tomorrow prep',
'Weekly Summary': 'Weekly task board summary and metrics',
'Ideas Backlog': 'Review and prioritise ideas backlog',
'Stale Ideas Purge': 'Archive stale ideas older than 90 days',
'Personal Tasks': 'Check Google Tasks for personal items',
'Hourly GitHub': 'Check repos for new issues, PRs, and alerts',
'CI Audit': 'Audit CI pipelines across all repos',
'Staleness Scan': 'Find stale docs that need updating',
'Runbook Testing': 'Verify runbooks are still accurate',
'PR Sweep': 'Review, fix, and merge open pull requests',
'Log Watch': 'Scan gateway logs for errors and anomalies',
'Ads + Woo Snapshot': 'Daily ads spend, GA4, and WooCommerce stats',
'MCP Smoke Test': 'Health check all MCP server containers',
'FPL Brief': 'Pre-deadline Fantasy Premier League briefing',
}
def get_cron_description(job_name):
"""Match a cron job name to a brief description."""
for key, desc in CRON_DESCRIPTIONS.items():
if key.lower() in job_name.lower():
return desc
return ''
# Cron job completions/failures (from cron jobs state)
if os.path.exists(cron_path):
try:
with open(cron_path) as _f:
_cron_jobs = json.load(_f).get('jobs', [])
for job in _cron_jobs:
state = job.get('state', {})
last_run_ms = state.get('lastRunAtMs', 0)
if last_run_ms > 0:
try:
run_dt = datetime.fromtimestamp(last_run_ms/1000, tz=local_tz)
age_h = (now - run_dt).total_seconds() / 3600
if age_h <= 12:
status = state.get('lastStatus', 'unknown')
icon = '✅' if status == 'ok' else '❌' if status == 'error' else '⏰'
dur = state.get('lastDurationMs', 0)
dur_str = f" ({dur/1000:.0f}s)" if dur else ''
agent_id = job.get('agentId', '')
agent_name = AGENT_NAMES.get(agent_id, agent_id)
job_name = job.get('name', '?')
desc = get_cron_description(job_name)
activity_feed.append({
'time': run_dt.strftime('%H:%M'),
'timestamp': last_run_ms,
'icon': icon,
'message': f'Cron: {job_name} {status}{dur_str}',
'agent': agent_name,
'description': desc,
'type': 'cron',
})
except Exception:
pass
except Exception as _e:
import sys; print(f"[dashboard warn] activity feed cron: {_e}", file=sys.stderr)
# Watchdog events (from log file, last 12h)
watchdog_log = os.path.expanduser('~/logs/agent-session-watcher.log')
if os.path.exists(watchdog_log):
try:
with open(watchdog_log) as _f:
lines = _f.readlines()
for line in lines[-200:]:
line = line.strip()
if not line:
continue
parts = line.split(' | ', 1)
if len(parts) < 2:
continue
try:
ts_str = parts[0].strip()
ts_dt = datetime.strptime(ts_str, '%Y-%m-%d %H:%M:%S').replace(tzinfo=local_tz)
age_h = (now - ts_dt).total_seconds() / 3600
if age_h <= 12:
msg = parts[1].strip()
icon = msg[0] if msg and ord(msg[0]) > 127 else '📋'
activity_feed.append({
'time': ts_dt.strftime('%H:%M'),
'timestamp': int(ts_dt.timestamp() * 1000),
'icon': icon,
'message': msg[2:].strip() if msg and ord(msg[0]) > 127 else msg,
'type': 'watchdog',
})
except (ValueError, IndexError):
continue
except Exception as _e:
import sys; print(f"[dashboard warn] activity feed watchdog: {_e}", file=sys.stderr)
# Sort by timestamp descending, limit to 20
activity_feed.sort(key=lambda x: -x.get('timestamp', 0))
activity_feed = activity_feed[:20]
# ── Sessions ──
known_sids = {}
sessions_list = []
for store_file in glob.glob(os.path.join(base, '*/sessions/sessions.json')):
try:
with open(store_file) as _f:
store = json.load(_f)
agent_name = store_file.split('/agents/')[1].split('/')[0]
for key, val in store.items():
sid = val.get('sessionId', '')
if not sid: continue
# Skip cron run sessions (duplicates of parent cron)
if ':run:' in key: continue
if 'cron:' in key: stype = 'cron'
elif 'subagent:' in key: stype = 'subagent'
elif 'group:' in key: stype = 'group'
elif 'telegram' in key: stype = 'telegram'
elif key.endswith(':main'): stype = 'main'
else: stype = 'other'
known_sids[sid] = stype
# Build session info for active sessions panel
ctx_tokens = val.get('contextTokens', 0)
total_tokens = val.get('totalTokens', 0)
ctx_pct = round(total_tokens / ctx_tokens * 100, 1) if ctx_tokens > 0 else 0
updated = val.get('updatedAt', 0)
if updated > 0:
try:
updated_dt = datetime.fromtimestamp(updated/1000, tz=local_tz)
updated_str = updated_dt.strftime('%H:%M:%S')
age_min = (now - updated_dt).total_seconds() / 60
except Exception as _e:
import sys; print(f"[dashboard warn] {_e}", file=sys.stderr)
updated_str = ''; age_min = 9999
else: updated_str = ''; age_min = 9999
# Only include recently active sessions (last 24h)
if age_min < 1440:
raw_label = val.get('label', '')
origin_label = val.get('origin', {}).get('label', '') if val.get('origin') else ''
subject = val.get('subject', '')
# Friendly display name: prefer task label for sub-agents, group subject for roots
# Last resort: strip agent prefix + group id noise from key
key_short = key
for pfx in ('agent:work:','agent:main:','agent:group:'):
if key.startswith(pfx): key_short = key[len(pfx):]; break
# Trim long Telegram group ids from display name (e.g. "OpenClaw Dev & Admin id:-100...")
def _trim(s): return _re.sub(r'\s*id[:\-]\s*-?\d+','',s).strip() if s else s
display_name = _trim(raw_label) or _trim(subject) or _trim(origin_label) or key_short
# Trigger: what context spawned/drives this session
trigger = subject or origin_label or raw_label or ''
# Resolve model priority chain:
# 1) Gateway live data (most accurate, includes runtime model)
# 2) providerOverride/modelOverride (sub-agent spawn params)
# 3) session store 'model' field
# 4) JSONL model_change event
# 5) agent default
_gateway_model = gateway_model_map.get(key, '')
_prov_override = val.get('providerOverride', '')
_model_override = val.get('modelOverride', '')
if _gateway_model:
resolved_model = _gateway_model
elif _prov_override and _model_override:
resolved_model = f'{_prov_override}/{_model_override}'
else:
resolved_model = val.get('model', '') or get_session_model(key, agent_name, sid)
if resolved_model == 'unknown' or not resolved_model:
resolved_model = get_session_model(key, agent_name, sid)
# Apply alias if available
resolved_model = model_aliases.get(resolved_model, resolved_model)
sessions_list.append({
'name': display_name[:50],
'key': key,
'agent': agent_name,
'model': resolved_model,
'contextPct': min(ctx_pct, 100),
'lastActivity': updated_str,
'updatedAt': updated,
'totalTokens': total_tokens,
'type': stype,
'spawnedBy': val.get('spawnedBy', ''),
'active': age_min < 30,
'label': raw_label,
'subject': trigger[:50]
})
except Exception as _e:
import sys; print(f"[dashboard warn] {_e}", file=sys.stderr)
sessions_list.sort(key=lambda x: -x.get('updatedAt', 0))
sessions_list = sessions_list[:20] # Top 20 most recent
# Backfill channel connectivity from recent session activity (runtime signal)
# Session key pattern: agent:<agentId>:<channel>:...
channel_recent_active = {}
for s in sessions_list:
key = s.get('key', '')
if not isinstance(key, str):
continue
parts = key.split(':')
if len(parts) < 4 or parts[0] != 'agent':
continue
channel = parts[2]
# Ignore non-channel pseudo channels
if channel in ('main', 'cron', 'subagent', 'run'):
continue
channel_recent_active[channel] = channel_recent_active.get(channel, False) or bool(s.get('active', False))
# Apply runtime hint only when config does not already provide explicit connected value
if isinstance(agent_config, dict) and isinstance(agent_config.get('channelStatus'), dict):
for ch_name, st in agent_config['channelStatus'].items():
if not isinstance(st, dict):
continue
if st.get('connected') is None and channel_recent_active.get(ch_name):
st['connected'] = True
if st.get('health') in (None, '', False):
st['health'] = 'active'
# ── Cron jobs ──
crons = []
if os.path.exists(cron_path):
try:
with open(cron_path) as _f:
jobs = json.load(_f).get('jobs', [])
for job in jobs:
sched = job.get('schedule', {})
kind = sched.get('kind', '')
if kind == 'cron': schedule_str = sched.get('expr', '')
elif kind == 'every':
ms = sched.get('everyMs', 0)
if ms >= 86400000: schedule_str = f"Every {ms//86400000}d"
elif ms >= 3600000: schedule_str = f"Every {ms//3600000}h"
elif ms >= 60000: schedule_str = f"Every {ms//60000}m"
else: schedule_str = f"Every {ms}ms"
elif kind == 'at': schedule_str = sched.get('at', '')[:16]
else: schedule_str = str(sched)
state = job.get('state', {})
last_status = state.get('lastStatus', 'none')
last_run_ms = state.get('lastRunAtMs', 0)
next_run_ms = state.get('nextRunAtMs', 0)
duration_ms = state.get('lastDurationMs', 0)
last_run_str = ''
if last_run_ms:
try: last_run_str = datetime.fromtimestamp(last_run_ms/1000, tz=local_tz).strftime('%Y-%m-%d %H:%M')
except Exception as _e:
import sys; print(f"[dashboard warn] {_e}", file=sys.stderr)
next_run_str = ''
if next_run_ms:
try: next_run_str = datetime.fromtimestamp(next_run_ms/1000, tz=local_tz).strftime('%Y-%m-%d %H:%M')
except Exception as _e:
import sys; print(f"[dashboard warn] {_e}", file=sys.stderr)
crons.append({
'name': job.get('name', 'Unknown'),
'schedule': schedule_str,
'enabled': job.get('enabled', True),
'lastRun': last_run_str,
'lastStatus': last_status,
'lastDurationMs': duration_ms,
'nextRun': next_run_str,
'model': job.get('payload', {}).get('model', ''),
'agentId': job.get('agentId', ''),
})
except Exception as _e:
import sys; print(f"[dashboard warn] {_e}", file=sys.stderr)
# ── Agent identities (from IDENTITY.md files) ──
agent_identities = {}
_identity_agent_ids = set()
for _ag in agent_config.get('agents', []):
_identity_agent_ids.add(_ag.get('id', ''))
# Ensure main is always included
_identity_agent_ids.add('main')
for _aid in sorted(_identity_agent_ids):
if not _aid:
continue
if _aid == 'main':
_id_path = os.path.join(openclaw_path, 'workspace', 'IDENTITY.md')
else:
_id_path = os.path.join(openclaw_path, 'workspaces', _aid, 'IDENTITY.md')
_identity = {}
if os.path.exists(_id_path):
try:
with open(_id_path) as _f:
_id_lines = _f.readlines()
_field_map = {'name': 'Name', 'creature': 'Creature', 'emoji': 'Emoji', 'vibe': 'Vibe'}
for _line in _id_lines:
for _key, _label in _field_map.items():
_pat = f'- **{_label}:**'
if _pat in _line:
_identity[_key] = _line.split(_pat, 1)[1].strip()
# Tagline: first non-empty line after ---
_found_hr = False
for _line in _id_lines: