-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaios_hub.py
More file actions
2037 lines (1816 loc) · 96.7 KB
/
Copy pathaios_hub.py
File metadata and controls
2037 lines (1816 loc) · 96.7 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
"""
AIOS Hub — the unified brain + interconnect for The AI OS.
One dashboard to talk to EVERYTHING (opencode, hermes, openclaw, CrewAI) and the
bus that lets the agents reach each other. Pure Python standard library.
Started by `aios start hub`. Config comes from the environment (aios injects it):
AIOS_HUB_PORT, AIOS_LLM_PROVIDER, AIOS_LLM_API_KEY, AIOS_LLM_BASE_URL,
AIOS_DEFAULT_MODEL, AIOS_OPENCODE_URL, AIOS_HERMES_URL, AIOS_OPENCLAW_URL,
AIOS_CREWAI_URL, AIOS_OPENCLAWOS_URL, AIOS_OPENCODE_DIR, AIOS_BUN, AIOS_DASHBOARD
"""
from __future__ import annotations
import copy
import json
import os
import re
import shutil
import socket
import subprocess
import threading
import time
import urllib.request
import urllib.error
from urllib.parse import parse_qs, urlparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
import aios_brain as brain # noqa: E402 durable state: memory, tasks, flows, audit
import aios_sec as sec # noqa: E402 the gate in front of full-control mode
import aios_tools as tools # noqa: E402 shell + channel/skill catalogs
import aios_updates as updates # noqa: E402 agent-supervised dependency updates
import aios_web as web # noqa: E402 YouTube / Reddit / HN / page readers
import aios_swarm as swarm # noqa: E402 decompose big tasks across agents
import aios_plugins as plugins # noqa: E402 the plugin store
import aios_vault as vault # noqa: E402 master password for destructive ops
PORT = int(os.environ.get("AIOS_HUB_PORT", "8787"))
ROOT = Path(os.environ.get("AIOS_ROOT", Path(__file__).resolve().parent))
DASHBOARD = Path(os.environ.get("AIOS_DASHBOARD", ROOT / "docs" / "dashboard.html"))
ENV_FILE = ROOT / ".env"
CONFIG_FILE = ROOT / "aios.config.yaml"
CHANNEL_KEYS = ["TELEGRAM_BOT_TOKEN", "DISCORD_BOT_TOKEN", "SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"]
EDITABLE_ENV = ["AIOS_LLM_PROVIDER", "AIOS_LLM_API_KEY", "AIOS_DEFAULT_MODEL",
"AIOS_LLM_BASE_URL", "OPENCODE_SERVER_PASSWORD"] + CHANNEL_KEYS
def _mask(v: str) -> str:
if not v:
return ""
return v[:4] + "…" + v[-4:] if len(v) > 8 else "*" * len(v)
def read_env_file() -> dict:
d = {}
if ENV_FILE.exists():
for line in ENV_FILE.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, _, v = line.partition("=")
d[k.strip()] = v.strip()
return d
def write_env_updates(updates: dict):
d = read_env_file()
for k, v in updates.items():
if v is None:
continue
if isinstance(v, str) and ("…" in v or (v and set(v) == {"*"})):
continue # ignore masked placeholders the UI echoed back
d[k] = v
lines = ["# The AI OS secrets — DO NOT COMMIT (edited via hub)"]
lines += [f"{k}={v}" for k, v in d.items()]
ENV_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8")
def run_aios(*a, background=False):
cmd = [sys.executable, str(ROOT / "aios.py"), *a]
# Strip inherited AIOS_LLM_*/model vars so the child setup reads .env (the
# file we just wrote), not the hub's own launch-time environment.
env = dict(os.environ)
for k in ("AIOS_LLM_PROVIDER", "AIOS_LLM_API_KEY", "AIOS_LLM_BASE_URL", "AIOS_DEFAULT_MODEL"):
env.pop(k, None)
env["AIOS_NO_UPDATE_CHECK"] = "1" # never git-pull during a hub-triggered restart
if background:
threading.Thread(target=lambda: subprocess.run(cmd, cwd=str(ROOT), env=env,
capture_output=True), daemon=True).start()
return {"ok": True, "started": " ".join(a)}
r = subprocess.run(cmd, cwd=str(ROOT), env=env, capture_output=True, text=True)
return {"ok": r.returncode == 0, "out": (r.stdout or r.stderr)[-2000:]}
# Registry of everything the hub knows about.
PEERS = {
"opencode": os.environ.get("AIOS_OPENCODE_URL", "http://127.0.0.1:4096"),
"hermes": os.environ.get("AIOS_HERMES_URL", "http://127.0.0.1:9119"),
"openclaw": os.environ.get("AIOS_OPENCLAW_URL", "http://127.0.0.1:18789"),
"crewai": os.environ.get("AIOS_CREWAI_URL", "http://127.0.0.1:4788"),
"claudecode": os.environ.get("AIOS_CLAUDECODE_URL", "http://127.0.0.1:8000"),
"codex": os.environ.get("AIOS_CODEX_URL", "http://127.0.0.1:8010"),
"openclaw-os": os.environ.get("AIOS_OPENCLAWOS_URL", "http://127.0.0.1:18789/plugins/openclawos/"),
}
CLAUDECODE = os.environ.get("AIOS_CLAUDECODE_URL", "http://127.0.0.1:8000").rstrip("/")
OPENCLAW_EMBED = os.environ.get("AIOS_OPENCLAWPROXY_URL", "http://127.0.0.1:8791/")
HERMES_EMBED = os.environ.get("AIOS_HERMESPROXY_URL", "http://127.0.0.1:8792/")
SCHEDULES_FILE = ROOT / ".aios" / "schedules.json"
SYSTEM_PROMPT_FILE = ROOT / ".aios" / "system_prompt.txt"
def read_system_prompt() -> str:
try:
return SYSTEM_PROMPT_FILE.read_text(encoding="utf-8").strip()
except Exception:
return ""
# Chat "targets" the AIOS API exposes as OpenAI-style models.
TARGETS = ["brain", "team", "swarm", "opencode", "crewai", "claudecode", "codex", "fabric", "all"]
MEMORY_FILE = ROOT / ".aios" / "memory.json"
USAGE_FILE = ROOT / ".aios" / "usage.json"
PROMPTS_FILE = ROOT / ".aios" / "prompts.json"
WIDGETS_FILE = ROOT / ".aios" / "widgets.json" # generative-UI canvas any agent can edit
def _load_json(p, default):
try:
return json.loads(p.read_text(encoding="utf-8"))
except Exception:
return default
def _save_json(p, data):
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps(data, indent=2), encoding="utf-8")
def read_memory() -> list:
"""All memories, newest first (the Memory page). Recall on a *turn* uses
active_recall() instead — searching beats dumping the whole file."""
return [m["text"] for m in brain.mem_all(200)]
def migrate_memory_once():
"""Old builds kept memory in .aios/memory.json. Fold it into SQLite once."""
if not MEMORY_FILE.exists():
return
try:
for item in _load_json(MEMORY_FILE, []):
brain.mem_add(str(item), kind="fact", source="memory.json")
MEMORY_FILE.rename(MEMORY_FILE.with_suffix(".json.migrated"))
except Exception:
pass
# --------------------------------------------------------------------------- #
# Active Memory — a memory sub-agent that fires on EVERY turn, not just at #
# session start. Recall is a free FTS query; extraction is one small async LLM #
# call, so remembering never slows down or bills the turn the user is waiting #
# on. #
# --------------------------------------------------------------------------- #
def active_memory_on() -> bool:
return os.environ.get("AIOS_ACTIVE_MEMORY", "1") == "1"
def active_recall(message: str, k: int = 6) -> str:
if not active_memory_on():
return ""
hits = brain.mem_search(message, k=k)
if not hits:
return ""
return ("\n\nRelevant things you already know about this user or system "
"(recalled for this turn):\n" + "\n".join("- " + h["text"] for h in hits))
_EXTRACT_SYS = (
"You maintain an agent's long-term memory. From the exchange below, extract "
"durable facts worth remembering across sessions: user preferences, names, "
"environment details, decisions, credentials' *locations* (never values). "
"Ignore anything transient or specific to this one task. "
"Output one fact per line, no bullets, no preamble. Output NOTHING if there is "
"nothing durable — that is the common case.")
def active_extract(user_msg: str, reply: str):
"""Fire-and-forget: learn from the turn without blocking it."""
if not active_memory_on():
return
try:
text = llm_chat([{"role": "user",
"content": f"User: {user_msg[:2000]}\n\nAssistant: {reply[:2000]}"}],
system=_EXTRACT_SYS)
for line in (text or "").splitlines():
fact = line.strip().lstrip("-•* ").strip()
if 8 < len(fact) < 300 and not fact.upper().startswith("NOTHING"):
brain.mem_add(fact, kind="fact", source="active-memory")
except Exception:
pass
def remember_async(user_msg: str, reply: str):
threading.Thread(target=active_extract, args=(user_msg, reply), daemon=True).start()
# --------------------------------------------------------------------------- #
# Self-improving skill loop — after a task that actually *did* something, judge #
# whether it taught a reusable procedure and, if so, write a SKILL.md that #
# every agent mounts. This is the closed loop: the system gets faster at the #
# things you actually ask it to do. #
# --------------------------------------------------------------------------- #
def skill_learn_on() -> bool:
return os.environ.get("AIOS_SKILL_LEARN", "1") == "1"
_LEARN_SYS = (
"You are the Curator: an agent that turns completed tasks into reusable skills.\n"
"Given a task, the commands that were run, and the outcome, decide whether this "
"taught a GENERALIZABLE procedure worth saving — something that would help next time "
"a similar task appears.\n\n"
"Reply with EXACTLY 'SKIP' if it was trivial, one-off, purely conversational, or failed.\n"
"Otherwise reply with a Markdown skill file and nothing else, in this shape:\n"
"---\nname: <kebab-case-name>\ndescription: <one line, when to use this>\n---\n\n"
"# <Title>\n\n## When to use\n...\n\n## Steps\n1. ...\n\n## Commands\n```sh\n...\n```\n")
def maybe_learn_skill(user_msg: str, reply: str, ran: list[str]):
"""Only fires when the turn ran commands — a conversation teaches no procedure."""
if not (skill_learn_on() and ran):
return
try:
ctx = (f"Task: {user_msg[:1500]}\n\nCommands run:\n" + "\n".join(f"$ {c}" for c in ran) +
f"\n\nOutcome:\n{reply[:1500]}")
out = (llm_chat([{"role": "user", "content": ctx}], system=_LEARN_SYS) or "").strip()
if not out or out.upper().startswith("SKIP") or "---" not in out:
return
name = ""
for line in out.splitlines():
if line.lower().startswith("name:"):
name = line.split(":", 1)[1].strip()
break
if not name:
return
tools.learn_skill(name, out, task=user_msg[:400])
_log_event("learned", "curator", f"Learned a new skill: {name}")
except Exception:
pass
def learn_async(user_msg: str, reply: str, ran: list[str]):
threading.Thread(target=maybe_learn_skill, args=(user_msg, reply, ran), daemon=True).start()
def bump_usage(target: str):
u = _load_json(USAGE_FILE, {})
u[target] = u.get(target, 0) + 1
# claude-code (subscription) and brain-on-subscription cost $0 in API terms.
_save_json(USAGE_FILE, u)
def _llm_key() -> str:
return (os.environ.get("AIOS_LLM_API_KEY") or os.environ.get("OPENROUTER_API_KEY")
or os.environ.get("OPENAI_API_KEY") or os.environ.get("ANTHROPIC_API_KEY") or "sk-aios")
def _models_from(url: str, key: str = "") -> list:
hdr = {"Authorization": f"Bearer {key}"} if key else {}
req = urllib.request.Request(url.rstrip("/") + "/models", headers=hdr)
data = json.loads(urllib.request.urlopen(req, timeout=15).read())
# OpenAI shape {"data":[{"id":..}]} or a bare list
items = data.get("data", data) if isinstance(data, dict) else data
return [m.get("id") for m in items if isinstance(m, dict) and m.get("id")]
def fetch_provider_models() -> dict:
"""List models the active provider serves (your Claude models via claude-code-api, etc.).
Returns {models, base, error} so the UI can show what happened."""
base, key = llm_base(), _llm_key()
out = {"models": [], "base": base, "error": ""}
try:
out["models"] = _models_from(base, key)
except Exception as e:
out["error"] = str(e)[:200]
# Fallback: if nothing came back, try claude-code-api directly (common case).
if not out["models"] and CLAUDECODE.rstrip("/") + "/v1" != base:
try:
m = _models_from(CLAUDECODE + "/v1")
if m:
out.update(models=m, base=CLAUDECODE + "/v1", error="")
except Exception:
pass
return out
# --------------------------------------------------------------------------- #
# LLM (OpenAI-compatible) — the "AIOS Brain" #
# --------------------------------------------------------------------------- #
def llm_base() -> str:
b = os.environ.get("AIOS_LLM_BASE_URL", "").strip()
if b:
return b.rstrip("/")
prov = os.environ.get("AIOS_LLM_PROVIDER", "openrouter").lower()
return {
"openrouter": "https://openrouter.ai/api/v1",
"openai": "https://api.openai.com/v1",
"gemini": "https://generativelanguage.googleapis.com/v1beta/openai",
"claudecode": CLAUDECODE + "/v1", # Claude Pro/Max via claude-code-api
}.get(prov, "https://openrouter.ai/api/v1")
def llm_chat(messages: list, system: str | None = None) -> str:
key = os.environ.get("AIOS_LLM_API_KEY") or os.environ.get("OPENROUTER_API_KEY") \
or os.environ.get("OPENAI_API_KEY") or os.environ.get("ANTHROPIC_API_KEY", "")
if not key:
return "⚠️ No model API key set. Run `aios setup --force` and enter your key, then restart."
model = os.environ.get("AIOS_DEFAULT_MODEL", "anthropic/claude-opus-4.6")
msgs = ([{"role": "system", "content": system}] if system else []) + messages
body = json.dumps({"model": model, "messages": msgs}).encode()
req = urllib.request.Request(
llm_base() + "/chat/completions", data=body, method="POST",
headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}",
"HTTP-Referer": "https://github.com/ZDStudios/AIOS", "X-Title": "The AI OS"})
try:
# Generous: when the provider is claude-code, every call shells out to the
# Claude CLI, which cold-starts slowly. Swarm planning is a big prompt and
# was timing out at 120s, which surfaced as "no usable plan".
with urllib.request.urlopen(req, timeout=int(
os.environ.get("AIOS_LLM_TIMEOUT", "300"))) as r:
data = json.loads(r.read())
return data["choices"][0]["message"]["content"]
except urllib.error.HTTPError as e:
return f"⚠️ LLM error {e.code}: {e.read().decode(errors='replace')[:400]}"
except Exception as e:
return f"⚠️ LLM error: {e}"
# --------------------------------------------------------------------------- #
# Per-agent adapters #
# --------------------------------------------------------------------------- #
def post_json(url: str, payload: dict, timeout=180) -> dict:
req = urllib.request.Request(url, data=json.dumps(payload).encode(),
method="POST", headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
def ask_crewai(message: str) -> str:
try:
out = post_json(PEERS["crewai"].rstrip("/") + "/chat", {"message": message})
return out.get("reply") or out.get("error") or json.dumps(out)
except Exception as e:
return f"⚠️ CrewAI service not reachable ({e}). Is it running? `aios start crewai`"
def ask_opencode(message: str) -> str:
"""Run a one-shot opencode prompt via its CLI (headless)."""
bun = os.environ.get("AIOS_BUN") or shutil.which("bun")
ocdir = os.environ.get("AIOS_OPENCODE_DIR", "")
if not (bun and ocdir and Path(ocdir).exists()):
return "⚠️ opencode not available (bun/opencode dir missing)."
try:
r = subprocess.run([bun, "src/index.ts", "run", message], cwd=ocdir,
capture_output=True, text=True, timeout=240, env=os.environ)
out = (r.stdout or "").strip() or (r.stderr or "").strip()
return out[-6000:] if out else "(opencode returned no output)"
except subprocess.TimeoutExpired:
return "⚠️ opencode timed out (240s)."
except Exception as e:
return f"⚠️ opencode error: {e}"
def ask_codex(message: str, history: list | None = None) -> str:
"""Codex CLI through its OpenAI-compatible bridge (services/codex_api.py)."""
base = os.environ.get("AIOS_CODEX_URL", "http://127.0.0.1:8010").rstrip("/")
msgs = (history or []) + [{"role": "user", "content": message}]
try:
d = post_json(base + "/v1/chat/completions",
{"model": "codex", "messages": msgs}, timeout=620)
return (d.get("choices") or [{}])[0].get("message", {}).get("content", "") or "(codex returned nothing)"
except urllib.error.HTTPError as e:
try:
return "⚠️ " + json.loads(e.read()).get("error", {}).get("message", str(e))
except Exception:
return f"⚠️ codex error: {e}"
except Exception as e:
return (f"⚠️ codex-api not reachable ({e}). Start it with `aios start codex`, "
f"and make sure the `codex` CLI is installed and logged in.")
def ask_claudecode(message: str, history: list | None = None) -> str:
"""Call claude-code-api's OpenAI-compatible endpoint."""
msgs = (history or []) + [{"role": "user", "content": message}]
body = json.dumps({"model": "claude-sonnet-4-5", "messages": msgs}).encode()
req = urllib.request.Request(CLAUDECODE + "/v1/chat/completions", data=body, method="POST",
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=180) as r:
return json.loads(r.read())["choices"][0]["message"]["content"]
except Exception as e:
return f"⚠️ claude-code-api not reachable ({e}). Start it (`aios start claudecode`) and make sure the `claude` CLI is installed + authenticated."
# --------------------------------------------------------------------------- #
# Agent modes — composable behavioural overlays from upstream projects: #
# caveman (JuliusBrussee/caveman) — trims how much the agent SAYS #
# ponytail (DietrichGebert/ponytail) — trims how much the agent BUILDS #
# State persists so toggles survive restarts. Both can be on at once. #
# --------------------------------------------------------------------------- #
MODES_FILE = ROOT / ".aios" / "modes.json"
def modes_state() -> dict:
st = _load_json(MODES_FILE, {})
return {k: {"enabled": bool(st.get(k, {}).get("enabled", False)),
"level": st.get(k, {}).get("level", "full")}
for k in tools.AGENT_MODES}
def set_mode(name: str, enabled: bool, level: str = "full") -> dict:
if name not in tools.AGENT_MODES:
return modes_state()
st = modes_state()
lv = level if level in tools.AGENT_MODES[name]["levels"] else "full"
st[name] = {"enabled": bool(enabled), "level": lv}
_save_json(MODES_FILE, st)
return st
def modes_prompt_suffix() -> str:
"""Every enabled mode's overlay, concatenated. They compose cleanly because
one governs prose style and the other governs engineering decisions."""
return "".join(tools.mode_overlay(n, s["level"])
for n, s in modes_state().items() if s["enabled"])
# --------------------------------------------------------------------------- #
# Fabric — run any of the 255 danielmiessler/fabric patterns through AIOS's own #
# model path. A pattern is a system prompt; the user's text is the input. #
# --------------------------------------------------------------------------- #
def run_fabric(pattern: str, text: str, target: str = "brain") -> str:
system = tools.fabric_pattern_system(pattern)
if system is None:
return f"⚠️ Unknown fabric pattern '{pattern}'. See the Patterns view for the full list."
system += modes_prompt_suffix()
# Route through claude-code when the brain is on the subscription, else the LLM.
if target in ("claudecode", "claude-code"):
return ask_claudecode(text, [{"role": "system", "content": system}])
return llm_chat([{"role": "user", "content": text}], system=system)
TOOL_PROTOCOL = (
"\n\nFULL CONTROL: you control the computer AIOS is installed on. To run a shell "
"command, emit a line of exactly this form:\n"
"RUN: <command>\n"
"Emit up to 3 RUN lines, then stop and wait — the outputs are fed back to you and you "
"continue. When you have the final answer, reply in normal prose with no RUN lines. "
"Only reach for the shell when the task actually needs the machine (inspecting files, "
"checking a service, git, installing packages). Never guess at output you could just go "
"and read.")
def brain_system_prompt(message: str) -> str:
sysp = read_system_prompt() or (
"You are the AIOS Brain — the orchestrator of The AI OS, which unifies six agents: "
"opencode (coding), hermes (autonomous), openclaw (channels), CrewAI (multi-agent crews), "
"claude-code (Claude Code API), and LifeOS (shared skills). Be concise and helpful. Suggest "
"which agent is best for a task.")
sysp += ("\n\nGENERATIVE UI (OpenUI): when a visual answer helps (charts, tables, forms, dashboards, "
"buttons, games), emit a fenced ```ui block containing a full, self-contained HTML document "
"(inline CSS/JS, no external URLs). The hub renders it live and interactive inside the chat. "
"Use the page's theme via CSS variables like var(--accent), var(--bg), var(--text). This is "
"OpenUI-style generative UI (https://www.openui.com).\n"
"If the user asks for it ON THE CANVAS or ON THE DASHBOARD, still just emit the ```ui block — "
"the hub pins it to the Canvas for you automatically. Don't try to curl the HTML anywhere, and "
"don't say you can't; building the block IS how it gets there. Make it self-contained and sized "
"to fit its container (use width:100%, and for a <canvas> set its size from JS on load).")
if tools.full_control():
sysp += TOOL_PROTOCOL
sysp += (
"\n\nRESTYLING THIS DASHBOARD: if the user asks to change how the Control Room "
f"looks — colours, text size, spacing/density, which sidebar items show, or adding "
f"a live panel — do it through the hub API, NEVER by editing docs/dashboard.html "
f"(editing the file can break the UI; the API cannot, and `reset` undoes it).\n"
f" RUN: curl -s http://127.0.0.1:{PORT}/api/dashboard\n"
f" RUN: curl -s -X POST http://127.0.0.1:{PORT}/api/dashboard -H 'Content-Type: application/json' "
"-d '{\"op\":\"set\",\"vars\":{\"--accent\":\"#4f9dff\"},\"scale\":1.1,\"density\":\"compact\"}'\n"
"Ops: set (vars/css/scale/density) · nav (hidden/order) · panel (add/del/clear, "
"slot top|chat|sidebar, self-contained HTML styled with var(--accent) etc.) · "
"reset (what: all|vars|css|panels|nav). Full reference: the `dashboard-designer` skill.")
sysp += (
"\n\nREADING THE WEB: you can read YouTube videos (full transcripts), Reddit "
"threads, Hacker News and any web page through the hub — use these instead of "
"writing your own scraper, and never claim you cannot open a link:\n"
f" RUN: curl -s -X POST http://127.0.0.1:{PORT}/api/web -H 'Content-Type: application/json' "
"-d '{\"op\":\"youtube\",\"url\":\"<link>\"}'\n"
"ops: youtube (transcript_timestamped + title/channel/chapters) · reddit (post+comments, "
"r/sub, or a search phrase) · hn · search · fetch (any URL -> readable text). "
"Add \"|python -c ...\" or pipe through jq to trim big payloads before reading them.")
sysp += active_recall(message) # Active Memory: relevant context, every turn
sysp += modes_prompt_suffix() # caveman / ponytail overlays when toggled on
return sysp
def _parse_runs(text: str) -> list[str]:
return [l.strip()[4:].strip() for l in (text or "").splitlines()
if l.strip().upper().startswith("RUN:") and len(l.strip()) > 4]
# One request == one thread (ThreadingHTTPServer), so the handler can pick up
# which commands the Brain ran on this turn without threading it through route().
_TL = threading.local()
def commands_this_turn() -> list[str]:
return list(getattr(_TL, "ran", []))
# --------------------------------------------------------------------------- #
# Live activity — what the agent is thinking/doing, streamed to the chat while #
# the turn is still running. The chat POST is blocking, so progress goes to a #
# side channel the browser polls (GET /api/activity) instead of restructuring #
# the whole request path around SSE. #
# --------------------------------------------------------------------------- #
_ACT: dict[str, dict] = {}
_ACT_LOCK = threading.Lock()
def act(kind: str, text: str, detail: str = ""):
"""Record a step for whichever turn this thread is serving. No-op if untracked."""
turn = getattr(_TL, "turn", "")
if not turn:
return
with _ACT_LOCK:
rec = _ACT.setdefault(turn, {"events": [], "done": False, "ts": time.time()})
rec["events"].append({"kind": kind, "text": str(text)[:400],
"detail": str(detail)[:1500], "t": time.time()})
rec["ts"] = time.time()
if len(rec["events"]) > 200:
rec["events"] = rec["events"][-200:]
def act_begin(turn: str):
_TL.turn = turn or ""
if turn:
with _ACT_LOCK:
_ACT[turn] = {"events": [], "done": False, "ts": time.time()}
# drop anything older than 10 minutes so this can't grow forever
for k in [k for k, v in _ACT.items() if time.time() - v["ts"] > 600]:
_ACT.pop(k, None)
def act_end():
turn = getattr(_TL, "turn", "")
if turn:
with _ACT_LOCK:
if turn in _ACT:
_ACT[turn]["done"] = True
_TL.turn = ""
def activity(turn: str, since: int = 0) -> dict:
with _ACT_LOCK:
rec = _ACT.get(turn)
if not rec:
return {"events": [], "done": False, "n": since}
ev = rec["events"][since:]
return {"events": ev, "done": rec["done"], "n": since + len(ev)}
def run_brain(message: str, history: list, max_rounds: int = 4) -> tuple[str, list[str]]:
"""The Brain with a body: think → RUN → read output → think again."""
sysp = brain_system_prompt(message)
msgs = list(history) + [{"role": "user", "content": message}]
ran: list[str] = []
_TL.ran = ran
out = ""
for round_i in range(max_rounds):
act("thinking", "Thinking…" if round_i == 0 else f"Thinking (step {round_i + 1})…")
out = llm_chat(msgs, system=sysp)
cmds = _parse_runs(out)
if not cmds or not tools.full_control():
prose = "\n".join(l for l in (out or "").splitlines()
if not l.strip().upper().startswith("RUN:")).strip()
if prose:
act("note", prose[:300])
return out, ran
results = []
for c in cmds[:3]:
act("run", c)
r = tools.shell(c, actor="brain")
ran.append(c)
body = (r["out"] or "") + (f"\n[stderr]\n{r['err']}" if r["err"] else "")
if r.get("blocked"):
body = r["err"]
act("blocked", c, body)
else:
act("result", f"exit {r['code']}", (body or "(no output)")[:900])
results.append(f"$ {c}\n(exit {r['code']})\n{body[:3000] or '(no output)'}")
last = round_i == max_rounds - 1
nudge = ("\n\nThat was the last command you may run. Give the final answer now, "
"with no RUN lines." if last else "")
msgs += [{"role": "assistant", "content": out},
{"role": "user", "content": "Command results:\n\n" + "\n\n".join(results) + nudge}]
out = llm_chat(msgs, system=sysp) # force a prose answer after the last round
return "\n".join(l for l in out.splitlines() if not l.strip().upper().startswith("RUN:")), ran
# A ```ui block in a reply renders inline in chat. But when you asked for it "on
# the canvas", inline isn't what you wanted — and making the model curl its own
# HTML back to /api/ui means shell-quoting a whole document, which is fragile.
# So the hub pins it for you: deterministic, no quoting, no extra model call.
_UI_BLOCK = re.compile(r"```(?:ui|html|openui)\s*\n([\s\S]*?)```", re.I)
_CANVAS_WORDS = re.compile(r"\b(canvas|dashboard|widget|pin(?:\s+it)?|add\s+.*\bto\s+the\s+"
r"(?:canvas|dashboard))\b", re.I)
def maybe_pin_to_canvas(user_msg: str, reply: str) -> str:
"""If the user asked for it on the canvas and the reply built UI, pin it there."""
if not _CANVAS_WORDS.search(user_msg or ""):
return ""
m = _UI_BLOCK.search(reply or "")
if not m:
return ""
html = m.group(1).strip()
if len(html) < 40:
return ""
title = "widget"
for line in (reply or "").splitlines(): # a heading near the block names it
s = line.strip().lstrip("#").strip()
if s and not s.startswith("```") and 3 < len(s) < 60:
title = s.rstrip(":")
break
words = re.findall(r"[a-z]+", (user_msg or "").lower())
for w in words: # prefer a noun the user actually used
if w in ("snake", "chart", "graph", "timer", "clock", "todo", "calculator",
"game", "board", "table", "form", "counter", "notes", "kanban"):
title = w.capitalize()
break
items = _load_json(WIDGETS_FILE, [])
items.insert(0, {"id": str(int(time.time() * 1000)), "title": title[:80],
"by": "brain", "html": html, "ts": time.time()})
_save_json(WIDGETS_FILE, items[:40])
brain.audit("brain", "canvas.pin", title)
return title
# --------------------------------------------------------------------------- #
# Swarm — a big request becomes a DAG of subtasks run by different specialists #
# in parallel, able to consult each other, then synthesized into one answer. #
# --------------------------------------------------------------------------- #
SWARM_FILE = ROOT / ".aios" / "swarm.json"
def swarm_enabled() -> bool:
return os.environ.get("AIOS_SWARM", "1") == "1"
def swarm_state() -> dict:
return _load_json(SWARM_FILE, {})
def run_swarm(message: str) -> dict:
"""Bind the hub's router + activity feed into the swarm engine, and publish
live progress so the dashboard can watch the DAG fill in."""
def _publish(snap):
_save_json(SWARM_FILE, {**snap, "message": message[:400], "ts": time.time()})
r = swarm.run(
message,
route=lambda agent, prompt: route(agent, prompt),
ask_llm=lambda msgs, system=None: llm_chat(msgs, system=system),
act=act,
on_update=_publish,
)
_save_json(SWARM_FILE, {"summary": r.get("summary", ""), "tasks": r.get("tasks", []),
"message": message[:400], "ts": time.time(),
"elapsed": r.get("elapsed"), "finished": True})
if r.get("swarm"):
brain.audit("swarm", "run", f"{len(r.get('tasks', []))} subtasks: {message[:120]}")
return r
def route(target: str, message: str, history: list | None = None) -> str:
history = history or []
target = (target or "brain").lower()
_TL.ran = [] # never attribute a previous turn's commands to this one
bump_usage(target)
if target in ("brain", "aios", "hub"):
reply, ran = run_brain(message, history)
if ran:
reply += "\n\n---\n🔧 Ran: " + ", ".join(f"`{c}`" for c in ran[:6])
return reply
if target == "crewai":
act("agent", "Handing off to CrewAI…")
return ask_crewai(message)
if target == "opencode":
act("agent", "Handing off to opencode…")
return ask_opencode(message)
if target in ("claudecode", "claude-code"):
return ask_claudecode(message, history)
if target == "codex":
act("agent", "Handing off to Codex…")
return ask_codex(message, history)
if target == "fabric":
# "pattern: text" → run that fabric pattern; else summarize by default.
pat, _, txt = message.partition(":")
if txt.strip():
return run_fabric(pat.strip(), txt.strip())
return run_fabric("summarize", message)
if target == "swarm":
r = run_swarm(message)
# A swarm that couldn't plan must not hand back an empty string — fall
# back to the team, which is a single round but always produces an answer.
return r.get("reply") or run_team(message, history)
if target in ("team", "auto", "merge"):
# A genuinely big ask gets the swarm — parallel specialists that can
# consult each other — rather than run_team's single shallow round.
if swarm_enabled() and swarm.looks_big(message):
act("plan", "Big task detected — deploying a swarm of agents")
r = run_swarm(message)
if r.get("swarm") and r.get("reply"):
return r["reply"]
act("note", "Swarm unavailable — using the team instead.")
return run_team(message, history)
if target == "all":
parts = []
for t in ("brain", "crewai", "opencode", "claudecode"):
parts.append(f"### {t}\n{route(t, message, history)}")
return "\n\n".join(parts)
return f"⚠️ Unknown target '{target}'. Use brain | team | crewai | opencode | claudecode | all."
# --------------------------------------------------------------------------- #
# Unique features: auto-router, arena (A/B), council (consensus), pipeline #
# --------------------------------------------------------------------------- #
def auto_route(message: str, history: list | None = None) -> dict:
"""Pick the best agent for the message automatically, then answer with it."""
sysp = ("Classify which AI OS agent should handle the user's request. Reply with ONLY one word: "
"opencode (writing/running code), crewai (multi-step research/workflows), "
"claudecode (coding via Claude Code), or brain (general/orchestration). Request:")
pick = (llm_chat([{"role": "user", "content": message}], system=sysp) or "brain").strip().lower()
pick = next((t for t in ("opencode", "crewai", "claudecode", "brain") if t in pick), "brain")
return {"chosen": pick, "reply": route(pick, message, history)}
def run_arena(message: str, targets: list, history: list | None = None) -> dict:
"""Same prompt to 2+ agents/models, side by side, to compare."""
return {"results": [{"target": t, "reply": route(t, message, history)} for t in targets[:4]]}
def run_council(message: str, targets: list, history: list | None = None) -> dict:
"""Ask several agents, then synthesize a consensus noting agreement/disagreement."""
results = [{"target": t, "reply": route(t, message, history)} for t in targets[:4]]
joined = "\n\n".join(f"[{r['target']}]\n{r['reply']}" for r in results)
consensus = llm_chat([{"role": "user", "content":
f"Question: {message}\n\nAnswers from the council:\n{joined}\n\n"
"Give one best answer. Note where they agree and flag any disagreement."}],
system="You are the council chair for The AI OS. Be decisive and concise.")
return {"results": results, "consensus": consensus}
def run_pipeline(message: str, steps: list, history: list | None = None) -> dict:
"""Chain agents: each step's output feeds the next (research → code → summarize)."""
out, cur = [], message
for t in steps[:6]:
r = route(t, cur, [])
out.append({"target": t, "output": r})
cur = r
return {"steps": out, "final": cur}
# --------------------------------------------------------------------------- #
# /dry — estimate tokens + cost before actually running a request #
# --------------------------------------------------------------------------- #
_PRICING = {"ts": 0.0, "map": {}}
def estimate_tokens(text: str) -> int:
return max(1, len(text or "") // 4) # ~4 chars/token (rough, English)
def _model_pricing(model: str):
"""Per-token USD pricing for the active model (OpenRouter exposes it on /models)."""
if os.environ.get("AIOS_LLM_PROVIDER", "openrouter").lower() != "openrouter":
return None
if time.time() - _PRICING["ts"] > 600 or not _PRICING["map"]:
try:
data = json.loads(urllib.request.urlopen(llm_base() + "/models", timeout=10).read())
m = {}
for it in data.get("data", []):
p = it.get("pricing") or {}
try:
m[it.get("id")] = {"prompt": float(p.get("prompt", 0) or 0),
"completion": float(p.get("completion", 0) or 0)}
except Exception:
pass
_PRICING.update(map=m, ts=time.time())
except Exception:
pass
return _PRICING["map"].get(model)
def dry_run(target: str, message: str, history: list | None = None) -> dict:
history = history or []
target = (target or "brain").lower()
sysp = read_system_prompt() or ("You are the AIOS Brain, orchestrator of six agents. "
"Be concise and helpful." * 3)
mem = read_memory()
ctx = (sysp + "\n" + "\n".join(str(m.get("content", "")) for m in history)
+ "\n" + "\n".join(str(x) for x in mem) + "\n" + message)
in_tok = estimate_tokens(ctx)
out_tok = 600
model = os.environ.get("AIOS_DEFAULT_MODEL", "(unset)")
prov = os.environ.get("AIOS_LLM_PROVIDER", "openrouter").lower()
# multi-agent modes call the model several times
mult = {"arena": 2, "team": 2, "council": 4, "pipeline": 3, "all": 4}.get(target, 1)
free = prov == "claudecode"
cost, priced, note = 0.0, False, ""
if free:
note = "Runs on your Claude Pro/Max subscription — $0 API cost."
else:
pr = _model_pricing(model)
if pr:
cost = (in_tok * pr["prompt"] + out_tok * pr["completion"]) * mult
priced = True
else:
note = "No public pricing for this model — token estimate only."
return {"target": target, "model": model, "provider": prov, "agents": mult,
"input_tokens": in_tok, "est_output_tokens": out_tok * mult,
"total_tokens": (in_tok + out_tok) * mult,
"free": free, "priced": priced, "est_cost_usd": round(cost, 6), "note": note}
# --------------------------------------------------------------------------- #
# Watchdog — if an agent goes down, restart it; if that fails, an agent debugs #
# --------------------------------------------------------------------------- #
HEALTH_FILE = ROOT / ".aios" / "health_events.json"
WATCH = ["opencode", "hermes", "openclaw", "crewai", "claudecode"]
_wd = {"seen_up": {}, "last_restart": {}}
def _log_event(kind: str, svc: str, msg: str):
ev = _load_json(HEALTH_FILE, [])
ev.insert(0, {"ts": time.time(), "kind": kind, "service": svc, "message": str(msg)[:2000]})
_save_json(HEALTH_FILE, ev[:60])
def _service_logs(svc: str, n: int = 40) -> str:
return (run_aios("logs", svc, "-n", str(n)).get("out") or "")[-3000:]
def _diagnose(svc: str, logtail: str) -> str:
"""Ask a healthy agent to debug the crashed one."""
q = (f"The AI OS service '{svc}' stopped responding and an automatic restart did not fix it.\n"
f"Log tail:\n\n{logtail}\n\n"
"In at most 3 bullets: the likely root cause, and the exact command to fix it.")
try:
helper = "opencode" if ping(PEERS.get("opencode", "")) else "brain"
return route(helper, q)
except Exception as e:
return f"(diagnosis unavailable: {e})"
def _watchdog_loop():
if os.environ.get("AIOS_WATCHDOG", "1") != "1":
return
interval = int(os.environ.get("AIOS_WATCHDOG_INTERVAL", "45"))
time.sleep(20) # let the stack finish booting before we judge it
while True:
try:
for svc in WATCH:
url = PEERS.get(svc)
if not url:
continue
if ping(url):
_wd["seen_up"][svc] = time.time()
continue
# Only heal services we've actually seen alive (never auto-start disabled ones)
if not _wd["seen_up"].get(svc):
continue
if time.time() - _wd["last_restart"].get(svc, 0) < 180:
continue # rate-limit: no restart storms
_wd["last_restart"][svc] = time.time()
_log_event("down", svc, f"{svc} stopped responding — auto-restarting…")
run_aios("restart", svc)
time.sleep(20)
if ping(url):
_log_event("healed", svc, f"{svc} is back up (automatic restart).")
else:
diag = _diagnose(svc, _service_logs(svc))
_log_event("failed", svc, f"Restart didn't fix {svc}. Agent diagnosis:\n{diag}")
except Exception:
pass
time.sleep(interval)
# --------------------------------------------------------------------------- #
# Claude login from the dashboard (interactive CLI session over HTTP) #
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
# Live dashboard customization — agents restyle the Control Room through an API, #
# never by editing dashboard.html. Overrides live server-side in one JSON doc #
# the page applies on top of the active theme, so a bad instruction is undone #
# with `reset` instead of a broken file. Panels are OpenUI: arbitrary agent HTML #
# rendered in the same sandboxed iframes the chat/canvas widgets use. #
# --------------------------------------------------------------------------- #
DASH_FILE = ROOT / ".aios" / "dashboard.json"
DASH_DEFAULT = {"vars": {}, "css": "", "scale": 1.0, "density": "normal",
"nav": {"hidden": [], "order": []}, "panels": [], "updated": 0}
DASH_SLOTS = ["top", "chat", "sidebar"]
_VAR_OK = re.compile(r"^--[A-Za-z0-9_-]{1,40}$")
# CSS can't execute script in a <style>, but it CAN beacon out via url(http…) and
# @import. Agents already own the machine, so this isn't a privilege boundary —
# it's to stop a careless instruction from silently phoning home.
_CSS_BAD = re.compile(r"</\s*style|@import|url\(\s*['\"]?\s*(https?:|//)", re.I)
def dashboard_cfg() -> dict:
# deepcopy, not {**DASH_DEFAULT}: a shallow copy shares the nested `vars`/`nav`
# dicts with the module-level default, so writing a var would mutate the
# defaults themselves and `reset` would restore the very values it should clear.
cfg = copy.deepcopy(DASH_DEFAULT)
cfg.update(_load_json(DASH_FILE, {}))
for k, v in DASH_DEFAULT.items(): # heal older/partial files
cfg.setdefault(k, copy.deepcopy(v))
return cfg
def _clean_var(k: str, v) -> tuple[str, str] | None:
k = str(k).strip()
if not k.startswith("--"):
k = "--" + k.lstrip("-")
if not _VAR_OK.match(k):
return None
val = str(v).strip()
# A value containing } or < would break out of the rule we inject it into.
if not val or len(val) > 200 or any(c in val for c in "}<>;{"):
return None
return k, val
def dashboard_update(payload: dict) -> dict:
cfg = dashboard_cfg()
op = (payload.get("op") or "set").lower()
rejected = []
if op == "reset":
what = payload.get("what", "all")
if what == "all":
cfg = copy.deepcopy(DASH_DEFAULT)
else:
cfg[what] = copy.deepcopy(DASH_DEFAULT.get(what, ""))
elif op == "set":
for k, v in (payload.get("vars") or {}).items():
cleaned = _clean_var(k, v)
if cleaned:
cfg["vars"][cleaned[0]] = cleaned[1]
else:
rejected.append(str(k))
if "css" in payload:
css = str(payload["css"] or "")[:20000]
if _CSS_BAD.search(css):
rejected.append("css (contains @import, remote url(), or </style>)")
else:
cfg["css"] = css
if "scale" in payload:
try:
cfg["scale"] = max(0.7, min(1.6, float(payload["scale"])))
except (TypeError, ValueError):
rejected.append("scale")
if payload.get("density") in ("normal", "compact", "comfortable"):
cfg["density"] = payload["density"]
elif op == "nav":
if isinstance(payload.get("hidden"), list):
cfg["nav"]["hidden"] = [str(x)[:40] for x in payload["hidden"]][:40]
if isinstance(payload.get("order"), list):
cfg["nav"]["order"] = [str(x)[:40] for x in payload["order"]][:40]
elif op == "panel":
act = (payload.get("action") or "add").lower()
if act == "add":
pid = payload.get("id") or f"p{int(time.time() * 1000) % 10**9}"
panel = {"id": str(pid)[:40],
"title": str(payload.get("title", "panel"))[:80],
"html": str(payload.get("html", ""))[:200000],
"slot": payload.get("slot") if payload.get("slot") in DASH_SLOTS else "top",
"height": max(60, min(1200, int(payload.get("height", 220) or 220))),
"by": str(payload.get("by", "agent"))[:40]}
cfg["panels"] = [p for p in cfg["panels"] if p["id"] != panel["id"]] + [panel]
cfg["panels"] = cfg["panels"][-24:]
elif act in ("del", "delete", "remove"):
cfg["panels"] = [p for p in cfg["panels"] if p["id"] != str(payload.get("id"))]
elif act == "clear":
cfg["panels"] = []
else:
return {"ok": False, "error": f"unknown op '{op}'", "config": cfg}