-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaion.py
More file actions
1813 lines (1617 loc) · 77.1 KB
/
aion.py
File metadata and controls
1813 lines (1617 loc) · 77.1 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
if "__file__" not in globals(): __file__ = __import__("os").path.abspath("aion.py")
"""
AION — Autonomous Intelligent Operations Node
=============================================
"""
import asyncio
import contextvars
import json
import os
import re
import shutil
import sys
import time
import uuid
from datetime import datetime, timezone
UTC = timezone.utc
from pathlib import Path
def _is_reasoning_model(model: str) -> bool:
return bool(model and (model.startswith("o1") or model.startswith("o3") or model.startswith("o4")))
def _max_tokens_param(model: str, n: int) -> dict:
"""Return the correct token-limit kwarg for the given model.
Reasoning models (o1/o3/o4-*) require max_completion_tokens and no temperature."""
if _is_reasoning_model(model):
return {"max_completion_tokens": n}
return {"max_tokens": n}
# Load all secrets from encrypted vault into os.environ at startup.
# Replaces load_dotenv(.env) — keys are stored in credentials/*.md.enc.
try:
from plugins.credentials.credentials import _vault_inject_all_sync as _via
_via()
del _via
except Exception:
pass
try:
from openai import AsyncOpenAI
except ImportError:
print("Error: 'openai' not installed. Please run 'pip install openai'.")
sys.exit(1)
try:
import httpx
except ImportError:
print("Error: 'httpx' not installed. Please run 'pip install httpx'.")
sys.exit(1)
try:
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.prompt import Prompt
console = Console()
HAS_RICH = True
except ImportError:
HAS_RICH = False
class _FallbackConsole:
def print(self, *args, **kwargs): print(*args)
def rule(self, *args, **kwargs): print("─" * 60)
console = _FallbackConsole()
# ── Configuration ─────────────────────────────────────────────────────────────
from core.aion_config import (
BOT_DIR, CONFIG_FILE, MEMORY_FILE, VECTORS_FILE, PLUGINS_DIR, TOOLS_DIR,
CHARACTER_FILE, MAX_MEMORY, MAX_TOOL_ITERATIONS, MAX_HISTORY_TURNS,
CHUNK_SIZE, CHARACTER_MAX_CHARS, RULES_COMPRESS_THRESHOLD,
LOG_FILE, LOG_MAX_BYTES, UTC,
_log_event, _load_config, save_model_config,
)
# Active channel for _dispatch — set at the beginning of stream()
_active_channel: contextvars.ContextVar[str] = contextvars.ContextVar("aion_channel", default="default")
# Model resolution: config.json → environment variable → fallback
_cfg = _load_config()
MODEL = _cfg.get("model") or os.environ.get("AION_MODEL", "gpt-4.1")
client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY", ""))
# ── Provider Registry ─────────────────────────────────────────────────────────
from core.aion_providers import (
_provider_registry, register_provider,
_resolve_ollama_prefix, _build_client, _api_model_name,
_CHEAP_CHECK_MODELS,
)
def _get_read_limit() -> int:
"""Returns safe single-file read limit in chars based on the active model's context window.
Uses 15% of the context window (converted to chars at ~4 chars/token).
Floor: 100_000 chars. Ceiling: 800_000 chars.
Falls back to 100_000 if the provider has no context_window registered.
"""
for entry in _provider_registry:
if MODEL.startswith(entry["prefix"]):
ctx = entry.get("context_window", 0)
if ctx > 0:
return min(800_000, max(20_000, int(ctx * 4 * 0.15)))
# OpenAI fallback: gpt-4o hat 128k Tokens → ~76k chars safe; gpt-4.1 hat 1M → cap bei 800k
# We take 100k as a safe average for unknown OpenAI models
return 100_000 # OpenAI-Fallback
def _get_check_model() -> str:
"""Gibt das günstigste geeignete Modell für interne YES/NO-Checks zurück.
Priorität:
1. config.json → "check_model" (explizite Überschreibung durch User)
2. Per-Provider-Günstig-Mapping (_CHEAP_CHECK_MODELS)
3. Aktuelles MODEL als Fallback
"""
cfg_model = _load_config().get("check_model", "").strip()
if cfg_model:
return cfg_model
for prefix, cheap in _CHEAP_CHECK_MODELS.items():
if MODEL.startswith(prefix):
return cheap
return MODEL
def _model_available(model: str) -> bool:
"""Prüft ob der Provider für das Modell konfiguriert ist (alle API-Keys gesetzt).
Provider ohne env_keys (z.B. Ollama, lokale Modelle) gelten immer als verfügbar.
Unbekannte Prefixe → prüft OPENAI_API_KEY als Fallback-Provider.
"""
for entry in _provider_registry:
if model.startswith(entry["prefix"]):
env_keys = entry.get("env_keys") or []
if not env_keys:
return True # Kein Key nötig (z.B. Ollama)
return all(os.environ.get(k, "").strip() for k in env_keys)
# Unbekannter Prefix → OpenAI-Fallback
return bool(os.environ.get("OPENAI_API_KEY", "").strip())
def _get_fallback_models(current_model: str) -> list[str]:
"""Returns available fallback models — only providers with set API keys.
Logik:
- Skip the own provider (the one that just failed)
- Nur Provider einbeziehen, deren env_keys alle gesetzt sind
- Provider ohne env_keys (z.B. Ollama) immer einbeziehen
- Jeweils das erste Modell aus der models-Liste nehmen
- Additionally: explicit model_fallback list from config.json (if set)
"""
fallbacks: list[str] = []
seen: set[str] = set()
for entry in _provider_registry:
# Skip own provider (the one that just failed)
if current_model.startswith(entry["prefix"]):
continue
# API key check: all env_keys must be set
env_keys = entry.get("env_keys") or []
if env_keys and not all(os.environ.get(k, "").strip() for k in env_keys):
continue
# Take first available model of this provider
models = entry.get("models") or []
if models:
m = models[0]
if m not in seen:
seen.add(m)
fallbacks.append(m)
# Explicit fallback list from config.json added (if present)
for m in _load_config().get("model_fallback", []):
if m != current_model and m not in seen:
seen.add(m)
fallbacks.append(m)
return fallbacks
from core.aion_permissions import (
PERMISSION_DEFAULTS, PERMISSION_LABELS,
_load_permissions, _permissions_prompt,
_match_pattern, _check_channel_allowlist, _get_thinking_prompt,
)
# ── Unsupported File Utility ───────────────────────────────────────────────────
def unsupported_file_message(label: str) -> str:
"""Standard response when a platform receives a file type AION cannot process yet.
Platforms (Telegram, Web UI, Discord, …) call this with a human-readable label
describing the file, e.g. 'Video «clip.mp4» (30s, 8.2 MB)'.
"""
return (
f"📥 Received: {label}\n\n"
"I can't process this file format yet. "
"Want me to learn? Just say so and I'll create a plugin for it."
)
from core.aion_character import (
DEFAULT_CHARACTER, _load_character,
_backup_file, _backup_code_file,
)
from core.aion_prompt import (
_load_changelog_snippet,
_sys_prompt_cache, invalidate_sys_prompt_cache,
_get_mood_hint, _get_temporal_hint, _get_relationship_hint,
)
def _build_system_prompt(channel: str = "") -> str:
# Cache-Key: (channel, aktives Modell, Anzahl geladener Plugin-Tools)
# Bei Änderungen (Modell-Wechsel, Plugin-Reload) wird der Cache automatisch ungültig.
_cache_key = (channel, MODEL, len(_plugin_tools))
if _cache_key in _sys_prompt_cache:
# Base prompt cached — append dynamic hints (mood, time, relationship, mistakes, doc-freshness, offline)
_mistakes = _get_mistakes_hint()
return (
_sys_prompt_cache[_cache_key]
+ _get_mood_hint()
+ _get_temporal_hint()
+ _get_relationship_hint()
+ _get_doc_freshness_hint()
+ _get_offline_hint()
+ ("\n\n" + _mistakes if _mistakes else "")
)
character = _load_character()
# Dynamic plugin block from README first lines (filled by plugin_loader)
plugin_lines = []
for k, v in sorted(_plugin_tools.items()):
if k.startswith("__plugin_readme_"):
name = k[len("__plugin_readme_"):]
plugin_lines.append(f"- **{name}**: {v}")
plugin_block = (
"\n\n=== GELADENE PLUGINS ===\n"
"These plugins are active and their tools are available to you:\n"
+ "\n".join(plugin_lines)
+ "\nFor full plugin docs: `read_plugin_doc(plugin_name)` — or call without args to list all."
) if plugin_lines else ""
# Changelog: opt-in via config (default off — saves ~150 tokens/turn)
changelog_block = ""
if _load_config().get("system_prompt_show_changelog", False):
changelog_snippet = _load_changelog_snippet()
if changelog_snippet:
changelog_block = (
"\n\n=== LATEST CHANGES (CHANGELOG) ===\n"
+ changelog_snippet
+ "\n→ Complete history: `file_read('CHANGELOG.md')`"
)
# ── Load rules from prompts/rules.md (editable via web UI) ────────────
rules_file = BOT_DIR / "prompts" / "rules.md"
if rules_file.is_file():
rules = rules_file.read_text(encoding="utf-8")
# Truncation guard: avoid loading huge rules files on every turn.
# Configurable via config.json["max_rules_chars"] (default 12000 ≈ 3000 tokens).
_max_rules = int(_load_config().get("max_rules_chars", 12_000))
if len(rules) > _max_rules:
rules = rules[:_max_rules] + "\n\n[rules.md truncated — full file: file_read('prompts/rules.md')]"
rules = rules.replace("{CHARAKTER}", character)
rules = rules.replace("{MODEL}", MODEL)
rules = rules.replace("{BOT_AION}", str(BOT_DIR / "aion.py"))
rules = rules.replace("{BOT_MEMORY}", str(MEMORY_FILE))
rules = rules.replace("{BOT_CHARACTER}", str(CHARACTER_FILE))
rules = rules.replace("{BOT_PLUGINS}", str(PLUGINS_DIR))
rules = rules.replace("{BOT_SELF}", str(BOT_DIR / "AION_SELF.md"))
perms_block = "\n\n" + _permissions_prompt(_load_permissions())
thinking_block = _get_thinking_prompt(channel)
# Grouped capability index — auto-generated from all registered tools (tier 1+2).
# Gives the LLM a semantic, grouped overview so it never has to guess tool names.
capability_block = "\n\n" + _build_capability_index()
_result = rules + plugin_block + changelog_block + perms_block + thinking_block + capability_block
if len(_sys_prompt_cache) > 20:
_sys_prompt_cache.clear()
_sys_prompt_cache[_cache_key] = _result
_mistakes = _get_mistakes_hint()
return (
_result
+ _get_mood_hint()
+ _get_temporal_hint()
+ _get_relationship_hint()
+ _get_doc_freshness_hint()
+ _get_offline_hint()
+ ("\n\n" + _mistakes if _mistakes else "")
)
# Fallback: hardcodierter Prompt (wird genutzt wenn prompts/rules.md fehlt)
_result = f"""You are AION (Autonomous Intelligent Operations Node) — an autonomous, \
selbst-lernender KI-Assistent.
=== DEIN CHARAKTER ===
{character}
=== LANGUAGE ===
Always respond in the same language the user writes in. Mirror the user's language automatically.
If the user writes German → respond in German. English → English. Never switch unless the user does first.
{plugin_block}{changelog_block}"""
_sys_prompt_cache[_cache_key] = _result
_mistakes = _get_mistakes_hint()
return (
_result
+ _get_mood_hint()
+ _get_temporal_hint()
+ _get_relationship_hint()
+ _get_doc_freshness_hint()
+ _get_offline_hint()
+ ("\n\n" + _mistakes if _mistakes else "")
)
# ── Context Compression ──────────────────────────────────────────────────────
_startup_compress_done = False
def _push_compress_status(message: str, status: str = "running") -> None:
"""Push a compression status notification to the web UI via SSE (fire-and-forget)."""
try:
import aion_web as _web
_q = getattr(_web, "_push_queue", None)
if _q is not None:
_loop = asyncio.get_running_loop()
asyncio.ensure_future(_q.put({"type": "compress", "status": status, "message": message}), loop=_loop)
except Exception:
pass
async def _compress_character(max_chars: int = CHARACTER_MAX_CHARS) -> bool:
"""LLM-rewrite of character.md to fit within max_chars. Returns True on success."""
content = CHARACTER_FILE.read_text(encoding="utf-8") if CHARACTER_FILE.is_file() else ""
if len(content) <= max_chars:
return True
_push_compress_status(f"Optimizing character.md ({len(content):,} → {max_chars:,} chars)…")
try:
resp = await client.chat.completions.create(
model=_api_model_name(MODEL),
messages=[{"role": "user", "content": (
f"Komprimiere diese character.md auf maximal {max_chars} Zeichen.\n"
f"Behalte alle einzigartigen Fakten, dedupliziere nur Redundantes.\n"
f"Alle ## Sektionsüberschriften erhalten. Nur Dateiinhalt zurückgeben.\n\n{content}"
)}],
**_max_tokens_param(MODEL, 1200),
**({} if _is_reasoning_model(MODEL) else {"temperature": 0.5}),
)
if not hasattr(resp, "choices"):
return False
new_content = (resp.choices[0].message.content or "").strip()
if len(new_content) < 100:
return False
if len(new_content) > max_chars:
new_content = new_content[:max_chars]
_backup_file(CHARACTER_FILE)
CHARACTER_FILE.write_text(new_content, encoding="utf-8")
_sys_prompt_cache.clear()
_push_compress_status(f"character.md optimized: {len(content):,} → {len(new_content):,} chars", "done")
print(f"[compress] character.md: {len(content)} → {len(new_content)} chars")
return True
except Exception as e:
print(f"[compress] character.md failed: {e}")
return False
async def _compress_rules() -> bool:
"""LLM-compression of rules.md when it exceeds RULES_COMPRESS_THRESHOLD."""
rules_file = BOT_DIR / "prompts" / "rules.md"
if not rules_file.is_file():
return False
content = rules_file.read_text(encoding="utf-8")
threshold = int(_load_config().get("rules_compress_threshold", RULES_COMPRESS_THRESHOLD))
if len(content) <= threshold:
return False
target = min(threshold, 8_000)
_push_compress_status(f"Optimizing rules.md ({len(content):,} → {target:,} chars)…")
try:
resp = await client.chat.completions.create(
model=_api_model_name(MODEL),
messages=[{"role": "user", "content": (
f"Komprimiere diese rules.md auf maximal {target} Zeichen.\n"
f"Behalte ALLE Regeln und Verbote — nichts inhaltlich weglassen.\n"
f"Entferne nur verbose Erklärungen/Beispiele, kürze auf direkte Anweisungen.\n"
f"Alle ## Sektionsüberschriften erhalten. Nur Dateiinhalt zurückgeben.\n\n{content}"
)}],
**_max_tokens_param(MODEL, 2000),
**({} if _is_reasoning_model(MODEL) else {"temperature": 0.3}),
)
if not hasattr(resp, "choices"):
return False
new_content = (resp.choices[0].message.content or "").strip()
if len(new_content) < 200:
return False
_backup_file(rules_file, max_backups=3)
rules_file.write_text(new_content, encoding="utf-8")
_sys_prompt_cache.clear()
_push_compress_status(f"rules.md optimized: {len(content):,} → {len(new_content):,} chars", "done")
print(f"[compress] rules.md: {len(content)} → {len(new_content)} chars")
return True
except Exception as e:
print(f"[compress] rules.md failed: {e}")
return False
async def _generate_self_doc_summary() -> bool:
"""Generate AION_SELF_SUMMARY.md — a compact index of AION_SELF.md."""
self_doc = BOT_DIR / "AION_SELF.md"
summary = BOT_DIR / "AION_SELF_SUMMARY.md"
if not self_doc.is_file():
return False
content = self_doc.read_text(encoding="utf-8")
_push_compress_status("Generating AION_SELF_SUMMARY.md…")
try:
resp = await client.chat.completions.create(
model=_api_model_name(MODEL),
messages=[{"role": "user", "content": (
"Erstelle ein komprimiertes Inhaltsverzeichnis dieser AION_SELF.md.\n"
"Pro Feature/Sektion EINEN Einzeiler: Was es tut + wo implementiert.\n"
"Format: ## Sektionsname\\n- feature: einzeiler\\n...\n"
"Ziel: 3–5 KB. Letzter Satz: '→ Volltext: file_read(\"AION_SELF.md\")'\n\n"
+ content[:10_000]
)}],
**_max_tokens_param(MODEL, 1000),
**({} if _is_reasoning_model(MODEL) else {"temperature": 0.3}),
)
if not hasattr(resp, "choices"):
return False
new_summary = (resp.choices[0].message.content or "").strip()
if len(new_summary) < 100:
return False
summary.write_text(new_summary, encoding="utf-8")
_push_compress_status(f"AION_SELF_SUMMARY.md generated ({len(new_summary):,} chars)", "done")
print(f"[compress] AION_SELF_SUMMARY.md: {len(new_summary)} chars")
return True
except Exception as e:
print(f"[compress] AION_SELF_SUMMARY.md failed: {e}")
return False
async def _startup_compress_check() -> None:
"""Background startup task: compress context files that exceed size thresholds."""
global _startup_compress_done
if _startup_compress_done:
return
_startup_compress_done = True
await asyncio.sleep(5) # Wait until AION is fully loaded
_cfg = _load_config()
_max_char = int(_cfg.get("character_max_chars", CHARACTER_MAX_CHARS))
if CHARACTER_FILE.is_file() and CHARACTER_FILE.stat().st_size > _max_char:
await _compress_character(_max_char)
rules_file = BOT_DIR / "prompts" / "rules.md"
_rules_thresh = int(_cfg.get("rules_compress_threshold", RULES_COMPRESS_THRESHOLD))
if rules_file.is_file() and rules_file.stat().st_size > _rules_thresh:
await _compress_rules()
self_doc = BOT_DIR / "AION_SELF.md"
summary = BOT_DIR / "AION_SELF_SUMMARY.md"
if self_doc.is_file() and (
not summary.is_file() or summary.stat().st_mtime < self_doc.stat().st_mtime
):
await _generate_self_doc_summary()
# ── Memory System ─────────────────────────────────────────────────────────
# AionMemory wurde nach aion_memory.py extrahiert — backward-compatible re-import:
from core.aion_memory import AionMemory
memory = AionMemory(MEMORY_FILE, VECTORS_FILE, MAX_MEMORY)
def _get_recent_thoughts(n: int = 5) -> str:
"""Reads the last N thought entries from thoughts.md for context injection."""
thoughts_file = BOT_DIR / "thoughts.md"
if not thoughts_file.is_file():
return ""
try:
content = thoughts_file.read_text(encoding="utf-8")
entries = [e.strip() for e in content.split("\n---\n") if e.strip() and "**[" in e]
if not entries:
return ""
recent = entries[-n:]
return "[AION LATEST THOUGHTS — your own reflections from previous conversations]\n" + "\n---\n".join(recent) + "\n[END THOUGHTS]"
except Exception:
return ""
def _get_mistakes_hint(n: int = 5) -> str:
"""Inject the last N recorded mistakes into the session context.
Gives AION immediate awareness of past errors at the start of every session,
creating a persistent self-improvement loop without manual maintenance.
"""
mistakes_file = BOT_DIR / "mistakes.md"
if not mistakes_file.is_file():
return ""
try:
content = mistakes_file.read_text(encoding="utf-8")
entries = [e.strip() for e in content.split("\n---\n") if e.strip() and "**Fehler:**" in e]
if not entries:
return ""
recent = entries[-n:]
return (
"[AION PAST MISTAKES — learn from these, do not repeat them]\n"
+ "\n---\n".join(recent)
+ "\n[END MISTAKES]"
)
except Exception:
return ""
def _get_doc_freshness_hint() -> str:
"""Warn AION if core source files are newer than AION_SELF.md.
Prevents acting on stale self-knowledge after code changes.
Lightweight: only checks file modification times, no I/O overhead.
"""
self_doc = BOT_DIR / "AION_SELF.md"
if not self_doc.is_file():
return ""
try:
doc_mtime = self_doc.stat().st_mtime
core_files = [
BOT_DIR / "aion.py",
BOT_DIR / "aion_session.py",
BOT_DIR / "plugin_loader.py",
BOT_DIR / "aion_web.py",
]
stale = [f.name for f in core_files if f.is_file() and f.stat().st_mtime > doc_mtime]
if not stale:
return ""
return (
f"\n⚠ SELF-DOC WARNING: {', '.join(stale)} were modified after AION_SELF.md. "
"Call read_self_doc() before answering architecture questions — your cached knowledge may be outdated."
)
except Exception:
return ""
def _get_offline_hint() -> str:
"""Inject offline duration into the system prompt so AION is aware of elapsed time.
Reads last_boot.txt written by the boot_session plugin.
Shown only when AION was offline for more than 1 hour — keeps context relevant.
"""
boot_file = BOT_DIR / "last_boot.txt"
if not boot_file.is_file():
return ""
try:
import datetime as _dt
last = _dt.datetime.fromisoformat(boot_file.read_text(encoding="utf-8").strip())
if last.tzinfo is None:
last = last.replace(tzinfo=_dt.timezone.utc)
offline_h = (_dt.datetime.now(_dt.timezone.utc) - last).total_seconds() / 3600
if offline_h < 1:
return ""
if offline_h < 2:
duration = f"{round(offline_h * 60)} minutes"
else:
duration = f"{offline_h:.1f} hours"
return (
f"\n[SESSION START — AION was offline for {duration}. "
"A background maintenance session ran automatically on startup. "
"Be aware that time has passed since your last conversation.]"
)
except Exception:
return ""
# ── Externe Tools laden ───────────────────────────────────────────────────────
_plugin_tools: dict = {}
def _normalize_schema(schema) -> dict:
"""Normalisiert Tool-Schemas fuer API-Kompatibilitaet (Gemini + OpenAI)."""
if not isinstance(schema, dict):
return {"type": "object", "properties": {}}
if schema.get("type") != "object":
schema = dict(schema)
schema["type"] = "object"
if not isinstance(schema.get("properties"), dict):
schema["properties"] = {}
props = set(schema["properties"].keys())
if "required" in schema:
cleaned = [r for r in schema["required"] if r in props]
if cleaned:
schema["required"] = cleaned
else:
del schema["required"]
return schema
# Plugin-Loader einbinden
_startup_t0 = time.monotonic()
if HAS_RICH:
console.print("[dim] ⟳ Loading plugins…[/dim]")
else:
print(" ⟳ Loading plugins…", flush=True)
try:
from plugin_loader import load_plugins
load_plugins(_plugin_tools)
_n_tools = len([k for k in _plugin_tools if not k.startswith("__")])
_elapsed = round(time.monotonic() - _startup_t0, 2)
if HAS_RICH:
console.print(f"[dim green] ✓ {_n_tools} tools loaded ({_elapsed}s)[/dim green]")
else:
print(f" ✓ {_n_tools} tools loaded ({_elapsed}s)", flush=True)
except Exception as exc:
print(f"[WARN] Plugin system failed to load: {exc}")
# ── Tool-Definitionen ─────────────────────────────────────────────────────────
def _build_tool_schemas(tier_threshold: int = 0) -> list[dict]:
"""Build the tools list for the LLM API call.
tier_threshold: 0 = use config value (default), 1 = tier-1 only, 2 = include tier-2.
"""
builtins = [
{
"type": "function",
"function": {
"name": "file_read",
"description": "Read a file from the filesystem.",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
},
{
"type": "function",
"function": {
"name": "file_write",
"description": "Write text to a file. Creates or overwrites.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"},
"content": {"type": "string"},
},
"required": ["path", "content"],
},
},
},
{
"type": "function",
"function": {
"name": "self_read_code",
"description": (
"Read AION's own source code. "
"Without 'path': list source files. With 'path': read the file. "
"Large files return multiple chunks — check total_chunks."
),
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"},
"chunk_index": {"type": "integer"},
},
},
},
},
{
"type": "function",
"function": {
"name": "self_patch_code",
"description": (
"Replace a targeted section in a file (old → new). "
"Creates a backup automatically. Preferred tool for aion.py. "
"Call without confirmed for preview, with confirmed=true to execute."
),
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"},
"old": {"type": "string", "description": "Exakter Originaltext (mind. 3-5 Zeilen Kontext)"},
"new": {"type": "string", "description": "Neuer Ersatztext"},
"confirmed": {"type": "boolean", "description": "true = ausführen (nur nach Nutzer-Bestätigung!), false/fehlt = nur Vorschau"},
},
"required": ["path", "old", "new"],
},
},
},
{
"type": "function",
"function": {
"name": "file_replace_lines",
"description": (
"Replace lines start_line–end_line (1-based, inclusive) in a file. "
"More reliable than self_patch_code — uses line numbers, no string matching. "
"Creates a backup. Call without confirmed for preview, with confirmed=true to execute."
),
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Dateipfad"},
"start_line": {"type": "integer", "description": "Erste zu ersetzende Zeile (1-basiert)"},
"end_line": {"type": "integer", "description": "Letzte zu ersetzende Zeile (1-basiert, inklusiv)"},
"new_content": {"type": "string", "description": "Neuer Inhalt für diesen Bereich"},
"confirmed": {"type": "boolean", "description": "true = ausführen, false/fehlt = Vorschau"},
},
"required": ["path", "start_line", "end_line", "new_content"],
},
},
},
{
"type": "function",
"function": {
"name": "self_modify_code",
"description": (
"Overwrite a small file completely. "
"Only for new files under 200 lines — use self_patch_code for existing files. "
"Call without confirmed for preview, with confirmed=true to execute."
),
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"},
"content": {"type": "string"},
"confirmed": {"type": "boolean", "description": "true = ausführen, false/fehlt = Vorschau"},
},
"required": ["path", "content"],
},
},
},
{
"type": "function",
"function": {
"name": "create_plugin",
"description": (
"Create a new AION plugin in plugins/{name}/{name}.py. "
"Must contain def register(api): and use api.register_tool(). "
"Loaded immediately. Call without confirmed for preview, with confirmed=true to execute."
),
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Dateiname ohne .py"},
"description": {"type": "string"},
"code": {"type": "string", "description": "Python-Code mit def register(api):"},
"confirmed": {"type": "boolean", "description": "true = erstellen, false/fehlt = Vorschau"},
},
"required": ["name", "description", "code"],
},
},
},
{
"type": "function",
"function": {
"name": "plugin_disable",
"description": "Disable a plugin — its tools become unavailable on next load. Re-enable with plugin_enable.",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Plugin-Name (Ordnername in plugins/)"},
},
"required": ["name"],
},
},
},
{
"type": "function",
"function": {
"name": "plugin_enable",
"description": "Re-enable a disabled plugin and load it immediately.",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Plugin-Name (Ordnername in plugins/)"},
},
"required": ["name"],
},
},
},
{
"type": "function",
"function": {
"name": "self_restart",
"description": "Hot-reload all plugins without stopping AION. For a full process restart use restart_with_approval.",
"parameters": {"type": "object", "properties": {}},
},
},
{
"type": "function",
"function": {
"name": "self_reload_tools",
"description": "Reload all plugin tools without restarting.",
"parameters": {"type": "object", "properties": {}},
},
},
{
"type": "function",
"function": {
"name": "set_thinking_level",
"description": (
"Set the thinking depth globally or per channel. "
"Levels: minimal → standard → deep → ultra. "
"With channel_override='telegram*' sets a channel-specific override."
),
"parameters": {
"type": "object",
"properties": {
"level": {"type": "string", "enum": ["minimal", "standard", "deep", "ultra"]},
"channel_override": {"type": "string", "description": "Optional: Channel-Pattern wie 'telegram*', 'discord_*'"},
},
"required": ["level"],
},
},
},
{
"type": "function",
"function": {
"name": "set_channel_allowlist",
"description": (
"Set which channels can process requests. Exact strings or wildcards ('telegram*'). "
"Empty list = all allowed."
),
"parameters": {
"type": "object",
"properties": {
"channels": {
"type": "array",
"items": {"type": "string"},
"description": "Liste erlaubter Channel-Patterns. Leer = alle erlauben."
},
},
"required": ["channels"],
},
},
},
{
"type": "function",
"function": {
"name": "get_control_settings",
"description": "Return current channel allowlist and thinking level settings.",
"parameters": {"type": "object", "properties": {}},
},
},
{
"type": "function",
"function": {
"name": "list_tools",
"description": (
"List all registered tools (including tier-2). "
"Returns name, tier, description. Use to discover capabilities before a task."
),
"parameters": {
"type": "object",
"properties": {
"filter": {
"type": "string",
"description": "Optional keyword to filter tool names/descriptions (e.g. 'desktop', 'file', 'audio').",
},
},
"required": [],
},
},
},
]
existing_names = {t["function"]["name"] for t in builtins}
# Tier threshold: 2 = all tools (default), 1 = tier-1 only (opt-in via config).
# Caller can override via tier_threshold parameter; 0 = use config value.
_tier_threshold = tier_threshold if tier_threshold > 0 else int(_load_config().get("tool_tier", 2))
for name, tool in _plugin_tools.items():
if name.startswith("__"): # interne Metadaten (z.B. __plugin_readme_*) überspringen
continue
if name in existing_names:
continue
# Skip tier-2 tools unless threshold allows it
if tool.get("tier", 1) > _tier_threshold:
continue
builtins.append({
"type": "function",
"function": {
"name": name,
"description": tool.get("description", ""),
"parameters": _normalize_schema(tool.get("input_schema", {})),
},
})
existing_names.add(name)
for t in builtins:
t["function"]["parameters"] = _normalize_schema(t["function"].get("parameters", {}))
return builtins
def _build_capability_index() -> str:
"""Build a grouped capability index from all registered tools (tier 1+2).
Groups tools by their name-prefix (e.g. 'desktop_click' → group DESKTOP).
Always reflects the current state of _plugin_tools — no manual maintenance.
Returned string is injected into the system prompt to give the LLM a compact,
semantic overview of all available capabilities.
"""
groups: dict[str, list[str]] = {}
for t in _build_tool_schemas(tier_threshold=2):
name = t["function"]["name"]
if name.startswith("__"):
continue
parts = name.split("_")
group = parts[0].upper() if len(parts) > 1 else "CORE"
groups.setdefault(group, []).append(name)
lines = ["=== AION CAPABILITY INDEX (all tools, grouped) ==="]
for group in sorted(groups):
tool_list = ", ".join(sorted(groups[group]))
lines.append(f"{group:12s}: {tool_list}")
lines.append(
"→ list_tools(filter=...) for descriptions · "
"lookup_rule(topic=...) for behavior rules · "
"Use ONLY names from this index."
)
return "\n".join(lines)
# ── Self-Healing Helpers ──────────────────────────────────────────────────────
def _classify_error(error_msg: str) -> str:
"""Classify a tool error into a category for retry-policy matching."""
msg = error_msg.lower()
if any(w in msg for w in ("timeout", "timed out", "connection", "network", "unreachable", "refused")):
return "network"
if any(w in msg for w in ("busy", "locked", "permission denied", "access denied")):
return "resource"
if any(w in msg for w in ("not found", "404", "missing", "does not exist")):
return "not_found"
return "fatal"
_TOOL_ALTERNATIVES: dict[str, list[str]] = {
"browser_open": ["web_fetch"],
"web_search": ["web_fetch"],
"send_telegram_message": ["send_discord_message"],
}
async def _dispatch_with_retry(name: str, inputs: dict, policy: dict) -> str:
"""Dispatch with automatic retry for transient errors.
Silently retries up to policy['max'] times with exponential backoff.
Only retries for error categories listed in policy['on'].
On permanent failure, appends alternative tool hint if available.
"""
max_retries = int(policy.get("max", 3))
backoff = float(policy.get("backoff", 2.0))
retry_on = set(policy.get("on", []))
last_result = json.dumps({"error": "no attempts"})
for attempt in range(max_retries):
# _bypass_retry=True prevents infinite recursion
last_result = await _dispatch(name, inputs, _bypass_retry=True)
try:
parsed = json.loads(last_result)
except Exception:
return last_result # non-JSON result — pass through unchanged
if "error" not in parsed:
return last_result # success
err_category = _classify_error(str(parsed.get("error", "")))
if err_category not in retry_on:
return last_result # non-retryable error — surface immediately
if attempt < max_retries - 1:
await asyncio.sleep(backoff ** attempt)
# Retry silently — user not notified until all attempts exhausted
# All retries exhausted — append alternative tool hint + snapshot hint if available
try:
parsed = json.loads(last_result)
parsed["_retry_exhausted"] = True
hint_parts = [f"'{name}' failed after {max_retries} attempts."]
alternatives = _TOOL_ALTERNATIVES.get(name, [])
if alternatives:
hint_parts.append(f"Consider trying: {', '.join(alternatives)}.")
# Check if any plugin snapshots exist — mention /snapshots restore as recovery option
try:
from plugin_loader import SNAPSHOTS_DIR, list_snapshots
# Tool name often matches plugin name prefix (e.g. "browser_open" → "playwright_browser")
# Check snapshots dir for a plugin whose name is a substring of the tool name
if SNAPSHOTS_DIR.is_dir():
for _pd in SNAPSHOTS_DIR.iterdir():
if _pd.is_dir() and (_pd.name in name or name.startswith(_pd.name.split("_")[0])):
_snaps = list_snapshots(_pd.name)
if _snaps:
hint_parts.append(
f"Plugin '{_pd.name}' has {len(_snaps)} snapshot(s) available — "
f"use '/snapshots restore {_pd.name}' if the plugin is broken."
)