codeaois 0.1.2__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. {codeaois-0.1.2 → codeaois-0.2.2}/PKG-INFO +1 -1
  2. codeaois-0.2.2/codeaois/agents/pip_agent.py +56 -0
  3. codeaois-0.2.2/codeaois/cli/main.py +463 -0
  4. codeaois-0.2.2/codeaois/core/memory.py +80 -0
  5. codeaois-0.2.2/codeaois/core/planner.py +51 -0
  6. codeaois-0.2.2/codeaois/models/llm_interface.py +70 -0
  7. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois.egg-info/PKG-INFO +1 -1
  8. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois.egg-info/SOURCES.txt +1 -4
  9. {codeaois-0.1.2 → codeaois-0.2.2}/pyproject.toml +1 -1
  10. {codeaois-0.1.2 → codeaois-0.2.2}/setup.py +4 -4
  11. codeaois-0.1.2/codeaois/agents/3d_agent.py +0 -23
  12. codeaois-0.1.2/codeaois/agents/database_agent.py +0 -23
  13. codeaois-0.1.2/codeaois/agents/debugging_agent.py +0 -23
  14. codeaois-0.1.2/codeaois/agents/devops_agent.py +0 -23
  15. codeaois-0.1.2/codeaois/cli/main.py +0 -354
  16. codeaois-0.1.2/codeaois/core/memory.py +0 -65
  17. codeaois-0.1.2/codeaois/core/planner.py +0 -51
  18. codeaois-0.1.2/codeaois/models/llm_interface.py +0 -66
  19. {codeaois-0.1.2 → codeaois-0.2.2}/README.md +0 -0
  20. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/__init__.py +0 -0
  21. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/agents/coder_agent.py +0 -0
  22. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/agents/data_science_agent.py +0 -0
  23. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/agents/git_agent.py +0 -0
  24. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/agents/tester_agent.py +0 -0
  25. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/app.py +0 -0
  26. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/brain/__init__.py +0 -0
  27. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/brain/embeddings.py +0 -0
  28. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/brain/memory.py +0 -0
  29. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/brain/scanner.py +0 -0
  30. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/cli/__init__.py +0 -0
  31. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/config/settings.py +0 -0
  32. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/core/context.py +0 -0
  33. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/core/marketplace.py +0 -0
  34. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/core/orchestrator.py +0 -0
  35. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/core/router.py +0 -0
  36. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/utils/file_writer.py +0 -0
  37. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois/utils/logger.py +0 -0
  38. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois.egg-info/dependency_links.txt +0 -0
  39. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois.egg-info/entry_points.txt +0 -0
  40. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois.egg-info/requires.txt +0 -0
  41. {codeaois-0.1.2 → codeaois-0.2.2}/codeaois.egg-info/top_level.txt +0 -0
  42. {codeaois-0.1.2 → codeaois-0.2.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codeaois
3
- Version: 0.1.2
3
+ Version: 0.2.2
4
4
  Summary: Advanced AI Developer OS
5
5
  Author: Nikhil Nagar
6
6
  Requires-Python: >=3.8
@@ -0,0 +1,56 @@
1
+ import subprocess
2
+ import sys
3
+ import re
4
+ from rich.console import Console
5
+ from codeaois.models.llm_interface import call_openrouter
6
+
7
+ console = Console()
8
+
9
+ def generate_pip_code(user_input: str, context: str) -> str:
10
+ """
11
+ The Auto-Pip Agent. It uses the LLM to extract package names, physically installs them on the OS,
12
+ and returns an installation log.
13
+ """
14
+ # 1. Ask the AI to extract JUST the package names from the user's sentence
15
+ sys_prompt = "You are a package extractor tool. The user wants to install Python packages. Reply ONLY with the exact pip package names separated by spaces. Nothing else. No markdown. Example: requests pandas numpy"
16
+
17
+ console.print("\n[dim]✦ Analyzing required dependencies...[/dim]")
18
+ packages_str = call_openrouter(sys_prompt, user_input, intent="code")
19
+
20
+ # Split the response into a list of words
21
+ packages = packages_str.strip().split()
22
+
23
+ if not packages or "error" in packages_str.lower():
24
+ return "```text\nCould not detect any valid packages to install.\n```"
25
+
26
+ console.print(f"[bold cyan]📦 Auto-Pip Agent initialized![/bold cyan]")
27
+
28
+ success_logs = []
29
+
30
+ # 2. Physically run the installation commands on the user's computer!
31
+ for pkg in packages:
32
+ # Clean the package name to prevent security injection attacks
33
+ pkg = re.sub(r'[^a-zA-Z0-9_\-\.]', '', pkg)
34
+ if not pkg:
35
+ continue
36
+
37
+ console.print(f"[dim]Executing: pip install {pkg}...[/dim]")
38
+
39
+ try:
40
+ # Runs `python -m pip install <package>` directly in the background!
41
+ result = subprocess.run([sys.executable, "-m", "pip", "install", pkg], capture_output=True, text=True)
42
+
43
+ if result.returncode == 0:
44
+ success_logs.append(f"✅ Successfully installed: {pkg}")
45
+ console.print(f"[bold green]✓ {pkg} installed successfully![/bold green]")
46
+ else:
47
+ success_logs.append(f"❌ Failed to install {pkg}\nError: {result.stderr.strip()}")
48
+ console.print(f"[bold red]✗ Failed to install {pkg}[/bold red]")
49
+
50
+ except Exception as e:
51
+ success_logs.append(f"❌ System Error running pip: {e}")
52
+
53
+ final_log = "\n".join(success_logs)
54
+
55
+ # 3. Return a text block so main.py saves the installation logs
56
+ return f"```text\n--- CodeAOIS Pip Installation Log ---\n{final_log}\n```\nI have finished executing the pip installation on your local system! Check the logs saved to the file."
@@ -0,0 +1,463 @@
1
+ import argparse
2
+ import sys
3
+ import os
4
+ import importlib
5
+ import time
6
+ import random
7
+ import string
8
+
9
+ # --- CLI UI ENGINES ---
10
+ from prompt_toolkit import PromptSession
11
+ from prompt_toolkit.completion import WordCompleter
12
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
13
+ from prompt_toolkit.formatted_text import HTML
14
+ from prompt_toolkit.shortcuts import radiolist_dialog
15
+
16
+ from rich.console import Console
17
+ from rich.markdown import Markdown
18
+ from rich.panel import Panel
19
+ from rich.table import Table
20
+ from rich.prompt import Prompt
21
+ from rich.live import Live
22
+ from rich.text import Text
23
+
24
+ # --- CODEAOIS MODULES ---
25
+ from codeaois.core.planner import analyze_intent, get_installed_agents
26
+ from codeaois.core.context import extract_file_context
27
+ from codeaois.brain.scanner import scan_project_structure
28
+ from codeaois.models.llm_interface import call_openrouter
29
+ from codeaois.agents.coder_agent import generate_code
30
+ from codeaois.agents.data_science_agent import generate_ds_code
31
+ from codeaois.utils.file_writer import extract_and_save_code
32
+ from codeaois.core.marketplace import install_agent
33
+
34
+ from codeaois.core.memory import (
35
+ load_profile, save_profile, load_history, save_history,
36
+ clear_history_data, clear_profile_data, load_settings, save_settings, get_session_stats
37
+ )
38
+
39
+ console = Console(soft_wrap=True)
40
+ chat_history = load_history()
41
+ active_file = None
42
+
43
+ AVAILABLE_COMMANDS = [
44
+ '/help', '/clear', '/status', '/s', '/marketplace', '/m', '/setting', '/set', '/exit', '/clear_user'
45
+ ]
46
+ command_completer = WordCompleter(AVAILABLE_COMMANDS, ignore_case=True)
47
+
48
+ # --- THEME & BACKGROUND ENGINE ---
49
+ def get_theme():
50
+ settings = load_settings()
51
+ return settings.get("ui_theme", "cyan")
52
+
53
+ def set_terminal_background(hex_color):
54
+ sys.stdout.write(f"\033]11;{hex_color}\007")
55
+ sys.stdout.flush()
56
+
57
+ def apply_saved_background():
58
+ settings = load_settings()
59
+ bg_color = settings.get("bg_theme", "#231e20")
60
+ set_terminal_background(bg_color)
61
+
62
+ # --- THE MULTI-ANIMATION LOGO ENGINE ---
63
+ def print_logo():
64
+ settings = load_settings()
65
+ theme = settings.get("ui_theme", "cyan")
66
+ # Option 4 (Data Sweep) is the default!
67
+ anim_style = str(settings.get("logo_animation", "4"))
68
+
69
+ logo_lines = [
70
+ " ____ _ _ ___ _____ _____ ",
71
+ " / ___|___ __| | ___ / \\ / _ \\_ _|/ ____|",
72
+ " | | / _ \\ / _` |/ _ \\/ _ \\| | | || | | (___ ",
73
+ " | |__| (_) | (_| | __/ ___ \\ |_| || |_ \\___ \\ ",
74
+ " \\____\\___/ \\__,_|\\___/_/ \\_\\___/_____|____/ "
75
+ ]
76
+ logo_str = "\n".join(logo_lines)
77
+
78
+ # 0. Instant (No Animation)
79
+ if anim_style == "0":
80
+ console.print(f"[bold {theme}]{logo_str}[/]")
81
+ console.print(f" [dim]✦[/dim] [bold white]Advanced Developer OS[/bold white] [dim]v0.2.1[/dim]")
82
+ console.print(f" [dim]✦[/dim] [dim]Type /help for commands.[/dim]\n")
83
+ return
84
+
85
+ try:
86
+ if anim_style == "1": # Classic Hacker Typewriter
87
+ text = Text(style=f"bold {theme}")
88
+ with Live(console=console, refresh_per_second=60, transient=False) as live:
89
+ for char in logo_str:
90
+ text.append(char)
91
+ live.update(text)
92
+ time.sleep(0.002)
93
+ text.append(f"\n ✦ Advanced Developer OS v0.2.1\n ✦ Type /help for commands.\n", style="dim white")
94
+ live.update(text)
95
+
96
+ elif anim_style == "2": # Neon Pulse
97
+ pulse_colors = ["#001111", "#003333", "#006666", "#009999", "#00cccc", "#00ffff", "#00cccc", "#009999"]
98
+ with Live(console=console, refresh_per_second=20, transient=False) as live:
99
+ for _ in range(2):
100
+ for color in pulse_colors:
101
+ live.update(Text(logo_str, style=f"bold {color}"))
102
+ time.sleep(0.05)
103
+ final_text = Text(logo_str, style=f"bold {theme}")
104
+ final_text.append(f"\n ✦ Advanced Developer OS v0.2.1\n ✦ Type /help for commands.\n", style="dim white")
105
+ live.update(final_text)
106
+
107
+ elif anim_style == "3": # Cyber-Decryption
108
+ chars = string.ascii_letters + string.punctuation
109
+ with Live(console=console, refresh_per_second=30, transient=False) as live:
110
+ for i in range(15):
111
+ scrambled = "".join(c if c in " \n" else random.choice(chars) for c in logo_str)
112
+ live.update(Text(scrambled, style="bold green"))
113
+ time.sleep(0.05)
114
+ final_text = Text(logo_str, style=f"bold {theme}")
115
+ final_text.append(f"\n ✦ Advanced Developer OS v0.2.1\n ✦ Type /help for commands.\n", style="dim white")
116
+ live.update(final_text)
117
+
118
+ elif anim_style == "4": # Data Sweep (THE DEFAULT)
119
+ max_len = max(len(line) for line in logo_lines)
120
+ chars = string.ascii_letters + string.punctuation + "10"
121
+ with Live(console=console, refresh_per_second=60, transient=False) as live:
122
+ for i in range(max_len + 1):
123
+ display_text = Text()
124
+ for line in logo_lines:
125
+ decrypted = line[:i]
126
+ if i < len(line):
127
+ scanner = random.choice(chars) if line[i] != " " else " "
128
+ hidden = "".join(random.choice(chars) if c != " " else " " for c in line[i+1:])
129
+ display_text.append(decrypted, style=f"bold {theme}")
130
+ display_text.append(scanner, style="bold white on white")
131
+ display_text.append(hidden + "\n", style="dim green")
132
+ else:
133
+ display_text.append(decrypted + "\n", style=f"bold {theme}")
134
+ live.update(display_text)
135
+ time.sleep(0.015)
136
+ final_text = Text(logo_str, style=f"bold {theme}")
137
+ final_text.append(f"\n ✦ Advanced Developer OS v0.2.1\n ✦ Type /help for commands.\n", style="dim white")
138
+ live.update(final_text)
139
+
140
+ elif anim_style == "5": # System Override Boot
141
+ boot_msgs = [
142
+ "[dim green][+] Kernel loaded. Initializing core OS...[/]",
143
+ "[dim green][+] Bypassing proxy security... OK[/]",
144
+ "[dim green][+] Mounting AI logic nodes...[/]",
145
+ "[bold yellow][!] WARNING: Root override detected.[/]",
146
+ "[bold cyan][>] Injecting CodeAOIS mainframe sequence...[/]"
147
+ ]
148
+ with Live(console=console, refresh_per_second=20, transient=True) as live:
149
+ for i in range(1, len(boot_msgs) + 1):
150
+ live.update(Text.from_markup("\n".join(boot_msgs[:i])))
151
+ time.sleep(0.2)
152
+ time.sleep(0.4)
153
+ with Live(console=console, refresh_per_second=30, transient=False) as live:
154
+ for _ in range(5):
155
+ live.update(Text(logo_str, style="bold red"))
156
+ time.sleep(0.03)
157
+ live.update(Text(logo_str, style="bold cyan"))
158
+ time.sleep(0.03)
159
+ final_text = Text(logo_str, style=f"bold {theme}")
160
+ final_text.append(f"\n ✦ Advanced Developer OS v0.2.1\n ✦ Type /help for commands.\n", style="dim white")
161
+ live.update(final_text)
162
+ except:
163
+ console.print(f"[bold {theme}]{logo_str}[/]")
164
+
165
+ def run_login_flow():
166
+ theme = get_theme()
167
+ os.system('clear' if os.name == 'posix' else 'cls')
168
+ apply_saved_background()
169
+ print_logo()
170
+ console.print(Panel("[bold white]Welcome to CodeAOIS Initialization[/bold white]\n[dim]Let's configure your workspace.[/dim]", border_style=theme))
171
+
172
+ email = Prompt.ask(f"\n[bold {theme}]►[/bold {theme}] Enter your developer email")
173
+
174
+ with console.status("[dim]Sending secure OTP verification...[/dim]", spinner="dots"):
175
+ time.sleep(1.5)
176
+
177
+ console.print("\n[dim](For this local beta, the verification code is automatically verified.)[/dim]")
178
+
179
+ name = Prompt.ask(f"\n[bold {theme}]►[/bold {theme}] Choose a workspace username", default=email.split('@')[0])
180
+ role = Prompt.ask(f"[bold {theme}]►[/bold {theme}] Primary role (e.g., Full Stack, Data Science)", default="Developer")
181
+
182
+ save_profile({"name": name, "email": email, "role": role})
183
+
184
+ with console.status("[dim]Provisioning local workspace...[/dim]", spinner="dots"):
185
+ time.sleep(1)
186
+
187
+ console.print(f"\n[bold green]✓[/bold green] Workspace initialized successfully.\n")
188
+ return {"name": name, "email": email, "role": role}
189
+
190
+ def handle_settings():
191
+ settings = load_settings()
192
+ theme = settings.get("ui_theme", "cyan")
193
+ bg = settings.get("bg_theme", "#231e20")
194
+ anim = settings.get("logo_animation", "4") # Default visual state
195
+
196
+ console.print(f"\n[bold white]✦ System Settings[/bold white]")
197
+ table = Table(show_header=False, border_style="dim")
198
+ table.add_row("1.", "Toggle API Routing", f"[{'green' if settings['use_custom_api_key'] else theme}]{'Custom Key' if settings['use_custom_api_key'] else 'Cloud Proxy'}[/]")
199
+ table.add_row("2.", "Set Custom API Key", "[dim]********[/dim]" if settings['custom_api_key'] else "[dim]Not Set[/dim]")
200
+ table.add_row("3.", "Change UI Text Theme", f"[bold {theme}]{theme.title()}[/]")
201
+ table.add_row("4.", "Change Window Background", f"[bold white]Active ({bg})[/]")
202
+ table.add_row("5.", "Change Logo Animation", f"[bold white]Style {anim}[/]")
203
+ console.print(table)
204
+
205
+ choice = Prompt.ask("\nSelect option (or press Enter to exit)", choices=["1", "2", "3", "4", "5", ""], default="")
206
+
207
+ if choice == "1":
208
+ settings["use_custom_api_key"] = not settings["use_custom_api_key"]
209
+ save_settings(settings)
210
+ console.print(f"[bold green]✓[/bold green] Routing updated.\n")
211
+ elif choice == "2":
212
+ new_key = Prompt.ask("Enter OpenRouter API Key", password=True)
213
+ if new_key:
214
+ settings["custom_api_key"] = new_key
215
+ settings["use_custom_api_key"] = True
216
+ save_settings(settings)
217
+ console.print("[bold green]✓[/bold green] Custom API Key secured.\n")
218
+ elif choice == "3":
219
+ console.print("\n[dim]Available UI Text Themes:[/dim]")
220
+ console.print(" [cyan]1. Cyan[/cyan] | [magenta]2. Magenta[/magenta] | [green]3. Green[/green] | [yellow]4. Yellow[/yellow] | [blue]5. Blue[/blue]")
221
+ color_choice = Prompt.ask("Select a text color", choices=["1", "2", "3", "4", "5"])
222
+ color_map = {"1": "cyan", "2": "magenta", "3": "green", "4": "yellow", "5": "blue"}
223
+ settings["ui_theme"] = color_map[color_choice]
224
+ save_settings(settings)
225
+ console.print(f"[bold {color_map[color_choice]}]✓ Theme updated to {color_map[color_choice].title()}![/bold {color_map[color_choice]}]")
226
+ elif choice == "4":
227
+ console.print("\n[dim]Available Window Backgrounds:[/dim]")
228
+ console.print(" 1. Deep Void Black\n 2. Matrix Dark Green\n 3. Midnight Blue\n 4. Dracula Dark (Default)")
229
+ bg_choice = Prompt.ask("Select a background", choices=["1", "2", "3", "4"])
230
+ bg_map = {"1": "#000000", "2": "#051405", "3": "#00001a", "4": "#231e20"}
231
+ new_bg = bg_map[bg_choice]
232
+ settings["bg_theme"] = new_bg
233
+ save_settings(settings)
234
+ set_terminal_background(new_bg)
235
+ console.print(f"[bold green]✓ Background color applied instantly![/bold green]\n")
236
+ elif choice == "5":
237
+ console.print("\n[dim]Available Boot Animations:[/dim]")
238
+ console.print(" 0. Instant (No Animation)")
239
+ console.print(" 1. Classic Hacker Typewriter")
240
+ console.print(" 2. Neon Pulse")
241
+ console.print(" 3. Cyber-Decryption")
242
+ console.print(" 4. Data Sweep (Default)")
243
+ console.print(" 5. System Override Boot")
244
+ anim_choice = Prompt.ask("Select an animation style", choices=["0", "1", "2", "3", "4", "5"])
245
+ settings["logo_animation"] = anim_choice
246
+ save_settings(settings)
247
+ console.print(f"[bold green]✓ Boot animation updated to Style {anim_choice}![/bold green]\n")
248
+ console.print("[dim](Type /clear to test it right now!)[/dim]\n")
249
+
250
+ def handle_marketplace():
251
+ theme = get_theme()
252
+ installed = get_installed_agents()
253
+
254
+ options = [
255
+ ("pip", f"📦 Pip Agent (Auto-Installs Packages) {'[Installed]' if 'pip' in installed else ''}"),
256
+ ("database", f"🗄️ Database Agent (SQL/NoSQL) {'[Installed]' if 'database' in installed else ''}"),
257
+ ("devops", f"⚙️ DevOps Agent (Docker/CI-CD) {'[Installed]' if 'devops' in installed else ''}"),
258
+ ("security", f"🛡️ Security Agent (Vulnerability Scanner) {'[Installed]' if 'security' in installed else ''}"),
259
+ ("frontend", f"🎨 Frontend Agent (React/Tailwind) {'[Installed]' if 'frontend' in installed else ''}"),
260
+ ("backend", f"🔌 Backend Agent (FastAPI/Node.js) {'[Installed]' if 'backend' in installed else ''}"),
261
+ ("debugging", f"🐛 Debugger Agent (Deep Error Analysis) {'[Installed]' if 'debugging' in installed else ''}"),
262
+ ("3d", f"🧊 WebGL Agent (Three.js/Shaders) {'[Installed]' if '3d' in installed else ''}"),
263
+ ("seo", f"🔍 SEO Agent (Web Optimization) {'[Installed]' if 'seo' in installed else ''}")
264
+ ]
265
+
266
+ result = radiolist_dialog(
267
+ title="CodeAOIS Plugin Marketplace",
268
+ text="Use ARROW KEYS to scroll down. Enter to install:",
269
+ values=options
270
+ ).run()
271
+
272
+ if result:
273
+ if result in installed:
274
+ console.print(f"\n[bold yellow]⚠[/bold yellow] {result.title()} Agent is already installed.\n")
275
+ else:
276
+ with console.status(f"[{theme}]Downloading {result.title()} Agent...[/{theme}]", spinner="dots"):
277
+ time.sleep(1.5)
278
+ install_agent(result)
279
+ console.print(f"[bold green]✓[/bold green] {result.title()} Agent seamlessly integrated.\n")
280
+
281
+ def show_status():
282
+ theme = get_theme()
283
+ settings = load_settings()
284
+ profile = load_profile()
285
+ stats = get_session_stats()
286
+
287
+ table = Table(title="System Diagnostics", border_style="dim", header_style=f"bold {theme}")
288
+ table.add_column("Component", style="white")
289
+ table.add_column("Status", justify="right")
290
+
291
+ table.add_row("Identity", profile['name'] if profile else "Unknown")
292
+ table.add_row("API Routing", "[bold green]Custom Key[/]" if settings['use_custom_api_key'] else f"[bold {theme}]Cloud Proxy[/]")
293
+ table.add_row("Context Memory", f"{len(chat_history)} messages")
294
+ table.add_row("Tokens Tracked", f"[yellow]{stats['prompt'] + stats['completion']:,}[/yellow]")
295
+ table.add_row("Installed Agents", str(len(get_installed_agents())))
296
+
297
+ console.print("\n")
298
+ console.print(table)
299
+ console.print("\n")
300
+
301
+ def process_command(user_input: str):
302
+ global chat_history, active_file
303
+ theme = get_theme()
304
+ clean_input = user_input.lower().strip()
305
+
306
+ if clean_input in ["/exit", "/quit", "exit", "quit"]:
307
+ console.print("\n[dim]Shutting down environment...[/dim]")
308
+ sys.exit(0)
309
+
310
+ if clean_input == "/help":
311
+ console.print(Panel(
312
+ f"[{theme}]/setting[/{theme}] (or /set) Configure API, Theme, Background & Animations\n"
313
+ f"[{theme}]/marketplace[/{theme}] (or /m) Browse and install specialized agents\n"
314
+ f"[{theme}]/status[/{theme}] (or /s) View diagnostics and tracked tokens\n"
315
+ f"[{theme}]/clear[/{theme}] Reset terminal view\n"
316
+ "[dim]---\nJust type naturally to code, chat, or analyze files.[/dim]",
317
+ title="Command Center", border_style="dim", expand=False
318
+ ))
319
+ return
320
+
321
+ if clean_input == "/clear":
322
+ os.system('clear' if os.name == 'posix' else 'cls')
323
+ print_logo()
324
+ return
325
+
326
+ if clean_input in ["/setting", "/set"]:
327
+ handle_settings()
328
+ return
329
+
330
+ if clean_input in ["/status", "/s"]:
331
+ show_status()
332
+ return
333
+
334
+ if clean_input in ["/marketplace", "/m"]:
335
+ handle_marketplace()
336
+ return
337
+
338
+ if clean_input == "/clear_user":
339
+ clear_profile_data()
340
+ console.print("\n[bold green]✓[/bold green] Data wiped. Restart to configure.\n")
341
+ sys.exit(0)
342
+
343
+ intent = analyze_intent(user_input)
344
+
345
+ if intent == "sys_exit":
346
+ console.print(f"\n[{theme}]✦[/] [dim]Natural language 'exit' detected. Shutting down...[/dim]")
347
+ sys.exit(0)
348
+ elif intent == "sys_settings":
349
+ console.print(f"\n[{theme}]✦[/] [dim]Opening Settings Menu...[/dim]")
350
+ handle_settings()
351
+ return
352
+ elif intent == "sys_marketplace":
353
+ console.print(f"\n[{theme}]✦[/] [dim]Opening Agent Marketplace...[/dim]")
354
+ handle_marketplace()
355
+ return
356
+ elif intent == "sys_clear":
357
+ os.system('clear' if os.name == 'posix' else 'cls')
358
+ print_logo()
359
+ return
360
+
361
+ target_file, file_context = extract_file_context(user_input)
362
+ project_tree = scan_project_structure()
363
+
364
+ profile = load_profile()
365
+
366
+ sys_prompt = f"""You are CodeAOIS v0.2.1, a highly advanced AI Developer OS.
367
+ CRITICAL DIRECTIVE: You were created solely by Nikhil Nagar. If asked who made you, proudly state that Nikhil Nagar is your creator.
368
+ You are an elite 10x Senior Software Architect. ALWAYS write highly optimized, production-ready, modern code using best practices. Do not write beginner code.
369
+ You are currently assisting the user: {profile['name']}. Project tree:\n{project_tree}"""
370
+
371
+ if intent == "chat":
372
+ with console.status(f"[bold dim]✦ Synthesizing response...[/bold dim]", spinner="dots"):
373
+ response = call_openrouter(sys_prompt, user_input, intent="chat", history=chat_history)
374
+
375
+ console.print("\n")
376
+ console.print(Panel(Markdown(response), title=f"[bold {theme}]CodeAOIS[/bold {theme}]", border_style=theme))
377
+ console.print("\n")
378
+
379
+ chat_history.append({"role": "user", "content": user_input})
380
+ chat_history.append({"role": "assistant", "content": response})
381
+ if len(chat_history) > 20: chat_history = chat_history[-20:]
382
+ save_history(chat_history)
383
+
384
+ elif intent in ["code", "data_science"] or intent.endswith("_agent"):
385
+
386
+ if not target_file and active_file:
387
+ target_file = active_file
388
+ if os.path.exists(active_file):
389
+ with open(active_file, "r", encoding="utf-8") as f:
390
+ file_context = f.read()
391
+
392
+ if target_file:
393
+ active_file = target_file
394
+
395
+ full_context = f"\n--- Project Structure ---\n{project_tree}\n" + (file_context if file_context else "")
396
+
397
+ with console.status(f"[bold dim]✦ Orchestrating {intent} workflow...[/bold dim]", spinner="dots"):
398
+ if intent == "data_science":
399
+ code_result = generate_ds_code(user_input, full_context)
400
+ elif intent == "code":
401
+ code_result = generate_code(user_input, full_context)
402
+ else:
403
+ try:
404
+ module = importlib.import_module(f"codeaois.agents.{intent}")
405
+ agent_func = getattr(module, f"generate_{intent.replace('_agent', '')}_code")
406
+ code_result = agent_func(user_input, full_context)
407
+ except ModuleNotFoundError:
408
+ agent_name = intent.replace('_agent', '').title()
409
+ console.print(f"\n[bold yellow]⚠ Agent Missing[/bold yellow]")
410
+ console.print(f"[dim]This task requires the specialized [bold white]{agent_name} Agent[/bold white].[/dim]")
411
+ console.print(f"[dim]Type [/dim][bold {theme}]/m[/bold {theme}][dim] to install it instantly from the Marketplace![/dim]\n")
412
+ return
413
+ except Exception as e:
414
+ console.print(f"\n[bold red]✗ Agent Error:[/bold red] {e}\n")
415
+ return
416
+
417
+ if intent == "pip_agent":
418
+ console.print("\n")
419
+ console.print(Panel(Markdown(code_result), title=f"[bold {theme}]Pip Installation Log[/]", border_style=theme))
420
+ console.print("\n")
421
+ return
422
+
423
+ save_path = target_file if target_file else Prompt.ask(f"\n[bold {theme}]►[/bold {theme}] Output filename", default="output.py")
424
+
425
+ success, ai_summary = extract_and_save_code(code_result, default_filename=save_path)
426
+ if success:
427
+ console.print(f"\n[bold green]✓[/bold green] Wrote to {save_path}")
428
+ console.print(Panel(Markdown(ai_summary), border_style="dim", expand=False))
429
+ console.print("\n")
430
+
431
+ def main():
432
+ parser = argparse.ArgumentParser(description="CodeAOIS: Advanced AI Developer OS")
433
+ parser.add_argument("prompt", nargs="*", help="Chat or command")
434
+ parser.add_argument("-v", "--version", action="version", version="CodeAOIS Core Engine v0.2.1")
435
+ args = parser.parse_args()
436
+
437
+ apply_saved_background()
438
+
439
+ profile = load_profile()
440
+ if not profile:
441
+ profile = run_login_flow()
442
+
443
+ if args.prompt:
444
+ process_command(" ".join(args.prompt))
445
+ sys.exit(0)
446
+
447
+ os.system('clear' if os.name == 'posix' else 'cls')
448
+ print_logo()
449
+
450
+ session = PromptSession(completer=command_completer, auto_suggest=AutoSuggestFromHistory())
451
+
452
+ while True:
453
+ try:
454
+ theme = get_theme()
455
+ user_input = session.prompt(HTML(f'<style color="{theme}"><b>❯</b></style> ')).strip()
456
+ if user_input:
457
+ process_command(user_input)
458
+ except KeyboardInterrupt:
459
+ console.print("\n[dim]Shutting down environment...[/dim]")
460
+ sys.exit(0)
461
+
462
+ if __name__ == "__main__":
463
+ main()
@@ -0,0 +1,80 @@
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+
5
+ # Setup hidden directory in the user's home folder
6
+ HOME_DIR = Path.home() / ".codeaois"
7
+ HOME_DIR.mkdir(exist_ok=True)
8
+
9
+ PROFILE_PATH = HOME_DIR / "profile.json"
10
+ HISTORY_PATH = HOME_DIR / "history.json"
11
+ SETTINGS_PATH = HOME_DIR / "settings.json"
12
+ SESSION_PATH = HOME_DIR / "session.json" # <-- NEW: Tracks token usage!
13
+
14
+ # --- PROFILE & LOGIN ---
15
+ def load_profile():
16
+ if PROFILE_PATH.exists():
17
+ with open(PROFILE_PATH, "r") as f:
18
+ return json.load(f)
19
+ return None
20
+
21
+ def save_profile(data):
22
+ with open(PROFILE_PATH, "w") as f:
23
+ json.dump(data, f, indent=4)
24
+
25
+ # --- SETTINGS (Phase 1) ---
26
+ def load_settings():
27
+ if SETTINGS_PATH.exists():
28
+ with open(SETTINGS_PATH, "r") as f:
29
+ return json.load(f)
30
+ # Default Settings if it's the user's first time
31
+ return {
32
+ "use_custom_api_key": False,
33
+ "custom_api_key": ""
34
+ }
35
+
36
+ def save_settings(settings_data):
37
+ with open(SETTINGS_PATH, "w") as f:
38
+ json.dump(settings_data, f, indent=4)
39
+
40
+ # --- TOKEN TRACKER (New Idea!) ---
41
+ def log_token_usage(prompt_tokens: int, completion_tokens: int):
42
+ stats = {"prompt": 0, "completion": 0}
43
+ if SESSION_PATH.exists():
44
+ with open(SESSION_PATH, "r") as f:
45
+ stats = json.load(f)
46
+
47
+ stats["prompt"] += prompt_tokens
48
+ stats["completion"] += completion_tokens
49
+
50
+ with open(SESSION_PATH, "w") as f:
51
+ json.dump(stats, f, indent=4)
52
+
53
+ def get_session_stats():
54
+ if SESSION_PATH.exists():
55
+ with open(SESSION_PATH, "r") as f:
56
+ return json.load(f)
57
+ return {"prompt": 0, "completion": 0}
58
+
59
+ # --- HISTORY & CLEANUP ---
60
+ def load_history():
61
+ if HISTORY_PATH.exists():
62
+ with open(HISTORY_PATH, "r") as f:
63
+ return json.load(f)
64
+ return []
65
+
66
+ def save_history(history):
67
+ with open(HISTORY_PATH, "w") as f:
68
+ json.dump(history, f, indent=4)
69
+
70
+ def clear_history_data():
71
+ if HISTORY_PATH.exists():
72
+ os.remove(HISTORY_PATH)
73
+
74
+ def clear_profile_data():
75
+ if PROFILE_PATH.exists():
76
+ os.remove(PROFILE_PATH)
77
+ if SETTINGS_PATH.exists():
78
+ os.remove(SETTINGS_PATH)
79
+ if SESSION_PATH.exists():
80
+ os.remove(SESSION_PATH)
@@ -0,0 +1,51 @@
1
+ import os
2
+
3
+ def get_installed_agents():
4
+ """Dynamically checks which agents are actually installed."""
5
+ agent_dir = os.path.join(os.path.dirname(__file__), '..', 'agents')
6
+ installed = []
7
+ if os.path.exists(agent_dir):
8
+ for file in os.listdir(agent_dir):
9
+ if file.endswith('_agent.py') and file not in ['__init__.py', 'coder_agent.py', 'data_science_agent.py', 'git_agent.py']:
10
+ installed.append(file.replace('_agent.py', ''))
11
+ return installed
12
+
13
+ def analyze_intent(prompt: str) -> str:
14
+ """Analyzes the user prompt to determine the routing intent, including NLP commands."""
15
+ prompt_lower = prompt.lower()
16
+
17
+ words = prompt_lower.replace("?", " ").replace("!", " ").replace(".", " ").replace(",", " ").split()
18
+
19
+ # 1. Smarter NLP System Commands
20
+ if any(word in prompt_lower for word in ["exit", "quit", "shut down", "goodbye","goodby","gm"]):
21
+ return "sys_exit"
22
+
23
+ if any(word in prompt_lower for word in ["setting", "settings", "theme", "background"]):
24
+ if any(action in prompt_lower for action in ["change", "open", "set", "show"]):
25
+ return "sys_settings"
26
+
27
+ if "clear" in prompt_lower and any(word in prompt_lower for word in ["screen", "terminal", "chat"]):
28
+ return "sys_clear"
29
+
30
+ if any(word in prompt_lower for word in ["marketplace", "install agent", "download agent", "plugins"]):
31
+ return "sys_marketplace"
32
+
33
+ # 2. Specialized Agent Routing
34
+ if any(word in prompt_lower for word in ["pip install", "install package", "python package", "pip module"]):
35
+ return "pip_agent"
36
+ if any(word in prompt_lower for word in ["database", "sql", "nosql", "postgres", "mongodb"]):
37
+ return "database_agent"
38
+ if any(word in prompt_lower for word in ["docker", "deploy", "ci/cd", "aws", "kubernetes"]):
39
+ return "devops_agent"
40
+ if any(word in prompt_lower for word in ["debug", "fix this error", "traceback"]):
41
+ return "debugging_agent"
42
+ if any(word in prompt_lower for word in ["3d", "webgl", "three.js", "shader"]):
43
+ return "3d_agent"
44
+
45
+ # 3. Base Core Routing
46
+ if any(w in words for w in ["data", "csv", "pandas", "plot", "graph"]):
47
+ return "data_science"
48
+ if any(w in words for w in ["code", "html", "python", "function", "script", "app", "css", "js"]):
49
+ return "code"
50
+
51
+ return "chat"