Clipador em inglês (doc/clipador/IDIOMAS.md):
- Fonte en-US: analista, editor e varredura com prompts, glossário de chat e saída em inglês;
a mesma resposta traz o bloco `pt` (tradução para o painel, sem chamada extra).
- Fala do corte traduzida por frase (clips.translation_json, migração v13) e
POST /v1/clips/{id}/translate.
- caption.translation (só para desenvolver): português embaixo da legenda em inglês.
- Risada e gírias do chat em inglês na heurística (LMAO, LOL, 💀, 😭, no way, bruh...).
- Idioma do público → código do Whisper (en-US dava 422 no serviço de voz).
- Painel: bloco "Em português" no corte, análise/resumo em PT, título traduzido na lista,
coluna "Ao vivo" mostra a gravação ativa da fonte.
IA: monitor de uso do limite (ai-usage) e 4º provedor (Antigravity CLI).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
274 lines
12 KiB
Python
274 lines
12 KiB
Python
"""Configuração das IAs (Claude, Codex, Gemini) compartilhada com o painel — contrato em `doc/ia.md`.
|
|
|
|
O painel (Configurações → IA) escreve dois arquivos em `data/ai/`; o Clipador só LÊ:
|
|
- `settings.json` (sem segredo): quais IAs estão ligadas, modo de login (`oauth`/`apiKey`), ordem da reserva e
|
|
pausa depois de uma falha de indisponibilidade. Relido quando o `mtime` muda; ausente/inválido = padrão.
|
|
- `vault.bin`: as chaves de API, JSON cifrado com a DPAPI do Windows (usuário atual, entropia própria).
|
|
|
|
Daqui sai o ambiente (`env`) de cada chamada de CLI: no modo chave, a variável da chave só vale para a chamada;
|
|
no modo login, a variável é removida para a CLI usar a sessão já logada. O login global de cada CLI não muda.
|
|
|
|
Nos testes, a pasta e o cifrador são injetados (`AiConfig(folder, cipher=...)`); a DPAPI real só existe no Windows.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
import json
|
|
import logging
|
|
import os
|
|
import sys
|
|
import threading
|
|
import time
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
from typing import Protocol
|
|
|
|
from .config import REPO_ROOT
|
|
|
|
log = logging.getLogger("cenaforge_clipper.ai_settings")
|
|
|
|
AI_PROVIDERS = ("claude", "codex", "gemini")
|
|
# Pasta padrão dos arquivos do painel. Os testes trocam (conftest) para não ler o data/ai real.
|
|
DEFAULT_AI_DIR = REPO_ROOT / "data" / "ai"
|
|
# Leitura de uso mais velha que isso não decide (o painel relê a cada 5 min).
|
|
USAGE_STALE_S = 30 * 60
|
|
AUTH_MODES = ("oauth", "apiKey")
|
|
DEFAULT_COOLDOWN_MIN = 15.0
|
|
DEFAULT_SETTINGS: dict = {
|
|
"version": 1,
|
|
"providers": {
|
|
"claude": {"enabled": True, "authMode": "oauth"},
|
|
"codex": {"enabled": True, "authMode": "oauth"},
|
|
"gemini": {"enabled": False, "authMode": "apiKey"},
|
|
},
|
|
"order": ["claude", "codex", "gemini"],
|
|
"fallback": {"enabled": True, "cooldownMin": DEFAULT_COOLDOWN_MIN},
|
|
}
|
|
# Variável de ambiente da chave de API de cada CLI (tabela "Ambiente de cada chamada" do doc/ia.md).
|
|
API_KEY_ENV = {"claude": "ANTHROPIC_API_KEY", "codex": "CODEX_API_KEY", "gemini": "GEMINI_API_KEY"}
|
|
GEMINI_OAUTH_ENV = "GOOGLE_GENAI_USE_GCA"
|
|
|
|
# Entropia do cofre de IA (a mesma que o painel usa ao cifrar). Não é senha: só separa este cofre dos outros.
|
|
_VAULT_ENTROPY = b"CenaForge.AI.vault.v1"
|
|
|
|
|
|
class AiVaultError(RuntimeError):
|
|
"""O cofre de IA não abriu (outro usuário/máquina, corrompido, ou DPAPI indisponível)."""
|
|
|
|
|
|
class Cipher(Protocol):
|
|
def unprotect(self, data: bytes) -> bytes: ...
|
|
|
|
|
|
class DpapiCipher:
|
|
"""DPAPI via ctypes (crypt32.dll), só a decifragem — quem cifra é o painel. Mesmo padrão de
|
|
`publisher/app/vault.py` (pacotes separados: o código é copiado, não importado)."""
|
|
|
|
CRYPTPROTECT_UI_FORBIDDEN = 0x01
|
|
|
|
def __init__(self, entropy: bytes = _VAULT_ENTROPY) -> None:
|
|
if sys.platform != "win32":
|
|
raise AiVaultError("O cofre de IA usa a DPAPI do Windows; este sistema não tem.")
|
|
import ctypes
|
|
from ctypes import wintypes
|
|
|
|
class DataBlob(ctypes.Structure):
|
|
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
|
|
|
|
self._entropy = entropy
|
|
self._ctypes = ctypes
|
|
self._blob = DataBlob
|
|
self._crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
|
|
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
self._kernel32.LocalFree.argtypes = [ctypes.c_void_p]
|
|
self._kernel32.LocalFree.restype = ctypes.c_void_p
|
|
fn = self._crypt32.CryptUnprotectData
|
|
fn.argtypes = [ctypes.POINTER(DataBlob), ctypes.c_void_p, ctypes.POINTER(DataBlob), ctypes.c_void_p,
|
|
ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(DataBlob)]
|
|
fn.restype = wintypes.BOOL
|
|
|
|
def _to_blob(self, data: bytes):
|
|
buffer = self._ctypes.create_string_buffer(data, len(data))
|
|
blob = self._blob(len(data), self._ctypes.cast(buffer, self._ctypes.POINTER(self._ctypes.c_char)))
|
|
return blob, buffer # o buffer precisa continuar vivo enquanto o blob for usado
|
|
|
|
def unprotect(self, data: bytes) -> bytes:
|
|
ctypes = self._ctypes
|
|
in_blob, _keep_in = self._to_blob(data)
|
|
entropy, _keep_entropy = self._to_blob(self._entropy)
|
|
out_blob = self._blob()
|
|
ok = self._crypt32.CryptUnprotectData(ctypes.byref(in_blob), None, ctypes.byref(entropy), None, None,
|
|
self.CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out_blob))
|
|
if not ok:
|
|
raise AiVaultError(f"A DPAPI do Windows não conseguiu abrir o cofre de IA (erro {ctypes.get_last_error()}). "
|
|
"O arquivo pode ser de outro usuário ou de outro computador.")
|
|
try:
|
|
return ctypes.string_at(out_blob.pbData, out_blob.cbData)
|
|
finally:
|
|
self._kernel32.LocalFree(out_blob.pbData)
|
|
|
|
|
|
def normalize_settings(raw: object) -> dict:
|
|
"""Valida o settings.json do painel campo a campo. O que faltar ou vier errado fica no padrão do doc."""
|
|
settings = copy.deepcopy(DEFAULT_SETTINGS)
|
|
if not isinstance(raw, dict):
|
|
return settings
|
|
providers = raw.get("providers")
|
|
if isinstance(providers, dict):
|
|
for name in AI_PROVIDERS:
|
|
item = providers.get(name)
|
|
if not isinstance(item, dict):
|
|
continue
|
|
if isinstance(item.get("enabled"), bool):
|
|
settings["providers"][name]["enabled"] = item["enabled"]
|
|
if item.get("authMode") in AUTH_MODES:
|
|
settings["providers"][name]["authMode"] = item["authMode"]
|
|
order = raw.get("order")
|
|
if isinstance(order, list):
|
|
known = [p for p in dict.fromkeys(order) if p in AI_PROVIDERS]
|
|
# Quem ficou de fora da lista vai para o fim, na ordem padrão (a lista sempre tem as três).
|
|
settings["order"] = known + [p for p in AI_PROVIDERS if p not in known]
|
|
fallback = raw.get("fallback")
|
|
if isinstance(fallback, dict):
|
|
if isinstance(fallback.get("enabled"), bool):
|
|
settings["fallback"]["enabled"] = fallback["enabled"]
|
|
cooldown = fallback.get("cooldownMin")
|
|
if isinstance(cooldown, (int, float)) and not isinstance(cooldown, bool) and cooldown >= 0:
|
|
settings["fallback"]["cooldownMin"] = float(cooldown)
|
|
return settings
|
|
|
|
|
|
def _mtime(path: Path) -> int | None:
|
|
try:
|
|
return path.stat().st_mtime_ns
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
class AiConfig:
|
|
"""Leitura (com cache por mtime) do settings.json e do vault.bin do painel."""
|
|
|
|
def __init__(self, folder: Path | None = None, cipher: Cipher | None = None,
|
|
environ: dict[str, str] | None = None):
|
|
self.folder = Path(folder) if folder is not None else DEFAULT_AI_DIR
|
|
self._cipher = cipher
|
|
self._environ = environ # None = os.environ do momento da chamada
|
|
self._lock = threading.RLock()
|
|
self._settings_cache: tuple[int | None, dict] | None = None
|
|
self._keys_cache: tuple[int | None, dict[str, str]] | None = None
|
|
self.vault_error: str | None = None
|
|
|
|
@property
|
|
def settings_path(self) -> Path:
|
|
return self.folder / "settings.json"
|
|
|
|
@property
|
|
def vault_path(self) -> Path:
|
|
return self.folder / "vault.bin"
|
|
|
|
def settings(self) -> dict:
|
|
"""Configuração atual (cópia). Relê o arquivo só quando o mtime muda."""
|
|
with self._lock:
|
|
stamp = _mtime(self.settings_path)
|
|
if self._settings_cache is None or self._settings_cache[0] != stamp:
|
|
raw: object = None
|
|
if stamp is not None:
|
|
try:
|
|
raw = json.loads(self.settings_path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError) as exc:
|
|
log.warning("data/ai/settings.json inválido (%s); usando o padrão", exc)
|
|
self._settings_cache = (stamp, normalize_settings(raw))
|
|
return copy.deepcopy(self._settings_cache[1])
|
|
|
|
def provider(self, name: str) -> dict:
|
|
return self.settings()["providers"].get(name, {"enabled": False, "authMode": "oauth"})
|
|
|
|
@property
|
|
def usage_path(self) -> Path:
|
|
return self.folder / "usage.json"
|
|
|
|
def over_limit(self, provider: str, now: float | None = None) -> str | None:
|
|
"""Motivo para a IA sair da frente pelo USO (None = livre), lido de data/ai/usage.json, que o painel grava
|
|
a cada 5 min (Claude pelo /usage, Codex pelo app-server; ver doc/ia.md). Mesma regra do painel
|
|
(`overLimit` em lib/ai.ts): bateu o limite, ou uma janela ainda valendo em `limitPercent` ou mais.
|
|
Leitura com mais de 30 min, arquivo ausente ou inválido: não decide nada."""
|
|
now = time.time() if now is None else now
|
|
try:
|
|
data = json.loads(self.usage_path.read_text(encoding="utf-8"))
|
|
usage = data["providers"][provider]
|
|
at = datetime.fromisoformat(str(usage["at"]).replace("Z", "+00:00")).timestamp()
|
|
except (OSError, ValueError, KeyError, TypeError):
|
|
return None
|
|
if now - at > USAGE_STALE_S:
|
|
return None
|
|
live = []
|
|
for window in usage.get("windows") or []:
|
|
resets = window.get("resetsAt")
|
|
try:
|
|
if resets and datetime.fromisoformat(str(resets).replace("Z", "+00:00")).timestamp() <= now:
|
|
continue
|
|
live.append((str(window.get("label", "janela")), float(window.get("usedPercent", 0))))
|
|
except (ValueError, TypeError):
|
|
continue
|
|
hit = [label for label, used in live if used >= 100]
|
|
if usage.get("blocked") and hit:
|
|
return f"bateu o limite ({', '.join(hit)})"
|
|
try:
|
|
limit = float(data.get("limitPercent", 90))
|
|
except (TypeError, ValueError):
|
|
limit = 90.0
|
|
hot = sorted((w for w in live if w[1] >= limit), key=lambda w: -w[1])
|
|
return f"{hot[0][0]} em {round(hot[0][1])}% (limite {round(limit)}%)" if hot else None
|
|
|
|
def api_keys(self) -> dict[str, str]:
|
|
"""Chaves do cofre (só as que existem). Cofre ausente = {}; cofre que não abre = {} e `vault_error`."""
|
|
with self._lock:
|
|
stamp = _mtime(self.vault_path)
|
|
if self._keys_cache is None or self._keys_cache[0] != stamp:
|
|
self._keys_cache = (stamp, self._read_vault() if stamp is not None else {})
|
|
if stamp is None:
|
|
self.vault_error = None
|
|
return dict(self._keys_cache[1])
|
|
|
|
def _read_vault(self) -> dict[str, str]:
|
|
try:
|
|
raw = self.vault_path.read_bytes()
|
|
if not raw:
|
|
self.vault_error = None
|
|
return {}
|
|
cipher = self._cipher or DpapiCipher()
|
|
data = json.loads(cipher.unprotect(raw).decode("utf-8"))
|
|
except Exception as exc: # noqa: BLE001 - cofre ilegível não derruba o juiz: segue sem chaves
|
|
self.vault_error = str(exc)[:200] or "cofre de IA ilegível"
|
|
log.warning("não abri data/ai/vault.bin: %s", self.vault_error)
|
|
return {}
|
|
self.vault_error = None
|
|
if not isinstance(data, dict):
|
|
return {}
|
|
return {k: v.strip() for k, v in data.items() if k in AI_PROVIDERS and isinstance(v, str) and v.strip()}
|
|
|
|
def has_key(self, provider: str) -> bool:
|
|
return bool(self.api_keys().get(provider))
|
|
|
|
def provider_env(self, provider: str) -> dict[str, str]:
|
|
"""Ambiente da chamada da CLI de `provider`, conforme o modo de login (tabela do doc/ia.md)."""
|
|
env = dict(os.environ if self._environ is None else self._environ)
|
|
key_var = API_KEY_ENV.get(provider)
|
|
if not key_var:
|
|
return env
|
|
mode = self.provider(provider).get("authMode", "oauth")
|
|
if mode == "apiKey":
|
|
key = self.api_keys().get(provider)
|
|
if key:
|
|
env[key_var] = key
|
|
else:
|
|
env.pop(key_var, None)
|
|
if provider == "gemini":
|
|
env.pop(GEMINI_OAUTH_ENV, None)
|
|
else:
|
|
env.pop(key_var, None)
|
|
if provider == "gemini":
|
|
env[GEMINI_OAUTH_ENV] = "true"
|
|
return env
|