|
| 1 | +# weco/env.py |
| 2 | +"""High-level interface to the weco CLI environment. |
| 3 | +
|
| 4 | +Provides a single object that encapsulates version info, authentication |
| 5 | +state, installed skills, event context, and update checking. |
| 6 | +
|
| 7 | +Usage:: |
| 8 | +
|
| 9 | + env = WecoEnv(via_skill=args.via_skill) |
| 10 | + env.check_for_updates() |
| 11 | +
|
| 12 | + if env.is_authenticated: |
| 13 | + ... |
| 14 | +
|
| 15 | + send_event(SomeEvent(), env.event_context) |
| 16 | +""" |
| 17 | + |
| 18 | +import pathlib |
| 19 | +import time |
| 20 | +from dataclasses import dataclass |
| 21 | + |
| 22 | +import requests |
| 23 | +from packaging.version import parse as parse_version |
| 24 | + |
| 25 | +from . import __pkg_version__, __base_url__, __dashboard_url__ |
| 26 | +from .config import load_weco_api_key |
| 27 | +from .events import EventContext, create_event_context, set_event_context |
| 28 | + |
| 29 | + |
| 30 | +_UNSET = object() |
| 31 | + |
| 32 | +# Update checking |
| 33 | +_CLI_UPDATE_PYPI_URL = "https://pypi.org/pypi/weco/json" |
| 34 | + |
| 35 | + |
| 36 | +@dataclass(frozen=True) |
| 37 | +class InstalledSkill: |
| 38 | + """A locally installed weco skill.""" |
| 39 | + |
| 40 | + tool: str # "claude-code" or "cursor" |
| 41 | + path: pathlib.Path |
| 42 | + version: str # Installed skill version ("" if unknown) |
| 43 | + |
| 44 | + |
| 45 | +class WecoEnv: |
| 46 | + """High-level interface to the weco CLI environment. |
| 47 | +
|
| 48 | + Encapsulates version info, authentication state, installed skills, |
| 49 | + event context, and update checking behind a single object that CLI |
| 50 | + commands can depend on. |
| 51 | + """ |
| 52 | + |
| 53 | + # Read once at class-load time — these never change within a process. |
| 54 | + version: str = __pkg_version__ |
| 55 | + base_url: str = __base_url__ |
| 56 | + dashboard_url: str = __dashboard_url__ |
| 57 | + |
| 58 | + def __init__(self, via_skill: bool = False): |
| 59 | + self._via_skill = via_skill |
| 60 | + # _UNSET distinguishes "not yet loaded" from None ("no key configured"). |
| 61 | + self._api_key = _UNSET |
| 62 | + self._event_ctx: EventContext | None = None |
| 63 | + |
| 64 | + # ── Authentication ────────────────────────────────────────── |
| 65 | + |
| 66 | + @property |
| 67 | + def api_key(self) -> str | None: |
| 68 | + """Weco API key (loaded lazily from env var or credentials file).""" |
| 69 | + if self._api_key is _UNSET: |
| 70 | + self._api_key = load_weco_api_key() |
| 71 | + return self._api_key |
| 72 | + |
| 73 | + @property |
| 74 | + def is_authenticated(self) -> bool: |
| 75 | + """Whether a valid API key is available.""" |
| 76 | + return self.api_key is not None |
| 77 | + |
| 78 | + @property |
| 79 | + def auth_headers(self) -> dict[str, str]: |
| 80 | + """Authorization headers for API requests (empty if not authenticated).""" |
| 81 | + if self.api_key: |
| 82 | + return {"Authorization": f"Bearer {self.api_key}"} |
| 83 | + return {} |
| 84 | + |
| 85 | + def clear_cached_api_key(self) -> None: |
| 86 | + """Reset the cached API key so it will be re-loaded on next access.""" |
| 87 | + self._api_key = _UNSET |
| 88 | + |
| 89 | + # ── Installed Skills ──────────────────────────────────────── |
| 90 | + |
| 91 | + @property |
| 92 | + def installed_skills(self) -> list[InstalledSkill]: |
| 93 | + """Discover locally installed weco skills.""" |
| 94 | + from .setup import WECO_SKILL_DIR, CURSOR_WECO_SKILL_DIR |
| 95 | + |
| 96 | + skills = [] |
| 97 | + for tool, path in [("claude-code", WECO_SKILL_DIR), ("cursor", CURSOR_WECO_SKILL_DIR)]: |
| 98 | + if path.exists(): |
| 99 | + version = "" |
| 100 | + try: |
| 101 | + version = (path / "VERSION").read_text().strip() |
| 102 | + except (OSError, FileNotFoundError): |
| 103 | + pass |
| 104 | + skills.append(InstalledSkill(tool=tool, path=path, version=version)) |
| 105 | + return skills |
| 106 | + |
| 107 | + # ── Event Context ─────────────────────────────────────────── |
| 108 | + |
| 109 | + @property |
| 110 | + def event_context(self) -> EventContext: |
| 111 | + """Event context for this CLI invocation (created lazily). |
| 112 | +
|
| 113 | + Also sets the module-level global so that code using |
| 114 | + ``get_event_context()`` continues to work. |
| 115 | + """ |
| 116 | + if self._event_ctx is None: |
| 117 | + self._event_ctx = create_event_context(via_skill=self._via_skill) |
| 118 | + set_event_context(self._event_ctx) |
| 119 | + return self._event_ctx |
| 120 | + |
| 121 | + # ── Update Checking ───────────────────────────────────────── |
| 122 | + |
| 123 | + def check_for_updates(self) -> None: |
| 124 | + """Check for CLI package and skill updates. |
| 125 | +
|
| 126 | + Prints a yellow warning and pauses briefly for each available |
| 127 | + update. Fails silently — never disrupts the user. |
| 128 | + """ |
| 129 | + self._check_cli_updates() |
| 130 | + self._check_skill_updates() |
| 131 | + |
| 132 | + def _check_cli_updates(self) -> None: |
| 133 | + """Check PyPI for a newer CLI version.""" |
| 134 | + try: |
| 135 | + response = requests.get(_CLI_UPDATE_PYPI_URL, timeout=5) |
| 136 | + response.raise_for_status() |
| 137 | + latest_version_str = response.json()["info"]["version"] |
| 138 | + |
| 139 | + if parse_version(latest_version_str) > parse_version(self.version): |
| 140 | + _print_update_warning( |
| 141 | + f"New Weco CLI version ({latest_version_str}) available (you have {self.version}). Run: pipx upgrade weco" |
| 142 | + ) |
| 143 | + except Exception: |
| 144 | + pass |
| 145 | + |
| 146 | + def _check_skill_updates(self) -> None: |
| 147 | + """Check the Weco API for a newer skill version.""" |
| 148 | + try: |
| 149 | + if not self.installed_skills: |
| 150 | + return |
| 151 | + |
| 152 | + skill = self.installed_skills[0] |
| 153 | + |
| 154 | + response = requests.get(f"{self.base_url}/version", timeout=5) |
| 155 | + if response.status_code != 200: |
| 156 | + return |
| 157 | + |
| 158 | + latest_version = response.json().get("latest_skill_version", "") |
| 159 | + if not latest_version: |
| 160 | + return |
| 161 | + |
| 162 | + # If installed skill has no version (pre-VERSION file install), always prompt to update |
| 163 | + if not skill.version: |
| 164 | + commands = ", ".join(f"weco setup {s.tool}" for s in self.installed_skills) |
| 165 | + _print_update_warning(f"New weco skill version ({latest_version}) available. Run: {commands}") |
| 166 | + return |
| 167 | + |
| 168 | + if parse_version(latest_version) > parse_version(skill.version): |
| 169 | + commands = ", ".join(f"weco setup {s.tool}" for s in self.installed_skills) |
| 170 | + _print_update_warning( |
| 171 | + f"New weco skill version ({latest_version}) available (you have {skill.version}). Run: {commands}" |
| 172 | + ) |
| 173 | + except Exception: |
| 174 | + pass |
| 175 | + |
| 176 | + |
| 177 | +def _print_update_warning(message: str) -> None: |
| 178 | + """Print a yellow warning and pause briefly so the user sees it.""" |
| 179 | + print(f"\033[93m{message}\033[0m") |
| 180 | + time.sleep(2) |
0 commit comments