Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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`

Expand Down
12 changes: 11 additions & 1 deletion weco/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
85 changes: 23 additions & 62 deletions weco/auth.py
Original file line number Diff line number Diff line change
@@ -1,76 +1,22 @@
# weco/auth.py
import os
import pathlib
import json
import stat
import time
import requests
import webbrowser
from rich.console import Console
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...")
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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}"
)
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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

Expand Down
50 changes: 40 additions & 10 deletions weco/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)"
)


Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
Loading