-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcli.py
More file actions
731 lines (641 loc) · 24.2 KB
/
cli.py
File metadata and controls
731 lines (641 loc) · 24.2 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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
# SPDX-License-Identifier: MIT
"""Command Line Interface for Trae Agent."""
import asyncio
import os
import shutil
import subprocess
import sys
import traceback
from pathlib import Path
import click
from dotenv import load_dotenv
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from trae_agent.agent import Agent
from trae_agent.utils.cli import CLIConsole, ConsoleFactory, ConsoleMode, ConsoleType
from trae_agent.utils.config import Config, TraeAgentConfig
# Load environment variables
_ = load_dotenv()
console = Console()
def resolve_config_file(config_file: str) -> str:
"""
Resolve config file with backward compatibility.
First tries the specified file, then falls back to JSON if YAML doesn't exist.
"""
if config_file.endswith(".yaml") or config_file.endswith(".yml"):
yaml_path = Path(config_file)
json_path = Path(config_file.replace(".yaml", ".json").replace(".yml", ".json"))
if yaml_path.exists():
return str(yaml_path)
elif json_path.exists():
console.print(f"[yellow]YAML config not found, using JSON config: {json_path}[/yellow]", markup=False)
return str(json_path)
else:
console.print(
"[red]Error: Config file not found. Please specify a valid config file in the command line option --config-file[/red]"
)
sys.exit(1)
else:
return config_file
def check_docker(timeout=3):
# 1) Check whether the docker CLI is installed
if shutil.which("docker") is None:
return {
"cli": False,
"daemon": False,
"version": None,
"error": "docker CLI not found",
}
# 2) Check whether the Docker daemon is reachable (this makes a real request)
try:
cp = subprocess.run(
["docker", "version", "--format", "{{.Server.Version}}"],
capture_output=True,
text=True,
timeout=timeout,
)
if cp.returncode == 0 and cp.stdout.strip():
return {
"cli": True,
"daemon": True,
"version": cp.stdout.strip(),
"error": None,
}
else:
# The daemon may not be running or permissions may be insufficient
return {
"cli": True,
"daemon": False,
"version": None,
"error": (cp.stderr or cp.stdout).strip(),
}
except Exception as e:
return {"cli": True, "daemon": False, "version": None, "error": str(e)}
def build_with_pyinstaller():
os.system("rm -rf trae_agent/dist")
print("--- Building edit_tool ---")
subprocess.run(
[
"pyinstaller",
"--name",
"edit_tool",
"trae_agent/tools/edit_tool_cli.py",
],
check=True,
)
print("\n--- Building json_edit_tool ---")
subprocess.run(
[
"pyinstaller",
"--name",
"json_edit_tool",
"--hidden-import=jsonpath_ng",
"trae_agent/tools/json_edit_tool_cli.py",
],
check=True,
)
os.system("mkdir trae_agent/dist")
os.system("cp dist/edit_tool/edit_tool trae_agent/dist")
os.system("cp -r dist/json_edit_tool/_internal trae_agent/dist")
os.system("cp dist/json_edit_tool/json_edit_tool trae_agent/dist")
os.system("rm -rf dist")
@click.group()
@click.version_option(version="0.1.0")
def cli():
"""Trae Agent - LLM-based agent for software engineering tasks."""
pass
@cli.command()
@click.argument("task", required=False)
@click.option("--file", "-f", "file_path", help="Path to a file containing the task description.")
@click.option("--provider", "-p", help="LLM provider to use")
@click.option("--model", "-m", help="Specific model to use")
@click.option("--model-base-url", help="Base URL for the model API")
@click.option("--api-key", "-k", help="API key (or set via environment variable)")
@click.option("--max-steps", help="Maximum number of execution steps", type=int)
@click.option("--working-dir", "-w", help="Working directory for the agent")
@click.option("--must-patch", "-mp", is_flag=True, help="Whether to patch the code")
@click.option(
"--config-file",
help="Path to configuration file",
default="trae_config.yaml",
envvar="TRAE_CONFIG_FILE",
)
@click.option("--trajectory-file", "-t", help="Path to save trajectory file")
@click.option("--patch-path", "-pp", help="Path to patch file")
# --- Docker Mode Start ---
@click.option(
"--docker-image",
type=str,
default=None,
help="Specify a Docker image to run the task in a new container",
)
@click.option(
"--docker-container-id",
type=str,
default=None,
help="Attach to an existing Docker container by ID",
)
@click.option(
"--dockerfile-path",
type=click.Path(exists=True, dir_okay=False, resolve_path=True),
default=None,
help="Absolute path to a Dockerfile to build an environment",
)
@click.option(
"--docker-image-file",
type=click.Path(exists=True, dir_okay=False, resolve_path=True),
default=None,
help="Path to a local Docker image file (tar archive) to load.",
)
@click.option(
"--docker-keep",
type=bool,
default=True,
help="Keep or remove the Docker container after finishing the task",
)
# --- Docker Mode End ---
@click.option(
"--console-type",
"-ct",
default="simple",
type=click.Choice(["simple", "rich"], case_sensitive=False),
help="Type of console to use (simple or rich)",
)
@click.option(
"--agent-type",
"-at",
type=click.Choice(["trae_agent"], case_sensitive=False),
help="Type of agent to use (trae_agent)",
default="trae_agent",
)
def run(
task: str | None,
file_path: str | None,
patch_path: str,
provider: str | None = None,
model: str | None = None,
model_base_url: str | None = None,
api_key: str | None = None,
max_steps: int | None = None,
working_dir: str | None = None,
must_patch: bool = False,
config_file: str = "trae_config.yaml",
trajectory_file: str | None = None,
console_type: str | None = "simple",
agent_type: str | None = "trae_agent",
# --- Add Docker Mode ---
docker_image: str | None = None,
docker_container_id: str | None = None,
dockerfile_path: str | None = None,
docker_image_file: str | None = None,
docker_keep: bool = True,
):
"""
Run is the main function of trae. it runs a task using Trae Agent.
Args:
tasks: the task that you want your agent to solve. This is required to be in the input
model: the model expected to be use
working_dir: the working directory of the agent. This should be set either in cli or in the config file
Return:
None (it is expected to be ended after calling the run function)
"""
docker_config: dict[str, str | None] | None = None
if (
sum(
[
bool(docker_image),
bool(docker_container_id),
bool(dockerfile_path),
bool(docker_image_file),
]
)
> 1
):
console.print(
"[red]Error: --docker-image, --docker-container-id, --dockerfile-path, and --docker-image-file are mutually exclusive.[/red]"
)
sys.exit(1)
if dockerfile_path:
docker_config = {"dockerfile_path": dockerfile_path}
console.print(
f"[blue]Docker mode enabled. Building from Dockerfile: {dockerfile_path}[/blue]"
)
elif docker_image_file:
docker_config = {"docker_image_file": docker_image_file}
console.print(
f"[blue]Docker mode enabled. Loading from image file: {docker_image_file}[/blue]"
)
elif docker_container_id:
docker_config = {"container_id": docker_container_id}
console.print(
f"[blue]Docker mode enabled. Attaching to container: {docker_container_id}[/blue]"
)
elif docker_image:
docker_config = {"image": docker_image}
console.print(f"[blue]Docker mode enabled. Using image: {docker_image}[/blue]", markup=False)
# --- ADDED END ---
# Apply backward compatibility for config file
config_file = resolve_config_file(config_file)
if docker_config:
check_msg = check_docker()
if check_msg["cli"] and check_msg["daemon"] and check_msg["version"]:
print("Docker is configured correctly.")
else:
print(f"Docker is configured incorrectly. {check_msg['error']}")
sys.exit(1)
if not (os.path.exists("trae_agent/dist") and os.path.exists("trae_agent/dist/_internal")):
print("Building tools of Docker mode for the first use, waiting for a few seconds...")
build_with_pyinstaller()
print("Building finished.")
if file_path:
if task:
console.print(
"[red]Error: Cannot use both a task string and the --file argument.[/red]"
)
sys.exit(1)
try:
task = Path(file_path).read_text()
except FileNotFoundError:
console.print(f"[red]Error: File not found: {file_path}[/red]", markup=False)
sys.exit(1)
elif not task:
console.print(
"[red]Error: Must provide either a task string or use the --file argument.[/red]"
)
sys.exit(1)
config = Config.create(
config_file=config_file,
).resolve_config_values(
provider=provider,
model=model,
model_base_url=model_base_url,
api_key=api_key,
max_steps=max_steps,
)
if not agent_type:
console.print("[red]Error: agent_type is required.[/red]")
sys.exit(1)
# Create CLI Console
console_mode = ConsoleMode.RUN
if console_type:
selected_console_type = (
ConsoleType.SIMPLE if console_type.lower() == "simple" else ConsoleType.RICH
)
else:
selected_console_type = ConsoleFactory.get_recommended_console_type(console_mode)
cli_console = ConsoleFactory.create_console(
console_type=selected_console_type, mode=console_mode
)
# For rich console in RUN mode, set the initial task
if selected_console_type == ConsoleType.RICH and hasattr(cli_console, "set_initial_task"):
cli_console.set_initial_task(task)
# agent = Agent(agent_type, config, trajectory_file, cli_console)
if docker_config is not None:
docker_config["workspace_dir"] = working_dir # now type-safe
# Change working directory if specified
if working_dir:
try:
Path(working_dir).mkdir(parents=True, exist_ok=True)
# os.chdir(working_dir)
console.print(f"[blue]Changed working directory to: {working_dir}[/blue]", markup=False)
working_dir = os.path.abspath(working_dir)
except Exception as e:
error_text = Text(f"Error changing directory: {e}", style="red")
console.print(error_text)
sys.exit(1)
else:
working_dir = os.getcwd()
console.print(f"[blue]Using current directory as working directory: {working_dir}[/blue]", markup=False)
# Ensure working directory is an absolute path
if not Path(working_dir).is_absolute():
console.print(
f"[red]Working directory must be an absolute path: {working_dir}, it should start with `/`[/red]"
)
sys.exit(1)
agent = Agent(
agent_type,
config,
trajectory_file,
cli_console,
docker_config=docker_config,
docker_keep=docker_keep,
)
if not docker_config:
try:
os.chdir(working_dir)
except Exception as e:
error_text = Text(f"Error changing directory: {e}", style="red")
console.print(error_text)
sys.exit(1)
try:
task_args = {
"project_path": working_dir,
"issue": task,
"must_patch": "true" if must_patch else "false",
"patch_path": patch_path,
}
# Set up agent context for rich console if applicable
if selected_console_type == ConsoleType.RICH and hasattr(cli_console, "set_agent_context"):
cli_console.set_agent_context(agent, config.trae_agent, config_file, trajectory_file)
# Agent will handle starting the appropriate console
_ = asyncio.run(agent.run(task, task_args))
console.print(f"\n[green]Trajectory saved to: {agent.trajectory_file}[/green]", markup=False)
except KeyboardInterrupt:
console.print("\n[yellow]Task execution interrupted by user[/yellow]")
console.print(f"[blue]Partial trajectory saved to: {agent.trajectory_file}[/blue]", markup=False)
sys.exit(1)
except Exception as e:
try:
from docker.errors import DockerException
if isinstance(e, DockerException):
error_text = Text(f"Docker Error: {e}", style="red")
console.print(f"\n{error_text}")
console.print(
"[yellow]Please ensure the Docker daemon is running and you have the necessary permissions.[/yellow]"
)
else:
raise e
except ImportError:
error_text = Text(f"Unexpected error: {e}", style="red")
console.print(f"\n{error_text}")
console.print(traceback.format_exc())
except Exception:
error_text = Text(f"Unexpected error: {e}", style="red")
console.print(f"\n{error_text}")
console.print(traceback.format_exc())
console.print(f"[blue]Trajectory saved to: {agent.trajectory_file}[/blue]", markup=False)
sys.exit(1)
@cli.command()
@click.option("--provider", "-p", help="LLM provider to use")
@click.option("--model", "-m", help="Specific model to use")
@click.option("--model-base-url", help="Base URL for the model API")
@click.option("--api-key", "-k", help="API key (or set via environment variable)")
@click.option(
"--config-file",
help="Path to configuration file",
default="trae_config.yaml",
envvar="TRAE_CONFIG_FILE",
)
@click.option("--max-steps", help="Maximum number of execution steps", type=int, default=20)
@click.option("--trajectory-file", "-t", help="Path to save trajectory file")
@click.option(
"--console-type",
"-ct",
type=click.Choice(["simple", "rich"], case_sensitive=False),
help="Type of console to use (simple or rich)",
)
@click.option(
"--agent-type",
"-at",
type=click.Choice(["trae_agent"], case_sensitive=False),
help="Type of agent to use (trae_agent)",
default="trae_agent",
)
def interactive(
provider: str | None = None,
model: str | None = None,
model_base_url: str | None = None,
api_key: str | None = None,
config_file: str = "trae_config.yaml",
max_steps: int | None = None,
trajectory_file: str | None = None,
console_type: str | None = "simple",
agent_type: str | None = "trae_agent",
):
"""
This function starts an interactive session with Trae Agent.
Args:
console_type: Type of console to use for the interactive session
"""
# Apply backward compatibility for config file
config_file = resolve_config_file(config_file)
config = Config.create(
config_file=config_file,
).resolve_config_values(
provider=provider,
model=model,
model_base_url=model_base_url,
api_key=api_key,
max_steps=max_steps,
)
if config.trae_agent:
trae_agent_config = config.trae_agent
else:
console.print("[red]Error: trae_agent configuration is required in the config file.[/red]")
sys.exit(1)
# Create CLI Console for interactive mode
console_mode = ConsoleMode.INTERACTIVE
if console_type:
selected_console_type = (
ConsoleType.SIMPLE if console_type.lower() == "simple" else ConsoleType.RICH
)
else:
selected_console_type = ConsoleFactory.get_recommended_console_type(console_mode)
cli_console = ConsoleFactory.create_console(
console_type=selected_console_type,
lakeview_config=config.lakeview,
mode=console_mode,
)
if not agent_type:
console.print("[red]Error: agent_type is required.[/red]")
sys.exit(1)
# Create agent
agent = Agent(agent_type, config, trajectory_file, cli_console)
# Get the actual trajectory file path (in case it was auto-generated)
trajectory_file = agent.trajectory_file
# For simple console, use traditional interactive loop
if selected_console_type == ConsoleType.SIMPLE:
asyncio.run(
_run_simple_interactive_loop(
agent, cli_console, trae_agent_config, config_file, trajectory_file
)
)
else:
# For rich console, start the textual app which handles interaction
asyncio.run(
_run_rich_interactive_loop(
agent, cli_console, trae_agent_config, config_file, trajectory_file
)
)
async def _run_simple_interactive_loop(
agent: Agent,
cli_console: CLIConsole,
trae_agent_config: TraeAgentConfig,
config_file: str,
trajectory_file: str | None,
):
"""Run the interactive loop for simple console."""
while True:
try:
task = cli_console.get_task_input()
if task is None:
console.print("[green]Goodbye![/green]")
break
if task.lower() == "help":
console.print(
Panel(
"""[bold]Available Commands:[/bold]
• Type any task description to execute it
• 'status' - Show agent status
• 'clear' - Clear the screen
• 'exit' or 'quit' - End the session""",
title="Help",
border_style="yellow",
)
)
continue
working_dir = cli_console.get_working_dir_input()
if task.lower() == "status":
console.print(
Panel(
f"""[bold]Provider:[/bold] {agent.agent_config.model.model_provider.provider}
[bold]Model:[/bold] {agent.agent_config.model.model}
[bold]Available Tools:[/bold] {len(agent.agent.tools)}
[bold]Config File:[/bold] {config_file}
[bold]Working Directory:[/bold] {os.getcwd()}""",
title="Agent Status",
border_style="blue",
)
)
continue
if task.lower() == "clear":
console.clear()
continue
# Set up trajectory recording for this task
console.print(f"[blue]Trajectory will be saved to: {trajectory_file}[/blue]", markup=False)
task_args = {
"project_path": working_dir,
"issue": task,
"must_patch": "false",
}
# Execute the task
console.print(f"\n[blue]Executing task: {task}[/blue]", markup=False)
# Start console and execute task
console_task = asyncio.create_task(cli_console.start())
execution_task = asyncio.create_task(agent.run(task, task_args))
# Wait for execution to complete
_ = await execution_task
_ = await console_task
console.print(f"\n[green]Trajectory saved to: {trajectory_file}[/green]", markup=False)
except KeyboardInterrupt:
console.print("\n[yellow]Use 'exit' or 'quit' to end the session[/yellow]")
except EOFError:
console.print("\n[green]Goodbye![/green]")
break
except Exception as e:
error_text = Text(f"Error: {e}", style="red")
console.print(error_text)
async def _run_rich_interactive_loop(
agent: Agent,
cli_console: CLIConsole,
trae_agent_config: TraeAgentConfig,
config_file: str,
trajectory_file: str | None,
):
"""Run the interactive loop for rich console."""
# Set up the agent in the rich console so it can handle task execution
if hasattr(cli_console, "set_agent_context"):
cli_console.set_agent_context(agent, trae_agent_config, config_file, trajectory_file)
# Start the console UI - this will handle the entire interaction
await cli_console.start()
@cli.command()
@click.option(
"--config-file",
help="Path to configuration file",
default="trae_config.yaml",
envvar="TRAE_CONFIG_FILE",
)
@click.option("--provider", "-p", help="LLM provider to use")
@click.option("--model", "-m", help="Specific model to use")
@click.option("--model-base-url", help="Base URL for the model API")
@click.option("--api-key", "-k", help="API key (or set via environment variable)")
@click.option("--max-steps", help="Maximum number of execution steps", type=int)
def show_config(
config_file: str,
provider: str | None,
model: str | None,
model_base_url: str | None,
api_key: str | None,
max_steps: int | None,
):
"""Show current configuration settings."""
# Apply backward compatibility for config file
config_file = resolve_config_file(config_file)
config_path = Path(config_file)
if not config_path.exists():
console.print(
Panel(
f"""[yellow]No configuration file found at: {config_file}[/yellow]
Using default settings and environment variables.""",
title="Configuration Status",
border_style="yellow",
)
)
config = Config.create(
config_file=config_file,
).resolve_config_values(
provider=provider,
model=model,
model_base_url=model_base_url,
api_key=api_key,
max_steps=max_steps,
)
if config.trae_agent:
trae_agent_config = config.trae_agent
else:
console.print("[red]Error: trae_agent configuration is required in the config file.[/red]")
sys.exit(1)
# Display general settings
general_table = Table(title="General Settings")
general_table.add_column("Setting", style="cyan")
general_table.add_column("Value", style="green")
general_table.add_row(
"Default Provider",
str(trae_agent_config.model.model_provider.provider or "Not set"),
)
general_table.add_row("Max Steps", str(trae_agent_config.max_steps or "Not set"))
console.print(general_table)
# Display provider settings
provider_config = trae_agent_config.model.model_provider
provider_table = Table(title=f"{provider_config.provider.title()} Configuration")
provider_table.add_column("Setting", style="cyan")
provider_table.add_column("Value", style="green")
provider_table.add_row("Model", trae_agent_config.model.model or "Not set")
provider_table.add_row("Base URL", provider_config.base_url or "Not set")
provider_table.add_row("API Version", provider_config.api_version or "Not set")
provider_table.add_row(
"API Key",
(
f"Set ({provider_config.api_key[:4]}...{provider_config.api_key[-4:]})"
if provider_config.api_key
else "Not set"
),
)
provider_table.add_row("Max Tokens", str(trae_agent_config.model.max_tokens))
provider_table.add_row("Temperature", str(trae_agent_config.model.temperature))
provider_table.add_row("Top P", str(trae_agent_config.model.top_p))
if trae_agent_config.model.model_provider.provider == "anthropic":
provider_table.add_row("Top K", str(trae_agent_config.model.top_k))
console.print(provider_table)
@cli.command()
def tools():
"""Show available tools and their descriptions."""
from .tools import tools_registry
tools_table = Table(title="Available Tools")
tools_table.add_column("Tool Name", style="cyan")
tools_table.add_column("Description", style="green")
for tool_name in tools_registry:
try:
tool = tools_registry[tool_name]()
tools_table.add_row(tool.name, tool.description)
except Exception as e:
tools_table.add_row(tool_name, f"[red]Error loading: {e}[/red]")
console.print(tools_table)
def main():
"""Main entry point for the CLI."""
cli()
if __name__ == "__main__":
main()