Codez-Agent 0.2.1__tar.gz → 0.2.5__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: Codez-Agent
3
- Version: 0.2.1
3
+ Version: 0.2.5
4
4
  Summary: Un assistente AI per il terminale con accesso ai comandi
5
5
  Home-page: https://github.com/tuonome/codez
6
6
  Author: Mattia Ristori
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: Codez-Agent
3
- Version: 0.2.1
3
+ Version: 0.2.5
4
4
  Summary: Un assistente AI per il terminale con accesso ai comandi
5
5
  Home-page: https://github.com/tuonome/codez
6
6
  Author: Mattia Ristori
@@ -0,0 +1,204 @@
1
+ import os
2
+ import requests
3
+ import subprocess
4
+ import json
5
+ import psutil
6
+ import datetime
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+ from rich.prompt import Prompt
10
+
11
+ # --- CONFIGURAZIONE GLOBALE ---
12
+ VERSIONE_ATTUALE = "0.2.7"
13
+ console = Console()
14
+
15
+ def logo():
16
+ """Pulisce lo schermo e stampa il logo ASCII di Codez."""
17
+ os.system('cls' if os.name == 'nt' else 'clear')
18
+ ascii_art = r"""
19
+ [bold cyan]
20
+ /$$$$$$ /$$
21
+ /$$__ $$ | $$
22
+ | $$ \__/ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$$$
23
+ | $$ /$$__ $$ /$$__ $$ /$$__ $$|____ /$$/
24
+ | $$ | $$ \ $$| $$ | $$| $$$$$$$$ /$$$$/
25
+ | $$ $$| $$ \ $$| $$ | $$| $$_____/ /$$__/
26
+ | $$$$$$/| $$$$$$/| $$$$$$$| $$$$$$$ /$$$$$$$$
27
+ \______/ \______/ \_______/ \_______/|________/
28
+ [/bold cyan]
29
+ """
30
+ console.print(Panel(ascii_art, border_style="cyan", title=f"CODEZ AGENT v{VERSIONE_ATTUALE}"))
31
+
32
+ def check_updates():
33
+ """Controlla se esiste una nuova versione su PyPI (Accessibilità)."""
34
+ try:
35
+ # Interroga l'API di PyPI per il tuo pacchetto
36
+ response = requests.get("https://pypi.org/pypi/Codez-Agent/json", timeout=1.5)
37
+ ultima_v = response.json()["info"]["version"]
38
+ if ultima_v != VERSIONE_ATTUALE:
39
+ console.print(Panel(f"🚀 [bold yellow]Nuova versione disponibile: {ultima_v}[/bold yellow]\n"
40
+ f"Stai usando la {VERSIONE_ATTUALE}.\n"
41
+ f"Aggiorna con: [cyan]pip install --upgrade Codez-Agent[/cyan]",
42
+ title="Update Check", border_style="yellow"))
43
+ else:
44
+ log_msg("INFO", "Il software è aggiornato.")
45
+ except:
46
+ pass # Se offline o pacchetto non trovato, proseguiamo
47
+
48
+ def log_msg(tipo, messaggio):
49
+ """Stampa messaggi con tag colorati per migliorare la leggibilità."""
50
+ colori = {
51
+ "INFO": "[bold blue][INFO][/bold blue]",
52
+ "SUCCESS": "[bold green][SUCCESS][/bold green]",
53
+ "WARNING": "[bold yellow][WARNING][/bold yellow]",
54
+ "ERROR": "[bold red][ERROR][/bold red]"
55
+ }
56
+ tag = colori.get(tipo, "[INFO]")
57
+ console.print(f"{tag} {messaggio}")
58
+
59
+ def scrivi_log_md(comando, esito):
60
+ """Salva la cronologia in formato Markdown (Open Source & Educativo)."""
61
+ orario = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
62
+ file_log = "CODEZ_HISTORY.md"
63
+
64
+ # Puliamo l'esito PRIMA di metterlo nella f-string per evitare l'errore del backslash
65
+ esito_pulito = esito[:200].strip().replace('\n', ' ')
66
+
67
+ # Crea intestazione se il file è nuovo
68
+ if not os.path.exists(file_log):
69
+ with open(file_log, "w", encoding="utf-8") as f:
70
+ f.write("# 📜 Diario di Bordo Codez Agent\n\n")
71
+ f.write("In questo file trovi tutti i comandi che hai imparato a usare.\n\n")
72
+
73
+ with open(file_log, "a", encoding="utf-8") as f:
74
+ f.write(f"### 🕒 Sessione: {orario}\n")
75
+ f.write(f"**💻 Comando Terminale:**\n```bash\n{comando}\n```\n")
76
+ f.write(f"**📝 Risultato (estratto):**\n> {esito_pulito}...\n\n")
77
+ f.write("---\n")
78
+
79
+ def system_doctor():
80
+ """Monitora le risorse hardware (Principio Budget 0)."""
81
+ cpu = psutil.cpu_percent(interval=0.5)
82
+ ram = psutil.virtual_memory().percent
83
+
84
+ status = "[bold green]OTTIMO[/bold green]" if ram < 75 else "[bold red]CRITICO[/bold red]"
85
+ color = "green" if ram < 75 else "red"
86
+
87
+ panel_content = f"💻 CPU: {cpu}% | 🧠 RAM: {ram}% | Stato: {status}"
88
+ console.print(Panel(panel_content, title="🏥 System Doctor", border_style=color))
89
+
90
+ def configura_sessione():
91
+ """Configura il provider e scansiona i modelli disponibili."""
92
+ console.print("\n[italic]Inserisci 'ollama' per locale o la tua API Key per il cloud[/italic]")
93
+ key = input("Chiave: ").strip()
94
+
95
+ if key.lower() == "ollama":
96
+ prov, url = "Ollama", "http://localhost:11434/v1"
97
+ try:
98
+ r = requests.get("http://localhost:11434/api/tags", timeout=2)
99
+ modelli = [m['name'] for m in r.json()['models']]
100
+ except:
101
+ log_msg("WARNING", "Ollama non risponde. Uso modelli predefiniti.")
102
+ modelli = ["llama3", "phi3", "mistral"]
103
+ else:
104
+ prov, url = "Cloud AI", "https://api.groq.com/openai/v1" if key.startswith("gsk_") else "https://api.openai.com/v1"
105
+ modelli = ["gpt-4o", "llama3-70b-8192", "mixtral-8x7b-32768"]
106
+
107
+ console.print("\n[bold yellow]Modelli Rilevati:[/bold yellow]")
108
+ for i, m in enumerate(modelli):
109
+ console.print(f"{i+1}. {m}")
110
+
111
+ scelta = int(Prompt.ask("\nQuale modello vuoi usare?", default="1")) - 1
112
+ return key, prov, url, modelli[scelta]
113
+
114
+ def esegui_comando(comando):
115
+ """Esegue il comando, gestisce gli errori e salva il log Markdown."""
116
+ console.print(f"\n[bold orange3]PROPOSTA COMANDO:[/bold orange3] [white on blue] {comando} [/white on blue]")
117
+
118
+ if Prompt.ask("Vuoi eseguire?", choices=["y", "n"], default="y") == "y":
119
+ try:
120
+ res = subprocess.run(comando, shell=True, capture_output=True, text=True)
121
+
122
+ if res.returncode == 0:
123
+ log_msg("SUCCESS", "Eseguito correttamente.")
124
+ scrivi_log_md(comando, res.stdout)
125
+ return f"OUTPUT:\n{res.stdout}"
126
+ else:
127
+ log_msg("ERROR", f"Il terminale ha risposto: {res.stderr}")
128
+ # Logghiamo anche l'errore per studiarlo
129
+ scrivi_log_md(comando, f"ERRORE: {res.stderr}")
130
+ return f"ERRORE:\n{res.stderr}"
131
+ except Exception as e:
132
+ log_msg("ERROR", f"Errore di sistema: {e}")
133
+ return str(e)
134
+
135
+ return "Esecuzione annullata."
136
+
137
+ def main():
138
+ logo()
139
+ check_updates() # Controlla PyPI all'avvio
140
+
141
+ key, prov, url, mod = configura_sessione()
142
+ log_msg("SUCCESS", f"Codez è attivo! Modello: {mod}")
143
+ console.print("[dim]Comandi speciali: /status | /history | /explain | /stop[/dim]\n")
144
+
145
+ ultimo_comando_generato = ""
146
+
147
+ while True:
148
+ user_input = input(f"({mod}) > ").strip()
149
+
150
+ if not user_input: continue
151
+ if user_input == "/stop": break
152
+
153
+ if user_input == "/status":
154
+ system_doctor()
155
+ continue
156
+
157
+ if user_input == "/history":
158
+ log_msg("INFO", "Apro il diario Markdown...")
159
+ os.system('notepad CODEZ_HISTORY.md' if os.name == 'nt' else 'open CODEZ_HISTORY.md')
160
+ continue
161
+
162
+ if user_input == "/explain":
163
+ if not ultimo_comando_generato:
164
+ log_msg("WARNING", "Non ci sono ancora comandi da spiegare.")
165
+ continue
166
+ user_input = f"Spiegami come a un principiante cosa fa questo comando: {ultimo_comando_generato}"
167
+ log_msg("INFO", "Generazione spiegazione...")
168
+
169
+ # --- LOGICA INTELLIGENZA ARTIFICIALE ---
170
+ prompt_sistema = (
171
+ "Sei Codez, un assistente terminale open-source. "
172
+ "Se devi suggerire un'azione, usa sempre il prefisso 'COMMAND: ' seguito dal codice. "
173
+ "Se l'utente chiede spiegazioni, sii semplice e accessibile. "
174
+ "Usa un tono amichevole ma professionale."
175
+ )
176
+
177
+ payload = {
178
+ "model": mod,
179
+ "messages": [
180
+ {"role": "system", "content": prompt_sistema},
181
+ {"role": "user", "content": user_input}
182
+ ]
183
+ }
184
+
185
+ try:
186
+ headers = {"Authorization": f"Bearer {key}"} if key.lower() != "ollama" else {}
187
+ r = requests.post(f"{url}/chat/completions", headers=headers, json=payload)
188
+ r.raise_for_status()
189
+ risposta = r.json()['choices'][0]['message']['content']
190
+
191
+ if "COMMAND: " in risposta:
192
+ # Estraiamo il comando pulito
193
+ cmd = risposta.split("COMMAND: ")[1].strip().replace('`', '')
194
+ ultimo_comando_generato = cmd
195
+ esito = esegui_comando(cmd)
196
+ console.print(f"[dim]{esito}[/dim]")
197
+ else:
198
+ console.print(f"\n[cyan]AI:[/cyan] {risposta}\n")
199
+
200
+ except Exception as e:
201
+ log_msg("ERROR", f"Impossibile connettersi all'IA: {e}")
202
+
203
+ if __name__ == "__main__":
204
+ main()
@@ -3,7 +3,7 @@ from setuptools import setup
3
3
 
4
4
  setup(
5
5
  name='Codez-Agent', # Prova a usare un nome unico come questo
6
- version='0.2.1',
6
+ version='0.2.5',
7
7
  description='Un assistente AI per il terminale con accesso ai comandi',
8
8
  long_description=open('README.md').read(),
9
9
  long_description_content_type='text/markdown',
@@ -1,157 +0,0 @@
1
- import os
2
- import requests
3
- import subprocess
4
- import json
5
- import psutil
6
- import datetime
7
- from rich.console import Console
8
- from rich.panel import Panel
9
- from rich.prompt import Prompt
10
-
11
- # Inizializzazione della console
12
- console = Console()
13
-
14
- def logo():
15
- """Pulisce lo schermo e stampa il logo ASCII."""
16
- os.system('cls' if os.name == 'nt' else 'clear')
17
- ascii_art = r"""
18
- [bold cyan]
19
- /$$$$$$ /$$
20
- /$$__ $$ | $$
21
- | $$ \__/ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$$$
22
- | $$ /$$__ $$ /$$__ $$ /$$__ $$|____ /$$/
23
- | $$ | $$ \ $$| $$ | $$| $$$$$$$$ /$$$$/
24
- | $$ $$| $$ \ $$| $$ | $$| $$_____/ /$$__/
25
- | $$$$$$/| $$$$$$/| $$$$$$$| $$$$$$$ /$$$$$$$$
26
- \______/ \______/ \_______/ \_______/|________/
27
- [/bold cyan]
28
- """
29
- console.print(Panel(ascii_art, border_style="cyan", title="CODEZ AGENT v2.1 - Open Source & Accessible"))
30
-
31
- def scrivi_log(comando, esito):
32
- """Salva i comandi riusciti in un file di testo locale (Principio: Educativo)."""
33
- orario = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
34
- with open("codez_history.txt", "a", encoding="utf-8") as f:
35
- f.write(f"[{orario}] COMANDO: {comando}\n")
36
- f.write(f"ESITO: {esito[:150]}...\n")
37
- f.write("-" * 40 + "\n")
38
-
39
- def system_doctor():
40
- """Monitora le risorse del sistema (Principio: Budget 0)."""
41
- cpu = psutil.cpu_percent(interval=0.5)
42
- ram = psutil.virtual_memory().percent
43
- status = "[bold green]OK[/bold green]" if ram < 80 else "[bold red]FULL[/bold red]"
44
- info = f"💻 CPU: {cpu}% | 🧠 RAM: {ram}% | 📊 Stato: {status}"
45
- console.print(Panel(info, title="🏥 System Doctor", border_style="blue"))
46
-
47
- def configura_sessione():
48
- """Scansione automatica modelli (Principio: Accessibilità)."""
49
- console.print("\n[italic]Digita 'ollama' o incolla la tua API Key[/italic]")
50
- key = input("Chiave: ").strip()
51
-
52
- if key.lower() == "ollama":
53
- prov, url = "Ollama", "http://localhost:11434/v1"
54
- try:
55
- r = requests.get("http://localhost:11434/api/tags", timeout=2)
56
- modelli = [m['name'] for m in r.json()['models']]
57
- except:
58
- modelli = ["llama3", "phi3", "mistral"]
59
- else:
60
- prov, url = "Cloud AI", "https://api.groq.com/openai/v1" if key.startswith("gsk_") else "https://api.openai.com/v1"
61
- modelli = ["gpt-4o", "llama3-70b-8192", "mixtral-8x7b-32768"]
62
-
63
- console.print("\n[bold yellow]Modelli Rilevati:[/bold yellow]")
64
- for i, m in enumerate(modelli):
65
- console.print(f"{i+1}. {m}")
66
-
67
- scelta = int(Prompt.ask("\nScegli numero", default="1")) - 1
68
- return key, prov, url, modelli[scelta]
69
-
70
- def esegui_comando(comando):
71
- """Esegue comandi, salva i log e rileva errori di installazione."""
72
- console.print(f"\n[bold orange3]PROPOSTA:[/bold orange3] [white on blue] {comando} [/white on blue]")
73
-
74
- if Prompt.ask("Eseguire?", choices=["y", "n"], default="y") == "y":
75
- res = subprocess.run(comando, shell=True, capture_output=True, text=True)
76
-
77
- # Se il comando ha successo
78
- if res.returncode == 0:
79
- console.print("[bold green]Successo![/bold green]")
80
- scrivi_log(comando, res.stdout)
81
- return f"Output: {res.stdout}"
82
-
83
- # Se il comando fallisce (Auto-Installer Logic)
84
- else:
85
- errore = res.stderr.lower()
86
- if "not found" in errore or "non è riconosciuto" in errore:
87
- console.print(f"[bold red]ERRORE:[/bold red] Sembra che lo strumento per '{comando.split()[0]}' non sia installato.")
88
- console.print("[yellow]Suggerimento: Prova a chiedere a Codez come installarlo![/yellow]")
89
- return f"Errore: {res.stderr}"
90
-
91
- return "Annullato dall'utente."
92
-
93
- def main():
94
- logo()
95
- key, prov, url, mod = configura_sessione()
96
-
97
- console.print(f"\n[bold green]Codez v2.1 Pronta! ({mod})[/bold green]")
98
- console.print("[dim]/status | /explain | /history (apre i log) | /stop[/dim]\n")
99
-
100
- ultimo_comando_proposto = ""
101
-
102
- while True:
103
- user_input = input(f"({mod}) > ").strip()
104
-
105
- if not user_input: continue
106
- if user_input == "/stop": break
107
-
108
- if user_input == "/status":
109
- system_doctor()
110
- continue
111
-
112
- if user_input == "/history":
113
- if os.path.exists("codez_history.txt"):
114
- os.system('notepad codez_history.txt' if os.name == 'nt' else 'open codez_history.txt')
115
- else:
116
- console.print("[yellow]Nessuna cronologia trovata.[/yellow]")
117
- continue
118
-
119
- if user_input == "/explain":
120
- if not ultimo_comando_proposto:
121
- console.print("[yellow]Nessun comando da spiegare![/yellow]")
122
- continue
123
- user_input = f"Spiegami come a un principiante cosa fa: {ultimo_comando_proposto}"
124
-
125
- # Richiesta all'IA
126
- prompt_sistema = (
127
- "Sei Codez, un assistente terminale per neofiti. "
128
- "Se devi agire sul PC rispondi SOLO con 'COMMAND: ' seguito dal comando. "
129
- "Se l'utente ha avuto un errore, suggerisci come installare i pacchetti mancanti (es. pip, brew, apt)."
130
- )
131
-
132
- payload = {
133
- "model": mod,
134
- "messages": [
135
- {"role": "system", "content": prompt_sistema},
136
- {"role": "user", "content": user_input}
137
- ]
138
- }
139
-
140
- try:
141
- h = {"Authorization": f"Bearer {key}"} if key.lower() != "ollama" else {}
142
- r = requests.post(f"{url}/chat/completions", headers=h, json=payload)
143
- risposta = r.json()['choices'][0]['message']['content']
144
-
145
- if "COMMAND: " in risposta:
146
- cmd = risposta.split("COMMAND: ")[1].strip().replace('`', '')
147
- ultimo_comando_proposto = cmd
148
- esito = esegui_comando(cmd)
149
- console.print(f"[dim]{esito}[/dim]")
150
- else:
151
- console.print(f"\n[bold cyan]AI:[/bold cyan] {risposta}\n")
152
-
153
- except Exception as e:
154
- console.print(f"[red]Errore critico: {e}[/red]")
155
-
156
- if __name__ == "__main__":
157
- main()
File without changes
File without changes
File without changes