-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathroutes.py
431 lines (363 loc) Β· 17.9 KB
/
routes.py
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
import sys
import logging
import asyncio
from dotenv import load_dotenv
import os
from managers.gui_manager import GUIManager
# Load environment variables
load_dotenv()
# Get default model from environment or fallback
DEFAULT_MODEL = os.getenv('DEFAULT_MODEL', 'gpt-4o-mini')
from managers.agents_manager import AgentsManager
from managers.objective_manager import ObjectiveManager
from managers.aider_manager import AiderManager
from managers.agent_runner import AgentRunner
from utils.logger import Logger
def main():
if len(sys.argv) < 2:
print("Usage: kin <command> [options]")
sys.exit(1)
# Get model from command line args
model = DEFAULT_MODEL # Set default value
if "--model" in sys.argv:
try:
model_index = sys.argv.index("--model") + 1
model = sys.argv[model_index]
except (ValueError, IndexError):
print(f"Invalid value for --model. Using default ({DEFAULT_MODEL})")
command = sys.argv[1]
# Route commands to appropriate managers
if command == "generate":
if len(sys.argv) < 3:
print("Usage: kin generate <agents|objective|map|viz> [options]")
sys.exit(1)
subcommand = sys.argv[2]
if subcommand == "map":
manager = AiderManager()
manager.logger.logger.setLevel(logging.DEBUG) # Set log level to DEBUG
manager.run_map_maintenance_for_all_folders()
elif subcommand == "agents":
manager = AgentsManager(model=model)
# Optional mission file path
mission_path = sys.argv[3] if len(sys.argv) > 3 else ".aider.mission.md"
asyncio.run(manager.generate_agents(mission_path))
elif subcommand == "viz":
from managers.vision_manager import VisionManager
manager = VisionManager()
asyncio.run(manager.generate_visualization())
manager = ObjectiveManager()
# Parse arguments
if len(sys.argv) < 4 or sys.argv[3] != "--agent":
print("Usage: kin generate objective --agent <agent_name>")
sys.exit(1)
if len(sys.argv) < 5:
print("Usage: kin generate objective --agent <agent_name>")
sys.exit(1)
agent_name = sys.argv[4]
agent_path = f".aider.agent.{agent_name}.md"
mission_path = ".aider.mission.md"
manager.generate_objective(mission_path, agent_path)
elif command == "run":
if len(sys.argv) < 3:
print("Usage: kin run <agents|aider|map|gui> [options]")
print("Options:")
print(" --generate Generate agents if missing")
print(" --verbose Show detailed debug information")
print(" --mission Specify mission file path")
print(" --model Specify model to use (default: gpt-4o-mini)")
sys.exit(1)
subcommand = sys.argv[2]
if subcommand == "agents":
# Create and initialize runner asynchronously
async def init_and_run_agents():
# Get model name from outer scope
nonlocal model
run_model = model # Use the model from command line
if "--model" in sys.argv:
try:
model_index = sys.argv.index("--model") + 1
run_model = sys.argv[model_index]
except (ValueError, IndexError):
print("Invalid value for --model. Using default (gpt-4o-mini)")
# Use the factory method to create and initialize the runner
runner = await AgentRunner.create(model=run_model)
# Set global log level based on verbose flag
if "--verbose" in sys.argv:
Logger.set_global_level(logging.DEBUG)
else:
Logger.set_global_level(logging.SUCCESS)
# Get mission file path
mission_path = ".aider.mission.md" # default
if "--mission" in sys.argv:
try:
mission_index = sys.argv.index("--mission") + 1
if mission_index < len(sys.argv):
mission_path = sys.argv[mission_index]
except (ValueError, IndexError):
print("Missing value for --mission flag")
sys.exit(1)
# Get agent count
agent_count = 5 # Default value
if "--count" in sys.argv:
try:
count_index = sys.argv.index("--count") + 1
agent_count = int(sys.argv[count_index])
except (ValueError, IndexError):
print("Invalid value for --count. Using default (5)")
# Get model name
model = None # Will use default from command line
if "--model" in sys.argv:
try:
model_index = sys.argv.index("--model") + 1
model = sys.argv[model_index]
except (ValueError, IndexError):
print("Invalid value for --model. Using default model")
# Check for --generate flag
should_generate = "--generate" in sys.argv
# Display startup message
runner.logger.success("π Starting KinOS...")
# Run with the initialized runner
await runner.run(
mission_path,
generate_agents=should_generate,
agent_count=agent_count,
model=model
)
# Run the async initialization and execution
asyncio.run(init_and_run_agents())
elif subcommand == "gui":
# Create and initialize GUI manager
async def init_and_run_gui():
try:
# First check if PyQt6 is installed
try:
from PyQt6.QtWidgets import QApplication
from PyQt6.QtCore import Qt
except ImportError:
Logger(model=model).error("PyQt6 not installed. Please run: pip install PyQt6 qasync pillow")
return
# Create and start GUI manager
manager = GUIManager(model=model)
Logger(model=model).info("Starting GUI manager...")
# Run the GUI and wait for it to complete
try:
await manager.start_gui()
except KeyboardInterrupt:
Logger(model=model).info("GUI stopped by user")
except Exception as e:
Logger(model=model).error(f"GUI failed: {str(e)}")
raise
finally:
# Ensure cleanup happens
manager.cleanup()
except Exception as e:
Logger(model=model).error(f"GUI initialization failed: {str(e)}")
import traceback
Logger(model=model).error(f"Traceback:\n{traceback.format_exc()}")
raise
# Run with proper asyncio handling
try:
if os.name == 'nt': # Windows
# Use ProactorEventLoop on Windows
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
loop = asyncio.get_event_loop()
loop.run_until_complete(init_and_run_gui())
except KeyboardInterrupt:
Logger(model=model).info("GUI stopped by user")
except Exception as e:
Logger(model=model).error(f"GUI failed to start: {str(e)}")
raise
elif subcommand == "aider":
manager = AiderManager()
# Parse arguments
if len(sys.argv) < 4 or sys.argv[3] != "--agent":
print("Usage: kin run aider --agent <agent_name>")
sys.exit(1)
if len(sys.argv) < 5:
print("Usage: kin run aider --agent <agent_name>")
sys.exit(1)
agent_name = sys.argv[4]
# Use default paths based on agent name
agent_path = f".aider.agent.{agent_name}.md"
objective_path = f".aider.objective.{agent_name}.md" # Default objective path
map_path = f".aider.map.{agent_name}.md" # Default map path
manager.run_aider(
objective_filepath=objective_path,
agent_filepath=agent_path
)
elif command == "interactive":
from managers.interactive_manager import InteractiveManager
manager = InteractiveManager(model=model)
asyncio.run(manager.start_session())
elif command == "redundancy":
if len(sys.argv) < 3:
print("Usage: kin redundancy <analyze|add|report|delete|reset> [options]")
print("\nCommands:")
print(" analyze Analyze files for redundancy")
print(" add Add files to redundancy database")
print(" report Generate redundancy report")
print(" reset Clear all data from redundancy database")
print("\nOptions:")
print(" --file Specify single file")
print(" --threshold Set similarity threshold (0.0-1.0)")
print(" --output Specify output file for report")
sys.exit(1)
from managers.redundancy_manager import RedundancyManager
manager = RedundancyManager(model=model)
subcommand = sys.argv[2]
if subcommand == "analyze":
# Parse options
file_path = None
threshold = 0.85
if "--file" in sys.argv:
try:
file_index = sys.argv.index("--file") + 1
file_path = sys.argv[file_index]
except IndexError:
print("Missing value for --file")
sys.exit(1)
if "--threshold" in sys.argv:
try:
threshold_index = sys.argv.index("--threshold") + 1
threshold = float(sys.argv[threshold_index])
except (IndexError, ValueError):
print("Invalid value for --threshold")
sys.exit(1)
# Set log level to INFO to see more details
manager.logger.logger.setLevel(logging.INFO)
# Perform analysis
if file_path:
manager.logger.info(f"π Analyzing single file: {file_path}")
results = manager.analyze_file(file_path, threshold)
manager.logger.info(f"β¨ Analysis complete for {file_path}")
else:
manager.logger.info("π Starting full project analysis...")
results = manager.analyze_all_files(threshold)
manager.logger.info(f"β¨ Project analysis complete")
# Generate and save report
manager.logger.info("π Generating redundancy report...")
report = manager.generate_redundancy_report(results)
output_file = "redundancy_report.md"
if "--output" in sys.argv:
try:
output_index = sys.argv.index("--output") + 1
output_file = sys.argv[output_index]
except IndexError:
print("Missing value for --output")
sys.exit(1)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(report)
# Show summary
stats = results.get('statistics', {})
manager.logger.success(
f"\nπ Analysis Summary:\n"
f" - Files analyzed: {stats.get('files_analyzed', 0)}\n"
f" - Total paragraphs: {stats.get('total_paragraphs', 0)}\n"
f" - Redundant paragraphs: {stats.get('redundant_paragraphs', 0)}\n"
f" - Redundancy clusters: {stats.get('cluster_count', 0)}"
)
manager.logger.success(f"\nπ Report saved to: {output_file}")
elif subcommand == "add":
# Parse file option
file_path = None
if "--file" in sys.argv:
try:
file_index = sys.argv.index("--file") + 1
file_path = sys.argv[file_index]
except IndexError:
print("Missing value for --file")
sys.exit(1)
# Set log level to INFO to see more details
manager.logger.logger.setLevel(logging.INFO)
# Add content
if file_path:
manager.add_file(file_path)
else:
stats = manager.add_all_files()
manager.logger.success(
f"β¨ Added {stats['total_paragraphs']} paragraphs from {stats['total_files']} files"
)
if stats['errors']:
manager.logger.warning("\nβ οΈ Errors encountered:")
for error in stats['errors']:
manager.logger.warning(f" - {error['file']}: {error['error']}")
elif subcommand == "report":
# Generate report from existing database
results = manager.analyze_all_files()
report = manager.generate_redundancy_report(results)
output_file = "redundancy_report.md"
if "--output" in sys.argv:
try:
output_index = sys.argv.index("--output") + 1
output_file = sys.argv[output_index]
except IndexError:
print("Missing value for --output")
sys.exit(1)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(report)
print(f"Report generated and saved to {output_file}")
elif subcommand == "delete":
# Parse options
auto_mode = "--auto" in sys.argv
dry_run = "--dry-run" in sys.argv
interactive = "--interactive" in sys.argv
threshold = 0.95 # Default threshold for auto mode
if "--threshold" in sys.argv:
try:
threshold_index = sys.argv.index("--threshold") + 1
threshold = float(sys.argv[threshold_index])
except (IndexError, ValueError):
print("Invalid value for --threshold")
sys.exit(1)
# Set strategy for which version to keep
keep_strategy = "longest" # Default strategy
if "--keep-first" in sys.argv:
keep_strategy = "first"
# Set verbose logging if requested
if "--verbose" in sys.argv:
manager.logger.logger.setLevel(logging.DEBUG)
print("π Verbose logging enabled")
# Perform deletion
if not any([auto_mode, interactive]):
print("Please specify either --auto or --interactive mode")
print("\nOptions:")
print(" --auto Automatically delete duplicates")
print(" --interactive Review and select which duplicates to delete")
print(" --threshold Set similarity threshold (default: 0.95)")
print(" --keep-longest Keep longest version (default)")
print(" --keep-first Keep first occurrence")
print(" --dry-run Show what would be deleted without making changes")
print(" --verbose Show detailed debug information")
sys.exit(1)
results = manager.delete_duplicates(
auto_mode=auto_mode,
interactive=interactive,
threshold=threshold,
keep_strategy=keep_strategy,
dry_run=dry_run
)
# Show results
if dry_run:
print("\nDry run - no changes made")
print(f"\nResults:")
print(f"- Files modified: {results['files_modified']}")
print(f"- Duplicates removed: {results['duplicates_removed']}")
if results['errors']:
print("\nErrors encountered:")
for error in results['errors']:
print(f"- {error}")
elif subcommand == "reset":
# Reset the redundancy database
manager = RedundancyManager(model=model)
manager._reset_collection()
print("β¨ Redundancy database has been reset")
else:
print(f"Unknown redundancy command: {subcommand}")
sys.exit(1)
else:
print(f"Unknown command: {command}")
sys.exit(1)
if __name__ == "__main__":
main()