|
| 1 | +"""Setup commands for integrating Weco with various AI tools.""" |
| 2 | + |
| 3 | +import pathlib |
| 4 | +import sys |
| 5 | +import tempfile |
| 6 | +import time |
| 7 | + |
| 8 | +from rich.console import Console |
| 9 | +from rich.prompt import Prompt |
| 10 | + |
| 11 | +from ...events import ( |
| 12 | + create_event_context, |
| 13 | + send_event, |
| 14 | + SkillInstallCompletedEvent, |
| 15 | + SkillInstallFailedEvent, |
| 16 | + SkillInstallStartedEvent, |
| 17 | +) |
| 18 | +from ...utils import DownloadError |
| 19 | +from .install import SafetyError, SetupError, download_skill_archive, install_target |
| 20 | +from .targets import ALL_SETUP_OPTION_LABEL, ALL_SETUP_OPTION_NAME, SETUP_TARGET_BY_NAME, SETUP_TARGET_NAMES, SETUP_TARGETS |
| 21 | + |
| 22 | + |
| 23 | +class _SkillSource: |
| 24 | + """Resolves the skill source directory on first use, downloading once if needed. |
| 25 | +
|
| 26 | + Use as a context manager so any downloaded tempdir is cleaned up on exit. |
| 27 | + The resolved path is reused across every target so ``weco setup all`` |
| 28 | + downloads exactly once. |
| 29 | + """ |
| 30 | + |
| 31 | + def __init__(self, local_path: pathlib.Path | None, console: Console): |
| 32 | + self._local_path = local_path |
| 33 | + self._console = console |
| 34 | + self._tmp_dir: tempfile.TemporaryDirectory | None = None |
| 35 | + self._downloaded_path: pathlib.Path | None = None |
| 36 | + |
| 37 | + def __enter__(self) -> "_SkillSource": |
| 38 | + return self |
| 39 | + |
| 40 | + def __exit__(self, *exc_info) -> None: |
| 41 | + if self._tmp_dir is not None: |
| 42 | + self._tmp_dir.cleanup() |
| 43 | + self._tmp_dir = None |
| 44 | + |
| 45 | + @property |
| 46 | + def kind(self) -> str: |
| 47 | + return "local" if self._local_path else "download" |
| 48 | + |
| 49 | + def path(self) -> pathlib.Path: |
| 50 | + if self._local_path is not None: |
| 51 | + return self._local_path |
| 52 | + if self._downloaded_path is None: |
| 53 | + self._tmp_dir = tempfile.TemporaryDirectory() |
| 54 | + dest = pathlib.Path(self._tmp_dir.name) / "skill" |
| 55 | + download_skill_archive(dest, self._console) |
| 56 | + self._downloaded_path = dest |
| 57 | + return self._downloaded_path |
| 58 | + |
| 59 | + |
| 60 | +def prompt_tool_selection(console: Console) -> list[str]: |
| 61 | + """Prompt the user to select which tool(s) to set up.""" |
| 62 | + tool_names = list(SETUP_TARGET_NAMES) |
| 63 | + all_option = len(tool_names) + 1 |
| 64 | + |
| 65 | + console.print("\n[bold cyan]Available tools to set up:[/]\n") |
| 66 | + for i, target in enumerate(SETUP_TARGETS, 1): |
| 67 | + console.print(f" {i}. {target.label} [dim]({target.name})[/]") |
| 68 | + console.print(f" {all_option}. {ALL_SETUP_OPTION_LABEL} [dim](default)[/]") |
| 69 | + |
| 70 | + valid_choices = [str(i) for i in range(1, all_option + 1)] |
| 71 | + choice = Prompt.ask("\n[bold]Select an option[/]", choices=valid_choices, default=str(all_option), show_choices=True) |
| 72 | + |
| 73 | + idx = int(choice) |
| 74 | + if idx == all_option: |
| 75 | + return tool_names |
| 76 | + return [tool_names[idx - 1]] |
| 77 | + |
| 78 | + |
| 79 | +def run_setup_for_tool(tool: str, console: Console, source: _SkillSource, ctx) -> None: |
| 80 | + """Run setup for a single tool with event tracking and error handling.""" |
| 81 | + send_event(SkillInstallStartedEvent(tool=tool, source=source.kind), ctx) |
| 82 | + start_time = time.time() |
| 83 | + |
| 84 | + try: |
| 85 | + source_path = source.path() |
| 86 | + install_target(SETUP_TARGET_BY_NAME[tool], console, source_path) |
| 87 | + except DownloadError as e: |
| 88 | + send_event(SkillInstallFailedEvent(tool=tool, source=source.kind, error_type="download_error", stage="download"), ctx) |
| 89 | + console.print(f"\n[bold red]Error:[/] {e}") |
| 90 | + sys.exit(1) |
| 91 | + except SafetyError as e: |
| 92 | + send_event(SkillInstallFailedEvent(tool=tool, source=source.kind, error_type="safety_error", stage="setup"), ctx) |
| 93 | + console.print(f"\n[bold red]Safety Error:[/] {e}") |
| 94 | + sys.exit(1) |
| 95 | + except (SetupError, FileNotFoundError, OSError, ValueError) as e: |
| 96 | + send_event(SkillInstallFailedEvent(tool=tool, source=source.kind, error_type=type(e).__name__, stage="setup"), ctx) |
| 97 | + console.print(f"\n[bold red]Error:[/] {e}") |
| 98 | + sys.exit(1) |
| 99 | + |
| 100 | + duration_ms = int((time.time() - start_time) * 1000) |
| 101 | + send_event(SkillInstallCompletedEvent(tool=tool, source=source.kind, duration_ms=duration_ms), ctx) |
| 102 | + |
| 103 | + |
| 104 | +def handle_setup_command(args, console: Console) -> None: |
| 105 | + """Handle the ``weco setup`` command.""" |
| 106 | + ctx = create_event_context() |
| 107 | + |
| 108 | + if args.tool is None: |
| 109 | + selected_tools = prompt_tool_selection(console) |
| 110 | + elif args.tool == ALL_SETUP_OPTION_NAME: |
| 111 | + selected_tools = list(SETUP_TARGET_NAMES) |
| 112 | + elif args.tool in SETUP_TARGET_BY_NAME: |
| 113 | + selected_tools = [args.tool] |
| 114 | + else: |
| 115 | + available = ", ".join((*SETUP_TARGET_NAMES, ALL_SETUP_OPTION_NAME)) |
| 116 | + console.print(f"[bold red]Error:[/] Unknown tool: {args.tool}") |
| 117 | + console.print(f"Available tools: {available}") |
| 118 | + sys.exit(1) |
| 119 | + |
| 120 | + local_path = None |
| 121 | + if getattr(args, "local", None): |
| 122 | + local_path = pathlib.Path(args.local).expanduser().resolve() |
| 123 | + console.print(f"[bold cyan]Using local skill source:[/] {local_path}\n") |
| 124 | + |
| 125 | + with _SkillSource(local_path, console) as source: |
| 126 | + for tool in selected_tools: |
| 127 | + run_setup_for_tool(tool, console, source, ctx) |
| 128 | + |
| 129 | + console.print("\n[bold green]Setup complete.[/]") |
0 commit comments