-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
347 lines (312 loc) · 14 KB
/
main.py
File metadata and controls
347 lines (312 loc) · 14 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
import asyncio
from pathlib import Path
import sys
import click
from dotenv import load_dotenv
load_dotenv()
from agent.agent import Agent
from agent.events import AgentEventType
from agent.persistence import PersistenceManager, SessionSnapshot
from agent.session import Session
from config.config import ApprovalPolicy, Config
from config.loader import load_config
from ui.tui import TUI, get_console
console = get_console()
class CLI:
def __init__(self, config: Config):
self.agent: Agent | None = None
self.config = config
self.tui = TUI(config, console)
async def run_single(self, message: str) -> str | None:
async with Agent(self.config) as agent:
self.agent = agent
return await self._process_message(message)
async def run_interactive(self) -> str | None:
self.tui.print_welcome(
"CodeCortex AI",
lines=[
f"model: {self.config.model_name}",
f"cwd: {self.config.cwd}",
"commands: /help /config /approval /model /exit",
],
)
async with Agent(
self.config,
confirmation_callback=self.tui.handle_confirmation,
) as agent:
self.agent = agent
while True:
try:
user_input = console.input("\n[user]>[/user] ").strip()
if not user_input:
continue
if user_input.startswith("/"):
should_continue = await self._handle_command(user_input)
if not should_continue:
break
continue
await self._process_message(user_input)
except KeyboardInterrupt:
console.print("\n[dim]Use /exit to quit[/dim]")
except EOFError:
break
console.print("\n[dim]Goodbye![/dim]")
def _get_tool_kind(self, tool_name: str) -> str | None:
tool = self.agent.session.tool_registry.get(tool_name)
if not tool:
return None
return tool.kind.value
async def _process_message(self, message: str) -> str | None:
if not self.agent:
return None
assistant_streaming = False
final_response: str | None = None
async for event in self.agent.run(message):
if event.type == AgentEventType.TEXT_DELTA:
content = event.data.get("content", "")
if not assistant_streaming:
self.tui.begin_assistant()
assistant_streaming = True
self.tui.stream_assistant_delta(content)
elif event.type == AgentEventType.TEXT_COMPLETE:
final_response = event.data.get("content")
if assistant_streaming:
self.tui.end_assistant()
assistant_streaming = False
elif event.type == AgentEventType.AGENT_ERROR:
error = event.data.get("error", "Unknown error")
console.print(f"\n[error]Error: {error}[/error]")
elif event.type == AgentEventType.TOOL_CALL_START:
tool_name = event.data.get("name", "unknown")
tool_kind = self._get_tool_kind(tool_name)
self.tui.tool_call_start(
event.data.get("call_id", ""),
tool_name,
tool_kind,
event.data.get("arguments", {}),
)
elif event.type == AgentEventType.TOOL_CALL_COMPLETE:
tool_name = event.data.get("name", "unknown")
tool_kind = self._get_tool_kind(tool_name)
self.tui.tool_call_complete(
event.data.get("call_id", ""),
tool_name,
tool_kind,
event.data.get("success", False),
event.data.get("output", ""),
event.data.get("error"),
event.data.get("metadata"),
event.data.get("diff"),
event.data.get("truncated", False),
event.data.get("exit_code"),
)
return final_response
async def _handle_command(self, command: str) -> bool:
cmd = command.lower().strip()
parts = cmd.split(maxsplit=1)
cmd_name = parts[0]
cmd_args = parts[1] if len(parts) > 1 else ""
if cmd_name == "/exit" or cmd_name == "/quit":
return False
elif command == "/help":
self.tui.show_help()
elif command == "/clear":
self.agent.session.context_manager.clear()
self.agent.session.loop_detector.clear()
console.print("[success]Conversation cleared [/success]")
elif command == "/config":
console.print("\n[bold]Current Configuration[/bold]")
console.print(f" Model: {self.config.model_name}")
console.print(f" Temperature: {self.config.temperature}")
console.print(f" Approval: {self.config.approval.value}")
console.print(f" Working Dir: {self.config.cwd}")
console.print(f" Max Turns: {self.config.max_turns}")
console.print(f" Hooks Enabled: {self.config.hooks_enabled}")
elif cmd_name == "/model":
if cmd_args:
self.config.model_name = cmd_args
console.print(f"[success]Model changed to: {cmd_args} [/success]")
else:
console.print(f"Current model: {self.config.model_name}")
elif cmd_name == "/approval":
if cmd_args:
try:
approval = ApprovalPolicy(cmd_args)
self.config.approval = approval
console.print(
f"[success]Approval policy changed to: {cmd_args} [/success]"
)
except:
console.print(
f"[error]Incorrect approval policy: {cmd_args} [/error]"
)
console.print(
f"Valid options: {', '.join(p for p in ApprovalPolicy)}"
)
else:
console.print(f"Current approval policy: {self.config.approval.value}")
elif cmd_name == "/stats":
stats = self.agent.session.get_stats()
console.print("\n[bold]Session Statistics [/bold]")
for key, value in stats.items():
console.print(f" {key}: {value}")
elif cmd_name == "/tools":
tools = self.agent.session.tool_registry.get_tools()
console.print(f"\n[bold]Available tools ({len(tools)}) [/bold]")
for tool in tools:
console.print(f" • {tool.name}")
elif cmd_name == "/mcp":
mcp_servers = self.agent.session.mcp_manager.get_all_servers()
console.print(f"\n[bold]MCP Servers ({len(mcp_servers)}) [/bold]")
for server in mcp_servers:
status = server["status"]
status_color = "green" if status == "connected" else "red"
console.print(
f" • {server['name']}: [{status_color}]{status}[/{status_color}] ({server['tools']} tools)"
)
elif cmd_name == "/save":
persistence_manager = PersistenceManager()
session_snapshot = SessionSnapshot(
session_id=self.agent.session.session_id,
created_at=self.agent.session.created_at,
updated_at=self.agent.session.updated_at,
turn_count=self.agent.session.turn_count,
messages=self.agent.session.context_manager.get_messages(),
total_usage=self.agent.session.context_manager.total_usage,
)
persistence_manager.save_session(session_snapshot)
console.print(
f"[success]Session saved: {self.agent.session.session_id}[/success]"
)
elif cmd_name == "/sessions":
persistence_manager = PersistenceManager()
sessions = persistence_manager.list_sessions()
console.print("\n[bold]Saved Sessions[/bold]")
for s in sessions:
console.print(
f" • {s['session_id']} (turns: {s['turn_count']}, updated: {s['updated_at']})"
)
elif cmd_name == "/resume":
if not cmd_args:
console.print(f"[error]Usage: /resume <session_id> [/error]")
else:
persistence_manager = PersistenceManager()
snapshot = persistence_manager.load_session(cmd_args)
if not snapshot:
console.print(f"[error]Session does not exist [/error]")
else:
session = Session(
config=self.config,
)
await session.initialize()
session.session_id = snapshot.session_id
session.created_at = snapshot.created_at
session.updated_at = snapshot.updated_at
session.turn_count = snapshot.turn_count
session.context_manager.total_usage = snapshot.total_usage
for msg in snapshot.messages:
if msg.get("role") == "system":
continue
elif msg["role"] == "user":
session.context_manager.add_user_message(
msg.get("content", "")
)
elif msg["role"] == "assistant":
session.context_manager.add_assistant_message(
msg.get("content", ""), msg.get("tool_calls")
)
elif msg["role"] == "tool":
session.context_manager.add_tool_result(
msg.get("tool_call_id", ""), msg.get("content", "")
)
await self.agent.session.client.close()
await self.agent.session.mcp_manager.shutdown()
self.agent.session = session
console.print(
f"[success]Resumed session: {session.session_id}[/success]"
)
elif cmd_name == "/checkpoint":
persistence_manager = PersistenceManager()
session_snapshot = SessionSnapshot(
session_id=self.agent.session.session_id,
created_at=self.agent.session.created_at,
updated_at=self.agent.session.updated_at,
turn_count=self.agent.session.turn_count,
messages=self.agent.session.context_manager.get_messages(),
total_usage=self.agent.session.context_manager.total_usage,
)
checkpoint_id = persistence_manager.save_checkpoint(session_snapshot)
console.print(f"[success]Checkpoint created: {checkpoint_id}[/success]")
elif cmd_name == "/restore":
if not cmd_args:
console.print(f"[error]Usage: /restore <checkpoint_id> [/error]")
else:
persistence_manager = PersistenceManager()
snapshot = persistence_manager.load_checkpoint(cmd_args)
if not snapshot:
console.print(f"[error]Checkpoint does not exist [/error]")
else:
session = Session(
config=self.config,
)
await session.initialize()
session.session_id = snapshot.session_id
session.created_at = snapshot.created_at
session.updated_at = snapshot.updated_at
session.turn_count = snapshot.turn_count
session.context_manager.total_usage = snapshot.total_usage
for msg in snapshot.messages:
if msg.get("role") == "system":
continue
elif msg["role"] == "user":
session.context_manager.add_user_message(
msg.get("content", "")
)
elif msg["role"] == "assistant":
session.context_manager.add_assistant_message(
msg.get("content", ""), msg.get("tool_calls")
)
elif msg["role"] == "tool":
session.context_manager.add_tool_result(
msg.get("tool_call_id", ""), msg.get("content", "")
)
await self.agent.session.client.close()
await self.agent.session.mcp_manager.shutdown()
self.agent.session = session
console.print(
f"[success]Resumed session: {session.session_id}, checkpoint: {cmd_args}[/success]"
)
else:
console.print(f"[error]Unknown command: {cmd_name}[/error]")
return True
@click.command()
@click.argument("prompt", required=False)
@click.option(
"--cwd",
"-c",
type=click.Path(exists=True, file_okay=False, path_type=Path),
help="Current working directory",
)
def main(
prompt: str | None,
cwd: Path | None,
):
try:
config = load_config(cwd=cwd)
except Exception as e:
console.print(f"[error]Configuration Error: {e}[/error]")
sys.exit(1)
errors = config.validate()
if errors:
for error in errors:
console.print(f"[error]{error}[/error]")
sys.exit(1)
cli = CLI(config)
# messages = [{"role": "user", "content": prompt}]
if prompt:
result = asyncio.run(cli.run_single(prompt))
if result is None:
sys.exit(1)
else:
asyncio.run(cli.run_interactive())
main()