Repository navigation
Expand file tree
/
Copy pathagent_console.py
More file actions
5775 lines (5360 loc) · 353 KB
/
Copy pathagent_console.py
File metadata and controls
5775 lines (5360 loc) · 353 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 python3
"""Agent Console prototype: single-page Hermes agent console."""
from __future__ import annotations
import base64
import hashlib
import json
import math
import mimetypes
import os
import re
import shutil
import sqlite3
import subprocess
import threading
import time
import traceback
import struct
import urllib.error
import urllib.parse
import urllib.request
import uuid
import zlib
from pathlib import Path
import requests
try:
from cryptography.fernet import Fernet, InvalidToken
except Exception: # pragma: no cover - runtime dependency guard for the prototype
Fernet = None # type: ignore[assignment]
InvalidToken = Exception # type: ignore[misc,assignment]
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from html import escape
from typing import Any
HOST = os.environ.get("AGENT_CONSOLE_HOST") or os.environ.get("NEREUS_HOST", "0.0.0.0")
PORT = int(os.environ.get("AGENT_CONSOLE_PORT") or os.environ.get("NEREUS_PORT", "4200"))
ELEVENLABS_API_URL_BASE =os.environ.get("AGENT_CONSOLE_ELEVENLABS_API_URL") or os.environ.get("NEREUS_ELEVENLABS_API_URL", "https://api.elevenlabs.io/v1")
ELEVENLABS_MODEL = os.environ.get("AGENT_CONSOLE_ELEVENLABS_MODEL") or os.environ.get("NEREUS_ELEVENLABS_MODEL", "eleven_multilingual_v2")
OPENAI_TRANSCRIPTIONS_URL = os.environ.get("AGENT_CONSOLE_OPENAI_TRANSCRIPTIONS_URL") or os.environ.get("NEREUS_OPENAI_TRANSCRIPTIONS_URL", "https://api.openai.com/v1/audio/transcriptions")
OPENAI_REALTIME_CALLS_URL = os.environ.get("AGENT_CONSOLE_OPENAI_REALTIME_CALLS_URL") or os.environ.get("NEREUS_OPENAI_REALTIME_CALLS_URL", "https://api.openai.com/v1/realtime/calls")
OPENAI_TRANSCRIPTION_MODEL = os.environ.get("AGENT_CONSOLE_OPENAI_TRANSCRIPTION_MODEL") or os.environ.get("NEREUS_OPENAI_TRANSCRIPTION_MODEL", "gpt-4o-mini-transcribe")
OPENAI_REALTIME_TRANSCRIPTION_MODEL = os.environ.get("AGENT_CONSOLE_REALTIME_TRANSCRIPTION_MODEL") or os.environ.get("NEREUS_REALTIME_TRANSCRIPTION_MODEL", "gpt-realtime-whisper")
OPENAI_REALTIME_TRANSCRIPTION_DELAY = os.environ.get("AGENT_CONSOLE_REALTIME_TRANSCRIPTION_DELAY") or os.environ.get("NEREUS_REALTIME_TRANSCRIPTION_DELAY", "low")
COO_ENV_PATH = Path(
os.environ.get("AGENT_CONSOLE_AGENT_ENV_PATH")
or os.environ.get("NEREUS_COO_ENV_PATH")
or str(Path.home() / ".hermes/profiles/coo/.env")
).expanduser()
MAX_BODY_BYTES = 8_000_000
MAX_TTS_CHARS = 5_000
MISSIONS: dict[str, dict[str, Any]] = {}
MISSIONS_LOCK = threading.Lock()
CUSTOM_SKILLS_ROOT = Path(
os.environ.get("AGENT_CONSOLE_CUSTOM_SKILLS_ROOT")
or str(Path.home() / "workspace/shared_volume/skills")
).expanduser()
CUSTOM_SKILL_NAMESPACES = {"claude", "morpheus", "nereus", "optimus", "perseon", "wordpress"}
PWA_VERSION = "20260716d"
PWA_THEME_COLOR = "#050506"
PWA_BACKGROUND_COLOR = "#000000"
PWA_ICON_CACHE: dict[int, bytes] = {}
NEREUS_ICON_MATRIX = [
[0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1],
[0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1],
[0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
]
def pwa_manifest() -> dict[str, Any]:
return {
"name": "Agent Console",
"short_name": "Agent Console",
"description": "Single-page Hermes agent console for the selected agent.",
"id": "/?source=pwa",
"start_url": "/?source=pwa",
"scope": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": PWA_BACKGROUND_COLOR,
"theme_color": PWA_THEME_COLOR,
"categories": ["productivity", "utilities"],
"icons": [
{"src": "/apple-touch-icon.png?v=" + PWA_VERSION, "sizes": "180x180", "type": "image/png", "purpose": "any"},
{"src": "/icon-192.png?v=" + PWA_VERSION, "sizes": "192x192", "type": "image/png", "purpose": "any maskable"},
{"src": "/icon-512.png?v=" + PWA_VERSION, "sizes": "512x512", "type": "image/png", "purpose": "any maskable"},
],
}
def png_chunk(kind: bytes, data: bytes) -> bytes:
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
def build_pwa_icon(size: int) -> bytes:
cached = PWA_ICON_CACHE.get(size)
if cached:
return cached
bg = (0, 0, 0, 255)
panel = (5, 5, 7, 255)
accent = (120, 226, 255, 255)
accent_soft = (1, 199, 252, 82)
border = (38, 38, 44, 255)
pixels = [[bg for _ in range(size)] for _ in range(size)]
radius = max(18, size // 9)
pad = max(16, size // 12)
def rounded_rect(x0: int, y0: int, x1: int, y1: int, r: int, color: tuple[int, int, int, int]) -> None:
for y in range(max(0, y0), min(size, y1)):
for x in range(max(0, x0), min(size, x1)):
dx = max(x0 + r - x, 0, x - (x1 - r - 1))
dy = max(y0 + r - y, 0, y - (y1 - r - 1))
if dx * dx + dy * dy <= r * r:
pixels[y][x] = color
rounded_rect(pad, pad, size - pad, size - pad, radius, panel)
rounded_rect(pad + 2, pad + 2, size - pad - 2, size - pad - 2, radius - 2, panel)
for i in range(3):
rounded_rect(pad + i, pad + i, size - pad - i, size - pad - i, radius - i, border if i == 0 else panel)
center_x = size // 2
center_y = size // 2 + size // 56
glow_radius = int(size * 0.38)
for y in range(size):
for x in range(size):
dist = math.hypot(x - center_x, y - center_y)
if dist < glow_radius and pixels[y][x] == panel:
alpha = int((1 - dist / glow_radius) * accent_soft[3])
pixels[y][x] = (max(panel[0], alpha // 6), max(panel[1], alpha // 3), max(panel[2], alpha // 2), 255)
rows = len(NEREUS_ICON_MATRIX)
cols = len(NEREUS_ICON_MATRIX[0])
cell = max(10, size // 18)
icon_w = cols * cell
icon_h = rows * cell
start_x = (size - icon_w) // 2
start_y = (size - icon_h) // 2 + size // 56
for r, row in enumerate(NEREUS_ICON_MATRIX):
for c, on in enumerate(row):
if not on:
continue
x0 = start_x + c * cell
y0 = start_y + r * cell
for y in range(y0, min(size, y0 + cell - 1)):
for x in range(x0, min(size, x0 + cell - 1)):
pixels[y][x] = accent
raw = bytearray()
for row in pixels:
raw.append(0)
for px in row:
raw.extend(px)
png = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0)) + png_chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + png_chunk(b"IEND", b"")
PWA_ICON_CACHE[size] = png
return png
def send_bytes(handler: BaseHTTPRequestHandler, raw: bytes, content_type: str, cache: str = "public, max-age=86400") -> None:
try:
handler.send_response(200)
handler.send_header("Content-Type", content_type)
handler.send_header("Content-Length", str(len(raw)))
handler.send_header("Cache-Control", cache)
handler.end_headers()
handler.wfile.write(raw)
except (BrokenPipeError, ConnectionResetError):
pass # browser/proxy closed the icon request before the bytes finished writing
PROFILES_ROOT = Path(
os.environ.get("AGENT_CONSOLE_PROFILES_ROOT")
or str(Path.home() / ".hermes/profiles")
).expanduser().resolve()
SINGLE_PROFILE_DIR = (
Path(os.environ["AGENT_CONSOLE_PROFILE_DIR"]).expanduser().resolve()
if os.environ.get("AGENT_CONSOLE_PROFILE_DIR")
else None
)
DEFAULT_PROFILE_URL = (
os.environ.get("AGENT_CONSOLE_PROFILE_URL")
or os.environ.get("NEREUS_PROFILE_URL")
or (str(SINGLE_PROFILE_DIR) if SINGLE_PROFILE_DIR else "coo")
)
MISSIONS_ENABLED = os.environ.get("AGENT_CONSOLE_MISSIONS_ENABLED", "").strip().lower() in {"1", "true", "yes", "on"}
TRUTHY_VALUES = {"1", "true", "yes", "on"}
AGENT_METADATA = {
"ceo": {"name": "Perseon", "role": "CEO", "initials": "PE", "color": "#007a62"},
"coo": {"name": "COO Agent", "role": "Operations Agent", "initials": "CO", "color": "#78e2ff"},
"assistant": {"name": "Aria", "role": "Executive Assistant", "initials": "AR", "color": "#ffc857"},
"developer": {"name": "Forge", "role": "Developer", "initials": "FG", "color": "#55a6ff"},
"researcher": {"name": "Astra", "role": "Researcher", "initials": "AS", "color": "#b46bff"},
"content": {"name": "Quill", "role": "Content", "initials": "QU", "color": "#ff8c42"},
"reviewer": {"name": "Sentinel", "role": "Reviewer", "initials": "SE", "color": "#ff5d7d"},
}
SAFE_ENV_KEYS = (
"API_SERVER_ENABLED",
"API_SERVER_PORT",
"AGENT_NAME",
"AGENT_COLOUR_HASH",
"AGENT_CONSOLE_MISSIONS_ENABLED",
"ELEVENLABS_API_KEY",
"ELEVENLABS_API_KEY_ENC",
"ELEVENLABS_VOICE_ID",
"VOICE_TOOLS_OPENAI_KEY",
)
SECRET_KEY_HINTS = ("KEY", "TOKEN", "SECRET", "PASSWORD", "CREDENTIAL")
def normalize_agent_colour(value: str) -> str:
raw = str(value or "").strip()
if not raw:
return ""
candidate = raw[1:] if raw.startswith("#") else raw
if re.fullmatch(r"[0-9a-fA-F]{3}|[0-9a-fA-F]{6}", candidate):
return f"#{candidate.lower()}"
return ""
def metadata_for_profile(slug: str, env: dict[str, str] | None = None) -> dict[str, str]:
meta = {"name": slug.title(), "role": "Hermes Agent", "initials": slug[:2].upper(), "color": "#78E2FF"}
meta.update(AGENT_METADATA.get(slug, {}))
env = env or {}
env_name = env.get("AGENT_NAME", "").strip()
if env_name:
meta["name"] = env_name
env_colour = normalize_agent_colour(env.get("AGENT_COLOUR_HASH", ""))
if env_colour:
meta["color"] = env_colour
return meta
def missions_enabled_for_env(env: dict[str, str]) -> bool:
raw = env.get("AGENT_CONSOLE_MISSIONS_ENABLED")
if raw is None:
return MISSIONS_ENABLED
return str(raw).strip().lower() in TRUTHY_VALUES
def read_dotenv(path: Path) -> dict[str, str]:
"""Read dotenv keys without logging or returning secret values by default."""
values: dict[str, str] = {}
try:
for raw_line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
name, value = line.split("=", 1)
name = name.strip()
value = value.strip()
if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")):
value = value[1:-1]
values[name] = value
except OSError:
return {}
return values
def format_dotenv_value(key: str, value: str) -> str:
clean = str(value or "").strip()
if key == "AGENT_COLOUR_HASH":
return clean.lstrip("#").lower()
if re.fullmatch(r"[A-Za-z0-9_./:@+-]+", clean):
return clean
escaped = clean.replace("\\", "\\\\").replace('"', '\\"')
return f'"{escaped}"'
def write_dotenv_updates(path: Path, updates: dict[str, str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
try:
lines = path.read_text(encoding="utf-8", errors="ignore").splitlines()
except OSError:
lines = []
remaining = dict(updates)
output: list[str] = []
for line in lines:
stripped = line.strip()
if not stripped or stripped.startswith("#") or "=" not in line:
output.append(line)
continue
name = line.split("=", 1)[0].strip()
if name in updates:
if name in remaining:
output.append(f"{name}={format_dotenv_value(name, updates[name])}")
remaining.pop(name, None)
continue
output.append(line)
for key, value in remaining.items():
output.append(f"{key}={format_dotenv_value(key, value)}")
tmp_path = path.with_suffix(path.suffix + ".tmp")
tmp_path.write_text("\n".join(output).rstrip() + "\n", encoding="utf-8")
os.replace(tmp_path, path)
def write_dotenv_updates_remove(path: Path, updates: dict[str, str], remove_keys: set[str] | None = None) -> None:
"""Update profile .env keys and remove explicitly deprecated secret keys."""
path.parent.mkdir(parents=True, exist_ok=True)
remove_keys = remove_keys or set()
try:
lines = path.read_text(encoding="utf-8", errors="ignore").splitlines()
except OSError:
lines = []
remaining = dict(updates)
output: list[str] = []
for line in lines:
stripped = line.strip()
if not stripped or stripped.startswith("#") or "=" not in line:
output.append(line)
continue
name = line.split("=", 1)[0].strip()
if name in remove_keys:
continue
if name in updates:
if name in remaining:
output.append(f"{name}={format_dotenv_value(name, updates[name])}")
remaining.pop(name, None)
continue
output.append(line)
for key, value in remaining.items():
output.append(f"{key}={format_dotenv_value(key, value)}")
tmp_path = path.with_suffix(path.suffix + ".tmp")
tmp_path.write_text("\n".join(output).rstrip() + "\n", encoding="utf-8")
os.replace(tmp_path, path)
def _settings_encryption_master() -> str:
"""Resolve the server-side secret used to encrypt Agent Console settings."""
for key in (
"AGENT_CONSOLE_SETTINGS_KEY",
"AGENT_CONSOLE_SECRET_KEY",
"AGENT_CONSOLE_HERMES_API_KEY",
"API_SERVER_KEY",
):
value = os.environ.get(key, "").strip()
if value:
return value
return ""
def _settings_fernet() -> Any:
if Fernet is None:
raise RuntimeError("cryptography is required to encrypt ElevenLabs settings.")
master = _settings_encryption_master()
if not master:
raise RuntimeError("AGENT_CONSOLE_SETTINGS_KEY or API_SERVER_KEY is required before saving encrypted settings.")
key = base64.urlsafe_b64encode(hashlib.sha256(master.encode("utf-8")).digest())
return Fernet(key)
def encrypt_setting_secret(value: str) -> str:
clean = str(value or "").strip()
if not clean:
return ""
token = _settings_fernet().encrypt(clean.encode("utf-8")).decode("ascii")
return f"fernet:v1:{token}"
def decrypt_setting_secret(value: str) -> str:
raw = str(value or "").strip()
if not raw:
return ""
if not raw.startswith("fernet:v1:"):
return raw
token = raw.split(":", 2)[2]
try:
return _settings_fernet().decrypt(token.encode("ascii")).decode("utf-8")
except InvalidToken as exc:
raise RuntimeError("Encrypted ElevenLabs API key could not be decrypted with the current server key.") from exc
def encrypted_key_name(key: str) -> str:
return f"{key}_ENC"
def update_agent_env_metadata(profile_url: str, agent_name: str, agent_colour_hash: str) -> dict[str, Any]:
env_path = profile_env_path(profile_url)
clean_name = re.sub(r"\s+", " ", str(agent_name or "")).strip()
clean_colour = normalize_agent_colour(str(agent_colour_hash or ""))
if not clean_name:
raise ValueError("Agent name is required.")
if not clean_colour:
raise ValueError("Agent color must be a valid 3 or 6 digit hex color.")
write_dotenv_updates(env_path, {
"AGENT_NAME": clean_name,
"AGENT_COLOUR_HASH": clean_colour.lstrip("#"),
})
return agent_config(str(env_path.parent))
def update_missions_settings(profile_url: str, enabled: bool) -> dict[str, Any]:
env_path = profile_env_path(profile_url)
write_dotenv_updates(env_path, {
"AGENT_CONSOLE_MISSIONS_ENABLED": "true" if bool(enabled) else "false",
})
return agent_config(str(env_path.parent))
def update_elevenlabs_settings(profile_url: str, api_key: str, voice_id: str) -> dict[str, Any]:
"""Save selected-profile ElevenLabs settings without exposing raw secrets back to the browser."""
env_path = profile_env_path(profile_url)
clean_api_key = str(api_key or "").strip()
clean_voice_id = str(voice_id or "").strip()
updates: dict[str, str] = {}
remove_keys: set[str] = set()
if clean_api_key:
if len(clean_api_key) < 20:
raise ValueError("ElevenLabs API key looks too short.")
updates["ELEVENLABS_API_KEY_ENC"] = encrypt_setting_secret(clean_api_key)
remove_keys.add("ELEVENLABS_API_KEY")
else:
env = read_dotenv(env_path)
legacy_key = env.get("ELEVENLABS_API_KEY", "").strip()
encrypted_key = env.get("ELEVENLABS_API_KEY_ENC", "").strip()
if legacy_key and not encrypted_key:
updates["ELEVENLABS_API_KEY_ENC"] = encrypt_setting_secret(legacy_key)
remove_keys.add("ELEVENLABS_API_KEY")
if clean_voice_id:
if not re.fullmatch(r"[A-Za-z0-9_-]{8,120}", clean_voice_id):
raise ValueError("ElevenLabs voice ID must contain only letters, numbers, hyphens or underscores.")
updates["ELEVENLABS_VOICE_ID"] = clean_voice_id
if not updates:
return voice_config_payload(str(env_path.parent))
write_dotenv_updates_remove(env_path, updates, remove_keys)
return voice_config_payload(str(env_path.parent))
def _profile_candidate(profile_url: str) -> str:
raw = (profile_url or DEFAULT_PROFILE_URL).strip() or DEFAULT_PROFILE_URL
parsed = urllib.parse.urlparse(raw)
candidate = parsed.path if parsed.scheme in {"file", "http", "https"} else raw
candidate = urllib.parse.unquote(candidate).strip().rstrip("/")
return candidate or DEFAULT_PROFILE_URL
def _explicit_profile_env_path(candidate: str) -> Path | None:
if not candidate:
return None
expanded = Path(candidate).expanduser()
looks_like_path = expanded.is_absolute() or candidate.startswith((".", "~")) or "/" in candidate or "\\" in candidate
if not looks_like_path:
return None
path = expanded.resolve(strict=False)
return path if path.name == ".env" else path / ".env"
def profile_slug_from_url(profile_url: str) -> str:
candidate = _profile_candidate(profile_url)
explicit = _explicit_profile_env_path(candidate)
if explicit is not None:
return explicit.parent.name
parts = [part for part in candidate.split("/") if part]
if ".env" in parts:
env_index = parts.index(".env")
if env_index > 0:
return parts[env_index - 1]
if "profiles" in parts:
index = parts.index("profiles")
if len(parts) > index + 1:
return parts[index + 1]
return parts[-1] if parts else profile_slug_from_url(DEFAULT_PROFILE_URL)
def profile_env_path(profile_url: str) -> Path:
candidate = _profile_candidate(profile_url)
explicit = _explicit_profile_env_path(candidate)
if explicit is not None:
return explicit.resolve(strict=False)
slug = profile_slug_from_url(candidate)
path = (PROFILES_ROOT / slug / ".env").resolve(strict=False)
try:
path.relative_to(PROFILES_ROOT)
except ValueError as exc:
raise ValueError("Profile URL must resolve under the Hermes profiles directory.") from exc
return path
def agent_config(profile_url: str = "") -> dict[str, Any]:
env_path = profile_env_path(profile_url)
slug = env_path.parent.name
env = read_dotenv(env_path)
meta = metadata_for_profile(slug, env)
port = env.get("API_SERVER_PORT") or os.environ.get("AGENT_CONSOLE_API_SERVER_PORT") or ("8643" if slug == "coo" else "8642")
api_url = (
os.environ.get("AGENT_CONSOLE_HERMES_API_URL")
or env.get("API_SERVER_URL")
or f"http://127.0.0.1:{port}/v1/chat/completions"
)
model = os.environ.get("AGENT_CONSOLE_HERMES_MODEL") or env.get("HERMES_MODEL") or slug
session_id = os.environ.get("AGENT_CONSOLE_HERMES_SESSION_ID") or env.get("HERMES_SESSION_ID") or f"agent-console-{slug}-chat"
session_key = os.environ.get("AGENT_CONSOLE_HERMES_SESSION_KEY") or env.get("HERMES_SESSION_KEY") or f"agent-console-{slug}"
safe_env = {}
for key in SAFE_ENV_KEYS:
value = env.get(key, "")
safe_env[key] = {
"present": bool(value),
"value": "configured" if any(hint in key for hint in SECRET_KEY_HINTS) and value else value,
"secret": any(hint in key for hint in SECRET_KEY_HINTS),
}
try:
elevenlabs_api_key, api_key_source = elevenlabs_env_value(str(env_path.parent), "ELEVENLABS_API_KEY")
except Exception:
elevenlabs_api_key, api_key_source = "", "missing"
safe_env["ELEVENLABS_API_KEY"] = {
"present": bool(elevenlabs_api_key),
"value": "configured" if elevenlabs_api_key else "",
"secret": True,
"source": safe_config_source(api_key_source),
"encrypted": api_key_source.endswith("ELEVENLABS_API_KEY_ENC"),
}
safe_env["ELEVENLABS_API_KEY_ENC"] = {
"present": any(env.get(name, "") for name in ("ELEVENLABS_API_KEY_ENC", f"{slug.upper().replace('-', '_')}_ELEVENLABS_API_KEY_ENC", "NEREUS_ELEVENLABS_API_KEY_ENC")),
"value": "configured" if any(env.get(name, "") for name in ("ELEVENLABS_API_KEY_ENC", f"{slug.upper().replace('-', '_')}_ELEVENLABS_API_KEY_ENC", "NEREUS_ELEVENLABS_API_KEY_ENC")) else "",
"secret": True,
}
return {
"profileUrl": str(env_path.parent),
"profileSlug": slug,
"envPath": str(env_path),
"envExists": env_path.exists(),
"agent": meta,
"apiUrl": api_url,
"apiPort": str(port),
"model": model,
"sessionId": session_id,
"sessionKey": session_key,
"apiServerKeyConfigured": bool(env.get("API_SERVER_KEY") or os.environ.get("AGENT_CONSOLE_HERMES_API_KEY") or os.environ.get("API_SERVER_KEY")),
"missionsEnabled": missions_enabled_for_env(env),
"env": safe_env,
"availableProfiles": available_profiles(),
}
def available_profiles() -> list[dict[str, str]]:
profiles: list[dict[str, str]] = []
seen: set[str] = set()
if SINGLE_PROFILE_DIR is not None:
env_path = (SINGLE_PROFILE_DIR / ".env").resolve(strict=False)
slug = SINGLE_PROFILE_DIR.name
meta = metadata_for_profile(slug, read_dotenv(env_path))
profiles.append({"slug": slug, "url": str(SINGLE_PROFILE_DIR), **meta})
seen.add(str(SINGLE_PROFILE_DIR))
try:
dirs = sorted(path for path in PROFILES_ROOT.iterdir() if path.is_dir())
except OSError:
dirs = []
for path in dirs:
resolved = str(path.resolve(strict=False))
if resolved in seen:
continue
slug = path.name
meta = metadata_for_profile(slug, read_dotenv(path / ".env"))
profiles.append({"slug": slug, "url": str(path), **meta})
return profiles
def _read_json_file(path: Path) -> dict[str, Any]:
try:
data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
return data if isinstance(data, dict) else {}
except (OSError, json.JSONDecodeError):
return {}
def _safe_line(value: Any, limit: int = 220) -> str:
text = re.sub(r"\s+", " ", str(value or "")).strip()
if len(text) > limit:
text = text[: limit - 1].rstrip() + "…"
return text
def _frontmatter(text: str) -> dict[str, Any]:
if not text.startswith("---"):
return {}
end = text.find("\n---", 3)
if end == -1:
return {}
data: dict[str, Any] = {}
current: str | None = None
current_list: list[str] | None = None
for raw in text[3:end].splitlines():
if not raw.strip():
continue
item = re.match(r"^\s*-\s+(.*)$", raw)
if item and current and current_list is not None:
current_list.append(_safe_line(item.group(1), 60))
continue
match = re.match(r"^([A-Za-z_][\w-]*)\s*:\s*(.*)$", raw)
if not match:
continue
if current and current_list is not None:
data[current] = current_list
current, value = match.group(1), match.group(2).strip()
if value:
data[current] = value.strip('"\'')
current_list = None
else:
current_list = []
if current and current_list is not None:
data[current] = current_list
return data
def _skill_file(folder: Path) -> Path | None:
for name in ("SKILL.md", "skill.md", "Skill.md"):
candidate = folder / name
if candidate.is_file():
return candidate
return None
def _is_custom_skill(folder: Path, root: Path) -> bool:
"""Return True for Perseon-owned shared/profile custom skills only."""
try:
rel_parts = folder.relative_to(root).parts
except ValueError:
rel_parts = ()
namespace = rel_parts[0] if rel_parts else ""
if namespace in CUSTOM_SKILL_NAMESPACES:
return True
try:
resolved = folder.resolve(strict=False)
custom_root = CUSTOM_SKILLS_ROOT.resolve(strict=False)
resolved.relative_to(custom_root)
return True
except (OSError, ValueError):
return False
def agent_skills(profile_url: str = "") -> dict[str, Any]:
env_path = profile_env_path(profile_url)
slug = env_path.parent.name
root = env_path.parent / "skills"
skills: list[dict[str, Any]] = []
categories: dict[str, int] = {}
if root.is_dir():
try:
entries = sorted((p for p in root.iterdir() if not p.name.startswith(".")), key=lambda p: p.name.lower())
except OSError:
entries = []
for entry in entries:
folders: list[tuple[Path, str]] = []
direct = _skill_file(entry)
if direct:
folders.append((entry, ""))
elif entry.is_dir():
try:
for child in sorted((p for p in entry.iterdir() if not p.name.startswith(".")), key=lambda p: p.name.lower()):
if _skill_file(child):
folders.append((child, entry.name))
except OSError:
pass
for folder, category in folders:
skill_file = _skill_file(folder)
if not skill_file:
continue
try:
stat = skill_file.stat()
raw = skill_file.read_text(encoding="utf-8", errors="replace")[:32768]
rel = folder.relative_to(root).as_posix()
except OSError:
continue
if not _is_custom_skill(folder, root):
continue
front = _frontmatter(raw)
category = str(front.get("category") or category or "").strip()
categories[category or "uncategorized"] = categories.get(category or "uncategorized", 0) + 1
is_symlink = folder.is_symlink()
target_tail = ""
if is_symlink:
try:
target_tail = os.readlink(folder).split("/")[-1]
except OSError:
target_tail = ""
skills.append({
"slug": rel,
"name": _safe_line(front.get("name") or folder.name, 80),
"category": category,
"description": _safe_line(front.get("description") or "", 320),
"author": _safe_line(front.get("author") or "", 80),
"version": _safe_line(front.get("version") or "", 40),
"tags": front.get("tags") if isinstance(front.get("tags"), list) else [],
"isSymlink": is_symlink,
"targetTail": target_tail,
"modifiedAt": int(stat.st_mtime),
})
skills.sort(key=lambda item: ((item.get("category") or "~").lower(), item.get("name", "").lower()))
namespaces = {str(s.get("slug", "")).split("/", 1)[0] for s in skills if str(s.get("slug", ""))}
return {
"profileSlug": slug,
"root": str(root),
"available": root.is_dir(),
"totals": {"total": len(skills), "categories": len(categories), "namespaces": len(namespaces), "customOnly": True},
"categories": categories,
"skills": skills,
}
WORKSPACE_MAX_ENTRIES = 300
WORKSPACE_MAX_SEARCH_RESULTS = 150
WORKSPACE_MAX_PREVIEW_BYTES = 220 * 1024
WORKSPACE_TEXT_EXTENSIONS = {
".md", ".markdown", ".txt", ".py", ".js", ".css", ".html", ".htm", ".json",
".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".sh", ".sql", ".csv", ".xml", ".svg",
".ts", ".tsx", ".jsx", ".mjs", ".cjs", ".log",
}
WORKSPACE_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg"}
WORKSPACE_LOCKED_NAMES = {".env", "id_rsa", "id_ed25519", "auth.json", "credentials", "credentials.json", "token", "tokens", "state.db"}
WORKSPACE_LOCKED_PARTS = {".ssh", ".gnupg", ".aws", ".cache", ".claude", ".hermes", ".openclaw", "secrets", "secret", "tokens", "token", "credentials", "credential", "private", "password", "__pycache__", "node_modules", ".venv", "venv", ".pytest_cache", ".mypy_cache", ".next", "dist", "build"}
WORKSPACE_LOCKED_EXTENSIONS = {".pem", ".key", ".p12", ".pfx", ".crt", ".sqlite", ".sqlite3", ".db"}
def profile_workspace_root(profile_url: str = "") -> tuple[str, Path]:
env_path = profile_env_path(profile_url)
slug = env_path.parent.name
return slug, (env_path.parent / "workspace").resolve(strict=False)
def _workspace_resolve(profile_url: str = "", relative_path: str = "") -> tuple[str, Path, Path]:
slug, root = profile_workspace_root(profile_url)
rel = (relative_path or "").strip().strip("/")
# Reject absolute paths and any parent-traversal component up front. `.absolute()`
# does not collapse `..`, so a lexical `relative_to` check alone is fooled by
# `../../..` and lets the browser escape the workspace. Legitimate navigation only
# ever sends relative paths built from real directory entries, never `..`.
if rel and (Path(rel).is_absolute() or ".." in Path(rel).parts):
raise ValueError("Path escapes the selected agent workspace.")
# Containment is otherwise checked against the lexical workspace path, not the fully
# resolved target, because Hermes profile workspaces intentionally contain symlinks
# back into the local workspace. Sensitive paths are still locked by name/extension
# heuristics before preview.
target = root / rel
try:
target.absolute().relative_to(root.absolute())
except ValueError as exc:
raise ValueError("Path escapes the selected agent workspace.") from exc
return slug, root, target
def _workspace_relative(root: Path, path: Path) -> str:
try:
rel = path.absolute().relative_to(root.absolute()).as_posix()
except ValueError:
return "[outside-workspace]"
return "" if rel == "." else rel
def _workspace_lock_reason(root: Path, path: Path) -> str | None:
try:
rel = path.absolute().relative_to(root.absolute())
except ValueError:
return "outside workspace"
name = path.name.lower()
if name in WORKSPACE_LOCKED_NAMES or name.startswith(".env"):
return "sensitive filename"
if path.suffix.lower() in WORKSPACE_LOCKED_EXTENSIONS:
return "sensitive extension"
for part in (p.lower() for p in rel.parts):
if part in WORKSPACE_LOCKED_PARTS:
return "sensitive/runtime directory"
if any(term in part for term in ("secret", "credential", "password", "private", "token")):
return "secret-like path"
return None
def _workspace_kind(path: Path, is_dir: bool) -> str:
if is_dir:
return "folder"
ext = path.suffix.lower()
if ext in WORKSPACE_IMAGE_EXTENSIONS:
return "image"
if ext in WORKSPACE_TEXT_EXTENSIONS:
return "text"
mime = mimetypes.guess_type(path.name)[0] or ""
if mime.startswith("audio/"):
return "audio"
if mime.startswith("video/"):
return "video"
if mime == "application/pdf":
return "pdf"
return "file"
def _workspace_entry(root: Path, path: Path) -> dict[str, Any] | None:
try:
st = path.stat()
except OSError:
return None
is_dir = path.is_dir()
locked = _workspace_lock_reason(root, path)
ext = "" if is_dir else path.suffix.lower()
kind = _workspace_kind(path, is_dir)
preview_mode = "image" if (not is_dir and not locked and ext in WORKSPACE_IMAGE_EXTENSIONS) else "text" if (not is_dir and not locked and ext in WORKSPACE_TEXT_EXTENSIONS and st.st_size <= WORKSPACE_MAX_PREVIEW_BYTES) else None
rel = _workspace_relative(root, path)
return {
"name": ("Restricted folder" if is_dir else "Restricted file") if locked else (path.name or "workspace"),
"relativePath": "[restricted]" if locked else rel,
"absolutePath": "[restricted]" if locked else str(path.absolute()),
"kind": kind,
"extension": ext,
"isDirectory": is_dir,
"sizeBytes": None if is_dir else st.st_size,
"modifiedAt": int(st.st_mtime * 1000),
"locked": bool(locked),
"lockReason": locked,
"previewable": bool(preview_mode),
"previewMode": preview_mode,
}
def _workspace_breadcrumbs(relative_path: str) -> list[dict[str, str]]:
rel = (relative_path or "").strip().strip("/")
crumbs = [{"label": "workspace", "path": ""}]
current: list[str] = []
for part in Path(rel).parts if rel else []:
current.append(part)
crumbs.append({"label": part, "path": Path(*current).as_posix()})
return crumbs
def agent_workspace(profile_url: str = "", relative_path: str = "", query: str = "") -> dict[str, Any]:
slug, root, target = _workspace_resolve(profile_url, relative_path)
available = root.is_dir()
if not available:
return {"profileSlug": slug, "available": False, "root": str(root), "current": {}, "parent": "", "breadcrumbs": _workspace_breadcrumbs(""), "entries": [], "totals": {"shown": 0, "directories": 0, "files": 0}}
if not target.exists():
raise ValueError("Workspace path does not exist.")
if _workspace_lock_reason(root, target):
raise ValueError("Workspace path is blocked by safety policy.")
if not target.is_dir():
raise ValueError("Workspace path is not a directory.")
q = (query or "").strip().lower()
entries: list[dict[str, Any]] = []
if q:
for dirpath, dirnames, filenames in os.walk(target, followlinks=False):
current = Path(dirpath)
dirnames[:] = [d for d in sorted(dirnames) if not _workspace_lock_reason(root, current / d)]
for name in sorted([*dirnames, *filenames]):
candidate = current / name
rec = _workspace_entry(root, candidate)
if not rec:
continue
haystack = f"{rec.get('name')} {rec.get('relativePath')} {rec.get('kind')}".lower()
if q in haystack:
entries.append(rec)
if len(entries) >= WORKSPACE_MAX_SEARCH_RESULTS:
break
if len(entries) >= WORKSPACE_MAX_SEARCH_RESULTS:
break
else:
try:
children = sorted(target.iterdir(), key=lambda child: (not child.is_dir(), child.name.lower()))
except OSError as exc:
raise ValueError(f"Cannot read workspace directory: {exc}") from exc
for child in children[:WORKSPACE_MAX_ENTRIES]:
rec = _workspace_entry(root, child)
if rec:
entries.append(rec)
rel = _workspace_relative(root, target)
parent = ""
if rel:
parent = Path(rel).parent.as_posix()
if parent == ".":
parent = ""
return {
"profileSlug": slug,
"available": True,
"root": str(root),
"current": _workspace_entry(root, target) or {},
"parent": parent,
"breadcrumbs": _workspace_breadcrumbs(rel),
"entries": entries,
"query": query or "",
"totals": {
"shown": len(entries),
"directories": sum(1 for item in entries if item.get("isDirectory")),
"files": sum(1 for item in entries if not item.get("isDirectory")),
},
}
def agent_workspace_file(profile_url: str = "", relative_path: str = "") -> dict[str, Any]:
_slug, root, target = _workspace_resolve(profile_url, relative_path)
if not target.exists() or not target.is_file():
raise ValueError("Workspace file does not exist.")
reason = _workspace_lock_reason(root, target)
if reason:
raise ValueError(f"Preview blocked: {reason}.")
ext = target.suffix.lower()
if ext not in WORKSPACE_TEXT_EXTENSIONS:
raise ValueError("Preview is limited to text, code, markdown, HTML, and image files.")
st = target.stat()
if st.st_size > WORKSPACE_MAX_PREVIEW_BYTES:
raise ValueError("File exceeds preview size limit.")
rec = _workspace_entry(root, target) or {}
raw = target.read_text(encoding="utf-8", errors="replace")
rec["content"] = raw[:WORKSPACE_MAX_PREVIEW_BYTES]
rec["rawContent"] = rec["content"]
rec["renderMode"] = "preview" if ext in {".md", ".markdown", ".html", ".htm"} else "raw"
rec["readOnly"] = True
return rec
def agent_workspace_image(profile_url: str = "", relative_path: str = "") -> tuple[bytes, str]:
_slug, root, target = _workspace_resolve(profile_url, relative_path)
if not target.exists() or not target.is_file():
raise ValueError("Workspace image does not exist.")
reason = _workspace_lock_reason(root, target)
if reason:
raise ValueError(f"Image blocked: {reason}.")
if target.suffix.lower() not in WORKSPACE_IMAGE_EXTENSIONS:
raise ValueError("Not an image file.")
if target.stat().st_size > 20 * 1024 * 1024:
raise ValueError("Image is too large for inline preview.")
content_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
return target.read_bytes(), content_type
def _session_preview(text: str) -> str:
clean = re.sub(r"\s+", " ", str(text or "")).strip()
if not clean:
return "No preview captured."
return _safe_line(clean, 180)
def agent_sessions(profile_url: str = "", limit: int = 15) -> dict[str, Any]:
env_path = profile_env_path(profile_url)
slug = env_path.parent.name
state_db = env_path.parent / "state.db"
sessions: list[dict[str, Any]] = []
total = 0
available = state_db.is_file()
if available:
try:
con = sqlite3.connect(state_db)
con.row_factory = sqlite3.Row
total = int(con.execute("SELECT COUNT(*) FROM sessions WHERE archived = 0").fetchone()[0])
rows = con.execute(
"""
SELECT id, source, model, started_at, ended_at, end_reason,
message_count, tool_call_count, api_call_count,
estimated_cost_usd, actual_cost_usd, title
FROM sessions
WHERE archived = 0
ORDER BY COALESCE(ended_at, started_at) DESC
LIMIT ?
""",
(max(1, min(int(limit or 15), 20)),),
).fetchall()
for row in rows:
first_message = con.execute(
"""
SELECT content FROM messages
WHERE session_id = ? AND role IN ('user', 'assistant') AND content IS NOT NULL AND content != ''
ORDER BY timestamp ASC LIMIT 1
""",
(row["id"],),
).fetchone()
title = _safe_line(row["title"] or "", 90)
preview = _session_preview(first_message["content"] if first_message else "")
sessions.append({
"id": row["id"],
"shortId": str(row["id"] or "")[:8],
"source": _safe_line(row["source"] or "unknown", 40),
"model": _safe_line(row["model"] or "", 60),
"startedAt": int(float(row["started_at"] or 0) * 1000) if row["started_at"] else None,
"endedAt": int(float(row["ended_at"] or 0) * 1000) if row["ended_at"] else None,
"status": "active" if not row["ended_at"] else (row["end_reason"] or "ended"),
"messageCount": int(row["message_count"] or 0),
"toolCallCount": int(row["tool_call_count"] or 0),
"apiCallCount": int(row["api_call_count"] or 0),
"costUsd": row["actual_cost_usd"] if row["actual_cost_usd"] is not None else row["estimated_cost_usd"],
"title": title or preview,
"preview": preview,
})
except (OSError, sqlite3.Error, ValueError):
sessions = []
total = 0
finally:
try:
con.close() # type: ignore[name-defined]
except Exception:
pass
active = sum(1 for item in sessions if item.get("status") == "active")
return {
"profileSlug": slug,
"source": str(state_db),
"available": available,
"totals": {"total": total, "shown": len(sessions), "active": active},
"sessions": sessions,
}