-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3729 lines (3332 loc) · 156 KB
/
Copy pathmain.py
File metadata and controls
3729 lines (3332 loc) · 156 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
"""
Kyrozen: self-learning AI Agent powered by DeepSeek API + tools.
(Run `python main.py` to launch the agent)
"""
import pathlib
import shutil
import sys
import warnings
# Suppress all DeprecationWarnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Ensure the package directory is on sys.path (needed when installed via pip)
import os as _os
_PKG_DIR = _os.path.dirname(_os.path.abspath(__file__))
if _PKG_DIR not in sys.path:
sys.path.insert(0, _PKG_DIR)
# Guard: Python 3.14 has an import-system deadlock with openai 2.x
if sys.version_info >= (3, 14):
sys.exit(
"OpenKyrozen does not support Python 3.14+ due to a known import deadlock "
"with the OpenAI SDK. Use Python 3.12 or 3.13 instead.\n"
"Rebuild the venv with: make reinstall PYTHON=python3.12"
)
# Platform detection for cross-platform startup info
_PLATFORM = sys.platform
_IS_WINDOWS = _PLATFORM == "win32"
_IS_MACOS = _PLATFORM == "darwin"
_IS_LINUX = _PLATFORM.startswith("linux")
# Terminal capability detection (Windows cmd.exe has limited Unicode/ANSI support)
def _terminal_supports_unicode() -> bool:
"""Return True if the terminal can render Unicode box-drawing and special chars."""
if not _IS_WINDOWS:
return True
# Windows Terminal, VS Code terminal, and ConEmu all set WT_SESSION
if _os.environ.get("WT_SESSION") or _os.environ.get("TERM_PROGRAM") == "vscode":
return True
# PowerShell 6+ generally supports UTF-8
if "pwsh" in _os.environ.get("TERM_PROGRAM", "").lower():
return True
# Check codepage — 65001 is UTF-8
try:
import ctypes
if ctypes.windll.kernel32.GetConsoleOutputCP() == 65001:
return True
except Exception:
pass
return False
_UNICODE_OK = _terminal_supports_unicode()
# Dual character sets: Unicode preferred, ASCII fallback for legacy terminals
if _UNICODE_OK: _SPINNER_FRAMES = ["◜", "◠", "◝", "◞", "◡", "◟"]; _BAR_FILL = "█"; _BAR_EMPTY = "░"; _CHECK = "✓"; _CIRCLE = "○"; _HALF = "◷"; _BOX_TL = "┌"; _BOX_H = "─"; _BOX_BL = "└"; _BOX_V = "│"; _DOT = "·"; _NBHYPHEN = "‑"
else: _SPINNER_FRAMES = ["/", "-", "\\", "|"]; _BAR_FILL = "#"; _BAR_EMPTY = "."; _CHECK = "+"; _CIRCLE = "o"; _HALF = ">"; _BOX_TL = "+"; _BOX_H = "-"; _BOX_BL = "+"; _BOX_V = "|"; _DOT = "."; _NBHYPHEN = "-"
# Delete stale __pycache__ before any imports to avoid loading deprecated bytecode
for p in pathlib.Path(__file__).parent.rglob("__pycache__"):
shutil.rmtree(p, ignore_errors=True)
import ast
import json
import os
import re
import subprocess
from concurrent.futures import ThreadPoolExecutor
# macOS: suppress "MallocStackLogging: can't turn off malloc stack logging"
# warnings from child Python processes spawned during self-learning
if _IS_MACOS:
for _mk in ("MallocStackLogging", "MallocStackLoggingNoCompact"):
os.environ.pop(_mk, None)
import sys
import traceback
import threading
import time
import datetime
# Patch datetime.UTC for Python <3.11
if not hasattr(datetime, 'UTC'):
datetime.UTC = datetime.timezone.utc
UTC = datetime.timezone.utc
from pathlib import Path
from typing import Any
from openai import OpenAI
from rich.console import Console
from rich.markdown import Markdown
from rich.markup import escape as rich_escape
from rich.panel import Panel
from rich import print as rprint
from memory import MemoryBank
from task_engine import TaskManager
from event_store import stable_hash
from learning_engine import LearningEngine
from skill_registry import SkillRegistry
from instruction_loader import format_instructions
from subagents import AgentProfile, SubAgentManager
from capability_tokens import issue_capability_token
from dynamic_tools import SAFE_BUILTINS, validate_tool_source
from tools import (AVAILABLE_TOOLS, set_workspace_root as _set_tools_workspace_root,
resolve_capabilities, tool_capability)
from providers import (
ProviderConfig, LLMProvider, get_provider, detect_provider,
save_provider_config, PROVIDER_DEFAULT_MODELS, PROVIDER_ENV_VARS,
get_fallback_provider, get_cost_summary, reset_cost_tracker,
save_provider_config_encrypted, encrypt_api_key, decrypt_api_key,
)
# aliases for flexible action recognition
TOOL_ALIASES: dict[str, str] = {
"bash": "run_cmd",
"shell": "run_cmd",
"sh": "run_cmd",
"browse_summary": "read_webpage",
"run_terminal_command": "execute_terminal_command",
"run_terminal": "execute_terminal_command",
"terminal": "execute_terminal_command",
"run_command": "run_cmd",
"cmd": "run_cmd",
"exec": "run_cmd",
"execute": "run_cmd",
"list_tree": "list_tree",
"tree": "list_tree",
"check_memory": "check_stored_data",
"run_shell_command": "run_cmd",
"run_shell": "run_cmd",
"shell_command": "run_cmd",
"execute_shell": "run_cmd",
"shell_cmd": "run_cmd",
"bash_cmd": "run_cmd",
"command": "run_cmd",
"run": "run_cmd",
"run_shell": "run_cmd",
"write": "write_file",
# Git aliases
"status": "git_status",
"diff": "git_diff",
"log": "git_log",
"branch": "git_branch",
"add": "git_add",
"commit": "git_commit",
"push": "git_push",
"pull": "git_pull",
"checkout": "git_checkout",
"stash": "git_stash",
"clone": "git_clone",
"reset": "git_reset",
"show": "git_show",
"remote": "git_remote",
}
def _is_valid_action(name: str | None) -> bool:
if not name:
return False
return name in AVAILABLE_TOOLS or name in TOOL_ALIASES
def _detect_unknown_action(text: str) -> str | None:
"""Return the first action name in the text that is not a valid tool."""
for obj in _extract_json_objects(text):
action = obj.get("action")
if action and not _is_valid_action(action):
return str(action)
return None
def _workspace_info() -> str:
"""Return a message describing the current working location,
adjusting when the agent is inside an OpenKyrozen folder."""
cwd = os.getcwd()
parent = os.path.dirname(cwd)
if os.path.basename(cwd) == "OpenKyrozen":
return (
f"OpenKyrozen is installed inside `{cwd}`.\n"
f"Your workspace (the folder you are working on) is located one level above:\n"
f"{parent}\n\n"
"You should treat all file operations relative to your workspace.\n"
"For example, to list files in your workspace use `list_dir('.')`.\n"
"To read a file that is in your workspace (not inside OpenKyrozen), "
"use an absolute or relative path as usual – the agent is currently running "
"inside the OpenKyrozen folder, but your project files are in your workspace."
)
else:
return (
f"You are currently working inside the directory:\n{cwd}\n\n"
"You can use relative paths like '.' or 'main.py' directly.\n"
"Do not ask the user to supply a local path or a remote URL unless you intend to "
"use the `analyze_remote_repo` tool to clone an external repository."
)
console = Console()
bg_console = Console(stderr=True)
# ---- Task status panel (rendered at bottom via Rich, no scroll regions) ----
def _tasks_panel_height() -> int:
if not tasks.tasks:
return 0
return min(len(tasks.tasks) + 3, 12)
def _tasks_panel_content() -> str:
"""Build task panel as Rich-markup string (no raw ANSI)."""
if not tasks.tasks:
return ""
total = len(tasks.tasks)
done = sum(1 for t in tasks.tasks if t["status"] in {"done", "succeeded"})
bar_w = 20
filled = int(bar_w * done / max(total, 1))
bar = _BAR_FILL * filled + _BAR_EMPTY * (bar_w - filled)
lines = [f"[bold white on {_ACCENT_BG}] {_BOX_TL}{_BOX_H}{_BOX_H} TASKS [{bar}] {done}/{total} [/]"]
for i, t in enumerate(tasks.tasks):
icon = _CHECK if t["status"] in {"done", "succeeded"} else _CIRCLE if t["status"] == "pending" else _HALF
color = _SUCCESS if t["status"] in {"done", "succeeded"} else _WARNING if t["status"] == "pending" else _ACCENT
desc = t["description"][:55]
lines.append(f"[white on {_ACCENT_BG}] {_BOX_V} [{color}]{icon}[/{color}] [{_MUTED}]{i}[/{_MUTED}] {desc} [/]")
pending = sum(1 for t in tasks.tasks if t["status"] not in {"done", "succeeded", "failed", "blocked", "cancelled"})
if pending > 0:
lines.append(f"[bold white on {_ACCENT_BG}] {_BOX_BL}{_BOX_H}{_BOX_H} {pending} remaining — DO NOT STOP [/]")
else:
lines.append(f"[bold white on {_ACCENT_BG}] {_BOX_BL}{_BOX_H}{_BOX_H} All tasks complete {_CHECK} [/]")
return "\n".join(lines)
def _update_tasks_panel() -> None:
"""Render task panel at current cursor position via Rich."""
content = _tasks_panel_content()
if not content:
return
try:
console.print(Panel(content, title="Tasks", border_style=_ACCENT))
except Exception:
pass
def _clear_tasks_panel() -> None:
"""No‑op — panel is inline, cleared naturally by new output."""
pass
# ---- Theme ----
_ACCENT = "#00f0ff" # primary brand colour
_ACCENT_DIM = "#007788" # muted variant for secondary elements
_ACCENT_BG = "#001a1f" # dark background tint
_SUCCESS = "#00ff88" # success green
_WARNING = "#ffaa00" # warning amber
_ERROR = "#ff4466" # error red
_MUTED = "#445566" # subtle grey
# ---- Constants ----
SHORT_TERM_CAP = 16
MAX_TOOL_RETRIES = 3
MAX_STEPS_PER_TURN = 50 # how many tool-call rounds the LLM may perform in one user turn
MAX_UNKNOWN_TOOL_RETRIES = 3 # how many times to re-prompt when LLM uses an unrecognised action name
CONFIG_PATH = os.path.expanduser("~/.kyrozen_config.json")
IDLE_CONSOLIDATION_TIMEOUT = 60 # 1 minute
_EXECUTION_SURFACE = os.environ.get("KYROZEN_EXECUTION_SURFACE", "cli").strip().lower()
_dynamic_tools_env = os.environ.get("KYROZEN_ALLOW_DYNAMIC_TOOLS")
_surface_capabilities = os.environ.get(
f"KYROZEN_{_EXECUTION_SURFACE.upper()}_CAPABILITIES", ""
).strip().lower()
_execution_capability_token = issue_capability_token(
f"surface:{_EXECUTION_SURFACE}",
resolve_capabilities(
_surface_capabilities or ("full" if _EXECUTION_SURFACE == "cli" else "workspace"),
default="workspace",
),
)
ALLOW_DYNAMIC_TOOLS = (
_dynamic_tools_env.strip().lower() in {"1", "true", "yes"}
if _dynamic_tools_env is not None
else _EXECUTION_SURFACE == "cli" or _surface_capabilities == "full"
)
_APPROVAL_REQUIRED_TOOLS = frozenset({
"git_push", "git_pull", "git_checkout", "git_stash", "git_reset", "git_remote",
})
_APPROVAL_LOG_PATH = Path("kyrozen_audit.log")
def _record_tool_approval(action: str, decision: str, args: str = "") -> None:
"""Write a minimal local audit record without persisting obvious secrets."""
safe_args = re.sub(r"(?i)(token|password|secret|api[_-]?key)\s*[:=]\s*\S+", r"\1=<redacted>", str(args))
safe_args = re.sub(r"\bsk-[A-Za-z0-9_-]+", "sk-<redacted>", safe_args)
safe_args = safe_args.replace("\n", " ")[:240]
try:
ts = datetime.datetime.now(UTC).isoformat(timespec="seconds")
with _APPROVAL_LOG_PATH.open("a", encoding="utf-8") as audit_file:
audit_file.write(f"[{ts}] [local-cli] TOOL_{decision.upper()} | {action} | {safe_args}\n")
except OSError:
pass
def _confirm_tool_action(action: str, args: str = "") -> bool:
"""Confirm high-impact local CLI actions while keeping normal tools frictionless."""
if action not in _APPROVAL_REQUIRED_TOOLS or _EXECUTION_SURFACE != "cli":
return True
mode = os.environ.get("KYROZEN_APPROVAL_MODE", "dangerous").strip().lower()
if mode in {"never", "none", "off"}:
_record_tool_approval(action, "approved", args)
return True
if not sys.stdin.isatty():
_record_tool_approval(action, "denied_noninteractive", args)
return False
prompt = (
f"High-impact action: {action} {args[:180]}\n"
"This may change remote or working-tree state. Continue? [y/N]: "
)
try:
approved = console.input(prompt).strip().lower() in {"y", "yes"}
except (EOFError, KeyboardInterrupt):
approved = False
_record_tool_approval(action, "approved" if approved else "denied", args)
return approved
# ---- Provider (multi-LLM support) ----
_provider_config: ProviderConfig | None = None
llm_provider: LLMProvider | None = None
# Backward-compatible aliases (used throughout the codebase)
DEEPSEEK_MODEL_SIMPLE = "deepseek-chat" # set at init time from provider
DEEPSEEK_MODEL_COMPLEX = "deepseek-reasoner"
MODEL_NAME = "deepseek-chat (V4 auto-select)" # updated at init
# -------- Self-learning feature flags (toggled via /self-learning) --------
_SELF_LEARNING_FLAGS: dict[str, bool] = {
"auto_learn_conversations": True,
"load_project_files_into_memory": True,
"age_out_old_coded_entries": True,
"auto_debug_tool": True,
"consolidate_memories": True,
"review_tools": True,
"targeted_inquiry": True,
"maybe_trigger_reflection": True,
"maybe_strategy_distillation": True,
"auto_patch_new_technology": True,
"invent_skills": True,
}
tasks = TaskManager()
# -------- Regression Testing --------
# Core test suite covering the most important built-in tools
_CORE_TESTS = [
{
"description": "list_dir returns a non-empty string",
"action": "list_dir",
"args": ".",
"check": "nonempty"
},
{
"description": "read_file returns content of main.py (contains 'Kyrozen')",
"action": "read_file",
"args": "main.py",
"check": "contains",
"expected": "Kyrozen"
},
{
"description": "find_files finds all .py files in top level",
"action": "find_files",
"args": "*.py",
"check": "nonempty"
},
{
"description": "run_cmd echoes a simple message",
"action": "run_cmd",
"args": "echo 'regression_test_ok'",
"check": "contains",
"expected": "regression_test_ok"
},
{
"description": "write_file creates a test file and read_file reads it back",
"action": "write_file",
"args": "_test_regression_tmp.txt|hello from regression",
"check": "nonempty"
},
{
"description": "execute_terminal_command works (alias for run_cmd)",
"action": "execute_terminal_command",
"args": "echo 'alias_ok'",
"check": "contains",
"expected": "alias_ok"
},
{
"description": "list_dir on non‑existent folder returns error",
"action": "list_dir",
"args": "_nonexistent_xyz",
"check": "error"
},
]
# Snapshot management for user‑defined tools
_BUILTIN_TOOL_NAMES = {
"write_file","read_file","run_cmd","search_web","find_files","list_dir",
"git_clone","git_status","execute_terminal_command","analyze_remote_repo",
"list_tree","read_webpage","check_stored_data","search_memory",
"git_diff","git_log","git_branch","git_add","git_commit",
"git_push","git_pull","git_checkout","git_stash","git_reset",
"git_show","git_remote",
"browser_open","browser_snapshot","browser_click","browser_type","browser_close",
}
_saved_user_tools: dict[str, Any] = {}
def _take_tool_snapshot() -> None:
global _saved_user_tools
_saved_user_tools = {k: v for k, v in AVAILABLE_TOOLS.items() if k not in _BUILTIN_TOOL_NAMES}
def _restore_tool_snapshot() -> None:
global _saved_user_tools
# Remove current user‑defined tools
keys_to_remove = [k for k in AVAILABLE_TOOLS if k not in _BUILTIN_TOOL_NAMES]
for k in keys_to_remove:
del AVAILABLE_TOOLS[k]
# Restore from snapshot
AVAILABLE_TOOLS.update(_saved_user_tools)
def _run_regression_tests() -> bool:
"""Execute the core test suite and return True iff all tests pass."""
all_pass = True
for test in _CORE_TESTS:
action = test["action"]
args = test["args"]
expected = test.get("expected", "")
check_type = test["check"]
fn = AVAILABLE_TOOLS.get(action)
if fn is None:
all_pass = False
continue
try:
result = fn(args)
except Exception as e:
result = f"Error: {e}"
passed = False
if check_type == "nonempty":
passed = bool(result.strip())
elif check_type == "contains":
passed = expected in result
elif check_type == "error":
passed = result.strip().lower().startswith("error")
if not passed:
all_pass = False
else:
pass
return all_pass
# -------- Error‑Driven Learning (Failure Memory) --------
_FAILURE_STORE_PREFIX = "FAILURE:"
def _store_failure(original_request: str, attempted_action: str, error_info: str, resolution: str) -> None:
"""Store a failure incident in long‑term memory for later retrieval."""
entry = (
f"{_FAILURE_STORE_PREFIX}\n"
f"Request: {original_request}\n"
f"Attempted: {attempted_action}\n"
f"Error: {error_info}\n"
f"Resolution: {resolution}\n"
)
memory_bank.add_log(entry)
def _retrieve_failure(query: str, n: int = 3) -> list[str]:
"""Retrieve relevant failure records from memory."""
results = memory_bank.recall(query, n_results=n)
return [r for r in results if r.startswith(_FAILURE_STORE_PREFIX)]
# -------- Tool Performance Tracking --------
_tool_stats: dict[str, dict] = {} # {tool_name: {"calls":int,"successes":int,"avg_time":float,"total_time":float}}
_total_prompt_tokens: int = 0
_total_completion_tokens: int = 0
_last_prompt_tokens: int = 0
_last_completion_tokens: int = 0
_turn_cost_log: list[dict] = [] # {"tokens":int, "time":float, "tool_calls":int}
def _track_tool_performance(action: str, result: str, elapsed: float) -> None:
stats = _tool_stats.setdefault(action, {"calls":0,"successes":0,"total_time":0.0})
stats["calls"] += 1
stats["total_time"] += elapsed
if not _is_tool_error(result):
stats["successes"] += 1
# persist stats to memory periodically (handled in consolidation)
# -------- Post‑Task Reflection --------
_last_task_end = time.time()
def _maybe_trigger_reflection_after_complex_task(num_tool_calls: int) -> None:
"""Trigger reflection after a multi‑tool task ends (not idle)."""
global _last_task_end
now = time.time()
if now - _last_task_end < 60:
return # at most once per minute
_last_task_end = now
# Only reflect on tasks that required several tool calls
if num_tool_calls < 2:
return
recent = memory_bank.get_recent(20)
if not recent:
return
recent_tokens = sum(entry.get("tokens", 0) for entry in _turn_cost_log[-5:])
recent_time = sum(entry.get("time", 0) for entry in _turn_cost_log[-5:])
cost_summary = f"Recent token count: {recent_tokens}, recent runtime: {recent_time:.1f}s" if _turn_cost_log else ""
reflect_prompt = (
"You are Kyrozen's reflection module. The last task used {num_tool_calls} tool calls. "
"Analyse whether a more efficient approach exists. "
f"{cost_summary}\n"
"Output the optimised strategy as a numbered list. If nothing to improve, output '—'.\n\n"
+ "\n".join(recent[-10:])
)
try:
messages = [{"role": "system", "content": reflect_prompt}]
answer = _get_llm_response(messages).strip()
if answer and answer not in ("—", ""):
memory_bank.add_log(f"REFLECTION:\n{answer}")
except Exception:
pass
def _maybe_trigger_reflection() -> None:
"""If at least 3 messages have been exchanged since last reflection and idle, reflect."""
global _last_task_end
now = time.time()
if now - _last_task_end < 300:
return # not idle long enough
_last_task_end = now
recent = memory_bank.get_recent(20)
if not recent:
return
# Compute token cost of recent turns
recent_tokens = sum(
entry.get("tokens", 0) for entry in _turn_cost_log[-5:]
)
recent_time = sum(
entry.get("time", 0) for entry in _turn_cost_log[-5:]
)
cost_summary = f"Recent token count: {recent_tokens}, recent runtime: {recent_time:.1f}s" if _turn_cost_log else ""
reflect_prompt = (
"You are Kyrozen's reflection module. Read the recent interactions and find a non‑trivial task "
"that took several steps. Analyse whether a more efficient approach exists. "
f"{cost_summary}\n"
"Output the optimised strategy as a numbered list. If nothing to improve, output '—'.\n\n"
+ "\n".join(recent[-10:])
)
try:
messages = [{"role": "system", "content": reflect_prompt}]
answer = _get_llm_response(messages).strip()
if answer and answer not in ("—", ""):
memory_bank.add_log(f"REFLECTION:\n{answer}")
except Exception:
pass
def _maybe_strategy_distillation() -> None:
"""If recent turns consumed many tokens, distill an efficient strategy."""
if len(_turn_cost_log) < 3:
return
recent_total = sum(entry.get("tokens", 0) for entry in _turn_cost_log[-5:])
if recent_total < 5000:
return
# Gather recent conversation context for analysis
recent_logs = memory_bank.get_recent(30)
if not recent_logs:
return
# Filter out system‑internal entries
user_logs = [r for r in recent_logs if r and not r.startswith(("FILE:", "FACT:", "LEARNED:", "SKILL:", "DEBUG:", "TOOL_REVIEW:"))]
if len(user_logs) < 5:
return
distill_prompt = (
"You are Kyrozen's strategy distillation module. Recent turns consumed "
f"{recent_total} tokens. Analyse the conversation patterns below and "
"distill 1‑3 concise strategies the agent should adopt to work more "
"efficiently (fewer tool calls, less token waste, faster execution).\n\n"
"Output each strategy on a new line prefixed with 'STRATEGY:'.\n"
"If no clear improvement, output '—'.\n\n"
+ "\n".join(user_logs[-15:])
)
try:
messages = [{"role": "system", "content": distill_prompt}]
answer = _get_llm_response(messages).strip()
if answer and answer not in ("—", ""):
for line in answer.split("\n"):
line = line.strip()
if line.startswith("STRATEGY:"):
memory_bank.add_log(f"STRATEGY: {line}")
except Exception:
pass
# -------- Sleep & Consolidation (Dream Cycle) --------
_last_user_interaction = time.time()
_last_code_scan_time = 0
def _age_out_old_coded_entries() -> None:
"""Remove file snapshots for .py files that no longer exist on disk."""
global _last_code_scan_time
now = time.time()
if now - _last_code_scan_time < 3600: # once per hour
return
_last_code_scan_time = now
project_root = _get_workspace_root()
skip_dirs = {".venv", "venv", "chroma_memory", "__pycache__", ".git"}
valid: set[str] = set()
for py_file in project_root.rglob("*.py"):
if not any(part in py_file.parts for part in skip_dirs):
valid.add(str(py_file.relative_to(project_root)))
memory_bank.remove_stale_files(valid)
def _consolidate_memories() -> None:
global _saved_user_tools
_take_tool_snapshot()
"""Cluster, deduplicate and summarise recent facts and logs."""
recent = memory_bank.get_recent(50)
if not recent:
return
# Keep only non‑trivial logs
non_trivial = [r for r in recent if r and not r.startswith("FILE:")]
if len(non_trivial) < 3:
return
consolidate_prompt = (
"You are Kyrozen's memory consolidation module. Read the following recent logs "
"and merge duplicates, remove contradictions (keeping the most recent), "
"and extract a minimal set of important facts. "
"Output each consolidated fact on a new line prefixed with 'FACT:'. "
"If nothing important, output only '—'.\n\n"
+ "\n".join(non_trivial)
)
try:
messages = [{"role": "system", "content": consolidate_prompt}]
answer = _get_llm_response(messages).strip()
if answer and not answer.startswith("—"):
# Store consolidated facts
for line in answer.split("\n"):
line = line.strip()
if line.startswith("FACT:"):
memory_bank.add_log(line)
# Remove the original logs that were just consolidated (to avoid duplication)
# We can delete them via ChromaDB if available
_remove_consolidated_entries(non_trivial)
except Exception:
pass
def _remove_consolidated_entries(logs: list[str]) -> None:
"""Delete exact source logs through the durable memory facade."""
if not logs:
return
try:
memory_bank.delete_logs(logs)
except Exception as exc:
memory_bank.store.append_event(
"memory.cleanup_failed", {"error": str(exc)[:500], "count": len(logs)},
user_id=memory_bank.user_id, workspace_id=memory_bank.workspace_id,
session_id=memory_bank.session_id,
)
def _register_tool(name: str, code: str, description: str = "") -> bool:
return False
# -------- Tool Refactoring --------
def _review_tools() -> None:
"""Analyse tool usage patterns and suggest merges or improvements."""
if len(_tool_stats) < 3:
return # not enough data
# Build a summary of tool usage
summary_lines = []
for name, stats in sorted(_tool_stats.items(),
key=lambda x: x[1].get("calls", 0), reverse=True)[:10]:
calls = stats.get("calls", 0)
successes = stats.get("successes", 0)
avg_time = stats.get("total_time", 0) / max(calls, 1)
summary_lines.append(
f" {name}: {calls} calls, {successes} successes, "
f"avg {avg_time:.2f}s per call"
)
if not summary_lines:
return
review_prompt = (
"You are Kyrozen's tool review module. Review the following tool usage "
"statistics and suggest improvements:\n"
"- Are there tools that could be merged (similar functionality)?\n"
"- Are any tools under‑used and candidates for removal?\n"
"- Could any tool be made faster or more robust?\n"
"Output each suggestion on a new line prefixed with 'TOOL_REVIEW:'.\n"
"If no improvements needed, output '—'.\n\n"
+ "\n".join(summary_lines)
)
try:
messages = [{"role": "system", "content": review_prompt}]
answer = _get_llm_response(messages).strip()
if answer and answer not in ("—", ""):
for line in answer.split("\n"):
line = line.strip()
if line.startswith("TOOL_REVIEW:"):
memory_bank.add_log(f"TOOL_REVIEW: {line}")
except Exception:
pass
# -------- Active Exploration (Self‑Learning Code Analysis) --------
_last_inquiry_time = time.time()
_inquired_functions: set[str] = set()
def _targeted_inquiry() -> None:
"""Scan project files for undocumented functions and infer their purpose via LLM.
This is self-learning: the agent analyses code itself, never asks the user."""
global _last_inquiry_time
now = time.time()
if now - _last_user_interaction < 300:
return
if now - _last_inquiry_time < 600: # once per 10 min
return
_last_inquiry_time = now
project_root = _get_workspace_root()
for py_file in project_root.rglob("*.py"):
if "__pycache__" in str(py_file) or py_file.name.startswith("test_"):
continue
content = py_file.read_text(encoding="utf-8", errors="ignore")
# Find function definitions without docstrings
for match in re.finditer(
r"def\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*\S+\s*)?:\s*\n(\s+)(\S.*)",
content
):
func_name = match.group(1)
func_params = match.group(2)
indent = match.group(3)
first_line = match.group(4).strip()
inquiry_key = f"{py_file}:{func_name}:{stable_hash(content[match.start():match.end()]) if 'stable_hash' in globals() else hash(content[match.start():match.end()])}"
if inquiry_key in _inquired_functions:
continue
_inquired_functions.add(inquiry_key)
# Skip if it already has a docstring
if first_line.startswith('"""') or first_line.startswith("'''"):
continue
# Extract function body (up to ~30 lines for context)
func_start = match.start()
body_start = content.index("\n", match.end(3)) + 1
lines = content[body_start:].split("\n")
body_lines = []
for line in lines:
if line.strip() and not line.startswith(indent):
break
body_lines.append(line)
if len(body_lines) >= 30:
break
body_text = "\n".join(body_lines)
# Use LLM to infer what this function does
analyze_prompt = (
"You are Kyrozen's code analysis module. Examine this Python "
f"function from {py_file.name} and infer its purpose.\n\n"
f"```python\ndef {func_name}({func_params}):\n{body_text}\n```\n\n"
"Output a single line starting with 'PURPOSE: ' followed by "
"a concise description of what this function does, its inputs, "
"and its outputs. If unclear, output 'PURPOSE: unclear'."
)
try:
messages = [{"role": "system", "content": analyze_prompt}]
answer = _get_llm_response(messages).strip()
if answer.startswith("PURPOSE: "):
purpose = answer[len("PURPOSE: "):].strip()
if purpose.lower() != "unclear":
memory_bank.add_log(
f"CODE_DOC: Function '{func_name}' in {py_file.name} "
f"({func_params}) — {purpose}"
)
except Exception as exc:
memory_bank.store.append_event(
"learning.inquiry_failed", {"path": str(py_file), "function": func_name, "error": str(exc)[:500]},
user_id=memory_bank.user_id, workspace_id=memory_bank.workspace_id,
session_id=memory_bank.session_id,
)
return # one function per cycle, with a durable cursor
def _invent_skills() -> None:
"""Examine recent conversation logs and create a reusable skill
(workflow) that the agent can later call via memory retrieval."""
recent = memory_bank.get_recent(40)
if not recent:
return
# Exclude system‑internal logs (FILE, FACT, SKILL, LEARNED)
logs = [
r for r in recent
if not r.startswith("FILE:")
and not r.startswith("FACT:")
and not r.startswith("LEARNED:")
and not r.startswith("SKILL:")
]
if len(logs) < 5:
return
prompt = (
"You are Kyrozen's skill invention module. Read the following recent "
"conversation logs and extract a reusable skill (workflow) that the "
"agent could follow in the future to accomplish similar tasks more "
"efficiently.\n\n"
"Output exactly in this format, nothing else:\n\n"
"Skill Name: <short name>\n"
"Description: <short description>\n"
"Steps:\n"
"1. <step>\n"
"2. <step>\n"
"...\n\n"
"If you cannot identify a useful skill, output only the single character '—'.\n\n"
+ "\n".join(logs[-20:])
)
try:
messages = [{"role": "system", "content": prompt}]
answer = _get_llm_response(messages).strip()
if answer in ("—", ""):
return
# Parse the answer
name_match = re.search(r"Skill Name:\s*(.+)", answer, re.IGNORECASE)
desc_match = re.search(r"Description:\s*(.+)", answer, re.IGNORECASE)
steps_match = re.search(r"Steps:\s*(.+)", answer, re.DOTALL | re.IGNORECASE)
skill_name = name_match.group(1).strip() if name_match else "unknown"
description = desc_match.group(1).strip() if desc_match else ""
steps_text = steps_match.group(1).strip() if steps_match else ""
lines = steps_text.split("\n")
steps_clean = [line.strip() for line in lines if line.strip() and line.strip()[:1].isdigit()]
steps_str = "\n".join(steps_clean)
stored = f"SKILL: {skill_name} | {description}\nSteps:\n{steps_str}"
learning_engine.submit("skill", stored, evidence_id=stable_hash("\n".join(logs[-5:])),
confidence=0.4, metadata={"source": "skill_invention"})
learning_engine.submit("fact", f"Learned a reusable skill called '{skill_name}' ({description})",
evidence_id=stable_hash(stored), confidence=0.4,
metadata={"source": "skill_invention"})
except Exception as exc:
memory_bank.store.append_event(
"learning.skill_invention_failed", {"error": str(exc)[:1000]},
user_id=memory_bank.user_id, workspace_id=memory_bank.workspace_id,
session_id=memory_bank.session_id,
)
# -------- Auto‑Patching (Background Knowledge) --------
_known_libraries = set()
_technology_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="kyrozen-learning")
_technology_in_flight: set[str] = set()
_technology_lock = threading.Lock()
def _auto_patch_new_technology(user_input: str) -> None:
"""If user mentions an unknown library, fetch its docs in background."""
detected: set[str] = set()
def _extract_words(text: str) -> list[str]:
"""Split text into words, handling CJK by treating each CJK char as a word boundary."""
result: list[str] = []
buf: list[str] = []
for ch in text:
cp = ord(ch)
if (0x4E00 <= cp <= 0x9FFF or 0x3400 <= cp <= 0x4DBF or
0x20000 <= cp <= 0x2A6DF or 0x3040 <= cp <= 0x30FF or
0xAC00 <= cp <= 0xD7AF):
if buf:
result.extend(''.join(buf).split())
buf = []
elif ch.isspace() or ch in '"\'`,.;:!?()[]{}':
if buf:
result.extend(''.join(buf).split())
buf = []
else:
buf.append(ch)
if buf:
result.extend(''.join(buf).split())
return result or text.split()
words = _extract_words(user_input)
for w in words:
# Pattern 1: suffix based detection (lib, py, framework, package)
if w.endswith(("lib","py","framework","package")) and w not in _known_libraries:
detected.add(w)
# Pattern 2: detect "use <Library>" or "using <Library>" phrases
for match in re.finditer(r"(?:use|using)\s+([A-Za-z_]\w*)", user_input, re.IGNORECASE | re.UNICODE):
lib = match.group(1)
if lib.lower() not in ("a","an","the","this","that","it","my","our","your"):
detected.add(lib)
# Pattern 3: import statements in code or conversation
for match in re.finditer(r"(?:import|from)\s+([A-Za-z_]\w*)", user_input, re.UNICODE):
lib = match.group(1)
if lib.lower() not in ("a","an","the","os","sys","re","json","time","math"):
detected.add(lib)
# Pattern 4: "pip install <lib>" or "install <lib>"
for match in re.finditer(r"(?:pip\s+install|install)\s+([A-Za-z_][\w.-]*)", user_input, re.IGNORECASE | re.UNICODE):
lib = match.group(1)
detected.add(lib)
# Pattern 5: well‑known library heuristics (capitalised or compound names)
well_known = {
"numpy","pandas","scipy","matplotlib","seaborn","plotly",
"sklearn","scikit-learn","tensorflow","keras","pytorch","torch",
"flask","django","fastapi","starlette","aiohttp","httpx","requests",
"sqlalchemy","alembic","pydantic","celery","redis","rabbitmq",
"pytest","unittest","mypy","ruff","black","isort","pre-commit",
"docker","kubernetes","nginx","postgresql","mysql","mongodb",
"react","vue","angular","svelte","next.js","tailwind","bootstrap",
"graphql","grpc","protobuf","websocket","openapi","swagger",
}
for w in words:
clean = w.strip('"\'`,.;:!?()[]{}').lower()
if clean in well_known and clean not in _known_libraries:
detected.add(clean)
# Spawn background fetches for new discoveries
for lib in detected:
_known_libraries.add(lib)
with _technology_lock:
if len(_technology_in_flight) >= 8 or lib in _technology_in_flight:
continue
_technology_in_flight.add(lib)
_technology_executor.submit(_fetch_library_info, lib)
def _fetch_library_info(lib_name: str) -> None:
"""Search web for core concepts and store in memory."""
from tools import search_web
try:
result = search_web(f"{lib_name} documentation overview")
if result and "Search" not in result:
memory_bank.add_log(f"LIBRARY_INFO: {lib_name}\n{result[:2000]}")
except Exception as exc:
memory_bank.store.append_event(
"learning.library_fetch_failed", {"library": lib_name, "error": str(exc)[:500]},
user_id=memory_bank.user_id, workspace_id=memory_bank.workspace_id,
session_id=memory_bank.session_id,
)
finally:
with _technology_lock:
_technology_in_flight.discard(lib_name)
# ---- Spinner for LLM waiting ----
_SPINNER_STOP = threading.Event()
_SPINNER_THREAD: threading.Thread | None = None
# _SPINNER_FRAMES defined at module level (dual-set Unicode/ASCII)
def _spinner_worker(stop_event: threading.Event) -> None:
while not stop_event.is_set():
for frame in _SPINNER_FRAMES:
if stop_event.is_set():
break
sys.stdout.write("\r" + frame + " ")
sys.stdout.flush()
time.sleep(0.25)
def _call_llm_with_spinner(messages: list[dict], model: str | None = None) -> str:
global _SPINNER_STOP, _SPINNER_THREAD
_SPINNER_STOP.clear()
_SPINNER_THREAD = threading.Thread(target=_spinner_worker, args=(_SPINNER_STOP,), daemon=True)
_SPINNER_THREAD.start()
try:
result = _get_llm_response(messages, model=model)
finally:
_SPINNER_STOP.set()
if _SPINNER_THREAD:
_SPINNER_THREAD.join(timeout=2)
sys.stdout.write("\r" + " " * 70 + "\r")
sys.stdout.flush()
return result
# ---- Existing functions (unchanged) ----
def _load_config_key() -> str | None:
if os.path.exists(CONFIG_PATH):
try:
with open(CONFIG_PATH, "r") as f:
data = json.load(f)
key = data.get("api_key")
if data.get("encrypted") and isinstance(key, str):
key = decrypt_api_key(key)
if key and isinstance(key, str) and key.strip():
os.environ["DEEPSEEK_API_KEY"] = key.strip()
return key.strip()
except (json.JSONDecodeError, OSError):
pass
return None