-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
320 lines (284 loc) · 12.1 KB
/
Copy pathmain.py
File metadata and controls
320 lines (284 loc) · 12.1 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
import asyncio
import logging
from pathlib import Path
import sys
import click
if sys.platform == "win32":
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
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(
"AI Agent",
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
def _take_snapshot(self) -> SessionSnapshot:
session = self.agent.session
return SessionSnapshot(
session_id=session.session_id,
created_at=session.created_at,
updated_at=session.updated_at,
turn_count=session.turn_count,
messages=session.context_manager.get_messages(),
total_usage=session.context_manager.total_usage,
)
async def _adopt_snapshot(self, snapshot: SessionSnapshot) -> None:
"""Replace the live session with one rebuilt from a snapshot."""
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:
role = msg.get("role")
# the system prompt is rebuilt by the new session, not replayed
if role == "user":
session.context_manager.add_user_message(msg.get("content", ""))
elif role == "assistant":
session.context_manager.add_assistant_message(
msg.get("content", ""), msg.get("tool_calls")
)
elif 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
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 cmd_name == "/help":
self.tui.show_help()
elif cmd_name == "/clear":
self.agent.session.context_manager.clear()
self.agent.session.loop_detector.clear()
console.print("[success]Conversation cleared [/success]")
elif cmd_name == "/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 ValueError:
console.print(
f"[error]Incorrect approval policy: {cmd_args} [/error]"
)
console.print(
f"Valid options: {', '.join(p.value 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":
PersistenceManager().save_session(self._take_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("[error]Usage: /resume <session_id>[/error]")
else:
snapshot = PersistenceManager().load_session(cmd_args)
if not snapshot:
console.print("[error]Session does not exist[/error]")
else:
await self._adopt_snapshot(snapshot)
console.print(
f"[success]Resumed session: {snapshot.session_id}[/success]"
)
elif cmd_name == "/checkpoint":
checkpoint_id = PersistenceManager().save_checkpoint(self._take_snapshot())
console.print(f"[success]Checkpoint created: {checkpoint_id}[/success]")
elif cmd_name == "/restore":
if not cmd_args:
console.print("[error]Usage: /restore <checkpoint_id>[/error]")
else:
snapshot = PersistenceManager().load_checkpoint(cmd_args)
if not snapshot:
console.print("[error]Checkpoint does not exist[/error]")
else:
await self._adopt_snapshot(snapshot)
console.print(
f"[success]Restored 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)
if config.debug:
logging.basicConfig(
level=logging.DEBUG,
format="%(levelname)s %(name)s: %(message)s",
stream=sys.stderr,
)
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())
if __name__ == "__main__":
main()