diff --git a/README.md b/README.md index c90ec74..4981d21 100644 --- a/README.md +++ b/README.md @@ -127,8 +127,8 @@ weco setup claude-code # For Claude Code weco setup cursor # For Cursor ``` -- **Claude Code**: Clones the Weco skill to `~/.claude/skills/weco/` and updates `~/.claude/CLAUDE.md` -- **Cursor**: Clones the Weco skill to `~/.cursor/skills/weco/` and creates `~/.cursor/rules/weco.mdc` +- **Claude Code**: Downloads the Weco skill to `~/.claude/skills/weco/` and updates `~/.claude/CLAUDE.md` +- **Cursor**: Downloads the Weco skill to `~/.cursor/skills/weco/` and creates `~/.cursor/rules/weco.mdc` ### Model Selection @@ -138,10 +138,10 @@ You can specify which LLM model to use with the `-M` or `--model` flag: weco run --model gpt-5 --source optimize.py [other options...] ``` -**Available models (30 total):** +**Available models (31 total):** **OpenAI Models:** -- GPT-5 Series: `gpt-5.1`, `gpt-5.1-codex`, `gpt-5.1-codex-mini`, `gpt-5-codex`, `gpt-5-pro`, `gpt-5`, `gpt-5-mini`, `gpt-5-nano` +- GPT-5 Series: `gpt-5.2`, `gpt-5.1`, `gpt-5.1-codex`, `gpt-5.1-codex-mini`, `gpt-5-codex`, `gpt-5-pro`, `gpt-5`, `gpt-5-mini`, `gpt-5-nano` - O-Series Reasoning: `o3-pro`, `o3`, `o3-mini`, `o4-mini`, `o1-pro`, `o1`, `codex-mini-latest` - GPT-4 Series: `gpt-4.1`, `gpt-4.1-mini`, `gpt-4.1-nano`, `gpt-4o`, `gpt-4o-mini` diff --git a/pyproject.toml b/pyproject.toml index ac07ac5..153c5df 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ name = "weco" authors = [{ name = "Weco AI Team", email = "contact@weco.ai" }] description = "Documentation for `weco`, a CLI for using Weco AI's code optimizer." readme = "README.md" -version = "0.3.11" +version = "0.3.12" license = { file = "LICENSE" } requires-python = ">=3.8" dependencies = [ diff --git a/weco/api.py b/weco/api.py index 3129fda..f5639aa 100644 --- a/weco/api.py +++ b/weco/api.py @@ -130,10 +130,20 @@ def start_optimization_run( timeout: Union[int, Tuple[int, int]] = (10, 3650), api_keys: Optional[Dict[str, str]] = None, require_review: bool = False, + installation_id: Optional[str] = None, + invocation_id: Optional[str] = None, + invoked_via: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Start the optimization run.""" with console.status("[bold green]Starting Optimization..."): try: + # Build metadata with client info and optional event context + metadata = {"client_name": invoked_via or "cli", "client_version": __pkg_version__} + if installation_id: + metadata["installation_id"] = installation_id + if invocation_id: + metadata["invocation_id"] = invocation_id + request_json = { "source_code": source_code, "source_path": source_path, @@ -149,7 +159,7 @@ def start_optimization_run( "save_logs": save_logs, "log_dir": log_dir, "require_review": require_review, - "metadata": {"client_name": "cli", "client_version": __pkg_version__}, + "metadata": metadata, } if api_keys: request_json["api_keys"] = api_keys diff --git a/weco/auth.py b/weco/auth.py index 74fdf76..29a332b 100644 --- a/weco/auth.py +++ b/weco/auth.py @@ -1,8 +1,4 @@ # weco/auth.py -import os -import pathlib -import json -import stat import time import requests import webbrowser @@ -10,67 +6,17 @@ from rich.live import Live from rich.prompt import Prompt from . import __base_url__ - -CONFIG_DIR = pathlib.Path.home() / ".config" / "weco" -CREDENTIALS_FILE = CONFIG_DIR / "credentials.json" - - -def ensure_config_dir(): - """Ensures the configuration directory exists.""" - CONFIG_DIR.mkdir(parents=True, exist_ok=True) - # Ensure directory permissions are secure (optional but good practice) - try: - os.chmod(CONFIG_DIR, stat.S_IRWXU) # Read/Write/Execute for owner only - except OSError as e: - print(f"Warning: Could not set permissions on {CONFIG_DIR}: {e}") - - -def save_api_key(api_key: str): - """Saves the Weco API key securely.""" - ensure_config_dir() - credentials = {"api_key": api_key} - try: - with open(CREDENTIALS_FILE, "w") as f: - json.dump(credentials, f) - # Set file permissions to read/write for owner only (600) - os.chmod(CREDENTIALS_FILE, stat.S_IRUSR | stat.S_IWUSR) - except OSError as e: - print(f"Error: Unable to save credentials file or set permissions on {CREDENTIALS_FILE}: {e}") - - -def load_weco_api_key() -> str | None: - """Loads the Weco API key.""" - if not CREDENTIALS_FILE.exists(): - return None - try: - # Check permissions before reading (optional but safer) - file_stat = os.stat(CREDENTIALS_FILE) - if file_stat.st_mode & (stat.S_IRWXG | stat.S_IRWXO): # Check if group/other have permissions - print(f"Warning: Credentials file {CREDENTIALS_FILE} has insecure permissions. Please set to 600.") - # Optionally, refuse to load or try to fix permissions - - with open(CREDENTIALS_FILE, "r") as f: - credentials = json.load(f) - return credentials.get("api_key") - except (IOError, json.JSONDecodeError, OSError) as e: - print(f"Warning: Unable to read credentials file at {CREDENTIALS_FILE}: {e}") - return None - - -def clear_api_key(): - """Removes the stored API key.""" - if CREDENTIALS_FILE.exists(): - try: - os.remove(CREDENTIALS_FILE) - print("Logged out successfully.") - except OSError as e: - print(f"Error: Unable to remove credentials file at {CREDENTIALS_FILE}: {e}") - else: - print("Already logged out.") +from .config import save_api_key, load_weco_api_key +from .events import send_event, get_event_context, AuthStartedEvent, AuthCompletedEvent, AuthFailedEvent def perform_login(console: Console): """Handles the device login flow.""" + ctx = get_event_context() + + # Track auth started + send_event(AuthStartedEvent(), ctx) + try: # 1. Initiate device login console.print("Initiating login...") @@ -109,6 +55,7 @@ def perform_login(console: Console): while True: # Check for timeout if time.time() - start_time > expires_in: + send_event(AuthFailedEvent(reason="timeout"), ctx) console.print("\n[bold red]Error:[/] Login request timed out.") return False @@ -118,7 +65,11 @@ def perform_login(console: Console): try: token_response = requests.post( f"{__base_url__}/auth/device/token", - json={"grant_type": "urn:ietf:params:oauth:grant-type:device_code", "device_code": device_code}, + json={ + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", + "device_code": device_code, + "installation_id": ctx.installation_id, + }, ) # Check for 202 Accepted - Authorization Pending @@ -129,6 +80,7 @@ def perform_login(console: Console): continue # Continue polling else: # Unexpected 202 response format + send_event(AuthFailedEvent(reason="unexpected_response"), ctx) console.print( f"\n[bold red]Error:[/] Received unexpected response from authentication server: {token_data}" ) @@ -142,12 +94,15 @@ def perform_login(console: Console): live_status.update(f"Waiting... (slowing down polling to {interval}s)") continue elif error_code == "expired_token": + send_event(AuthFailedEvent(reason="expired"), ctx) console.print("\n[bold red]Error:[/] Login request expired.") return False elif error_code == "access_denied": + send_event(AuthFailedEvent(reason="denied"), ctx) console.print("\n[bold red]Error:[/] Authorization denied by user.") return False else: # invalid_grant, etc. + send_event(AuthFailedEvent(reason=error_code), ctx) error_desc = token_data.get("error_description", "Unknown authentication error occurred.") console.print(f"\n[bold red]Error:[/] {error_desc} ({error_code})") return False @@ -159,10 +114,12 @@ def perform_login(console: Console): if "access_token" in token_data: api_key = token_data["access_token"] save_api_key(api_key) + send_event(AuthCompletedEvent(), ctx) console.print("\n[bold green]Login successful![/]") return True else: # Unexpected successful response format + send_event(AuthFailedEvent(reason="unexpected_response"), ctx) console.print("\n[bold red]Error:[/] Received unexpected response from server during polling.") print(token_data) return False @@ -174,12 +131,16 @@ def perform_login(console: Console): except requests.exceptions.HTTPError as e: from .api import handle_api_error # Import here to avoid circular imports + send_event(AuthFailedEvent(reason="http_error"), ctx) handle_api_error(e, console) + return False except requests.exceptions.RequestException as e: # Catch other request errors + send_event(AuthFailedEvent(reason="network_error"), ctx) console.print(f"\n[bold red]Network Error:[/] {e}") return False except Exception as e: + send_event(AuthFailedEvent(reason="error"), ctx) console.print(f"\n[bold red]An unexpected error occurred during login:[/] {e}") return False diff --git a/weco/cli.py b/weco/cli.py index 80cbf10..066db41 100644 --- a/weco/cli.py +++ b/weco/cli.py @@ -3,8 +3,17 @@ from rich.console import Console from rich.traceback import install -from .auth import clear_api_key, perform_login, load_weco_api_key +from .auth import perform_login +from .config import clear_api_key, load_weco_api_key from .constants import DEFAULT_MODELS +from .events import ( + send_event, + create_event_context, + get_event_context, + set_event_context, + CLIInvokedEvent, + RunStartAttemptedEvent, +) from .utils import check_for_cli_updates, get_default_model, UnrecognizedAPIKeysError, DefaultModelNotFoundError from .validation import validate_source_file, validate_log_directory, ValidationError, print_validation_error @@ -187,16 +196,8 @@ def _parse_credit_amount(value: str) -> float: def _add_setup_source_args(parser: argparse.ArgumentParser) -> None: """Add common source arguments to a setup subparser.""" - source_group = parser.add_mutually_exclusive_group() - source_group.add_argument( - "--local", type=str, metavar="PATH", help="Use a local weco-skill directory (creates symlink for development)" - ) - source_group.add_argument("--repo", type=str, metavar="URL", help="Use a different git repo URL (for forks or testing)") parser.add_argument( - "--ref", - type=str, - metavar="REF", - help="Checkout a specific branch, tag, or commit hash (used with git clone, not --local)", + "--local", type=str, metavar="PATH", help="Use a local weco-skill directory instead of downloading (for development)" ) @@ -254,6 +255,8 @@ def execute_run_command(args: argparse.Namespace) -> None: """Execute the 'weco run' command with all its logic.""" from .optimizer import optimize + ctx = get_event_context() + # Early validation — fail fast with helpful errors try: validate_source_file(args.source) @@ -279,6 +282,18 @@ def execute_run_command(args: argparse.Namespace) -> None: if api_keys: console.print(f"[bold yellow]Custom API keys provided. Using default model: {model} for the run.[/]") + # Send run attempt event before starting (helps measure dropoff before server) + send_event( + RunStartAttemptedEvent( + output_mode=args.output, + require_review=args.require_review, + save_logs=args.save_logs, + steps=args.steps, + model=model, + ), + ctx, + ) + success = optimize( source=args.source, eval_command=args.eval_command, @@ -336,6 +351,13 @@ def _main() -> None: formatter_class=argparse.RawDescriptionHelpFormatter, ) + # Global flags + parser.add_argument( + "--via-skill", + action="store_true", + help=argparse.SUPPRESS, # Hidden flag for AI agents invoking via skill + ) + subparsers = parser.add_subparsers( dest="command", help="Available commands" ) # Removed required=True for now to handle chatbot case easily @@ -371,6 +393,14 @@ def _main() -> None: args = parser.parse_args() + # Create event context with via_skill flag + via_skill = getattr(args, "via_skill", False) + ctx = create_event_context(via_skill=via_skill) + set_event_context(ctx) + + # Send CLI invocation event + send_event(CLIInvokedEvent(command=args.command or "help"), ctx) + if args.command == "login": # Check if already logged in existing_key = load_weco_api_key() diff --git a/weco/config.py b/weco/config.py new file mode 100644 index 0000000..5dea805 --- /dev/null +++ b/weco/config.py @@ -0,0 +1,124 @@ +# weco/config.py +"""Configuration and credential management for Weco CLI. + +This module handles: +- API key storage and retrieval +- Installation ID management for anonymous event tracking +- Config directory management +""" + +import os +import pathlib +import json +import stat +import uuid + + +CONFIG_DIR = pathlib.Path.home() / ".config" / "weco" +CREDENTIALS_FILE = CONFIG_DIR / "credentials.json" +INSTALLATION_FILE = CONFIG_DIR / "installation.json" + + +def ensure_config_dir(): + """Ensures the configuration directory exists.""" + CONFIG_DIR.mkdir(parents=True, exist_ok=True) + # Ensure directory permissions are secure (optional but good practice) + try: + os.chmod(CONFIG_DIR, stat.S_IRWXU) # Read/Write/Execute for owner only + except OSError as e: + print(f"Warning: Could not set permissions on {CONFIG_DIR}: {e}") + + +def save_api_key(api_key: str): + """Saves the Weco API key securely.""" + ensure_config_dir() + credentials = {"api_key": api_key} + try: + with open(CREDENTIALS_FILE, "w") as f: + json.dump(credentials, f) + # Set file permissions to read/write for owner only (600) + os.chmod(CREDENTIALS_FILE, stat.S_IRUSR | stat.S_IWUSR) + except OSError as e: + print(f"Error: Unable to save credentials file or set permissions on {CREDENTIALS_FILE}: {e}") + + +def load_weco_api_key() -> str | None: + """Loads the Weco API key.""" + if not CREDENTIALS_FILE.exists(): + return None + try: + # Check permissions before reading (optional but safer) + file_stat = os.stat(CREDENTIALS_FILE) + if file_stat.st_mode & (stat.S_IRWXG | stat.S_IRWXO): # Check if group/other have permissions + print(f"Warning: Credentials file {CREDENTIALS_FILE} has insecure permissions. Please set to 600.") + # Optionally, refuse to load or try to fix permissions + + with open(CREDENTIALS_FILE, "r") as f: + credentials = json.load(f) + return credentials.get("api_key") + except (IOError, json.JSONDecodeError, OSError) as e: + print(f"Warning: Unable to read credentials file at {CREDENTIALS_FILE}: {e}") + return None + + +def clear_api_key(): + """Removes the stored API key.""" + if CREDENTIALS_FILE.exists(): + try: + os.remove(CREDENTIALS_FILE) + print("Logged out successfully.") + except OSError as e: + print(f"Error: Unable to remove credentials file at {CREDENTIALS_FILE}: {e}") + else: + print("Already logged out.") + + +def get_or_create_installation_id() -> str: + """Gets or creates a persistent installation ID for anonymous event reporting. + + The installation ID is stored in ~/.config/weco/installation.json and + persists across CLI invocations. It is used to link anonymous events + to the user once they authenticate. + + Returns: + The installation ID (a UUID string prefixed with 'inst_'). + """ + ensure_config_dir() + + # Try to load existing installation ID + try: + with open(INSTALLATION_FILE, "r") as f: + data = json.load(f) + installation_id = data.get("installation_id") + if installation_id: + return installation_id + except (IOError, json.JSONDecodeError, FileNotFoundError): + pass # Will create a new one + + # Generate a new installation ID + installation_id = f"inst_{uuid.uuid4().hex}" + + # Save it + try: + with open(INSTALLATION_FILE, "w") as f: + json.dump({"installation_id": installation_id}, f) + # Set secure permissions + os.chmod(INSTALLATION_FILE, stat.S_IRUSR | stat.S_IWUSR) + except OSError: + pass # Non-fatal - we can still use the ID for this session + + return installation_id + + +def load_installation_id() -> str | None: + """Loads the installation ID if it exists. + + Returns: + The installation ID or None if not found. + """ + try: + with open(INSTALLATION_FILE, "r") as f: + data = json.load(f) + return data.get("installation_id") + except (IOError, json.JSONDecodeError, FileNotFoundError): + return None diff --git a/weco/credits.py b/weco/credits.py index f08733f..16d43a0 100644 --- a/weco/credits.py +++ b/weco/credits.py @@ -6,7 +6,8 @@ from rich.table import Table from . import __base_url__ from .api import handle_api_error -from .auth import load_weco_api_key, handle_authentication +from .auth import handle_authentication +from .config import load_weco_api_key def handle_credits_command(args, console: Console) -> None: diff --git a/weco/events.py b/weco/events.py new file mode 100644 index 0000000..99c7dd7 --- /dev/null +++ b/weco/events.py @@ -0,0 +1,294 @@ +# weco/events.py +"""Event reporting module for analytics. + +This module provides fire-and-forget event reporting to the Weco backend. +Events are sent asynchronously in a background thread to avoid blocking +the CLI execution. Failures are silently ignored. + +Usage: + from weco.events import send_event, EventContext, CLIInvokedEvent + + # Create a context for the CLI invocation + ctx = EventContext() + + # Send an event + send_event(CLIInvokedEvent(command="run"), ctx) + +Environment variables: + WECO_DISABLE_EVENTS: Set to "1" or "true" to disable event reporting. +""" + +import os +import uuid +import threading +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Any +import requests + +from pydantic import BaseModel, Field + +from . import __base_url__, __pkg_version__ +from .config import get_or_create_installation_id, load_weco_api_key + + +# ============================================================================= +# Event Definitions +# ============================================================================= + + +class BaseEvent(BaseModel): + """Base class for all events. Subclass to define specific events.""" + + # Client-side timestamp set at event creation time + timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) + + @property + def event_name(self) -> str: + """Return the event name. Must be implemented by subclasses.""" + raise NotImplementedError + + def to_properties(self) -> dict[str, Any]: + """Convert event fields to properties dict (excludes timestamp).""" + return self.model_dump(exclude={"timestamp"}, exclude_none=True) + + +class CLIInvokedEvent(BaseEvent): + """Tracked when the CLI is invoked.""" + + command: str # The command being run (run, login, setup, etc.) + + @property + def event_name(self) -> str: + return "cli.invoked" + + +class SkillInstallStartedEvent(BaseEvent): + """Tracked when skill installation begins.""" + + tool: str # 'cursor' or 'claude_code' + source: str # 'local' or 'repo' + + @property + def event_name(self) -> str: + return "skill.install.started" + + +class SkillInstallCompletedEvent(BaseEvent): + """Tracked when skill installation completes successfully.""" + + tool: str + source: str + duration_ms: int + + @property + def event_name(self) -> str: + return "skill.install.completed" + + +class SkillInstallFailedEvent(BaseEvent): + """Tracked when skill installation fails.""" + + tool: str + source: str + error_type: str + stage: str # 'git_operation', 'setup', etc. + + @property + def event_name(self) -> str: + return "skill.install.failed" + + +class RunStartAttemptedEvent(BaseEvent): + """Tracked when a run is attempted (before server contact).""" + + output_mode: str + require_review: bool + save_logs: bool + steps: int + model: str + + @property + def event_name(self) -> str: + return "run.start.attempted" + + +class AuthStartedEvent(BaseEvent): + """Tracked when authentication flow begins.""" + + @property + def event_name(self) -> str: + return "auth.started" + + +class AuthCompletedEvent(BaseEvent): + """Tracked when authentication completes successfully.""" + + @property + def event_name(self) -> str: + return "auth.completed" + + +class AuthFailedEvent(BaseEvent): + """Tracked when authentication fails.""" + + reason: str # 'timeout', 'denied', 'expired', 'error', etc. + + @property + def event_name(self) -> str: + return "auth.failed" + + +# ============================================================================= +# Event Context +# ============================================================================= + + +def _is_events_disabled() -> bool: + """Check if event reporting is disabled via environment variable.""" + val = os.environ.get("WECO_DISABLE_EVENTS", "").lower() + return val in ("1", "true", "yes") + + +@dataclass +class EventContext: + """Context for a CLI invocation. + + This holds information that should be attached to all events + during a single CLI invocation. + """ + + installation_id: str = field(default_factory=get_or_create_installation_id) + invocation_id: str = field(default_factory=lambda: f"inv_{uuid.uuid4().hex[:16]}") + client_version: str = field(default_factory=lambda: __pkg_version__) + invoked_via: str = "cli" # Set via create_event_context() + + +def create_event_context(via_skill: bool = False) -> EventContext: + """Create an event context for a CLI invocation. + + Args: + via_skill: If True, indicates this invocation is via an AI skill. + + Returns: + An EventContext instance. Returns a minimal context if creation fails. + """ + invoked_via = "skill" if via_skill else "cli" + try: + return EventContext(invoked_via=invoked_via) + except Exception: + # Return a minimal context if anything fails + return EventContext( + installation_id="unknown", + invocation_id=f"inv_{uuid.uuid4().hex[:16]}", + client_version="unknown", + invoked_via="cli", + ) + + +# Global event context for the current CLI invocation +_event_ctx: EventContext | None = None + + +def get_event_context() -> EventContext: + """Get the global event context, creating one if needed.""" + global _event_ctx + if _event_ctx is None: + _event_ctx = create_event_context() + return _event_ctx + + +def set_event_context(ctx: EventContext) -> None: + """Set the global event context.""" + global _event_ctx + _event_ctx = ctx + + +# ============================================================================= +# Event Sending +# ============================================================================= + + +def _send_event_request( + event_name: str, + timestamp: datetime, + installation_id: str | None, + invocation_id: str | None, + client_version: str | None, + invoked_via: str | None, + properties: dict[str, Any], + auth_headers: dict[str, str], +) -> None: + """Send an event to the backend (runs in background thread).""" + try: + payload = { + "event": event_name, + "timestamp": timestamp.isoformat(), + "installation_id": installation_id, + "invocation_id": invocation_id, + "client_version": client_version, + "invoked_via": invoked_via, + "properties": properties, + } + + # Remove None values + payload = {k: v for k, v in payload.items() if v is not None} + + requests.post( + f"{__base_url__}/events/", + json=payload, + headers=auth_headers, + timeout=5, # Short timeout to avoid blocking + ) + except Exception: + # Silently ignore errors - they should never affect the CLI + pass + + +def send_event(event: BaseEvent, ctx: EventContext | None = None, auth_headers: dict[str, str] | None = None) -> None: + """Send an event asynchronously. + + This function returns immediately and sends the event in a background + thread to avoid blocking the CLI. Failures are silently ignored. + + Args: + event: The event to send (a subclass of BaseEvent). + ctx: The event context (installation_id, invocation_id, etc.). + If None, a new context will be created. + auth_headers: Optional authentication headers for the API. + """ + try: + # Don't send if disabled + if _is_events_disabled(): + return + + # Create context if not provided + if ctx is None: + ctx = create_event_context() + + # Build auth headers if not provided + if auth_headers is None: + api_key = load_weco_api_key() + auth_headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} + + # Get event properties + properties = event.to_properties() + # Send in background thread (fire-and-forget) + thread = threading.Thread( + target=_send_event_request, + args=( + event.event_name, + event.timestamp, + ctx.installation_id, + ctx.invocation_id, + ctx.client_version, + ctx.invoked_via, + properties, + auth_headers, + ), + daemon=True, + ) + thread.start() + except Exception: + # Silently ignore all errors - event reporting should never break the CLI + pass diff --git a/weco/git.py b/weco/git.py deleted file mode 100644 index 15d6eb3..0000000 --- a/weco/git.py +++ /dev/null @@ -1,121 +0,0 @@ -# weco/git.py -""" -Git utilities for command execution and validation. -""" - -import pathlib -import shutil -import subprocess - - -class GitError(Exception): - """Raised when a git command fails.""" - - def __init__(self, message: str, stderr: str = ""): - super().__init__(message) - self.stderr = stderr - - -class GitNotFoundError(Exception): - """Raised when git is not available on the system.""" - - pass - - -def is_available() -> bool: - """Check if git is available on the system.""" - return shutil.which("git") is not None - - -def is_repo(path: pathlib.Path) -> bool: - """Check if a directory is a git repository.""" - return (path / ".git").is_dir() - - -def validate_ref(ref: str) -> None: - """ - Validate a git ref to prevent option injection. - - Raises: - ValueError: If ref could be interpreted as a git option. - """ - if ref.startswith("-"): - raise ValueError(f"Invalid git ref: {ref!r} (cannot start with '-')") - - -def validate_repo_url(url: str) -> None: - """ - Validate a git repository URL. - - Raises: - ValueError: If URL doesn't match expected patterns. - """ - valid_prefixes = ("git@", "https://", "http://", "ssh://", "file://", "/", "./", "../") - if not any(url.startswith(prefix) for prefix in valid_prefixes): - raise ValueError(f"Invalid repository URL: {url!r}") - - -def run(*args: str, cwd: pathlib.Path | None = None, error_msg: str = "Git command failed") -> subprocess.CompletedProcess: - """ - Run a git command and return the result. - - Args: - *args: Git subcommand and arguments (e.g., "clone", url, path). - Do NOT include "git" — it's prepended automatically. - cwd: Working directory for the command. - error_msg: Message to include in exception on failure. - - Raises: - GitError: If the command fails or returns non-zero. - """ - cmd = ["git", *args] - try: - result = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) - except Exception as e: - raise GitError(f"{error_msg}: {e}") from e - - if result.returncode != 0: - raise GitError(error_msg, result.stderr) - return result - - -def clone(repo_url: str, dest: pathlib.Path, ref: str | None = None) -> None: - """ - Clone a git repository. - - Args: - repo_url: The repository URL to clone. - dest: Destination directory. - ref: Optional branch, tag, or commit to checkout after cloning. - - Raises: - GitError: If clone or checkout fails. - """ - run("clone", repo_url, str(dest), error_msg="Failed to clone repository") - if ref: - run("checkout", ref, cwd=dest, error_msg=f"Failed to checkout '{ref}'") - - -def pull(repo_path: pathlib.Path) -> None: - """ - Pull latest changes in a git repository. - - Raises: - GitError: If pull fails. - """ - run("pull", cwd=repo_path, error_msg="Failed to pull repository") - - -def fetch_and_checkout(repo_path: pathlib.Path, ref: str) -> None: - """ - Fetch all remotes and checkout a specific ref. - - Args: - repo_path: Path to the git repository. - ref: Branch, tag, or commit to checkout. - - Raises: - GitError: If fetch or checkout fails. - """ - run("fetch", "--all", cwd=repo_path, error_msg="Failed to fetch from repository") - run("checkout", ref, cwd=repo_path, error_msg=f"Failed to checkout '{ref}'") diff --git a/weco/optimizer.py b/weco/optimizer.py index a0ce59a..a4ef8c9 100644 --- a/weco/optimizer.py +++ b/weco/optimizer.py @@ -24,6 +24,7 @@ submit_execution_result, ) from .auth import handle_authentication +from .events import get_event_context from .browser import open_browser from .ui import OptimizationUI, LiveOptimizationUI, PlainOptimizationUI from .utils import read_additional_instructions, read_from_path, write_to_path, run_evaluation_with_file_swap @@ -572,6 +573,9 @@ def optimize( } processed_instructions = read_additional_instructions(additional_instructions) + # Get event context for tracking + event_ctx = get_event_context() + # Start the run run_response = start_optimization_run( console=console, @@ -591,6 +595,9 @@ def optimize( auth_headers=auth_headers, api_keys=api_keys, require_review=require_review, + installation_id=event_ctx.installation_id, + invocation_id=event_ctx.invocation_id, + invoked_via=event_ctx.invoked_via, ) if run_response is None: diff --git a/weco/setup.py b/weco/setup.py index 7aa72f8..e2e7e81 100644 --- a/weco/setup.py +++ b/weco/setup.py @@ -3,14 +3,27 @@ Setup commands for integrating Weco with various AI tools. """ +import io import pathlib +import shutil import sys +import tempfile +import time +import zipfile +from urllib.error import HTTPError, URLError +from urllib.request import urlopen from rich.console import Console from rich.prompt import Confirm -from . import git -from .utils import copy_directory, copy_file, read_from_path, remove_directory, write_to_path +from .events import ( + send_event, + create_event_context, + SkillInstallStartedEvent, + SkillInstallCompletedEvent, + SkillInstallFailedEvent, +) +from .utils import copy_directory, copy_file, read_from_path, write_to_path # ============================================================================= @@ -30,15 +43,30 @@ class InvalidLocalRepoError(SetupError): pass +class DownloadError(SetupError): + """Raised when downloading the skill fails.""" + + pass + + +class SafetyError(SetupError): + """Raised when a safety check fails during directory operations.""" + + pass + + # ============================================================================= # Path constants # ============================================================================= +# Skill repository +WECO_SKILL_REPO_URL = "https://github.com/WecoAI/weco-skill" +WECO_SKILL_BRANCH = "main" + # Claude Code paths CLAUDE_DIR = pathlib.Path.home() / ".claude" CLAUDE_SKILLS_DIR = CLAUDE_DIR / "skills" WECO_SKILL_DIR = CLAUDE_SKILLS_DIR / "weco" -WECO_SKILL_REPO = "git@github.com:WecoAI/weco-skill.git" WECO_CLAUDE_SNIPPET_PATH = WECO_SKILL_DIR / "snippets" / "claude.md" WECO_CLAUDE_MD_PATH = WECO_SKILL_DIR / "CLAUDE.md" @@ -53,6 +81,88 @@ class InvalidLocalRepoError(SetupError): # Files/directories to skip when copying local repos _COPY_IGNORE_PATTERNS = {".git", "__pycache__", ".DS_Store"} +# Allowed parent directories for safe removal (defense in depth) +_ALLOWED_SKILL_PARENTS = {CLAUDE_SKILLS_DIR, CURSOR_SKILLS_DIR} + + +# ============================================================================= +# Safety utilities +# ============================================================================= + + +def safe_remove_directory(path: pathlib.Path, allowed_parents: set[pathlib.Path] | None = None) -> None: + """ + Safely remove a directory with multiple defensive checks. + + This function is paranoid by design to prevent accidental deletion of + important directories due to bugs, path traversal, or misconfiguration. + + Args: + path: The directory to remove. + allowed_parents: Optional set of allowed parent directories. If provided, + the path must be a direct child of one of these directories. + + Raises: + SafetyError: If any safety check fails. + """ + if allowed_parents is None: + allowed_parents = _ALLOWED_SKILL_PARENTS + + # Resolve to absolute path to prevent path traversal tricks + resolved_path = path.resolve() + + # Safety check 1: Path must exist (if not, nothing to do) + if not resolved_path.exists(): + return + + # Safety check 2: Must be a directory, not a file or symlink to file + if not resolved_path.is_dir(): + raise SafetyError(f"Refusing to remove: not a directory: {resolved_path}") + + # Safety check 3: Must not be a symlink (could point anywhere) + if resolved_path.is_symlink(): + raise SafetyError(f"Refusing to remove: path is a symlink: {resolved_path}") + + # Safety check 4: Must not be the home directory or root + home = pathlib.Path.home().resolve() + if resolved_path == home: + raise SafetyError(f"Refusing to remove: path is home directory: {resolved_path}") + if resolved_path == pathlib.Path("/").resolve(): + raise SafetyError(f"Refusing to remove: path is root directory: {resolved_path}") + + # Safety check 5: Must not be a parent of home directory + try: + home.relative_to(resolved_path) + raise SafetyError(f"Refusing to remove: path is a parent of home directory: {resolved_path}") + except ValueError: + pass # Good - resolved_path is not a parent of home + + # Safety check 6: Must be a direct child of one of the allowed parent directories + resolved_allowed = {p.resolve() for p in allowed_parents} + parent = resolved_path.parent + + if parent not in resolved_allowed: + raise SafetyError( + f"Refusing to remove: path {resolved_path} is not a direct child of allowed directories: " + f"{[str(p) for p in resolved_allowed]}" + ) + + # Safety check 7: Verify the path is exactly 1 level below the allowed parent + # This is redundant with check 6 but provides defense in depth + try: + relative = resolved_path.relative_to(parent) + if len(relative.parts) != 1: + raise SafetyError(f"Refusing to remove: path {resolved_path} is not exactly 1 level below parent {parent}") + except ValueError: + raise SafetyError(f"Refusing to remove: path {resolved_path} is not relative to any allowed parent") + + # Safety check 8: Directory name must be 'weco' (our expected skill directory name) + if resolved_path.name != "weco": + raise SafetyError(f"Refusing to remove: directory name is not 'weco': {resolved_path}") + + # All checks passed - safe to remove + shutil.rmtree(resolved_path) + # ============================================================================= # Domain helpers @@ -87,44 +197,132 @@ def validate_local_skill_repo(local_path: pathlib.Path) -> None: # ============================================================================= -# Installation functions +# Download functions # ============================================================================= -def install_skill_from_git(skill_dir: pathlib.Path, console: Console, repo_url: str | None, ref: str | None) -> None: +def get_zip_url() -> str: + """ + Build the GitHub zip download URL. + + Returns: + The zip download URL for the weco-skill repository. """ - Clone or update skill from git. + return f"{WECO_SKILL_REPO_URL}/archive/refs/heads/{WECO_SKILL_BRANCH}.zip" + + +def download_and_extract_zip(dest: pathlib.Path, console: Console) -> None: + """ + Download the weco-skill zip and extract its contents. + + GitHub archives have a single top-level directory (e.g., 'weco-skill-main/'), + so we extract that directory's contents directly to dest. + + Args: + dest: Destination directory for extracted contents. + console: Console for output. Raises: - git.GitNotFoundError: If git is not available. - git.GitError: If git operations fail. + DownloadError: If download or extraction fails. """ - if not git.is_available(): - raise git.GitNotFoundError("git is not installed or not in PATH") + url = get_zip_url() + console.print(f"[cyan]Downloading skill from {url}...[/]") + + try: + with urlopen(url, timeout=60) as response: + zip_data = io.BytesIO(response.read()) + except HTTPError as e: + raise DownloadError(f"Failed to download: HTTP {e.code} - {e.reason}") + except URLError as e: + raise DownloadError(f"Failed to download: {e.reason}") + except TimeoutError: + raise DownloadError("Failed to download: connection timed out") + except Exception as e: + raise DownloadError(f"Failed to download: {e}") + + try: + with zipfile.ZipFile(zip_data) as zf: + # GitHub zips have a single top-level dir like 'repo-branch/' + # Find it and extract contents to dest + top_level_dirs = {name.split("/")[0] for name in zf.namelist() if "/" in name} + + if len(top_level_dirs) != 1: + raise DownloadError("Unexpected zip structure: expected single top-level directory") + + top_dir = top_level_dirs.pop() + prefix = f"{top_dir}/" + + dest.mkdir(parents=True, exist_ok=True) + for member in zf.namelist(): + if not member.startswith(prefix): + continue + + # Strip the top-level directory prefix + relative_path = member[len(prefix) :] + if not relative_path: + continue + + target_path = dest / relative_path + + if member.endswith("/"): + target_path.mkdir(parents=True, exist_ok=True) + else: + target_path.parent.mkdir(parents=True, exist_ok=True) + with zf.open(member) as source, open(target_path, "wb") as target: + target.write(source.read()) + + console.print("[green]Skill downloaded and extracted successfully.[/]") + + except zipfile.BadZipFile: + raise DownloadError("Downloaded file is not a valid zip archive") + except DownloadError: + raise + except Exception as e: + raise DownloadError(f"Failed to extract zip: {e}") + + +# ============================================================================= +# Installation functions +# ============================================================================= + + +def install_skill_from_zip(skill_dir: pathlib.Path, console: Console) -> None: + """ + Download and install skill from GitHub zip archive. + + Downloads to a temporary directory first, validates the contents, + then moves to the final location for safer installation. + + Args: + skill_dir: Destination directory for the skill. + console: Console for output. + + Raises: + DownloadError: If download or extraction fails. + SafetyError: If directory removal fails safety checks. + """ skill_dir.parent.mkdir(parents=True, exist_ok=True) - if skill_dir.exists(): - if git.is_repo(skill_dir): - console.print(f"[cyan]Updating existing skill at {skill_dir}...[/]") - if ref: - git.fetch_and_checkout(skill_dir, ref) - console.print(f"[green]Checked out {ref}.[/]") - else: - git.pull(skill_dir) - console.print("[green]Skill updated successfully.[/]") - return + # Download to a temp location first for atomic replacement + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_path = pathlib.Path(tmp_dir) / "skill" - # Not a git repo — clear and re-clone - console.print(f"[cyan]Removing existing directory at {skill_dir}...[/]") - remove_directory(skill_dir) + download_and_extract_zip(tmp_path, console) - console.print(f"[cyan]Cloning Weco skill to {skill_dir}...[/]") - git.clone(repo_url or WECO_SKILL_REPO, skill_dir, ref=ref) - if ref: - console.print(f"[green]Cloned and checked out {ref}.[/]") - else: - console.print("[green]Skill cloned successfully.[/]") + # Validate before replacing + if not (tmp_path / "SKILL.md").exists(): + raise DownloadError("Downloaded content does not appear to be a valid weco-skill repository") + + # Now replace existing skill safely + if skill_dir.exists(): + console.print(f"[cyan]Replacing existing skill at {skill_dir}...[/]") + safe_remove_directory(skill_dir) + + # Move from temp to final location + shutil.move(str(tmp_path), str(skill_dir)) + + console.print("[green]Skill installed successfully.[/]") def install_skill_from_local(skill_dir: pathlib.Path, console: Console, local_path: pathlib.Path) -> None: @@ -133,6 +331,7 @@ def install_skill_from_local(skill_dir: pathlib.Path, console: Console, local_pa Raises: InvalidLocalRepoError: If local path is invalid. + SafetyError: If directory removal fails safety checks. OSError: If copy fails. """ validate_local_skill_repo(local_path) @@ -141,22 +340,18 @@ def install_skill_from_local(skill_dir: pathlib.Path, console: Console, local_pa if skill_dir.exists(): console.print(f"[cyan]Removing existing directory at {skill_dir}...[/]") - remove_directory(skill_dir) + safe_remove_directory(skill_dir) copy_directory(local_path, skill_dir, ignore_patterns=_COPY_IGNORE_PATTERNS) console.print(f"[green]Copied local repo from: {local_path}[/]") -def install_skill( - skill_dir: pathlib.Path, console: Console, local_path: pathlib.Path | None, repo_url: str | None, ref: str | None -) -> None: - """Install skill by copying from local path or cloning from git.""" +def install_skill(skill_dir: pathlib.Path, console: Console, local_path: pathlib.Path | None) -> None: + """Install skill by copying from local path or downloading from GitHub.""" if local_path: - if ref: - console.print("[bold yellow]Warning:[/] --ref is ignored when using --local") install_skill_from_local(skill_dir, console, local_path) else: - install_skill_from_git(skill_dir, console, repo_url, ref) + install_skill_from_zip(skill_dir, console) # ============================================================================= @@ -164,9 +359,7 @@ def install_skill( # ============================================================================= -def setup_claude_code( - console: Console, local_path: pathlib.Path | None = None, repo_url: str | None = None, ref: str | None = None -) -> None: +def setup_claude_code(console: Console, local_path: pathlib.Path | None = None) -> None: """Set up Weco skill for Claude Code.""" console.print("[bold blue]Setting up Weco for Claude Code...[/]\n") @@ -175,7 +368,7 @@ def setup_claude_code( # - `CLAUDE.md` lives *inside* that installed skill folder, so configuration is just # copying a file within the skill directory. # - There is no separate global config file to reconcile or prompt before overwriting. - install_skill(WECO_SKILL_DIR, console, local_path, repo_url, ref) + install_skill(WECO_SKILL_DIR, console, local_path) # Copy snippets/claude.md to CLAUDE.md (skip for local - user manages their own) if not local_path: @@ -188,9 +381,7 @@ def setup_claude_code( console.print(f"[dim]Skill installed at: {WECO_SKILL_DIR}[/]") -def setup_cursor( - console: Console, local_path: pathlib.Path | None = None, repo_url: str | None = None, ref: str | None = None -) -> None: +def setup_cursor(console: Console, local_path: pathlib.Path | None = None) -> None: """Set up Weco rules for Cursor.""" console.print("[bold blue]Setting up Weco for Cursor...[/]\n") @@ -202,7 +393,7 @@ def setup_cursor( # 1) compute desired content from the snippet # 2) check if it is already up to date # 3) prompt before creating/updating it - install_skill(CURSOR_WECO_SKILL_DIR, console, local_path, repo_url, ref) + install_skill(CURSOR_WECO_SKILL_DIR, console, local_path) snippet_content = read_from_path(CURSOR_RULES_SNIPPET_PATH) mdc_content = generate_cursor_mdc_content(snippet_content.strip()) @@ -257,6 +448,7 @@ def setup_cursor( def handle_setup_command(args, console: Console) -> None: """Handle the setup command with its subcommands.""" available_tools = ", ".join(SETUP_HANDLERS) + ctx = create_event_context() if args.tool is None: console.print("[bold red]Error:[/] Please specify a tool to set up.") @@ -270,26 +462,39 @@ def handle_setup_command(args, console: Console) -> None: console.print(f"Available tools: {available_tools}") sys.exit(1) - # Validate and extract args - repo_url = getattr(args, "repo", None) - ref = getattr(args, "ref", None) + # Extract local path if provided local_path = None if hasattr(args, "local") and args.local: local_path = pathlib.Path(args.local).expanduser().resolve() + # Determine source type for event reporting + source = "local" if local_path else "download" + + # Send skill install started event + send_event(SkillInstallStartedEvent(tool=args.tool, source=source), ctx) + + start_time = time.time() + try: - if repo_url: - git.validate_repo_url(repo_url) - if ref: - git.validate_ref(ref) + handler(console, local_path=local_path) - handler(console, local_path=local_path, repo_url=repo_url, ref=ref) + # Send successful completion event + duration_ms = int((time.time() - start_time) * 1000) + send_event(SkillInstallCompletedEvent(tool=args.tool, source=source, duration_ms=duration_ms), ctx) - except git.GitError as e: + except DownloadError as e: + # Send failure event + send_event(SkillInstallFailedEvent(tool=args.tool, source=source, error_type="download_error", stage="download"), ctx) console.print(f"[bold red]Error:[/] {e}") - if e.stderr: - console.print(f"[dim]{e.stderr}[/]") sys.exit(1) - except (SetupError, git.GitNotFoundError, FileNotFoundError, OSError, ValueError) as e: + except SafetyError as e: + # Send failure event + send_event(SkillInstallFailedEvent(tool=args.tool, source=source, error_type="safety_error", stage="setup"), ctx) + console.print(f"[bold red]Safety Error:[/] {e}") + sys.exit(1) + except (SetupError, FileNotFoundError, OSError, ValueError) as e: + # Send failure event + error_type = type(e).__name__ + send_event(SkillInstallFailedEvent(tool=args.tool, source=source, error_type=error_type, stage="setup"), ctx) console.print(f"[bold red]Error:[/] {e}") sys.exit(1)