Try to auto-discover Bay API key from credentials.json. Search order: 1. BAY_DATA_DIR env var 2. Mono-repo relative path: ../pkgs/bay/ (dev layout) 3. Current working directory Returns: API key string, or empty string if not found.
(endpoint: str)
| 132 | |
| 133 | |
| 134 | def _discover_bay_credentials(endpoint: str) -> str: |
| 135 | """Try to auto-discover Bay API key from credentials.json. |
| 136 | |
| 137 | Search order: |
| 138 | 1. BAY_DATA_DIR env var |
| 139 | 2. Mono-repo relative path: ../pkgs/bay/ (dev layout) |
| 140 | 3. Current working directory |
| 141 | |
| 142 | Returns: |
| 143 | API key string, or empty string if not found. |
| 144 | """ |
| 145 | candidates: list[Path] = [] |
| 146 | |
| 147 | # 1. BAY_DATA_DIR env var |
| 148 | bay_data_dir = os.environ.get("BAY_DATA_DIR") |
| 149 | if bay_data_dir: |
| 150 | candidates.append(Path(bay_data_dir) / "credentials.json") |
| 151 | |
| 152 | # 2. Mono-repo layout: AstrBot/../pkgs/bay/credentials.json |
| 153 | astrbot_root = Path(__file__).resolve().parents[3] # astrbot/core/computer/ → root |
| 154 | candidates.append(astrbot_root.parent / "pkgs" / "bay" / "credentials.json") |
| 155 | |
| 156 | # 3. Current working directory |
| 157 | candidates.append(Path.cwd() / "credentials.json") |
| 158 | |
| 159 | for cred_path in candidates: |
| 160 | if not cred_path.is_file(): |
| 161 | continue |
| 162 | try: |
| 163 | data = json.loads(cred_path.read_text()) |
| 164 | api_key = data.get("api_key", "") |
| 165 | if api_key: |
| 166 | # Optionally verify endpoint matches |
| 167 | cred_endpoint = data.get("endpoint", "") |
| 168 | if ( |
| 169 | cred_endpoint |
| 170 | and endpoint |
| 171 | and cred_endpoint.rstrip("/") != endpoint.rstrip("/") |
| 172 | ): |
| 173 | logger.warning( |
| 174 | "[Computer] credentials.json endpoint mismatch: " |
| 175 | "file=%s, configured=%s — using key anyway", |
| 176 | cred_endpoint, |
| 177 | endpoint, |
| 178 | ) |
| 179 | masked_key = f"{api_key[:4]}..." if len(api_key) >= 6 else "redacted" |
| 180 | logger.info( |
| 181 | "[Computer] Auto-discovered Bay API key from %s (prefix=%s)", |
| 182 | cred_path, |
| 183 | masked_key, |
| 184 | ) |
| 185 | return api_key |
| 186 | except (json.JSONDecodeError, OSError) as exc: |
| 187 | logger.debug("[Computer] Failed to read %s: %s", cred_path, exc) |
| 188 | |
| 189 | logger.debug("[Computer] No Bay credentials.json found in search paths") |
| 190 | return "" |
| 191 |