Clipador: fontes em inglês (juízes em inglês, painel em português) e monitor de uso da IA

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>
This commit is contained in:
2026-11-18 03:07:09 -03:00
co-authored by Claude Opus 5.5
parent ed31d52df0
commit 20a9805d2a
52 changed files with 1808 additions and 311 deletions
+26
View File
@@ -7,6 +7,32 @@ Versão semântica da **skill** (não do projeto):
Mantido pelo subagente `cenaforge-skill-updater`. Entradas mais novas no topo.
## 1.53.0 — 18/11/2026
IA: monitor de uso do limite e 4º provedor (Antigravity CLI).
- `references/ai.md`: seções "Monitor de uso e limite" (leituras sem gastar token, `overLimit`, `usage.json`, `over_limit` no
Clipador, regra de "pronta") e "Antigravity (`agy`)"; tabela "Onde mexer" com `ai-usage.ts`, `antigravityArgs`, ação `usage`.
- `references/gotchas.md`: 175 (OAuth do Gemini, AI Pro/Ultra), 176 (`/usage` no Git Bash), 177 (permissões do `agy`),
178 (handshake do `codex app-server`), 179 (IA "pronta" sem estar).
- `references/tools.md`: Antigravity CLI como candidata (1.5.10, desligada, sem tarefa real); `references/panel.md`: 4 provedores.
- `SKILL.md`: versão, `description`, linha "IA" em "Onde mexer", faixa de itens.
- Evidência: `pnpm --filter cenaforge-panel run test:panel` 117/117 (reexecutado); `agy` 1.5.10, `claude` 2.1.314,
`codex-cli` 0.169.0 (`--version`). Informado, não reexecutado: `ai.test.ts` 30, Clipador 346, leituras reais de uso, "Testar"
do Antigravity em 15 s. Não verificado: troca antecipada em tarefa real, UI no navegador, Gemini com chave.
## 1.52.0 — 18/11/2026
Clipador: fontes em inglês (vídeo em inglês, equipe vê português).
- `references/clipper.md`: banco em v13 (`clips.translation_json`); linha "Onde mexer" e seção "Fonte em inglês" (prompts `*_EN`,
bloco `pt` na mesma chamada, `translate_clip`/`translate_lines`, `caption.translation` com estilo `Trans`, `scoring.py` em
inglês, `voice_language`, como começar uma fonte gringa, painel); "Idioma" e "Testes e evidência" atualizados.
- `references/gotchas.md`: 173 (`en-US` voltava 422 no serviço de voz) e 174 (coluna "Ao vivo" com checagem velha).
- `references/panel.md`: linhas de `/clipper` e `/clipper/sources`.
- `SKILL.md`: versão, `description` (fonte em inglês), linha do Clipador, faixa de itens.
- Evidência: `pnpm test:clipper` → 346 passed (reexecutado, 101 s); conferidos no código `VOICE_LANGUAGES`, migração v13,
`caption.translation`, estilo `Trans`, `Intel.lang`, rota `translate`; corte 259 (sessão 15, Tfue) informado, não reexecutado.
Não verificado: IA real, painel no navegador, `pnpm typecheck`.
## 1.51.0 — 18/11/2026
IA: três provedores (Claude Code, Codex, Gemini CLI), login ou chave de API no cofre e IA reserva.
File diff suppressed because one or more lines are too long
+36 -10
View File
@@ -1,17 +1,18 @@
# IA: três provedores, login/chave e IA reserva
# IA: provedores, login/chave, IA reserva e monitor de uso
Fonte do contrato: **`doc/ia.md`** (arquivos, ambiente de cada chamada, o que conta como indisponível, Gemini
headless). Não duplique aqui; este arquivo diz onde mexer e o que não quebrar. Sempre pela **CLI oficial**
(`claude`, `codex`, `gemini`), nunca SDK/HTTP direto.
(`claude`, `codex`, `gemini`, `agy`), nunca SDK/HTTP direto. `antigravity` é o 4º provedor (começa **desligado**).
## Onde mexer
| Mudança | Arquivo(s) | Também atualizar |
|---|---|---|
| Configurações, cofre, detecção, instalação, login, teste, `providerEnv`, `isAvailabilityError`, pausa, `readyChain`/`nextFallback` | `panel/src/lib/ai.ts` | `panel/src/lib/ai.test.ts`, `doc/ia.md` |
| Agente do painel por provedor (`geminiArgs`, `normalizeGemini`, `--resume`, shell liberado), troca de IA ao cair | `panel/src/lib/agents.ts` (`prompts.ts`, `types.ts` para `AgentProvider`) | `ai.test.ts` (argumentos e eventos do Gemini) |
| Agente do painel por provedor (`geminiArgs`, `normalizeGemini`, `antigravityArgs`, `normalizeAntigravity`, `--resume`/`--conversation`, shell liberado), troca de IA ao cair | `panel/src/lib/agents.ts` (`prompts.ts`, `types.ts` para `AgentProvider`) | `ai.test.ts` (argumentos e eventos do Gemini) |
| Execução que continua outra que caiu | coluna `agent_runs.fallback_of` (migração v10 em `panel/src/lib/db.ts`), `followUpRunOf` (segue `resume_of` **e** `fallback_of`) | `publishing-db.test.ts` (conta de migrações) |
| API | `panel/src/app/api/ai/route.ts` (`GET/PUT /api/ai`), `.../ai/[provider]/route.ts` (`POST {action: install\|login\|verify\|test\|resume}`, `PUT/DELETE` = chave) | guarda `Origin`/JSON (gotchas, item 125) |
| Monitor de uso (leitura sem gastar token, `overLimit`, `usage.json`) | `panel/src/lib/ai-usage.ts` (`refreshUsage`, `ensureUsageMonitor`, `normalizeClaude`), `overLimit` em `lib/ai.ts`; `refreshUsage({maxAgeMs: 60_000})` nos 4 pontos que chamam `startRun` (`actions.ts`, `api/agent/runs`, `api/stories`, `api/characters/[id]/agent`); juiz: `AiConfig.over_limit` em `clipper/app/ai_settings.py` | `ai.test.ts`, `test_ai_fallback.py`, `doc/ia.md` |
| API | `panel/src/app/api/ai/route.ts` (`GET/PUT /api/ai`), `.../ai/[provider]/route.ts` (`POST {action: install\|login\|verify\|test\|resume\|usage}`, `PUT/DELETE` = chave) | guarda `Origin`/JSON (gotchas, item 125) |
| Tela | `panel/src/components/ai-settings.tsx` em `panel/src/app/settings/ai/page.tsx`; seletor de provedor em `agent-console.tsx` e `story-composer.tsx` | — |
| Subpáginas de Configurações | `panel/src/app/settings/{ai,publishing,apps,browser,modes}/page.tsx` + `layout.tsx`; seções em `SETTINGS_SECTIONS` de `components/settings-shell.tsx` (o menu lateral `sidebar-nav.tsx` as lê como `children`); `/settings` redireciona para `/settings/ai` | seção nova = entrada em `SETTINGS_SECTIONS` + pasta |
| Juiz do Clipador (3 provedores, reserva por chamada) | `clipper/app/judge.py` (`_gemini`, `find_gemini`, `parse_gemini_output`), leitura de settings e cofre `clipper/app/ai_settings.py` (DPAPI por `ctypes`), `main.py`, `config.py`, `intel.py` | `clipper/tests/test_ai_fallback.py`, `conftest.py`, `clipper/README.md` |
@@ -33,12 +34,37 @@ headless). Não duplique aqui; este arquivo diz onde mexer e o que não quebrar.
- Instalação: Claude pelo instalador nativo (`irm https://claude.ai/install.ps1 | iex`); Codex e Gemini por
`npm install -g`. O painel procura também em `~/.local/bin` e `%APPDATA%\npm`.
## Monitor de uso e limite
- **Leituras sem gastar token** (`ai-usage.ts`): Claude `claude -p "/usage"` (texto, US$ 0, modelo `<synthetic>`) e
`rate_limit_event` de cada execução (`normalizeClaude`); Codex `codex app-server` (`account/rateLimits/read`);
Antigravity `agy -p "/usage" --output-format stream-json`. **Gemini CLI: sem leitura**, só reativo (429).
- Renova a cada 5 min (`ensureUsageMonitor`, ligado pelo `GET /api/ai`) e antes de cada tarefa (`maxAgeMs: 60_000`).
- `overLimit` (`lib/ai.ts`): a IA bateu o limite, ou janela ainda valendo >= `fallback.usageLimitPercent` (padrão 90,
faixa 50-100). Leitura com mais de 30 min não decide. `startRun` troca para a próxima IA livre; **em retomada
(`resume`) não troca**.
- O painel escreve `data/ai/usage.json`; o Clipador lê por `AiConfig.over_limit` e põe a IA acima do limite depois das
livres em `fallback_chain`. UI: bloco "Uso do limite" por cartão, campo do limite no cartão da reserva,
`POST /api/ai/[provider] {action:"usage"}`.
- **Pronta:** IA cujo último teste falhou por indisponibilidade (login/cota) **não** é "pronta"; Gemini em modo conta só
conta como pronto depois de um teste que passou. "Testar" continua habilitado.
## Antigravity (`agy`)
- `agy.exe` em `~/.gemini/bin` (fora do PATH; `AGY_BIN` sobrescreve). Sem instalador por linha de comando
(`install.command` null; a UI mostra o site). Login conferido por `agy models`; atualizar = `agy update`.
- Agente: `agy -p <prompt> --output-format stream-json --mode accept-edits [--conversation <id>]`; shell **só** por regra
exata `command(<linha>)` via `--settings` (gotchas 177). Eventos e formatos: `doc/ia.md`, "Antigravity no painel".
- Começa desligado. **Aviso de termos:** a FAQ do Google diz que embrulhar o `agy` em programa de terceiro "não é
suportado" nos planos pessoais; a decisão de ligar é do usuário. O juiz do Clipador **não** usa antigravity.
## Estado verificado (18/11/2026)
- Nesta máquina: `claude` 2.1.314 e `codex` 0.169.0 (`--version` reconferido pela skill); `gemini` **não instalado**
(`command not found`).
- `pnpm --filter cenaforge-panel test:panel` inclui `ai.test.ts`: 21 testes, 21 passaram (reexecutado pela skill; um
usa a DPAPI real). Clipador: `pnpm test:clipper` → 335 passed (reexecutado). Suíte do painel 104/104: informada.
Ida e volta real do cofre painel → Clipador: informada, não repetida.
- Nesta máquina: `claude` 2.1.314, `codex` 0.169.0, `agy` 1.5.10 (`--version` reconferido); `gemini` **não instalado**.
- `pnpm --filter cenaforge-panel run test:panel`: 117/117 (reexecutado pela skill). `ai.test.ts` 30 testes (informado).
Clipador: 346 passed (informado; reexecutado na 1.52.0).
- Leituras reais informadas: Claude 4% / 67%; Codex janela de 5 h em 100% (`rate_limit_reached`), semanal 29%;
Antigravity 12% / 5%. "Testar" do Antigravity respondeu "ok" em 15 s.
- **Não verificado:** Gemini com chave real, `@arquivo` de imagem no juiz, envelope de erro do `-o json`, a UI
`/settings/ai` no navegador, troca de IA no meio de um agente real. Armadilhas: gotchas, itens 168–172.
`/settings/ai` no navegador, troca de IA no meio de um agente real, troca antecipada por `overLimit` em tarefa real.
Armadilhas: gotchas, itens 168-172 e 175-179.
+44 -3
View File
@@ -12,7 +12,7 @@ renderiza cortes verticais (1080×1920, padrão) ou horizontais (1920×1080, You
| O quê | Onde |
|---|---|
| Banco do Clipador | `data/clipper/clipper.db` (`PRAGMA user_version` 12, `SCHEMA` em `clipper/app/db.py`: v1 tabelas, v2 `settings`, v3 jogo/varredura/emotes/configuração do corte — colunas novas em `sessions`, `channels.settings_json`, `chat.emotes`, `clips.learned`, tabelas `games` e `emotes`; v4 `edits` (`clip_id`, `project_json`, `rev`, `cover`, `exported_at`, `created_at`, `updated_at`); v5 `face_track`; v6 `games.notes_json`/`games.edited_at`; v7 `edits.origin` (`ai`/`user`) + `edits.ai_project_json`; v8 `clips.aspect` (`vertical`/`horizontal`, padrão `vertical`, gravado no render); v9 `sessions.capture_json` (o que a captura gravou de fato; sessões antigas `NULL`); v10 tabela `deleted_clips` (marca do corte apagado, `ON DELETE CASCADE` com a sessão); v11 `channels.monitor_paused_at`/`monitor_paused_session`/`language` e `sessions.language`, padrão `''` = `CLIPPER_LANGUAGE`; v12 `games.profile_ai_json` (perfil em inglês), `translated_at`, `aliases_json`). Migra ao subir o serviço. **Nunca altere uma migração já aplicada** (o banco real estava em v4 quando a v7 nasceu): coluna nova = `ALTER` numa versão nova |
| Banco do Clipador | `data/clipper/clipper.db` (`PRAGMA user_version` 13, `SCHEMA` em `clipper/app/db.py`: v1 tabelas, v2 `settings`, v3 jogo/varredura/emotes/configuração do corte — colunas novas em `sessions`, `channels.settings_json`, `chat.emotes`, `clips.learned`, tabelas `games` e `emotes`; v4 `edits` (`clip_id`, `project_json`, `rev`, `cover`, `exported_at`, `created_at`, `updated_at`); v5 `face_track`; v6 `games.notes_json`/`games.edited_at`; v7 `edits.origin` (`ai`/`user`) + `edits.ai_project_json`; v8 `clips.aspect` (`vertical`/`horizontal`, padrão `vertical`, gravado no render); v9 `sessions.capture_json` (o que a captura gravou de fato; sessões antigas `NULL`); v10 tabela `deleted_clips` (marca do corte apagado, `ON DELETE CASCADE` com a sessão); v11 `channels.monitor_paused_at`/`monitor_paused_session`/`language` e `sessions.language`, padrão `''` = `CLIPPER_LANGUAGE`; v12 `games.profile_ai_json` (perfil em inglês), `translated_at`, `aliases_json`; v13 `clips.translation_json`, fala do corte em frases + português). Migra ao subir o serviço. **Nunca altere uma migração já aplicada** (o banco real estava em v4 quando a v7 nasceu): coluna nova = `ALTER` numa versão nova |
| Blocos gravados (`.ts` de 30 s + `segments.csv`) e frames | `data/clipper/sessions/<id>/` (frames em `frames/`) |
| Pesos do rastreio de reação (YuNet, MediaPipe, OpenSeeFace) | `data/clipper/models/`, fixados (URL imutável + sha256) em `clipper/models.lock.json` |
| Cortes prontos | `output/clipper/<sessão>/clip-<id>.mp4` + `clip-<id>.jpg` |
@@ -30,6 +30,7 @@ renderiza cortes verticais (1080×1920, padrão) ou horizontais (1920×1080, You
| Retomada de live (`Engine.live_check`, `keep_live`, `RESUME_DELAYS_S`, `resume_interrupted`), render que falha (`recover_orphan_renders`, `ORPHAN_RENDER_S` 300, `MAX_RENDER_ATTEMPTS` 3), cortes duplicados (`SAME_PEAK_S` 10, `SAME_MOMENT_OVERLAP` 0,6, `KEPT_STATUSES`/`VETO_STATUSES`, `discard_pending_duplicates`) | `clipper/app/worker.py` | `clipper/tests/test_resume.py`, `clipper/tests/test_render_and_duplicates.py` |
| Apagar cortes (`delete_clip`, `delete_many`, `select_ids`, `MAX_BATCH` 500, recusas `BUSY`/`PUBLISHED`/`CHANGED`, marca `marks`/`mark_spans`, arquivos só dentro das pastas do Clipador) | `clipper/app/clip_delete.py`; rotas em `main.py` (`ClipsDeleteIn`); marca lida em `worker.py` (veto depois do juiz) e na varredura (`intel.py`) | `clipper/tests/test_clip_delete.py`; `METHODS` em `panel/src/lib/clipper.ts`; seção "Apagar cortes" abaixo |
| Parar à mão e pausa do monitor (`Engine.stop_session(id, pause_monitor=True)`, `StopIn.pauseMonitor`), idioma por fonte/sessão (`check_language`, visões de fonte/sessão/corte com `language` resolvido; Whisper e `judge.output_language_note`) | `clipper/app/worker.py`, `main.py`, `db.py` (v11), `judge.py`; painel `ACCOUNT_LANGUAGES` em `panel/src/lib/languages.ts` | `clipper/tests/test_monitor_pause_and_language.py` (9); seção "Parar é parar e idioma" abaixo |
| Fonte em outro idioma (inglês): prompts `*_EN`, schemas com bloco `pt`, `lang_key`, `translate_lines`, `translate_clip`, `voice_language`, `phrases`, legenda `Trans` | `clipper/app/judge.py`, `intel.py` (`Intel.lang`), `worker.py`, `subtitles.py`, `scoring.py`, `layout.py`, `editor_render.py`, `editor_api.py` (`translation_for`), `main.py`; painel `clipper-client.ts`, `clipper-clip-dialog.tsx`, `clipper-clip-parts.tsx`, `clipper-clip-table.tsx`, `clipper-session-detail.tsx`, `clipper-cut-settings.tsx` | `clipper/tests/test_english_source.py` (9); seção "Fonte em inglês" abaixo |
| Chat (IRC anônimo da Twitch com `CAP REQ :twitch.tv/tags` → emotes nativos e `room-id`; Pusher da Kick, emotes `[emote:id:NOME]`) | `clipper/app/chat.py` | — |
| Heurística: pesos, base de 3 min, mínimo proporcional (`_required_messages`), reações (`min_reactions`), chat fraco (`sparse_rate` 0,5 msg/s), momentos do chat/áudio/rosto (`_chat_moments`/`_audio_moments`/`_face_moments`; `face_*` em `Params`), `pick_peaks`, `fit_window` (duração de todo corte automático) | `Params` e funções em `clipper/app/scoring.py`; alvo `min_target` em `layout.py` | `clipper/tests/test_scoring.py` (regressões de falso positivo, chat fraco e rosto), `test_duration_banner_fonts.py` |
| Rastreio de reação — E/S: backends (MediaPipe; plano B OpenSeeFace), download sob demanda com sha256, recorte FFmpeg 6 qps, laço `face` | `clipper/app/face.py` (`for_scoring`, `must_wait`, `view`, `reset`); laço `_face_loop` e uso de `must_wait` na decisão do corte em `worker.py`; bancada `clipper/tools/face_bench.py` | `clipper/tests/test_face.py`, `clipper/models.lock.json`, `doc/FACE_BAKEOFF.md` |
@@ -342,12 +343,47 @@ Texto completo no README do Clipador ("Parar é parar", "Idioma por fonte e por
sozinho (marcada = não pausa).
- **Idioma.** `language` em `channels` e `sessions` (`pt-BR`, `en-US`, `es-419`; `''` = `CLIPPER_LANGUAGE`), aceito em
`POST/PATCH /v1/channels` e `POST /v1/sessions`; as visões de fonte, sessão e corte devolvem o idioma **já resolvido**.
O Whisper usa o idioma da sessão; fora de pt-BR os prompts do editor e da varredura recebem a nota de idioma de saída.
O Whisper usa o idioma da sessão (pela fronteira `voice_language`, ver abaixo); espanhol mantém os prompts em português com a nota de idioma de saída; inglês tem juízes próprios (seção "Fonte em inglês").
No painel, `accounts.language` (migração v9 do painel, padrão `pt-BR`) e o aviso no diálogo Publicar quando o idioma do
canal difere do idioma do corte. Versões traduzidas de um mesmo corte: **ainda não existem** (próxima etapa).
canal difere do idioma do corte. Versão do corte em outro idioma para publicar: **ainda não existe**; a tradução em português guardada é só para a equipe ler.
- Sem reiniciar o Clipador as rotas novas não valem; o painel trata `language`/pausa como opcionais e não quebra
(gotchas, item 166).
## Fonte em inglês (18/11/2026)
Fonte do contrato: `doc/clipador/IDIOMAS.md`; README do Clipador, "Idioma por fonte e por sessão". Decisão do dono: o
**vídeo sai em inglês** (título, legenda, hashtags, gancho) e **a equipe vê tudo em português** no painel.
- **Regra:** `judge.lang_key(language)` = `"en"` para `en-*`, senão `"pt"`; `Intel.lang(session)` resolve. Em inglês, analista,
editor e varredura usam `ANALYST_SYSTEM_EN`/`JUDGE_SYSTEM_EN`/`SCAN_SYSTEM_EN`, `CLIP_GUIDE_EN`, `CHAT_GLOSSARY_EN` e
`LABELS` en nos montadores (parâmetro `lang` em `Judge.analyze/judge/scan`). Perfil do jogo no prompt = `profileAi`.
- **Tradução sem chamada extra:** os schemas `*_EN` exigem o bloco `pt` (analista: `what_happened`, `screen`, `speech`,
`chat_meaning`, `hook`; editor: `title`, `caption`, `reason`; varredura: `summary_pt` e `pt` por momento). Vai em
`judge_json.pt`, `memory[].summaryPt`, `reasons.proposalTitlePt/proposalReasonPt`. `analysis_block` tira o `pt` antes do editor.
Campo novo no schema inglês = pôr o `pt` correspondente e mostrar no painel.
- **Fala traduzida:** `Engine.translate_clip(clip_id, lo, hi, force)` (chamada quando o corte é mantido) grava
`clips.translation_json` `{language, startS, endS, model, lines: [{s, e, text, pt}]}`; frases de `subtitles.phrases`
(pausa > 0,7 s, fim de frase com 4+ palavras, 16 palavras ou 6 s) traduzidas por `Judge.translate_lines`.
`POST /v1/clips/{id}/translate` refaz (409 em fonte PT); `clip_view.translation`.
- **Legenda em português no vídeo (só para desenvolver):** `caption.translation` (padrão `false`) → estilo ASS `Trans`
(metade do tamanho, `&H00FFE79B`, `n8` + `\q0`) sob a legenda, seguindo o desvio do gancho; só entra no ASS quando
ligado **e** há tradução (sem isso o ASS é idêntico ao de antes). `editor_api.translation_for` alimenta render e prévia.
**Nunca publicar com isto ligado.**
- **Heurística:** `scoring.py` (`REACTION_PATTERNS`, `SPOKEN_REACTION`) reconhece reação em inglês (lmao, lol, 💀, 😭, no
way, bruh, holy, clutch, goated, clip that…). `judge.output_language_note` agora é vazio também para inglês.
- **Voz:** `worker.VOICE_LANGUAGES`/`voice_language()` converte `en-US` → `en` e `es-419` → `es` antes do Whisper (gotchas, item 173).
- **Começar uma fonte gringa:** Fontes → idioma English (US); jogo com perfil em inglês e gírias do público gringo
(Jogos → "acrescente as gírias…", ou `POST /v1/games/{id}/translate` se o perfil só existe em português); ligar
"Tradução em português embaixo (teste)" na configuração do corte do canal enquanto estiver testando.
- **Painel:** modal do corte com bloco "Em português" (título, legenda, "O que ele fala" frase a frase, botão "Traduzir a
fala"); lista com título traduzido (🇧🇷); resumo da sessão em português; switch em `clipper-cut-settings.tsx`; Fontes: a
coluna "Ao vivo" mostra "gravando #N" da sessão ativa e checagem do monitor com mais de 10 min vira "ao vivo há X"
apagado (gotchas, item 174).
- Medido (18/11/2026, sessão 15, twitch.tv/tfue, ROB RUN, 1080p60 h264, informado pelo coordenador): transcrição em
inglês ok; câmera pela YuNet em 12/12 quadros; corte manual 259 (30–100 s) com título, legenda e hashtags em inglês,
`judge.pt` em português, 27 frases traduzidas e vídeo 1080×1920 com inglês em cima e português embaixo. Não verificado
por mim: o render real (só a suíte foi reexecutada); qualidade da tradução fora desse corte; espanhol ponta a ponta.
## Perfil do jogo (aba Jogos)
Fonte do contrato: `doc/clipador/JOGOS.md`; seção "Contexto do jogo" de `clipper/README.md`. Toda rota abaixo devolve a
@@ -417,6 +453,11 @@ missão logo depois do gatilho de fim. Busca por nome casa `id` **ou** alias (ca
## Testes e evidência
Fonte em inglês (18/11/2026): `pnpm test:clipper` → **346 passed** (reexecutado nesta manutenção, 101 s); `test_english_source.py`
novo (9 testes) e ajustes em `test_monitor_pause_and_language.py`, `test_render_and_duplicates.py`, `test_intel.py`. Não
verificado: IA real com prompts em inglês (só o corte 259 informado), painel no navegador, `pnpm typecheck`, banco real em v13
(o serviço precisa reiniciar).
Perfis de jogo bilíngues, missões, cadastro e semente do GTA VI (18/11/2026): `pnpm test:clipper` → **335 passed**
(reexecutado nesta manutenção, 108 s; bate com o informado); 10 testes em `clipper/tests/test_game_profiles.py`. Não
verificado: IA real na pesquisa, tradução e refino bilíngues; modal e lista no navegador; serviço real em v12 (precisa
+31 -1
View File
@@ -785,9 +785,22 @@ observada num envio real ainda. Contexto em [publishing.md](publishing.md).
que falha deixa a outra versão como estava e `error` explica. Onde: `clipper/app/intel.py` (`import_seeds`,
`add_game`, `translate`), `main.py`, `db.py` (v12), `seeds/games/`; teste `clipper/tests/test_game_profiles.py`.
173. **Clipador: fonte em inglês sem transcrição (422 `language_not_supported` em todo bloco).** Causa: a fonte/sessão
guarda `en-US` (idioma do público), mas o serviço de voz só aceita `pt-BR`, `en` e `es`; antes de 18/11/2026 o idioma
gringo nunca tinha sido testado ponta a ponta. Correção: `worker.voice_language()` (`VOICE_LANGUAGES`) traduz na
fronteira, antes de mandar `X-Language`; idioma novo = entrada ali **e** em `WHISPER_LANGUAGES` de `voice/app/stt.py`.
Sintoma parecido: corte em inglês sem o português no painel = serviço sem reiniciar (item 144; banco precisa estar em
v13) ou corte anterior à mudança (use "Traduzir a fala" / `POST /v1/clips/{id}/translate`). Onde:
`clipper/app/worker.py`; teste `clipper/tests/test_english_source.py`.
174. **Clipador: Fontes mostrava "ao vivo" por checagem velha e parecia que a gravação estava na fonte errada.** Causa: a
coluna usava a última checagem do monitor (de 2 h antes) como se fosse agora; o Skipnho aparecia "ao vivo" enquanto a
sessão gravando era a do Tfue. Correção: a coluna mostra "gravando #N" da sessão ativa e trata checagem com mais de
10 min como "ao vivo há X" apagado. Onde: `panel/src/components/clipper-channels.tsx`.
## IA: provedores, login e reserva
Itens 168–172 informados em 18/11/2026 e conferidos contra `doc/ia.md` e o código. Contexto em [ai.md](ai.md).
Itens 168–172 e 175–179 informados em 18/11/2026 e conferidos contra `doc/ia.md` e o código. Contexto em [ai.md](ai.md).
168. **Gemini CLI com login Google: `IneligibleTierError: UNSUPPORTED_CLIENT`** (gemini-cli 0.68.0). Causa: o OAuth gratuito
"Code Assist for individuals" foi encerrado; o Google manda migrar para o Antigravity. OAuth só com plano elegível
@@ -808,6 +821,23 @@ Itens 168–172 informados em 18/11/2026 e conferidos contra `doc/ia.md` e o có
dois lugares além do PATH; mesmo assim, instalar e não ver = "Verificar" de novo na tela. Gemini no Windows: o
`gemini.cmd` exige shell, então roda `node …/@google/gemini-cli/bundle/gemini.js` (mesma família do item 28).
175. **Gemini CLI: nem conta pessoal AI Pro/Ultra entra.** OAuth de conta pessoal encerrado em 18/06/2026; Code Assist
Standard/Enterprise sem assinatura nova desde 09/10/2026. Correção: chave do AI Studio ou o provedor `antigravity`
(conta Google; atenção aos termos, ver [ai.md](ai.md)). Complementa o 168. Onde: `doc/ia.md`.
176. **`/usage` no Git Bash vira caminho e a CLI cobra uma resposta normal.** Causa: o MSYS converte `/usage` em
`C:/Program Files/Git/usage`. Correção no terminal: `MSYS_NO_PATHCONV=1 claude -p "/usage"`. O painel chama sem shell
e não é afetado. `claude -p "/usage"` bem formado custa US$ 0 (`<synthetic>`). Onde: `panel/src/lib/ai-usage.ts`.
177. **`agy`: shell recusado em silêncio.** Só vale correspondência exata `command(<linha>)` em `--settings`; prefixo,
`command(node)`, `command(node:*)` e `command(node -e *)` não liberam. O que não está liberado vira passo `ERROR`
+ mensagem `jetski:` no stderr com **código de saída 0**: não confie no código, leia os eventos. Não use
`--dangerously-skip-permissions`. Onde: `antigravityArgs`/`normalizeAntigravity` em `panel/src/lib/agents.ts`.
178. **`codex app-server`: leitura de limites falha sem o handshake.** Ordem: `initialize` → notificação `initialized` →
pedido. `account/read` sem `params` dá "missing field `params`". Onde: `panel/src/lib/ai-usage.ts`.
179. **IA aparecia "pronta" sem estar.** Causa: último teste falhado por login/cota não tirava a IA da cadeia, e o Gemini
em modo conta contava como pronto sem teste. Correção: teste falho por indisponibilidade tira de `readyChain`;
Gemini em conta só depois de um teste que passou; "Testar" segue habilitado. Onde: `panel/src/lib/ai.ts`;
teste `ai.test.ts`.
Relacionadas, já registradas acima:
- Patch por script em arquivos CRLF do painel (`lib/metrics.ts`, `components/metrics-view.tsx`, `dashboard-controls.tsx`,
`app/dashboard/page.tsx`): item 63 — uma substituição com "\n" não acha o trecho; normalize e grave de volta em CRLF.
+5 -5
View File
@@ -251,10 +251,10 @@ Cada trecho vira um MP4 de desenho 2D montado por peças a partir do texto; pers
informando o formato (o subagente é uma casca que lê `doc/roteiro/`; sem WebSearch, fato sem fonte fica
"a confirmar"); no **Codex** manda ler os guias e escrever sozinho, sem usar `.claude/agents/` (mesma
regra no `AGENTS.md`).
- **Três provedores** (`claude`, `codex`, `gemini`), configurados em **Configurações → IA** (`/settings/ai`: ligar/desligar,
conta ou chave de API, ordem da reserva, instalar, entrar, testar). **IA reserva:** agente que termina com erro de
- **Quatro provedores** (`claude`, `codex`, `gemini`, `antigravity` — este começa desligado), configurados em **Configurações → IA** (`/settings/ai`: ligar/desligar,
conta ou chave de API, ordem da reserva, instalar, entrar, testar, uso do limite). **IA reserva:** agente que termina com erro de
indisponibilidade é pausado e a mesma tarefa recomeça na próxima IA pronta (`agent_runs.fallback_of`; o console segue
o `followUpRunId` também nesse caso; vertentes religadas à nova execução). Contrato, API e armadilhas em
o `followUpRunId` também nesse caso; vertentes religadas à nova execução). Tarefa nova pula a IA acima do limite de uso (`overLimit`; não vale em retomada). Contrato, API e armadilhas em
[ai.md](ai.md). Configurações são subpáginas `/settings/{ai,publishing,apps,browser,modes}` (`/settings` → IA;
`SETTINGS_SECTIONS` em `settings-shell.tsx`, também no menu lateral); link antigo `/settings?tab=apps` não existe mais.
- Lista de modelos = `models()` (não há mais constante fixa; o Gemini usa `geminiModels()` de `lib/ai.ts`):
@@ -355,10 +355,10 @@ sidebar (`sidebar-nav.tsx`) mostra os mesmos subitens quando o Clipador está at
| Rota | Conteúdo | Arquivos |
|---|---|---|
| `/clipper` Cortes | lista `ClipTable` (uma linha por corte; ações rápidas Aprovar/Rejeitar/Publicar), filtros na URL (`?stage ?source ?session ?lang`), modal `ClipDialog` por `?clip=ID` com anterior/próximo | `clipper-clips-page.tsx`, `clipper-clip-table.tsx`, `clipper-clip-dialog.tsx`, `clipper-clip-parts.tsx`; ordenar/apagar/selecionar em utilitários de `clipper-queue.tsx` |
| `/clipper` Cortes | lista `ClipTable` (uma linha por corte; ações rápidas Aprovar/Rejeitar/Publicar), filtros na URL (`?stage ?source ?session ?lang`), modal `ClipDialog` por `?clip=ID` com anterior/próximo; em fonte inglesa, bloco "Em português" e título traduzido na lista ([clipper.md](clipper.md#fonte-em-inglês-18112026)) | `clipper-clips-page.tsx`, `clipper-clip-table.tsx`, `clipper-clip-dialog.tsx`, `clipper-clip-parts.tsx`; ordenar/apagar/selecionar em utilitários de `clipper-queue.tsx` |
| `/clipper/sessions` | lista de sessões; "Gravar pelo link" em diálogo (`RecordForm`) | `clipper-sessions-page.tsx` |
| `/clipper/sessions/[id]` | saúde, resumo da IA, tiles, gráfico do chat, emotes, configuração do corte | `clipper-session-detail.tsx` |
| `/clipper/sources` | fontes em tabela, "Adicionar fonte" em diálogo, monitor ligado/**pausado** + Religar, idioma da live, canais de publicação | `clipper-channels.tsx` |
| `/clipper/sources` | fontes em tabela, "Adicionar fonte" em diálogo, monitor ligado/**pausado** + Religar, idioma da live, canais de publicação; coluna "Ao vivo" = "gravando #N" (sessão ativa) ou "ao vivo há X" apagado se a checagem tem > 10 min (gotchas, item 174) | `clipper-channels.tsx` |
| `/clipper/games` | jogos em tabela (nome, gênero, estado, missões, última pesquisa/edição), "Adicionar jogo" em diálogo, `?game=ID` abre o modal do jogo e emotes do canal | `clipper-games-page.tsx`, `clipper-game-dialog.tsx` (modal), `clipper-game-parts.tsx` (seções, `AiChat`, editor à mão), `clipper-games.tsx` |
| `/clipper/settings` | abas Juiz (IA) / Serviço / Idiomas e públicos | `clipper-settings-page.tsx`, `clipper-judge.tsx` |
| `/clipper/edit/[clipId]` | editor em tela cheia, **fora** do grupo `(studio)` | ver "Editor de cortes" |
@@ -169,6 +169,7 @@ segurança).
| Ferramenta | Para quê | Situação |
|---|---|---|
| Gemini CLI (`@google/gemini-cli`) | terceiro provedor de IA (agentes do painel e juiz do Clipador; [ai.md](ai.md)) | **código pronto, nunca executado de verdade**: não instalado nesta máquina (18/11/2026, `gemini: command not found`); a versão 0.68.0 do contrato (`doc/ia.md`) vem de teste do dono e não foi reverificada aqui. Coberto só por testes sem CLI (`ai.test.ts`, `test_ai_fallback.py`). OAuth gratuito de conta pessoal encerrado (gotchas, item 168); uso real exige chave do AI Studio, ainda não testada. Passa a "Em uso" depois de uma tarefa real concluída por ele |
| Antigravity CLI (`agy`) | 4º provedor de IA, só agentes do painel (conta Google; substituto do Gemini CLI; [ai.md](ai.md)) | **candidata, desligada por padrão**: `agy` 1.5.10 em `~/.gemini/bin` (verificado em 18/11/2026). Testes informados: "Testar" respondeu "ok" em 15 s; leitura de uso 12%/5%; o painel chamou `-p` sem terminal. Nenhuma tarefa real de vídeo/história concluída por ele. Termos do Google: embrulhar o `agy` em app de terceiro "não é suportado" em planos pessoais (decisão do usuário). Juiz do Clipador não usa. Gotchas 177 |
| Meshy | gerar modelos GLB (personagens, objetos) e rig | citada na especificação; não testada |
| Mixamo | animações para personagens com rig | citada como não obrigatória; não testada |
| `.glb` carregado por `GLTFDocument` em tempo de execução (Godot) | modelos prontos dentro de cenas da biblioteca (`library/<id>/assets/`) | **só documentado** em `doc/godot/cenas.md`; nenhum `.glb` no repositório nem render com ele (17/11/2026). Personagens e barcos atuais são procedurais (`godot/kits/`) |
+5 -2
View File
@@ -67,8 +67,11 @@ a sessão pelo painel. `{"pauseMonitor": false}` no corpo do stop mantém o moni
sozinha) continua retomando **na mesma sessão** (`keep_live`), sem passar pela pausa.
**Idioma por fonte e por sessão.** `language` em `channels` e `sessions` (`pt-BR`, `en-US`, `es-419`; vazio = `CLIPPER_LANGUAGE`).
A sessão herda o da fonte; a transcrição manda esse idioma ao Whisper e, fora de pt-BR, o contexto do editor e da
varredura ganha a linha "Idioma de saída: …" (título, legenda e hashtags no idioma do público).
A sessão herda o da fonte; a transcrição manda esse idioma ao Whisper. **Fonte em inglês** (18/11/2026): os juízes
trabalham em inglês (prompts, glossário de chat e saída em inglês) e devolvem na mesma resposta um bloco `pt` para o
painel; a fala do corte é traduzida por frase (`clips.translation_json`) e `caption.translation` (só para testar) põe o
português embaixo da legenda. Regras completas: `doc/clipador/IDIOMAS.md`. Espanhol continua com a linha "Idioma de
saída: …" no contexto.
## Contexto do jogo
+41
View File
@@ -19,6 +19,8 @@ import logging
import os
import sys
import threading
import time
from datetime import datetime
from pathlib import Path
from typing import Protocol
@@ -29,6 +31,8 @@ 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 = {
@@ -180,6 +184,43 @@ class AiConfig:
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:
+5
View File
@@ -207,6 +207,11 @@ SCHEMA = [
ALTER TABLE games ADD COLUMN translated_at TEXT;
ALTER TABLE games ADD COLUMN aliases_json TEXT NOT NULL DEFAULT '[]';
""",
# v13: fonte em inglês (doc/clipador/IDIOMAS.md): a fala do corte em frases com tempo + tradução em português,
# para o painel e para a legenda de desenvolvimento (inglês em cima, português embaixo). NULL = não traduzido.
"""
ALTER TABLE clips ADD COLUMN translation_json TEXT;
""",
]
+17 -2
View File
@@ -112,7 +112,8 @@ def render_clip_edit(engine, clip: dict, session: dict, edit: dict, out: Path, t
log.warning("capa do corte %s falhou: %s", clip["id"], exc)
cover = None
editor_render.render_project(ffmpeg, engine.settings.ffprobe, engine._encoder, segments, project, base, credit, out,
REPO_ROOT, chat=chat_for(engine, project), cover_file=cover)
REPO_ROOT, chat=chat_for(engine, project), cover_file=cover,
translation=translation_for(engine, clip, project, base))
total = editor.output_duration(project["cuts"])
media.thumbnail(ffmpeg, out, min(3.0, total / 2), thumb)
# Formato em que ESTE arquivo saiu (camadas padrão ← canal ← sessão ← projeto): a fila desenha o player por ele.
@@ -120,6 +121,19 @@ def render_clip_edit(engine, clip: dict, session: dict, edit: dict, out: Path, t
return cover.relative_to(REPO_ROOT).as_posix() if cover else None
def translation_for(engine, clip: dict, project: dict, base: dict) -> list[dict] | None:
"""Frases traduzidas para a legenda de desenvolvimento (doc/clipador/IDIOMAS.md): só com `caption.translation`
ligado e fonte em inglês. Traduz o trecho do projeto se ainda não houver tradução que o cubra."""
cfg = editor.effective_settings(base, project)
if not cfg["caption"].get("translation"):
return None
ps = editor.pieces(project["cuts"])
if not ps:
return None
data = engine.translate_clip(clip["id"], ps[0].start, ps[-1].end)
return (data or {}).get("lines") or None
def chat_for(engine, project: dict) -> list | None:
"""Mensagens do chat da sessão para o bloco "chat na tela" (só quando o projeto pede)."""
if not (project.get("chat") or {}).get("enabled"):
@@ -365,7 +379,8 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
cover = None
editor_render.render_project(ffmpeg, settings.ffprobe, ["-c:v", "libx264", "-preset", "veryfast", "-crf", "24"],
segments, project, base, credit, out, REPO_ROOT,
out_range=(a, b), timeout=180, chat=chat_for(engine, project), cover_file=cover)
out_range=(a, b), timeout=180, chat=chat_for(engine, project), cover_file=cover,
translation=translation_for(engine, clip, project, base))
took = time.monotonic() - t
return {"file": out.relative_to(REPO_ROOT).as_posix(), "fromS": a, "toS": b, "seconds": round(took, 1), "version": now()}
+32 -9
View File
@@ -200,9 +200,11 @@ def chat_events(project: dict, chat: list | None, total: float,
def build_project_ass(project: dict, cfg: dict, credit: str, t0: float = 0.0, t1: float | None = None,
chat: list | None = None) -> str:
chat: list | None = None, translation: list[dict] | None = None) -> str:
"""ASS do projeto em tempo de saída. [t0, t1] recorta a janela (prévia real de poucos segundos).
`chat` = mensagens da sessão (ChatMessage) para o bloco de chat na tela, se o projeto pedir."""
`chat` = mensagens da sessão (ChatMessage) para o bloco de chat na tela, se o projeto pedir.
`translation` = frases da fala com tradução ({s, e, text, pt}, tempo da sessão; `clips.translation_json`):
com `caption.translation` ligado, o português sai embaixo da legenda (só para desenvolver, IDIOMAS.md)."""
cap, cred = cfg["caption"], cfg["credit"]
total = output_duration(project["cuts"])
t1 = total if t1 is None else min(t1, total)
@@ -211,6 +213,11 @@ def build_project_ass(project: dict, cfg: dict, credit: str, t0: float = 0.0, t1
credit_align, credit_side, credit_margin = layout.credit_placement(cfg)
cw, ch = layout.canvas_size(cfg)
font, size, ow = cap["font"], cap["size"], cap["outlineWidth"]
# Legenda em português (desenvolvimento): metade do tamanho; o estilo só entra quando ligada (o ASS do vídeo
# normal fica idêntico ao de antes).
tsize = max(30, int(size * 0.5))
trans_style = (f"Style: Trans,Arial,{tsize},&H00FFE79B,&H00FFE79B,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,"
f"{max(3, ow // 2)},2,8,60,60,0,1\n") if cap.get("translation") and translation else ""
header = f"""[Script Info]
ScriptType: v4.00+
PlayResX: {cw}
@@ -226,7 +233,7 @@ Style: Credit,Arial,{cred['size']},&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-
Style: Text,Arial Black,64,&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,6,2,5,60,60,0,1
Style: Box,Arial Black,64,&H00FFFFFF,&H00FFFFFF,&H004D1DE1,&H00000000,-1,0,0,0,100,100,0,0,3,18,0,5,60,60,0,1
Style: Bar,Arial,10,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,7,0,0,0,1
Style: Chat,Arial,{(project.get('chat') or {}).get('size', 34)},&H00FFFFFF,&H00FFFFFF,&H78000000,&H00000000,-1,0,0,0,100,100,0,0,3,5,0,1,0,0,0,1
{trans_style}Style: Chat,Arial,{(project.get('chat') or {}).get('size', 34)},&H00FFFFFF,&H00FFFFFF,&H78000000,&H00000000,-1,0,0,0,100,100,0,0,3,5,0,1,0,0,0,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
@@ -249,12 +256,17 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
pos = f"\\pos({cw // 2},{layout.caption_y(cfg)})"
dodges = hook_dodges(project, (cw, ch), layout.caption_y(cfg), int(cap["size"]), total)
def at(t: float) -> str:
"""Posição da legenda no instante t (saída): desviada enquanto um gancho a cobriria."""
def y_at(t: float) -> int:
"""Altura (centro) da legenda no instante t (saída): desviada enquanto um gancho a cobriria."""
for s, e, y in dodges:
if s <= t < e:
return f"\\pos({cw // 2},{y})"
return pos
return y
return layout.caption_y(cfg)
def at(t: float) -> str:
"""Posição da legenda no instante t (saída)."""
y = y_at(t)
return pos if y == layout.caption_y(cfg) else f"\\pos({cw // 2},{y})"
# Ênfase: palavra de saída ↔ palavra marcada no projeto (mesmo texto, mesmo instante), casada nos tempos
# ORIGINAIS. Depois as palavras são saneadas (ordem, sem sobreposição, duração mínima) — `clean_words` devolve
# a mesma quantidade, na mesma ordem — e os blocos abaixo nunca ficam dois na tela ao mesmo tempo.
@@ -303,6 +315,17 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
intro = "\\fscx85\\fscy85\\t(0,90,\\fscx100\\fscy100)" if preset == "pop" and i == 0 else ""
event(0, start, end, "Caption", f"{{{at(start)}{intro}}}" + " ".join(parts))
if cap.get("translation") and translation:
# Só para desenvolver (doc/clipador/IDIOMAS.md): a frase traduzida em português, menor e em azul claro,
# logo embaixo da legenda em inglês (\\an8 = cresce para baixo; \\q0 = quebra a linha se for longa).
for line in translation:
a, _ = to_output(float(line["s"]), project["cuts"])
b, _ = to_output(float(line["e"]), project["cuts"])
if b - a < 0.2 or not str(line.get("pt") or "").strip():
continue
y = y_at(a) + int(size * 0.62)
event(0, a, b, "Trans", f"{{\\an8\\pos({cw // 2},{y})\\q0}}{_escape(str(line['pt']))}")
cuts = project["cuts"]
for o in project["overlays"]:
if o["kind"] in ("zoom", "inset"):
@@ -586,7 +609,7 @@ def has_audio_stream(ffprobe: str | None, file: Path) -> bool:
def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segments: list[tuple[Path, float, float]],
project: dict, base_cfg: dict, credit: str, out_file: Path, repo_root: Path,
out_range: tuple[float, float] | None = None, timeout: float = 900, chat: list | None = None,
cover_file: Path | None = None) -> None:
cover_file: Path | None = None, translation: list[dict] | None = None) -> None:
"""Renderiza o projeto (ou só a saída [a, b] para a prévia real). `segments` = (arquivo, início, fim) da sessão.
`chat` = mensagens da sessão (para o chat na tela); `cover_file` = capa já renderizada, posta nos 2 primeiros
quadros quando o projeto pede (`cover.atStart`)."""
@@ -605,7 +628,7 @@ def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segment
stem = out_file.stem
segs, uniform = uniform_segments(ffmpeg, ffprobe, segs, work, stem) # emenda de resolução/codec (retomada)
ass_file = work / f"{stem}.ass"
ass_text = build_project_ass(project, cfg, credit, t0, t1, chat)
ass_text = build_project_ass(project, cfg, credit, t0, t1, chat, translation)
ass_file.write_text(ass_text, encoding="utf-8")
input0, concat = _concat_input(work, stem, segs, in0, in1 - in0)
+19 -7
View File
@@ -23,7 +23,7 @@ from .db import loads, now
from .emotes import EmoteCatalog, extract, learn_delta, message_bonus
from .face import FaceError, FaceUnavailable
from .hashtags import fold, to_tag
from .judge import JudgeError, build_scan_prompt, game_context, output_language_note
from .judge import JudgeError, build_scan_prompt, game_context, lang_key, output_language_note
from .scoring import fit_window
from .sources import parse_source
@@ -470,12 +470,17 @@ class Intel:
screen_profile = self.profile(screen) if screen.lower() not in ("", "desconhecido") else None
return (screen, screen_profile) if screen_profile else (game or ("" if screen.lower() == "desconhecido" else screen), None)
def lang(self, session: dict) -> str:
"""'en' = fonte em inglês (juízes em inglês, tradução para o painel); 'pt' = o resto."""
return lang_key(session.get("language") or self.e.settings.language)
def context(self, session: dict) -> str:
memory = loads(session.get("memory_json"), [])
confirmed = session.get("game_source") == "user" and bool(session.get("game"))
profile = self.profile(session.get("game", "")) or (None if confirmed else self.profile(session.get("screen_game", "")))
text = game_context(session.get("game", ""), session.get("screen_game", ""), profile, session.get("title", ""),
" | ".join(m["summary"] for m in memory[-3:] if m.get("summary")), confirmed=confirmed)
" | ".join(m["summary"] for m in memory[-3:] if m.get("summary")), confirmed=confirmed,
lang=self.lang(session))
# Sessão em outro idioma (fonte gringa): o editor e a varredura escrevem título/legenda nesse idioma.
note = output_language_note(session.get("language") or self.e.settings.language)
return f"{text}\n{note}" if note else text
@@ -635,10 +640,11 @@ class Intel:
"SELECT start_s, end_s, title FROM clips WHERE session_id = ? AND end_s > ? AND start_s < ?", session["id"], back_lo, hi)]
existing += clip_delete.mark_spans(self.e.db, session["id"], back_lo, hi) # apagados não voltam pela varredura
prompt = build_scan_prompt(self.e.streamer_name(session), session["platform"], lo, hi, back_lo, tl["words"],
tl["chat"], self.context(session), frames, existing, dur["minS"], dur["maxS"])
tl["chat"], self.context(session), frames, existing, dur["minS"], dur["maxS"],
lang=self.lang(session))
created = 0
try:
data = self.e.judge.scan(prompt, [p for _, p in frames])
data = self.e.judge.scan(prompt, [p for _, p in frames], lang=self.lang(session))
self.last_scan_error = None
except (JudgeError, json.JSONDecodeError) as exc:
# Avança mesmo assim: repetir a mesma janela com a CLI quebrada só gastaria cota.
@@ -655,10 +661,13 @@ class Intel:
log.info("varredura %s %.0f–%.0fs: %d proposta(s), %d candidato(s)", session["id"], lo, hi, len(proposals), created)
memory = loads(session.get("memory_json"), [])
if data.get("summary") or proposals:
memory.append({"fromS": lo, "toS": hi, "summary": str(data.get("summary") or "")[:240],
"proposals": len(proposals), "created": created})
item = {"fromS": lo, "toS": hi, "summary": str(data.get("summary") or "")[:240],
"proposals": len(proposals), "created": created}
if data.get("summary_pt"): # fonte em inglês: o resumo vai em inglês à IA e em português ao painel
item["summaryPt"] = str(data["summary_pt"])[:240]
memory.append(item)
screen = str(data.get("screen_game") or "")
if screen.lower() in ("desconhecido", "não identificável", "nao identificavel"):
if screen.lower() in ("desconhecido", "não identificável", "nao identificavel", "unknown"):
screen = ""
self.e.db.run("UPDATE sessions SET scanned_until = ?, memory_json = ?, screen_game = CASE WHEN ? != '' THEN ? ELSE screen_game END WHERE id = ?",
hi, json.dumps(memory[-MEMORY_KEEP:], ensure_ascii=False), screen, screen[:120], session["id"])
@@ -684,6 +693,9 @@ class Intel:
ts = now()
reasons = {"via": "varredura", "scanFromS": lo, "scanToS": hi, "proposalScore": score,
"proposalTitle": str(m.get("title", ""))[:100], "proposalReason": str(m.get("reason", ""))[:300]}
pt = m.get("pt") if isinstance(m.get("pt"), dict) else {}
if pt.get("title") or pt.get("reason"): # fonte em inglês: a mesma proposta em português para o painel
reasons |= {"proposalTitlePt": str(pt.get("title", ""))[:100], "proposalReasonPt": str(pt.get("reason", ""))[:300]}
self.e.db.run(
"INSERT INTO clips (session_id, peak_s, start_s, end_s, score, source, reasons_json, status, created_at, updated_at)"
" VALUES (?, ?, ?, ?, ?, 'ai', ?, 'candidate', ?, ?)",
+266 -51
View File
@@ -30,7 +30,7 @@ import sys
import tempfile
import threading
import time
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
@@ -353,6 +353,8 @@ class Verdict:
model: str
# Tags DO MOMENTO (sem "#"), escolhidas pela IA; as do canal e do jogo o sistema põe (app/hashtags.py).
hashtags: tuple[str, ...] = ()
# Fonte em inglês: título, legenda e motivo traduzidos para o painel ({} = sessão em português).
pt: dict = field(default_factory=dict)
class JudgeError(RuntimeError):
@@ -402,6 +404,163 @@ def extract_json_object(text: str, fences: bool = True) -> dict | None:
return None
# ---------------------------------------------------------------- juízes em inglês (fonte gringa)
# Pedido do dono (18/11/2026): "se a fonte está em inglês, os juízes trabalham em inglês". A equipe não fala inglês:
# o vídeo (gancho, título, legenda, hashtags) sai em inglês e a MESMA resposta traz um bloco `pt` com a tradução
# para o painel — sem chamada extra. Regras completas em doc/clipador/IDIOMAS.md.
CLIP_GUIDE_EN = """What makes a good live-stream clip (market research, 2026):
- Opens on the strong moment: viewers decide in 1–2 s. No "like I was saying".
- Explains itself: someone who never saw the stream gets it in a few seconds (minimal context at the start).
- Clip-worthy: strong reaction (jump scare, laughing fit, rage), insane play/comeback, funny fail, beef/drama, a story
that unfolds, a memorable line, and NEW GAME INFO (mechanic, secret, news, comparison) — around launches
(e.g. GTA 6) information is worth as much as a reaction.
- Not clip-worthy: waiting, menus/loading, reading donations/ads, chatter with no hook, stream inside jokes.
- TIMING: streamers usually comment AFTER the action. Go back to the start of the ACTION that triggered the
comment (20 s to 2 min before the line, up to the backtrack limit given) — the clip must show action and reaction.
- Tight ending: end right after the payoff (reaction/resolution)."""
CHAT_GLOSSARY_EN = """Common chat slang on English-speaking Twitch/Kick/YouTube (read it by context):
- Laughing: "LUL", "LULW", "KEKW", "OMEGALUL", "ICANT", "pepeLaugh", "LMAO", "LMFAO", "LOL", "ROFL", "💀"/"☠️"
("I'm dead" = so funny), "😭" (crying laughing), "dead", "I'm crying".
- Shock/confusion: "HUH", "?????", "WTF", "OMG", "no way", "nah", "bruh", "monkaS"/"monkaW" (tension), "Aware",
"Clueless" (ironic: he doesn't realise), "COPIUM" (denial), "Sadge" (sad).
- Hype/praise: "Pog", "POGGERS", "PogU", "W"/"dub" (win), "L" (loss), "LETSGO", "Clap", "EZ", "GG", "clutch",
"cracked" (very skilled), "goated", "sheesh", "diff" (skill gap).
- "F" = death/loss; "cooked"/"he's cooked" = doomed; "throwing"/"sold" = blew it; "bot"/"NPC" = bad/robotic play.
- "lag", "ping", "rubberbanding", "desync", "server dying" → the game/stream is lagging; the joke is the lag.
- "clip it"/"CLIP IT" → clip request; "hacker"/"cheater"/"aimbot" → suspected cheating.
- Channel emotes (streamer prefix + base emote, e.g. tfueLUL) carry the same reaction as the base emote."""
PT_NOTE = ("The team that reviews clips only reads Brazilian Portuguese: fill `pt` with a faithful Brazilian "
"Portuguese translation of the listed fields (keep game terms, names and slang meaning; do not add facts).")
ANALYST_SYSTEM_EN = """You are the ANALYST of a live-stream clipping team. You do not write titles: you describe
faithfully WHAT HAPPENED in the segment so the editor can decide. You get game context, a timed transcript (the
streamer speaks English), screen FRAMES with their timestamps and the chat.
Cross-check all three sources before concluding: speech alone misleads (e.g. "I'm playing three games... I died, I
died" plus chat "server dying?/LMAO" and the screen jumping = the game is lagging and he dies because of the lag).
Chat reacts a few seconds after the event.
""" + CHAT_GLOSSARY_EN + """
Fields (in English):
- situation: the moment type (one from the list; the ids are fixed, keep them as they are).
- what_happened: 2–3 factual sentences of what happened, in order, no exaggeration.
- screen: what the frames show (cite the frame #) — or "frames don't help".
- speech: what the speech reveals (cite the timestamp).
- chat_meaning: what chat is saying/laughing at and why.
- confidence: 0–1, how sure you are (lower it when sources disagree).
- action_start_s: second of the recording where the ACTION that caused the reaction starts (may be before the speech).
- reaction_end_s: second where the reaction/payoff ends.
- hook: what would hook someone in the first 2 seconds of the clip (English, it goes on screen).
- pt: what_happened, screen, speech, chat_meaning and hook translated. """ + PT_NOTE + """
Do not use tools beyond what was given. Answer only with the requested JSON."""
JUDGE_SYSTEM_EN = """You are the EDITOR of live-stream clips for Shorts, TikTok, Reels and YouTube, for an
English-speaking (US) audience. You get a candidate segment of a stream (game context, timed transcript, chat,
emotes) and, when available, the ANALYST's analysis, which already cross-checked screen, speech and chat. Trust the
analysis to understand WHAT happened; your job is to decide whether it makes a clip and write a title and caption
FAITHFUL to it.
""" + CLIP_GUIDE_EN + """
""" + CHAT_GLOSSARY_EN + """
Title and caption describe the real situation (if the analysis says lag, the title is about the lag, not about a
random line of the transcript). With analysis confidence < 0.5, be descriptive and do not invent details.
Use the analysis action_start_s/reaction_end_s as the base for start_s/end_s.
Answer rules:
- keep=false for what doesn't work; score 0–10 (7+ = strong clip; below 5 = discard).
- start_s and end_s in seconds of the recording, INSIDE the window given and within the min/max duration given;
start before the action (context) and end right after the reaction. Never cut mid-sentence.
- title: up to 70 characters, English, catchy but true, written like a native US clip channel (not a literal
translation), nothing that isn't in the speech/screen.
- caption: 1–2 sentences in English, NO hashtags and no links (the system adds channel/game hashtags and credit).
- hashtags: 2 to 4 tags OF THE MOMENT, English, without "#": the mission/activity, event, mode, place, item or
character in THIS segment. Prefer game-profile terms and what streamer and chat say. Nothing generic ("gameplay",
"live", "viral"), nothing that doesn't happen here, and do not repeat the channel or the game name.
- reason: one sentence on why you kept or discarded it (cite the screen if it helped).
- pt: title, caption and reason translated. """ + PT_NOTE + """
- Do not use tools or read anything beyond what was given. Answer only with the requested JSON."""
SCAN_SYSTEM_EN = """You are a live-stream clip editor WATCHING a stream in windows of a few minutes. The streamer
speaks English. You get game context, a timed transcript (seconds of the recording), screen frames with their
timestamps, the chat (may be almost empty) and clips already made in this region.
""" + CLIP_GUIDE_EN + """
""" + CHAT_GLOSSARY_EN + """
Task: point out 0 to 2 moments in this window that would make a good clip ON THEIR OWN. If nothing works, return
moments=[] (that's normal most of the time — don't force it). Don't repeat a clip already made.
- start_s/end_s inside the window (may start back to the "backtrack" limit to catch the action), within the
min/max duration given.
- screen_game: the game on screen (or "unknown"); has_webcam: is there a streamer camera in the frame?
- summary: 1 sentence of what's going on in the window (becomes memory for the next windows).
- title/caption/reason in English like an editor would write (title ≤ 70 characters, true).
- summary_pt and each moment's pt (title, reason): translated. """ + PT_NOTE + """
Do not use tools beyond what was given. Answer only with the requested JSON."""
def _pt_block(*keys: str) -> dict:
return {"type": "object", "properties": {k: {"type": "string"} for k in keys}, "required": list(keys),
"additionalProperties": False}
def _with(schema: dict, **extra: dict) -> dict:
"""Schema + campos novos obrigatórios (os CLIs exigem `required` com todas as propriedades)."""
return {**schema, "properties": {**schema["properties"], **extra}, "required": [*schema["required"], *extra]}
ANALYSIS_SCHEMA_EN = _with(ANALYSIS_SCHEMA, pt=_pt_block("what_happened", "screen", "speech", "chat_meaning", "hook"))
VERDICT_SCHEMA_EN = _with(VERDICT_SCHEMA, pt=_pt_block("title", "caption", "reason"))
SCAN_SCHEMA_EN = _with({**SCAN_SCHEMA, "properties": {**SCAN_SCHEMA["properties"],
"moments": {"type": "array", "items": _with(_MOMENT, pt=_pt_block("title", "reason"))}}},
summary_pt={"type": "string"})
# Tradução da fala de um corte (painel e legenda em português de desenvolvimento): frases numeradas → mesma quantidade.
LINES_SCHEMA = {
"type": "object",
"properties": {"lines": {"type": "array", "items": {"type": "string"}}},
"required": ["lines"],
"additionalProperties": False,
}
LINES_SYSTEM = """You translate the speech of a live-streamer (auto transcript, may have errors and slang) into
Brazilian Portuguese, for a team that doesn't speak English. You get numbered lines in order; they are one
continuous talk, so use the neighbours as context. Return `lines` with EXACTLY the same number of items, same order,
one translation per line: natural spoken Brazilian Portuguese, short, faithful (keep swearing level, game terms and
names; translate the slang's meaning, e.g. "he's cooked" -> "ele tá ferrado"). If a line is noise, translate it
as is. Answer only with the requested JSON."""
def lang_key(language: str | None) -> str:
"""'en' para fonte em inglês (juízes em inglês); 'pt' para o resto (prompts em português + nota de saída)."""
return "en" if (language or "").strip().lower().startswith("en") else "pt"
# Rótulos dos prompts montados aqui (o texto do usuário). Mesmas chaves nos dois idiomas.
LABELS = {
"pt": {"live_title": "Título da live", "unknown": "desconhecido", "channel": "Canal", "window": "Janela disponível",
"candidate": "Candidato da heurística", "peak": "pico de reação em", "duration": "Duração do corte",
"signals": "Sinais da heurística", "face": "Rosto do streamer (expressão medida na webcam, relativa ao normal dele)",
"transcript": "Transcrição", "no_speech": "(sem fala transcrita)", "chat_per": "Mensagens do chat por",
"no_chat": "sem chat", "top_emotes": "Emotes mais usados", "none": "nenhum", "chat_sample": "Amostra do chat",
"no_chat_p": "(sem chat)", "frames_none": "Frames: (nenhum)", "frames": "Frames anexados, em ordem",
"new_window": "Janela nova", "back_to": "pode voltar até {s}s para pegar o início de uma ação",
"done": "Cortes já feitos aqui", "analysis": "Análise do ANALISTA (cruzou tela, fala e chat)"},
"en": {"live_title": "Stream title", "unknown": "unknown", "channel": "Channel", "window": "Available window",
"candidate": "Heuristic candidate", "peak": "reaction peak at", "duration": "Clip duration",
"signals": "Heuristic signals", "face": "Streamer face (expression measured on the webcam, relative to his normal)",
"transcript": "Transcript", "no_speech": "(no transcribed speech)", "chat_per": "Chat messages per",
"no_chat": "no chat", "top_emotes": "Top emotes", "none": "none", "chat_sample": "Chat sample",
"no_chat_p": "(no chat)", "frames_none": "Frames: (none)", "frames": "Attached frames, in order",
"new_window": "New window", "back_to": "may go back to {s}s to catch the start of an action",
"done": "Clips already made here", "analysis": "ANALYST's analysis (cross-checked screen, speech and chat)"},
}
# ---------------------------------------------------------------- prompts
# Idiomas que o serviço conhece (fonte/sessão `language`; o painel oferece os mesmos). Nome legível para o prompt.
LANGUAGE_NAMES = {"pt-BR": "português do Brasil", "en-US": "English (US)", "es-419": "Español (Latinoamérica)"}
@@ -412,8 +571,8 @@ def output_language_note(language: str | None) -> str:
"""Linha que vai no contexto do EDITOR e da VARREDURA quando a saída não é em português: título, legenda e
hashtags no idioma do público. Vazia para pt-BR (os prompts já são em português)."""
code = (language or "").strip() or DEFAULT_LANGUAGE
if code == DEFAULT_LANGUAGE:
return ""
if code == DEFAULT_LANGUAGE or lang_key(code) == "en":
return "" # inglês: os juízes já trabalham em inglês (ANALYST/JUDGE/SCAN_SYSTEM_EN)
name = LANGUAGE_NAMES.get(code, code)
return (f"Idioma de saída: {name}. Título, legenda e hashtags em {name}, naturais para o público desse idioma "
f"(a transcrição e o chat podem estar em outro idioma; não traduza literalmente, escreva como um editor nativo).")
@@ -423,33 +582,39 @@ MISSIONS_IN_PROMPT = 25
MISSIONS_PROMPT_CHARS = 1500
def mission_lines(profile: dict) -> list[str]:
def mission_lines(profile: dict, lang: str = "pt") -> list[str]:
"""Gatilhos de fim de missão e as missões (nome + gatilhos) para o prompt, com teto de tamanho: o perfil do GTA
pode ter 100+ missões, e o contexto vai em todo julgamento."""
lines: list[str] = []
triggers = [str(t) for t in (profile.get("end_triggers") or [])[:10] if t]
if triggers:
lines.append("Sinais de fim de missão/objetivo neste jogo: " + "; ".join(triggers))
lines.append(("Mission/objective end signals in this game: " if lang == "en" else
"Sinais de fim de missão/objetivo neste jogo: ") + "; ".join(triggers))
missions = [m for m in (profile.get("missions") or []) if isinstance(m, dict) and m.get("name")]
if missions:
parts, used = [], 0
for m in missions[:MISSIONS_IN_PROMPT]:
ends = " / ".join(str(t) for t in (m.get("completion_triggers") or [])[:2] if t)
item = f"{m['name']}" + (f" (fim: {ends})" if ends else "")
item = f"{m['name']}" + (f" ({'end' if lang == 'en' else 'fim'}: {ends})" if ends else "")
if used + len(item) > MISSIONS_PROMPT_CHARS:
break
parts.append(item)
used += len(item) + 2
extra = len(missions) - len(parts)
lines.append("Missões da história: " + "; ".join(parts) + (f"; …e mais {extra}" if extra > 0 else ""))
more = (f"; …and {extra} more" if lang == "en" else f"; …e mais {extra}") if extra > 0 else ""
lines.append(("Story missions: " if lang == "en" else "Missões da história: ") + "; ".join(parts) + more)
if triggers or missions:
lines.append("Se o trecho é o fim de uma missão, termine o corte logo depois do gatilho de fim "
lines.append("If the segment is the end of a mission, end the clip right after the end trigger "
"(the win/fail moment is the climax)." if lang == "en" else
"Se o trecho é o fim de uma missão, termine o corte logo depois do gatilho de fim "
"(o momento de vitória/falha é o clímax).")
return lines
def game_context(game: str, screen_game: str, profile: dict | None, live_title: str, history: str = "",
confirmed: bool = False) -> str:
confirmed: bool = False, lang: str = "pt") -> str:
if lang == "en":
return _game_context_en(game, screen_game, profile, live_title, history, confirmed)
lines = [f"Título da live: {live_title or '(desconhecido)'}"]
if confirmed:
# O usuário confirmou no painel: não questionar (jogo novo/pouco conhecido lembra outros na tela).
@@ -472,7 +637,30 @@ def game_context(game: str, screen_game: str, profile: dict | None, live_title:
return "\n".join(lines)
def _transcript(words: list[Word], lo: float, hi: float) -> str:
def _game_context_en(game: str, screen_game: str, profile: dict | None, live_title: str, history: str,
confirmed: bool) -> str:
lines = [f"Stream title: {live_title or '(unknown)'}"]
if confirmed:
lines.append(f"Game CONFIRMED by the user: {game}. The screen may look like a similar game (e.g. GTA, Warzone) "
f"— don't question the game; use the profile below to understand what happens.")
else:
lines.append(f"Game from the platform category: {game or '(unknown)'}")
if screen_game and screen_game.lower() not in (game or "").lower():
lines.append(f"Game the AI saw on screen recently: {screen_game} (check the frames; the category may be wrong)")
if profile:
lines.append(f"Game profile: {profile.get('summary', '')}")
for key, label in (("clip_worthy", "Clip-worthy in this game"), ("avoid", "Not clip-worthy"),
("mechanics", "Mechanics/activities (terms for the moment hashtags)"),
("jargon", "Slang/terms"), ("news", "News")):
if profile.get(key):
lines.append(f"{label}: " + "; ".join(profile[key][:10]))
lines.extend(mission_lines(profile, "en"))
if history:
lines.append(f"What happened earlier in the stream: {history}")
return "\n".join(lines)
def _transcript(words: list[Word], lo: float, hi: float, lang: str = "pt") -> str:
lines, current, current_t = [], [], None
for word in sorted((w for w in words if lo <= w.start <= hi), key=lambda w: w.start):
if current_t is None or word.start - current_t > 4 or len(current) >= 14:
@@ -482,10 +670,12 @@ def _transcript(words: list[Word], lo: float, hi: float) -> str:
current.append(word.word)
if current:
lines.append(f"[{current_t:.0f}s] {' '.join(current)}")
return "\n".join(lines) or "(sem fala transcrita)"
return "\n".join(lines) or LABELS[lang]["no_speech"]
def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | None, bucket_s: int = 5) -> str:
def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | None, bucket_s: int = 5,
lang: str = "pt") -> str:
L = LABELS[lang]
buckets: dict[int, int] = {}
emotes: dict[str, int] = {}
sample: list[str] = []
@@ -498,50 +688,52 @@ def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | No
near = focus is None or focus - 10 <= message.t <= focus + 8
if near and len(sample) < 60:
sample.append(f"[{message.t:.0f}s] {message.text[:80]}")
rate = ", ".join(f"{t}s:{n}" for t, n in sorted(buckets.items())) or "sem chat"
top = ", ".join(f"{e}×{n}" for e, n in sorted(emotes.items(), key=lambda kv: -kv[1])[:12]) or "nenhum"
return (f"Mensagens do chat por {bucket_s} s: {rate}\nEmotes mais usados: {top}\n"
f"Amostra do chat:\n" + ("\n".join(sample) or "(sem chat)"))
rate = ", ".join(f"{t}s:{n}" for t, n in sorted(buckets.items())) or L["no_chat"]
top = ", ".join(f"{e}×{n}" for e, n in sorted(emotes.items(), key=lambda kv: -kv[1])[:12]) or L["none"]
return (f"{L['chat_per']} {bucket_s} s: {rate}\n{L['top_emotes']}: {top}\n"
f"{L['chat_sample']}:\n" + ("\n".join(sample) or L["no_chat_p"]))
def _frames_block(frames: list[tuple[float, Path]]) -> str:
def _frames_block(frames: list[tuple[float, Path]], lang: str = "pt") -> str:
if not frames:
return "Frames: (nenhum)"
return "Frames anexados, em ordem: " + ", ".join(f"#{i + 1} = {t:.0f}s" for i, (t, _) in enumerate(frames))
return LABELS[lang]["frames_none"]
return LABELS[lang]["frames"] + ": " + ", ".join(f"#{i + 1} = {t:.0f}s" for i, (t, _) in enumerate(frames))
def build_prompt(streamer: str, platform: str, start_s: float, end_s: float, peak_s: float,
words: list[Word], chat: list[ChatMessage], heuristic: dict, live_title: str = "", *,
context: str = "", frames: list[tuple[float, Path]] | None = None,
backtrack_s: float = DEFAULT_BACKTRACK_S, min_s: float = DEFAULT_MIN_S, max_s: float = DEFAULT_MAX_S,
face: str = "") -> str:
face: str = "", lang: str = "pt") -> str:
"""Prompt do juiz. Janela = candidato com `backtrack_s` para trás (a ação vem antes do comentário).
`face`: resumo do rosto do streamer na janela (face.FaceService.summary); vazio = sem câmera/rastreio."""
lo, hi = max(0.0, start_s - backtrack_s), end_s + CONTEXT_AFTER_S
L, to = LABELS[lang], ("to" if lang == "en" else "a")
return (
f"Canal: {streamer} ({platform})\n"
+ (context or f"Título da live: {live_title or '(desconhecido)'}") + "\n\n"
f"Janela disponível: {lo:.0f}s a {hi:.0f}s. Candidato da heurística: {start_s:.0f}s a {end_s:.0f}s; "
f"pico de reação em {peak_s:.0f}s. Duração do corte: {min_s:.0f} a {max_s:.0f} s.\n"
f"Sinais da heurística: {json.dumps(heuristic, ensure_ascii=False)}\n"
+ (f"Rosto do streamer (expressão medida na webcam, relativa ao normal dele): {face}\n" if face else "")
+ f"{_frames_block(frames or [])}\n\n"
f"Transcrição:\n{_transcript(words, lo, hi)}\n\n"
f"{_chat_block(chat, lo, hi, peak_s)}"
f"{L['channel']}: {streamer} ({platform})\n"
+ (context or f"{L['live_title']}: {live_title or '(' + L['unknown'] + ')'}") + "\n\n"
f"{L['window']}: {lo:.0f}s {to} {hi:.0f}s. {L['candidate']}: {start_s:.0f}s {to} {end_s:.0f}s; "
f"{L['peak']} {peak_s:.0f}s. {L['duration']}: {min_s:.0f} {to} {max_s:.0f} s.\n"
f"{L['signals']}: {json.dumps(heuristic, ensure_ascii=False)}\n"
+ (f"{L['face']}: {face}\n" if face else "")
+ f"{_frames_block(frames or [], lang)}\n\n"
f"{L['transcript']}:\n{_transcript(words, lo, hi, lang)}\n\n"
f"{_chat_block(chat, lo, hi, peak_s, lang=lang)}"
)
def build_scan_prompt(streamer: str, platform: str, lo: float, hi: float, back_lo: float, words: list[Word],
chat: list[ChatMessage], context: str, frames: list[tuple[float, Path]],
existing: list[tuple[float, float, str]], min_s: float, max_s: float) -> str:
done = "; ".join(f"{a:.0f}–{b:.0f}s ({t[:40]})" for a, b, t in existing) or "nenhum"
existing: list[tuple[float, float, str]], min_s: float, max_s: float, lang: str = "pt") -> str:
L, to = LABELS[lang], ("to" if lang == "en" else "a")
done = "; ".join(f"{a:.0f}–{b:.0f}s ({t[:40]})" for a, b, t in existing) or L["none"]
return (
f"Canal: {streamer} ({platform})\n{context}\n\n"
f"Janela nova: {lo:.0f}s a {hi:.0f}s (pode voltar até {back_lo:.0f}s para pegar o início de uma ação).\n"
f"Duração do corte: {min_s:.0f} a {max_s:.0f} s. Cortes já feitos aqui: {done}\n"
f"{_frames_block(frames)}\n\n"
f"Transcrição:\n{_transcript(words, back_lo, hi)}\n\n"
f"{_chat_block(chat, back_lo, hi, None, bucket_s=10)}"
f"{L['channel']}: {streamer} ({platform})\n{context}\n\n"
f"{L['new_window']}: {lo:.0f}s {to} {hi:.0f}s ({L['back_to'].format(s=f'{back_lo:.0f}')}).\n"
f"{L['duration']}: {min_s:.0f} {to} {max_s:.0f} s. {L['done']}: {done}\n"
f"{_frames_block(frames, lang)}\n\n"
f"{L['transcript']}:\n{_transcript(words, back_lo, hi, lang)}\n\n"
f"{_chat_block(chat, back_lo, hi, None, bucket_s=10, lang=lang)}"
)
@@ -563,6 +755,7 @@ def _clean(data: dict, start_s: float, end_s: float, model: str, lo: float | Non
title=str(data["title"]).strip()[:100], caption=str(data["caption"]).strip()[:600],
reason=str(data["reason"]).strip()[:300], model=model,
hashtags=tuple(str(t).strip()[:40] for t in (data.get("hashtags") or [])[:6] if str(t).strip()),
pt={k: str(v).strip()[:600] for k, v in (data.get("pt") or {}).items() if k in ("title", "caption", "reason") and v},
)
@@ -701,7 +894,8 @@ class Judge:
def fallback_chain(self) -> list[str]:
"""Ordem em que `ask` tenta as IAs: a escolhida no juiz primeiro, depois a `order` do painel, só as ligadas,
com CLI e (no modo chave) com chave; as em pausa são puladas. Reserva desligada: só a escolhida.
com CLI e (no modo chave) com chave; as em pausa são puladas e as perto do limite de uso vão para o fim.
Reserva desligada: só a escolhida.
Se TODAS as prontas estiverem em pausa, elas voltam como último recurso (melhor tentar do que parar)."""
if not self.enabled:
return []
@@ -710,9 +904,13 @@ class Judge:
if settings["fallback"]["enabled"]:
candidates += [p for p in settings["order"] if p != self.provider and p in AI_ENABLED]
ready = [p for p in candidates if self._skip_reason(p, settings) is None]
paused = self.pauses() if settings["fallback"]["enabled"] else {}
active = [p for p in ready if p not in paused]
return active or ready
if not settings["fallback"]["enabled"]:
return ready
paused = self.pauses()
# Perto do limite de uso (data/ai/usage.json, do painel): vai para depois das livres, antes das em pausa.
limited = {p for p in ready if p not in paused and self.ai.over_limit(p)}
active = [p for p in ready if p not in paused and p not in limited]
return (active + [p for p in ready if p in limited]) or ready
def describe(self) -> dict:
cmd = self.command() if self.enabled else None
@@ -734,9 +932,11 @@ class Judge:
return {"codex": codex_models(), "claude": CLAUDE_MODELS, "gemini": GEMINI_MODELS, "defaults": DEFAULT_MODELS}
# ---------- usos
def analyze(self, prompt: str, images: list[Path]) -> dict:
"""1º juiz (ANALISTA): o que aconteceu, cruzando tela + fala + chat. Não decide nem escreve título."""
data = self.ask(ANALYST_SYSTEM, prompt, ANALYSIS_SCHEMA, images, model=self.analyst_model or self.model)
def analyze(self, prompt: str, images: list[Path], lang: str = "pt") -> dict:
"""1º juiz (ANALISTA): o que aconteceu, cruzando tela + fala + chat. Não decide nem escreve título.
`lang="en"`: prompt em inglês e bloco `pt` (tradução para o painel) na mesma resposta."""
system, schema = (ANALYST_SYSTEM_EN, ANALYSIS_SCHEMA_EN) if lang == "en" else (ANALYST_SYSTEM, ANALYSIS_SCHEMA)
data = self.ask(system, prompt, schema, images, model=self.analyst_model or self.model)
missing = [k for k in ANALYSIS_SCHEMA["required"] if k not in data]
if missing:
raise JudgeError(f"análise sem os campos {missing}")
@@ -745,13 +945,27 @@ class Judge:
def judge(self, prompt: str, start_s: float, end_s: float, images: list[Path] | None = None, *,
lo: float | None = None, hi: float | None = None, min_s: float = DEFAULT_MIN_S,
max_s: float = DEFAULT_MAX_S) -> Verdict:
data = self.ask(JUDGE_SYSTEM, prompt, VERDICT_SCHEMA, images or [])
max_s: float = DEFAULT_MAX_S, lang: str = "pt") -> Verdict:
system, schema = (JUDGE_SYSTEM_EN, VERDICT_SCHEMA_EN) if lang == "en" else (JUDGE_SYSTEM, VERDICT_SCHEMA)
data = self.ask(system, prompt, schema, images or [])
# Modelo de quem DE FATO respondeu (a reserva pode ter entrado no lugar da escolhida).
return _clean(data, start_s, end_s, self.responder(), lo, hi, min_s, max_s)
def scan(self, prompt: str, images: list[Path]) -> dict:
data = self.ask(SCAN_SYSTEM, prompt, SCAN_SCHEMA, images)
def translate_lines(self, lines: list[str]) -> list[str]:
"""Fala de um corte (frases em ordem) → português, mesma quantidade. Para o painel e a legenda de
desenvolvimento; o vídeo publicado continua no idioma da fonte."""
if not lines:
return []
prompt = "\n".join(f"{i + 1}. {text}" for i, text in enumerate(lines))
data = self.ask(LINES_SYSTEM, prompt, LINES_SCHEMA, [])
out = [str(x).strip() for x in (data.get("lines") or [])]
if len(out) != len(lines):
raise JudgeError(f"tradução com {len(out)} linhas para {len(lines)} frases", unavailable=False)
return out
def scan(self, prompt: str, images: list[Path], lang: str = "pt") -> dict:
system, schema = (SCAN_SYSTEM_EN, SCAN_SCHEMA_EN) if lang == "en" else (SCAN_SYSTEM, SCAN_SCHEMA)
data = self.ask(system, prompt, schema, images)
if not isinstance(data.get("moments"), list):
raise JudgeError("varredura sem a lista de momentos")
return data
@@ -974,6 +1188,7 @@ def parse_gemini_output(stdout: str) -> dict:
return data
def analysis_block(analysis: dict) -> str:
"""Análise do 1º juiz no formato que o editor lê."""
return "Análise do ANALISTA (cruzou tela, fala e chat):\n" + json.dumps(analysis, ensure_ascii=False, indent=1)
def analysis_block(analysis: dict, lang: str = "pt") -> str:
"""Análise do 1º juiz no formato que o editor lê (sem o bloco `pt`, que é só para o painel)."""
data = {k: v for k, v in analysis.items() if k != "pt"}
return LABELS[lang]["analysis"] + ":\n" + json.dumps(data, ensure_ascii=False, indent=1)
+4 -1
View File
@@ -91,6 +91,9 @@ DEFAULTS: dict = {
"caption": {
"enabled": True, "font": "Arial Black", "size": 84, "color": "#FFFFFF", "highlight": "#FFE500",
"outline": "#000000", "outlineWidth": 7, "y": None, "uppercase": True, "maxWords": 3,
# Só para desenvolver (fonte em inglês, doc/clipador/IDIOMAS.md): a tradução em português da fala embaixo
# da legenda em inglês. Desligado = o vídeo publicável; nunca publicar com isto ligado.
"translation": False,
},
"credit": {"enabled": True, "position": "top", "size": 44},
"duration": {"minS": 60, "maxS": 90, "backtrackS": 120},
@@ -173,7 +176,7 @@ def validate(settings: dict) -> dict:
o["y"] = None if cap["y"] is None else float(cap["y"])
if o["y"] is not None and not 0.08 <= o["y"] <= 0.9:
raise LayoutError("caption.y vai de 0,08 a 0,9 (fração da altura) ou null = automático")
for key in ("enabled", "uppercase"):
for key in ("enabled", "uppercase", "translation"):
if key in cap:
o[key] = bool(cap[key])
out["caption"] = o
+11
View File
@@ -184,6 +184,9 @@ def clip_view(row: dict) -> dict:
"channelId": row.get("channel_id"), "platform": row.get("platform"), "sessionUrl": row.get("url"),
# Idioma da sessão (resolvido no SELECT: o da sessão ou o padrão do serviço). Ausente só em consultas antigas.
"language": row.get("language"),
# Fonte em inglês: a fala do corte em frases com a tradução ({language, startS, endS, model, lines: [{s, e,
# text, pt}]}); None = sessão em português ou ainda não traduzido (doc/clipador/IDIOMAS.md).
"translation": loads(row.get("translation_json"), None),
# Editor de cortes: existe projeto de edição? (o export renderiza por ele; capa gerada no export)
"edit": ({"updatedAt": row["edit_updated_at"], "exportedAt": row.get("edit_exported_at"), "cover": row.get("edit_cover"),
"origin": row.get("edit_origin")}
@@ -753,6 +756,14 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
engine.wake_clips.set()
return clip_view(_clip(clip_id))
@app.post("/v1/clips/{clip_id}/translate")
def translate_clip(clip_id: int):
"""Traduz (de novo) a fala do corte para o português. Só para fonte em inglês; 409 se não couber."""
_clip(clip_id)
if engine.translate_clip(clip_id, force=True) is None:
raise UserError("Sem tradução: a fonte não está em inglês, a IA está desligada ou não respondeu.", 409)
return clip_view(_clip(clip_id))
@app.post("/v1/clips/{clip_id}/rejudge")
def rejudge(clip_id: int):
_clip(clip_id)
+12 -6
View File
@@ -24,15 +24,21 @@ from . import reaction
# Peso extra por categoria de reação. Uma mensagem pode somar mais de uma.
REACTION_PATTERNS: dict[str, tuple[re.Pattern[str], float]] = {
"risada": (re.compile(r"(k{3,}|kek|lul|lmao|lmfao|omegalul|icant|pepelaugh|haha|hehe|rsrs|ksks|😂|🤣|xd\b)", re.I), 1.0),
# Chat em inglês (fonte gringa, 18/11/2026): a risada lá é LMAO/LOL/💀/😭 e "I'm dead", não "kkkk".
"risada": (re.compile(r"(k{3,}|kek|lul|lmao+|lmfao|omegalul|icant|pepelaugh|haha|hehe|rsrs|ksks|😂|🤣|xd\b|"
r"\blo+l+\b|\brofl\b|💀|☠️?|😭|\bi'?m dead\b|\bim crying\b|\bdying\b)", re.I), 1.0),
"susto": (re.compile(r"(caralho|crlh|caraca|nossa|meu deus|mds|wtf|omg|que isso|q isso|monkas|monkaw|\bhuh+\b|"
r"😱|😳|\?{3,}|!{3,})", re.I), 1.0),
"hype": (re.compile(r"(\bpog|pogchamp|poggers|\bw+\b|\bgg+\b|\bez\b|insano|absurdo|brabo|🔥)", re.I), 0.7),
r"😱|😳|\?{3,}|!{3,}|\bno+ ?wa+y+\b|\bna+h+\b|\bbru+h+\b|\bholy\b|\bjesus\b|"
r"\boh my god\b|\bwhat the\b)", re.I), 1.0),
"hype": (re.compile(r"(\bpog|pogchamp|poggers|\bw+\b|\bgg+\b|\bez\b|insano|absurdo|brabo|🔥|"
r"\blet'?s ?go+\b|\bletsgo+\b|\bshe+sh\b|\bclutch\b|\bcracked\b|\bgoated\b|\binsane\b|"
r"\bclap\b|\bdub\b)", re.I), 0.7),
# Palavra inteira: "clip5k1hmm" (emote) casava com \bclip e dava peso de pedido de clipe.
"clip": (re.compile(r"\b(clip|clips|clipa|clipe|clipou|clipar|clip it|clipit)\b", re.I), 3.0),
"clip": (re.compile(r"\b(clip|clips|clipa|clipe|clipou|clipar|clip it|clipit|clip that|clipped)\b", re.I), 3.0),
}
# Palavras faladas que indicam reação (modo sem chat).
SPOKEN_REACTION = re.compile(r"^(caralho|caraca|nossa|meu|deus|socorro|mano|nãããão|não|sim|vai|gente|que|isso|olha)$", re.I)
# Palavras faladas que indicam reação (modo sem chat), em português e em inglês (fonte gringa).
SPOKEN_REACTION = re.compile(r"^(caralho|caraca|nossa|meu|deus|socorro|mano|nãããão|não|sim|vai|gente|que|isso|olha|"
r"bro|bruh|dude|yo|what|no+|oh|wow|holy|fuck|shit|wait|god|jesus|yes+|bro+)$", re.I)
@dataclass(frozen=True)
+21
View File
@@ -96,6 +96,27 @@ def caption_blocks(words: list[Word], max_words: int = MAX_WORDS) -> list[tuple[
return out
PHRASE_GAP_S, PHRASE_MAX_S, PHRASE_MAX_WORDS = 0.7, 6.0, 16
_SENTENCE_END = (".", "?", "!")
def phrases(words: list[Word]) -> list[tuple[float, float, str]]:
"""Fala em frases curtas com tempo (início, fim, texto) para traduzir: quebra em pausa > 0,7 s, fim de frase
(. ? !) com 4+ palavras, 16 palavras ou 6 s. A tradução de uma frase inteira sai melhor que a de blocos de 3."""
out: list[tuple[float, float, str]] = []
current: list[Word] = []
for w in clean_words(words):
if current and (w.start - current[-1].end > PHRASE_GAP_S or w.end - current[0].start > PHRASE_MAX_S
or len(current) >= PHRASE_MAX_WORDS
or (current[-1].word.endswith(_SENTENCE_END) and len(current) >= 4)):
out.append((current[0].start, current[-1].end, " ".join(x.word for x in current)))
current = []
current.append(w)
if current:
out.append((current[0].start, current[-1].end, " ".join(x.word for x in current)))
return out
def build_ass(words: list[Word], clip_start: float, clip_end: float, credit: str, settings: dict | None = None) -> str:
"""`words` com tempos da sessão; a saída usa tempos relativos ao início do corte."""
cfg = settings or layout.merge()
+53 -6
View File
@@ -40,7 +40,7 @@ from .intel import Intel
from .judge import Judge, JudgeError, analysis_block, build_prompt
from .scoring import ChatMessage, Params, Word, find_moments, overlaps
from .sources import Source, parse_source
from .subtitles import build_ass
from .subtitles import build_ass, phrases
log = logging.getLogger("cenaforge_clipper")
LIVE_WINDOW_S = 900 # ao vivo, pontua só os últimos 15 min (o que veio antes já foi decidido)
@@ -51,6 +51,15 @@ def rel(path: Path) -> str:
# ---------------------------------------------------------------- serviço de voz
# O serviço de voz (voice/app/stt.py, WHISPER_LANGUAGES) aceita "pt-BR", "en" e "es"; fonte e sessão usam o idioma do
# público ("en-US", "es-419"). Tradução num ponto só, aqui na fronteira (medido 18/11/2026: "en-US" voltava 422).
VOICE_LANGUAGES = {"pt-BR": "pt-BR", "en-US": "en", "en": "en", "es-419": "es", "es": "es"}
def voice_language(code: str) -> str:
return VOICE_LANGUAGES.get(code, code.split("-")[0] if code and not code.startswith("pt") else "pt-BR")
class VoiceClient:
def __init__(self, url: str | None, key: str | None, language: str):
self.url, self.key, self.language = url, key, language
@@ -72,7 +81,7 @@ class VoiceClient:
if not self.configured:
raise RuntimeError("serviço de voz não instalado")
headers = {
"X-Service-Key": self.key or "", "Content-Type": "audio/wav", "X-Language": language or self.language,
"X-Service-Key": self.key or "", "Content-Type": "audio/wav", "X-Language": voice_language(language or self.language),
"X-Detail": "words", "X-Idempotency-Key": idempotency_key,
}
response = httpx.post(f"{self.url}/v1/transcribe", content=wav, headers=headers, timeout=180)
@@ -877,22 +886,25 @@ class Engine:
n_frames = 8 if hi - f_lo > 80 else 6
times = [f_lo + (hi - f_lo) * k / (n_frames - 1) for k in range(n_frames)]
frames = self.intel.frames(session, times, f"clip{clip['id']}")
# Fonte em inglês: os juízes trabalham em inglês e devolvem também o português do painel (IDIOMAS.md).
lang = self.intel.lang(session)
prompt = build_prompt(streamer, session["platform"], clip["start_s"], clip["end_s"], clip["peak_s"],
tl["words"], tl["chat"], heuristic, session["title"], context=self.intel.context(session),
frames=frames, backtrack_s=dur["backtrackS"], min_s=dur["minS"], max_s=dur["maxS"],
face=self.face.summary(session, lo, hi))
face=self.face.summary(session, lo, hi), lang=lang)
analysis = None
try:
# Dois juízes: o ANALISTA (vê os frames) diz o que aconteceu; o EDITOR decide e escreve a partir disso.
try:
analysis = self.judge.analyze(prompt, [p for _, p in frames])
analysis = self.judge.analyze(prompt, [p for _, p in frames], lang=lang)
except (JudgeError, json.JSONDecodeError, KeyError, ValueError) as exc:
log.warning("analista falhou no corte %s: %s (editor segue sozinho)", clip["id"], exc)
editor_prompt = prompt + ("\n\n" + analysis_block(analysis) if analysis else "")
editor_prompt = prompt + ("\n\n" + analysis_block(analysis, lang) if analysis else "")
# Sem análise, o editor recebe os frames; com análise, só texto (mais barato, a tela já foi lida).
verdict = self.judge.judge(editor_prompt, clip["start_s"], clip["end_s"],
[] if analysis else [p for _, p in frames],
lo=lo, hi=hi, min_s=layout.min_target({"duration": dur}), max_s=dur["maxS"])
lo=lo, hi=hi, min_s=layout.min_target({"duration": dur}), max_s=dur["maxS"],
lang=lang)
# Corte manual: quem decidiu foi você; o juiz só escreve título e legenda (e não mexe no trecho).
manual = clip["source"] == "manual"
keep = manual or (verdict.keep and verdict.score >= self.min_score)
@@ -904,6 +916,8 @@ class Engine:
"start_s": verdict.start_s, "end_s": verdict.end_s,
"judge": {"model": verdict.model, "keep": verdict.keep, "score": verdict.score,
"reason": verdict.reason, "analysis": analysis,
# Fonte em inglês: título/legenda/motivo em português (só o painel lê).
**({"pt": verdict.pt} if verdict.pt else {}),
"analystModel": (self.judge.analyst_model or self.judge.model) if analysis else None}}
except (JudgeError, json.JSONDecodeError, KeyError, ValueError) as exc:
# Falha do juiz não perde o momento: segue com a heurística e registra o motivo.
@@ -942,6 +956,8 @@ class Engine:
if update["status"] == "pending":
# Novo veredito: o projeto que a IA tinha gerado é refeito no render (o que você editou fica).
self.db.run("DELETE FROM edits WHERE clip_id = ? AND origin = 'ai'", clip["id"])
# Fonte em inglês: a fala do corte em português para o painel (falha não segura o corte).
self.translate_clip(clip["id"], update["start_s"], update["end_s"])
verdict_info = update["judge"] or {}
if clip["source"] != "manual" and "score" in verdict_info:
# Aprendizado fraco pela IA (o forte vem da sua aprovação/rejeição no painel).
@@ -950,6 +966,37 @@ class Engine:
elif verdict_info["score"] >= 7:
self.intel.learn_from_clip(clip, positive=True, factor=0.5)
def translate_clip(self, clip_id: int, lo: float | None = None, hi: float | None = None,
force: bool = False) -> dict | None:
"""Fonte em inglês (doc/clipador/IDIOMAS.md): a fala de [lo, hi] (padrão: o trecho do corte) em frases com
tempo da sessão + tradução em português, em `clips.translation_json`. Serve ao painel ("o que ele disse") e à
legenda de desenvolvimento (`caption.translation`). Reaproveita a tradução que já cobre o trecho.
Sessão em português, IA desligada ou falha da IA → None (o corte segue sem tradução)."""
clip = self.db.get("SELECT * FROM clips WHERE id = ?", clip_id)
session = self.db.get("SELECT * FROM sessions WHERE id = ?", clip["session_id"]) if clip else None
if not clip or not session or self.intel.lang(session) != "en" or not self.judge.enabled:
return None
lo = clip["start_s"] if lo is None else lo
hi = clip["end_s"] if hi is None else hi
current = loads(clip.get("translation_json"), None)
if (isinstance(current, dict) and not force and current.get("startS", 1e12) <= lo + 0.5
and current.get("endS", -1) >= hi - 0.5):
return current
tl = self.load_timeline(session["id"], max(0.0, lo - 30))
items = phrases([w for w in tl["words"] if lo - 0.3 <= w.start <= hi])
if not items:
return None
try:
pt = self.judge.translate_lines([text for _, _, text in items])
except (JudgeError, json.JSONDecodeError, KeyError, ValueError) as exc:
log.warning("tradução da fala do corte %s falhou: %s", clip_id, exc)
return None
data = {"language": "pt-BR", "startS": round(lo, 2), "endS": round(hi, 2), "model": self.judge.responder(),
"lines": [{"s": round(s, 3), "e": round(e, 3), "text": text, "pt": tr}
for (s, e, text), tr in zip(items, pt)]}
self.db.run("UPDATE clips SET translation_json = ? WHERE id = ?", json.dumps(data, ensure_ascii=False), clip_id)
return data
def render_pending(self) -> None:
self.recover_orphan_renders()
self.discard_pending_duplicates()
+42
View File
@@ -311,3 +311,45 @@ def test_api_accepts_gemini(env): # noqa: F811
body = r.json()
assert body["provider"] == "gemini" and body["model"] == "gemini-3.5-flash" and "gemini" in body["models"]
assert "chain" in body["fallback"] and isinstance(body["pauses"], list)
# ---------------------------------------------------------------- uso e limites (data/ai/usage.json do painel)
def write_usage(folder: Path, providers: dict, limit: int = 90, age_s: float = 0) -> None:
import time as _time
from datetime import datetime as _dt, timezone as _tz
iso = lambda t: _dt.fromtimestamp(t, _tz.utc).isoformat().replace("+00:00", "Z") # noqa: E731
now = _time.time()
data = {"updatedAt": iso(now), "limitPercent": limit, "providers": {
name: {"at": iso(now - age_s), "source": "cli", "blocked": spec.get("blocked", False), "plan": None, "note": None,
"error": None, "windows": [{"id": "five_hour", "label": "Sessão (5 h)", "usedPercent": spec["used"],
"resetsAt": iso(now + spec.get("resets_in", 3600))}]}
for name, spec in providers.items()}}
folder.mkdir(parents=True, exist_ok=True)
(folder / "usage.json").write_text(json.dumps(data), encoding="utf-8")
def test_over_limit_rule(ai_dir):
ai = AiConfig(ai_dir, cipher=ReversedCipher(), environ={})
assert ai.over_limit("claude") is None # sem arquivo
write_usage(ai_dir, {"claude": {"used": 93}, "codex": {"used": 100, "blocked": True}, "gemini": {"used": 50}})
assert ai.over_limit("claude") == "Sessão (5 h) em 93% (limite 90%)"
assert ai.over_limit("codex") == "bateu o limite (Sessão (5 h))"
assert ai.over_limit("gemini") is None
write_usage(ai_dir, {"claude": {"used": 93}}, limit=95)
assert ai.over_limit("claude") is None
write_usage(ai_dir, {"codex": {"used": 100, "blocked": True, "resets_in": -60}})
assert ai.over_limit("codex") is None # a janela já zerou
write_usage(ai_dir, {"claude": {"used": 99}}, age_s=3600)
assert ai.over_limit("claude") is None # leitura velha não decide
(ai_dir / "usage.json").write_text("{quebrado", encoding="utf-8")
assert ai.over_limit("claude") is None
def test_chain_puts_provider_near_limit_after_free_ones(make_judge, ai_dir):
judge = make_judge(provider="codex")
write_usage(ai_dir, {"codex": {"used": 100, "blocked": True}})
assert judge.fallback_chain() == ["claude", "codex"] # escolhida no limite: a livre vem antes
write_usage(ai_dir, {"codex": {"used": 95}, "claude": {"used": 97}})
assert judge.fallback_chain() == ["codex", "claude"] # todas no limite: melhor tentar do que parar
write_settings(ai_dir, {**settings_with(), "fallback": {"enabled": False, "cooldownMin": 15}})
assert judge.fallback_chain() == ["codex"] # reserva desligada: só a escolhida, mesmo no limite
+150
View File
@@ -0,0 +1,150 @@
"""Fonte em inglês (18/11/2026, doc/clipador/IDIOMAS.md): juízes em inglês com o português do painel na mesma
resposta, risada/gíria do chat em inglês, fala do corte traduzida por frase e legenda em português de desenvolvimento
(desligada por padrão)."""
import json
from pathlib import Path
from app import editor, editor_render, layout
from app.judge import (ANALYSIS_SCHEMA_EN, JUDGE_SYSTEM_EN, SCAN_SCHEMA_EN, VERDICT_SCHEMA_EN, Judge, Verdict,
analysis_block, build_prompt, lang_key)
from app.scoring import REACTION_PATTERNS, ChatMessage, Word
from app.subtitles import phrases
from .test_editor import validate
from .test_render_and_duplicates import add_clip
from .test_sources_and_api import env, seed_session # noqa: F401 - fixture reaproveitada
class EnglishJudge(Judge):
"""Juiz falso: registra o idioma pedido e devolve o bloco `pt`, como os schemas em inglês exigem."""
def __init__(self):
super().__init__("codex", "fake", Path("."))
self.seen: dict = {}
self.translated: list[list[str]] = []
def analyze(self, prompt, images, lang="pt"):
self.seen["analyze"] = (lang, prompt)
return {"situation": "jogada", "what_happened": "He robbed the bank.", "screen": "", "speech": "",
"chat_meaning": "", "confidence": 0.9, "action_start_s": 0, "reaction_end_s": 0, "hook": "NO WAY",
"pt": {"what_happened": "Ele roubou o banco.", "screen": "", "speech": "", "chat_meaning": "", "hook": "NÃO ACREDITO"}}
def judge(self, prompt, start_s, end_s, images=None, lang="pt", **_limits):
self.seen["judge"] = (lang, prompt)
return Verdict(True, 8.0, start_s, end_s, "He robbed the bank solo", "Insane solo heist.", "great play", "fake",
("heist",), pt={"title": "Ele roubou o banco sozinho", "caption": "Assalto solo insano.",
"reason": "jogada ótima"})
def translate_lines(self, lines):
self.translated.append(list(lines))
return [f"PT: {text}" for text in lines]
def _english_session(engine) -> int:
sid = seed_session(engine)
engine.db.run("UPDATE sessions SET language = 'en-US' WHERE id = ?", sid)
words = [[281.0, 281.3, "No"], [281.3, 281.6, "way"], [281.6, 282.0, "bro."], [284.0, 284.4, "Let's"], [284.4, 284.9, "go!"]]
engine.db.run("UPDATE segments SET words_json = '[]' WHERE session_id = ?", sid)
engine.db.run("UPDATE segments SET words_json = ? WHERE session_id = ? AND idx = 9", json.dumps(words), sid)
return sid
def test_lang_key():
assert lang_key("en-US") == "en" and lang_key("en") == "en"
assert lang_key("pt-BR") == "pt" and lang_key("es-419") == "pt" and lang_key("") == "pt" and lang_key(None) == "pt"
def test_english_schemas_require_the_portuguese_block():
assert ANALYSIS_SCHEMA_EN["required"][-1] == "pt" and VERDICT_SCHEMA_EN["required"][-1] == "pt"
assert "summary_pt" in SCAN_SCHEMA_EN["required"]
assert "pt" in SCAN_SCHEMA_EN["properties"]["moments"]["items"]["required"]
# Os CLIs exigem todas as propriedades em `required` (strict).
for schema in (ANALYSIS_SCHEMA_EN, VERDICT_SCHEMA_EN, SCAN_SCHEMA_EN):
assert set(schema["properties"]) == set(schema["required"])
assert "LMAO" in JUDGE_SYSTEM_EN and "💀" in JUDGE_SYSTEM_EN
def test_english_prompt_labels_and_analysis_block_without_pt():
prompt = build_prompt("Tfue", "twitch", 100, 160, 150, [Word(140, 141, "bro")], [ChatMessage(151, "LMAO")], {},
"GTA 6 Waiting Room", lang="en")
assert "Channel: Tfue" in prompt and "Transcript:" in prompt and "Chat sample:" in prompt
assert "Transcrição" not in prompt and "Canal:" not in prompt
block = analysis_block({"situation": "jogada", "pt": {"what_happened": "x"}}, "en")
assert block.startswith("ANALYST's analysis") and '"pt"' not in block
def test_english_chat_laughter_and_slang_count_as_reaction():
def tags(text):
return {tag for tag, (pattern, _) in REACTION_PATTERNS.items() if pattern.search(text)}
assert "risada" in tags("LMAO") and "risada" in tags("lol") and "risada" in tags("💀💀") and "risada" in tags("im dead")
assert "risada" in tags("😭😭") and "risada" not in tags("lollipop")
assert "susto" in tags("no way") and "susto" in tags("bruhhh") and "susto" in tags("nahhh")
assert "hype" in tags("LETS GOOO") and "hype" in tags("sheesh") and "hype" in tags("clutch")
assert "clip" in tags("clip that")
def test_phrases_split_on_sentence_end_and_pause():
words = [Word(0, 0.3, "No"), Word(0.3, 0.6, "way"), Word(0.6, 0.9, "bro."), Word(0.9, 1.2, "This"), Word(1.2, 1.5, "is"),
Word(1.5, 1.8, "crazy"), Word(1.8, 2.1, "man."), Word(3.5, 3.8, "Okay")]
assert [t for _, _, t in phrases(words)] == ["No way bro. This is crazy man.", "Okay"]
assert phrases([]) == []
def test_english_session_judges_in_english_and_stores_portuguese(env): # noqa: F811
client, engine = env
engine.judge = EnglishJudge()
sid = _english_session(engine)
add_clip(engine, sid, 1, "candidate", 285, 270, 340)
engine.judge_clip(engine.db.get("SELECT * FROM clips WHERE id = 1"))
assert engine.judge.seen["analyze"][0] == "en" and engine.judge.seen["judge"][0] == "en"
assert "Transcript:" in engine.judge.seen["judge"][1] and "ANALYST's analysis" in engine.judge.seen["judge"][1]
clip = client.get("/v1/clips/1", headers=_auth()).json()
assert clip["title"] == "He robbed the bank solo" # o vídeo/publicação: inglês
assert clip["judge"]["pt"]["title"] == "Ele roubou o banco sozinho" # o painel: português
assert clip["judge"]["analysis"]["pt"]["what_happened"] == "Ele roubou o banco."
lines = clip["translation"]["lines"]
assert [x["text"] for x in lines] == ["No way bro.", "Let's go!"]
assert lines[0]["pt"] == "PT: No way bro." and clip["translation"]["language"] == "pt-BR"
# Tradução que já cobre o trecho é reaproveitada (sem chamar a IA de novo).
engine.translate_clip(1)
assert len(engine.judge.translated) == 1
def test_portuguese_session_has_no_translation(env): # noqa: F811
client, engine = env
engine.judge = EnglishJudge()
sid = seed_session(engine)
add_clip(engine, sid, 1, "candidate", 300, 280, 350)
engine.judge_clip(engine.db.get("SELECT * FROM clips WHERE id = 1"))
assert engine.judge.seen["judge"][0] == "pt" and "Transcrição:" in engine.judge.seen["judge"][1]
assert client.get("/v1/clips/1", headers=_auth()).json()["translation"] is None
assert client.post("/v1/clips/1/translate", headers=_auth()).status_code == 409
def test_dev_translation_line_only_when_enabled(tmp_path):
clip = {"session_id": 1, "start_s": 10.0, "end_s": 75.0, "peak_s": 50.0, "title": "He robbed the bank", "source": "chat"}
words = [Word(20, 20.4, "No"), Word(20.4, 20.8, "way"), Word(20.8, 21.2, "bro.")]
lines = [{"s": 20.0, "e": 21.2, "text": "No way bro.", "pt": "Não acredito, mano."}]
for enabled in (False, True):
cfg = layout.merge({"caption": {"translation": enabled}})
p = validate(editor.auto_project(clip, None, words, [], 100.0, cfg), tmp_path)
ass = editor_render.build_project_ass(p, editor.effective_settings(cfg, p), "twitch.tv/tfue", translation=lines)
has = "Não acredito, mano." in ass and "Style: Trans," in ass
assert has is enabled
# Sem tradução disponível nada muda, mesmo ligado.
cfg = layout.merge({"caption": {"translation": True}})
p = validate(editor.auto_project(clip, None, words, [], 100.0, cfg), tmp_path)
assert "Style: Trans," not in editor_render.build_project_ass(p, editor.effective_settings(cfg, p), "x")
assert layout.DEFAULTS["caption"]["translation"] is False
assert layout.validate({"caption": {"translation": True}})["caption"]["translation"] is True
def _auth():
from .test_sources_and_api import auth
return auth()
def test_voice_language_maps_audience_codes_to_whisper_codes():
from app.worker import voice_language
assert voice_language("en-US") == "en" and voice_language("es-419") == "es" and voice_language("pt-BR") == "pt-BR"
assert voice_language("en-GB") == "en" and voice_language("") == "pt-BR"
+1 -1
View File
@@ -114,7 +114,7 @@ class ScanJudge(Judge):
super().__init__("codex", "fake", __import__("pathlib").Path("."))
self.prompts = []
def scan(self, prompt, images):
def scan(self, prompt, images, lang="pt"):
self.prompts.append(prompt)
return {"screen_game": "ROB RUN", "has_webcam": True, "summary": "tiroteio na base",
"moments": [{"score": 8, "start_s": 100, "end_s": 140, "title": "Emboscada", "caption": "c #robrun",
@@ -138,13 +138,19 @@ def test_language_on_channel_and_session(ready):
def test_language_note_reaches_the_ai_context(ready):
client, engine = ready
assert output_language_note("pt-BR") == "" and output_language_note("") == "" and output_language_note(None) == ""
assert "English (US)" in output_language_note("en-US")
# Inglês (18/11/2026): os juízes trabalham em inglês (prompts próprios), sem a nota; espanhol mantém a nota.
assert output_language_note("en-US") == ""
assert "Español" in output_language_note("es-419")
client.post("/v1/channels", json={"url": URL, "language": "en-US"}, headers=auth())
sid = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()["id"]
gringa = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
assert "Idioma de saída: English (US)" in engine.intel.context(gringa)
assert engine.intel.lang(gringa) == "en"
assert "Stream title:" in engine.intel.context(gringa)
engine.db.run("UPDATE sessions SET language = 'es-419' WHERE id = ?", sid)
assert "Idioma de saída: Español" in engine.intel.context(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid))
engine.db.run("UPDATE sessions SET language = '' WHERE id = ?", sid)
assert "Idioma de saída" not in engine.intel.context(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid))
br = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
assert "Idioma de saída" not in engine.intel.context(br) and "Título da live:" in engine.intel.context(br)
def test_transcription_uses_session_language(ready, monkeypatch):
+1 -1
View File
@@ -20,7 +20,7 @@ class RecuoJudge(Judge):
super().__init__("codex", "fake", Path("."))
self.back_to = back_to
def analyze(self, prompt, images):
def analyze(self, prompt, images, lang="pt"):
return {"situation": "lag_ou_bug", "confidence": 0.9, "action_start_s": 0, "reaction_end_s": 0, "hook": ""}
def judge(self, prompt, start_s, end_s, images=None, **_limits):
+52
View File
@@ -0,0 +1,52 @@
# Clipador — fontes em outro idioma (inglês)
Decisão do dono (18/11/2026), ao começar com lives gringas (ex.: twitch.tv/tfue jogando ROB RUN):
> A equipe não fala inglês e não precisa falar. O **vídeo sai em inglês** (título, legenda, hashtags, gancho na
> tela); **para a equipe, tudo aparece em português** no painel. Se a fonte está em inglês, **os juízes trabalham
> em inglês**.
## Regra de ouro
| O quê | Idioma |
| --- | --- |
| Transcrição (Whisper) | o da fonte (`language` da fonte/sessão → `X-Language`) |
| Prompts dos juízes (analista, editor, varredura) | **inglês** para fonte `en-*` (`ANALYST_SYSTEM_EN`, `JUDGE_SYSTEM_EN`, `SCAN_SYSTEM_EN`) |
| Glossário de chat no prompt | inglês (`CHAT_GLOSSARY_EN`: LMAO, LOL, 💀, 😭, KEKW, "no way", "bruh", "cooked", "W/L"…) |
| Perfil do jogo no prompt | inglês (`profile_ai_json`; o painel mostra a tradução `profile_json`) |
| Gancho na tela, título, legenda do post, hashtags do momento | **inglês** (é o que publica) |
| O que o painel mostra | **português**: bloco `pt` da mesma resposta da IA + fala traduzida |
Espanhol (`es-419`) ainda usa os prompts em português com a linha "Idioma de saída: …" (`output_language_note`).
## Onde está cada coisa
- `clipper/app/judge.py`: `lang_key(language)` → `"en"` | `"pt"`; prompts e schemas `*_EN`; os schemas em inglês
exigem o bloco `pt` (analista: `what_happened`, `screen`, `speech`, `chat_meaning`, `hook`; editor: `title`,
`caption`, `reason`; varredura: `summary_pt` e `pt` de cada momento). **Sem chamada extra**: a tradução vem na mesma
resposta. `analysis_block` tira o `pt` antes de passar a análise ao editor.
- `Judge.translate_lines`: a fala do corte em frases (`subtitles.phrases`: pausa > 0,7 s, fim de frase, 16 palavras ou
6 s) → português, mesma quantidade. Uma chamada por corte mantido, reaproveitada enquanto cobrir o trecho.
- `Engine.translate_clip` grava em `clips.translation_json` (`{language, startS, endS, model, lines: [{s, e, text, pt}]}`);
`POST /v1/clips/{id}/translate` refaz (409 em fonte em português).
- `clipper/app/scoring.py`: risada/susto/hype/clip do chat também em inglês; palavras faladas de reação (modo sem
chat) em inglês (`bro`, `bruh`, `what`, `holy`, `wait`…).
- Painel: modal do corte com o bloco **"Em português"** (título, legenda e "O que ele fala", frase a frase com o
original embaixo); análise e motivo em português; lista com a tradução do título (🇧🇷); resumo "Agora na live" em
português (`memory[].summaryPt`).
## Legenda em português no vídeo (só para desenvolver)
`caption.translation` (configuração do corte; padrão **desligado**): o vídeo sai com a legenda em inglês e, logo
embaixo, a frase traduzida em português (metade do tamanho, azul claro, quebra de linha automática). Serve para a
equipe conferir se a IA entendeu a fala. **Nunca publicar com isto ligado** — desligue no canal (Configuração do corte
→ "Tradução em português embaixo (teste)") e renderize de novo. Sem tradução disponível, o vídeo sai igual ao normal
(o estilo `Trans` nem entra no ASS).
## Como começar uma fonte gringa
1. Fontes → adicionar o link com idioma **English (US)**.
2. O jogo precisa de perfil em inglês com as gírias do público gringo (Jogos → pedir à IA "acrescente as gírias que
streamers americanos e o chat deles usam"). Perfil antigo só em português: `POST /v1/games/{id}/translate`.
3. Câmera: a detecção local (YuNet) acha o rosto nos 2 primeiros blocos, como em qualquer fonte.
4. Para a fase de teste, ligue "Tradução em português embaixo (teste)" na configuração do corte do canal.
+67
View File
@@ -1,5 +1,11 @@
# IA do CenaForge — provedores, login e reserva
> **18/11/2026 — Gemini CLI removido do painel.** O login pela conta pessoal acabou (ver abaixo) e o Antigravity CLI
> (`agy`) o substitui com a mesma conta Google. Os provedores do painel são `claude`, `codex` e `antigravity`. Um
> `settings.json` antigo com `"gemini"` é ignorado. O juiz do Clipador não oferece mais o Gemini na tela; o código
> Python do Gemini (`judge.py`) ficou inativo, porque o painel não liga mais essa IA. As seções sobre o Gemini CLI
> abaixo ficam como histórico do estudo.
Três IAs, sempre pela **CLI oficial** instalada no PC (nunca SDK/HTTP direto):
| Provedor | CLI | Instalação (Windows) | Login com a conta (OAuth) | Chave de API (variável) |
@@ -80,3 +86,64 @@ Falha que não é culpa do pedido: limite de uso ou cota (`rate limit`, `429`, `
então o schema vai no prompt e o JSON é extraído do texto. Leitura somente: `--approval-mode plan --skip-trust`, rodando numa pasta temporária fora do repositório (o `@arquivo` respeita o `.gitignore`).
- Modelos: `gemini models -o json` (não exige login).
- No Windows o npm instala `gemini.cmd`; rode `node <prefixo npm>/node_modules/@google/gemini-cli/bundle/gemini.js`.
## Estudo: uso e limites de cada IA pela CLI (18/11/2026)
Objetivo: mostrar quanto de cada IA já foi usado, trocar de IA ANTES de bater o limite e, se bater, mostrar o
uso e quando volta. Medido nesta máquina (claude 2.1.314, codex-cli 0.169.0, gemini-cli 0.68.0).
| IA | Como ler o uso | Custo da leitura | O que vem |
|---|---|---|---|
| Claude (assinatura) | `claude -p "/usage" --output-format stream-json --verbose` | **zero** (modelo `<synthetic>`, 0 tokens, US$ 0) | texto: "Current session: 2% used · resets …", "Current week (all models): 67%", "Current week (Fable): 24%" |
| Claude (em toda execução) | evento `rate_limit_event` do stream-json (vem logo após o `init`) | zero (já vem junto) | `unifiedWindows.five_hour/seven_day.utilization` (0–1), `resetsAt` (epoch), `status` (`allowed`…), `overageStatus`, `isUsingOverage` |
| Codex (ChatGPT) | `codex app-server` (JSON-RPC por stdin): `initialize` → `initialized` → `account/rateLimits/read` | **zero** (não roda modelo) | `primary` (janela 300 min) e `secondary` (10080 min): `usedPercent`, `resetsAt`; `ordinaryUsageAllowed`, `rateLimitReachedType`, `planType`, créditos de reset grátis |
| Codex (histórico) | `~/.codex/sessions/AAAA/MM/DD/rollout-*.jsonl`, evento `token_count.rate_limits` (`limit_id: "codex"`) | zero | mesmo conteúdo, com a hora em que foi gravado |
| Gemini (chave) | não há consulta de cota restante pela CLI nem pela API do AI Studio | — | só reativo: erro 429 `RESOURCE_EXHAUSTED`; o CLI distingue `RetryableQuotaError` (por minuto, traz `retryDelay`) de `TerminalQuotaError` (cota do dia acabou) |
Observações:
- No teste, o Codex estava com a janela de 5 h em **100%** (`rate_limit_reached`, `ordinaryUsageAllowed: false`):
com a leitura prévia, o painel o teria pulado em vez de esperar a falha.
- Cuidado no Git Bash: `/usage` vira caminho (`C:/Program Files/Git/usage`) e a CLI cobra uma resposta normal.
O painel chama sem shell, então não é afetado; no terminal use `MSYS_NO_PATHCONV=1`.
- `claude -p "/usage"` devolve texto em inglês, com datas no fuso local: o parser precisa ser tolerante e
preferir o `rate_limit_event` (estruturado) quando houver execução recente.
- Gemini com chave: contar nós mesmos as requisições e tokens do dia (o `result` do stream-json traz `stats`) e
pausar até o reset diário quando vier `TerminalQuotaError`.
### Implementado (18/11/2026)
- `panel/src/lib/ai-usage.ts`: leitura do Claude (`/usage` + `rate_limit_event` de cada execução) e do Codex
(`app-server`), monitor de 5 min (liga ao abrir Configurações → IA) e releitura antes de cada tarefa (> 60 s).
- `overLimit` (lib/ai.ts): bateu o limite ou janela ainda valendo ≥ `fallback.usageLimitPercent` (padrão 90) →
a tarefa nova começa na próxima IA livre; leitura com mais de 30 min não decide.
- `data/ai/usage.json` (escrito pelo painel): `{updatedAt, limitPercent, providers: {<ia>: {at, windows[], blocked, …}}}`.
O juiz do Clipador lê (`AiConfig.over_limit`) e põe a IA perto do limite depois das livres.
## Gemini pela conta: Antigravity CLI (pesquisa de 18/11/2026)
- O gemini-cli não aceita mais conta pessoal (nem AI Pro/Ultra) desde 18/06/2026; Code Assist Standard/Enterprise
não vende assinatura nova desde 09/10/2026. Fonte: developers.google.com/gemini-code-assist/docs/deprecations/code-assist-individuals
- Substituto oficial: **Antigravity CLI** (`%USERPROFILE%\.gemini\bin\agy.exe`, 1.5.10 nesta máquina, fora do PATH).
Headless parecido com o Claude: `agy -p <prompt> --output-format stream-json --mode accept-edits [--model] [--effort]
[--conversation <id>]`; `agy models` funciona com a conta logada (Gemini 4, Gemini 3.8 Flash, Claude, GPT-OSS).
- **Termos:** a FAQ (antigravity.google/docs/faq) diz que embrulhar o `agy` em app de terceiro "is not supported
under consumer plans"; recomenda chave do AI Studio ou Gemini Enterprise. Respostas de funcionários no fórum se
contradizem. Zona cinza: decisão do usuário.
- Os três pontos que estavam em aberto (saída sem TTY, edição com `accept-edits`, formato do stream-json) foram
testados e funcionam: ver "Antigravity no painel" abaixo.
### Antigravity no painel (implementado em 18/11/2026, agy 1.5.10)
Testado de verdade nesta máquina (prompts mínimos, conta Google logada):
- **Sem terminal funciona:** `agy -p "…" --output-format stream-json` chamado pelo Node respondeu em ~6 s.
- **Eventos:** `{"event":"init","conversation_id"}`, `step_update` (`step_type`: `user_input` | `agent_response` com
`text_delta` | `tool` com `tool_name`, `tool_info.parameters` e `state` ACTIVE/DONE/ERROR; `usage` por passo) e
`{"event":"result","result":{status:"SUCCESS",response,num_turns,usage}}`. Retomada: `--conversation <id>`.
- **Edição:** `--mode accept-edits` grava arquivos sem pedir.
- **Shell:** só com `--settings '{"permissions":{"allow":["command(<linha exata>)"]}}'` (vale só na sessão).
Testado: `command(node --version)` libera exatamente essa linha; prefixo, `command(node)`, `command(node:*)` e
`command(node -e *)` NÃO liberam. O que não estiver liberado é recusado (passo `ERROR` + aviso `jetski:` no
stderr; o processo sai com 0). Não usamos `--dangerously-skip-permissions`.
- **Uso, sem cota:** `agy -p "/usage" --output-format stream-json` → `{"event":"command_result","command":{"name":"usage",
"data":{"groups":[{"name":"Gemini Models","buckets":[{"window":"5h"|"weekly","remaining_fraction":0.88,"reset_time"}]},
{"name":"Claude and GPT models",…}]}}}`. O painel usa o grupo Gemini (modelos padrão do agente).
- **Login:** `agy models` só lista com a conta logada (sem gastar cota); "Entrar com a conta" abre `agy` interativo.
- **Modelos:** `agy models` → linhas `id<TAB>nome` (18 nesta conta), depois de uma linha "Fetching available models...".
- Começa **desligado**; o juiz do Clipador ainda não usa o Antigravity (só agentes do painel).
+2
View File
@@ -1,5 +1,6 @@
"use server";
// Ações de formulário (server actions). Devolvem { error } ou { message } para o formulário.
import { refreshUsage } from "@/lib/ai-usage";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prepareBranches } from "@/lib/branches";
@@ -54,6 +55,7 @@ export async function createStoryFromTextAction(_prev: FormState, form: FormData
const story = createStory({ title, id, logline: "", kind, branchCount: Number(form.get("branchCount") ?? 2) });
// Documental é um vídeo só: sem título de episódio ("Abertura" só faz sentido numa série).
const ep = createEpisode(story.id, { title: kind === "documentary" ? "" : "Abertura" });
await refreshUsage({ maxAgeMs: 60_000 }); // uso das IAs fresco antes de escolher (Configurações → IA)
const chosen = String(form.get("provider") ?? "");
const provider: Provider = (PROVIDERS as string[]).includes(chosen) ? (chosen as Provider) : defaultProviderFor("story");
// Modelo escolhido no formulário; vazio = padrão da tarefa (no Codex, o do config.toml). startRun valida.
+1 -1
View File
@@ -24,7 +24,7 @@ export default async function AgentPage({ searchParams }: { searchParams: Promis
const defaults: AgentDefaults = {
provider: map(defaultProviderFor),
preferred: PREFERRED_PROVIDER,
model: map((k) => ({ claude: defaultModelFor(k, "claude"), codex: defaultModelFor(k, "codex"), gemini: defaultModelFor(k, "gemini") })),
model: map((k) => ({ claude: defaultModelFor(k, "claude"), codex: defaultModelFor(k, "codex"), antigravity: defaultModelFor(k, "antigravity") })),
};
return (
+2
View File
@@ -1,3 +1,4 @@
import { refreshUsage } from "@/lib/ai-usage";
import { startRun } from "@/lib/agents";
import { errorResponse } from "@/lib/http";
import type { AgentKind, Provider } from "@/lib/types";
@@ -8,6 +9,7 @@ export async function POST(request: Request) {
provider: Provider; model?: string; kind: AgentKind; request: string;
storyId?: string | null; episodeId?: number | null; resumeRunId?: number | null;
};
await refreshUsage({ maxAgeMs: 60_000 }); // uso das IAs fresco antes de escolher (Configurações → IA)
const run = startRun({ ...body, model: body.model ?? "" });
return Response.json({ id: run.id });
} catch (error) {
+7 -2
View File
@@ -1,4 +1,5 @@
import { clearCooldown, openLoginTerminal, providerStatus, readAiSettings, setApiKey, startInstall, testProvider } from "@/lib/ai";
import { refreshUsage } from "@/lib/ai-usage";
import { errorResponse, readJson } from "@/lib/http";
import { UserError } from "@/lib/stories";
import { PROVIDERS, type Provider } from "@/lib/types";
@@ -16,12 +17,13 @@ async function mustProvider(ctx: Ctx): Promise<Provider> {
const payload = (refresh = false) => ({ settings: readAiSettings(), providers: providerStatus({ refresh }) });
/**
* Ações de uma IA: {action: "install" | "login" | "verify" | "test" | "resume"}.
* Ações de uma IA: {action: "install" | "login" | "verify" | "test" | "resume" | "usage"}.
* install — instala/atualiza a CLI em segundo plano (o log vem no GET /api/ai);
* login — abre um terminal com o login da CLI (OAuth no navegador);
* verify — refaz a detecção (depois do login ou da instalação);
* test — pergunta mínima para confirmar login/chave/cota (devolve {test});
* resume — tira a IA da pausa da reserva.
* resume — tira a IA da pausa da reserva;
* usage — relê agora quanto do limite (sessão de 5 h, semana) a IA já usou.
*/
export async function POST(request: Request, ctx: Ctx) {
try {
@@ -40,6 +42,9 @@ export async function POST(request: Request, ctx: Ctx) {
const test = await testProvider(id);
return Response.json({ ...payload(), test });
}
case "usage":
await refreshUsage({ only: id });
return Response.json(payload());
case "resume":
clearCooldown(id);
return Response.json(payload());
+3 -1
View File
@@ -1,4 +1,5 @@
import { providerStatus, readAiSettings, updateAiSettings, type AiSettingsPatch } from "@/lib/ai";
import { ensureUsageMonitor } from "@/lib/ai-usage";
import { errorResponse, readJson } from "@/lib/http";
export const dynamic = "force-dynamic";
@@ -7,13 +8,14 @@ export const dynamic = "force-dynamic";
export async function GET(request: Request) {
try {
const refresh = new URL(request.url).searchParams.get("refresh") === "1";
ensureUsageMonitor(); // uso das IAs: relê a cada 5 min enquanto o painel estiver aberto
return Response.json({ settings: readAiSettings(), providers: providerStatus({ refresh }) }, { headers: { "Cache-Control": "no-store" } });
} catch (error) {
return errorResponse(error);
}
}
/** Atualiza só o que vier: {providers?: {<ia>?: {enabled?, authMode?}}, order?: [...], fallback?: {enabled?, cooldownMin?}}. */
/** Atualiza só o que vier: {providers?: {<ia>?: {enabled?, authMode?}}, order?: [...], fallback?: {enabled?, cooldownMin?, usageLimitPercent?}}. */
export async function PUT(request: Request) {
try {
const settings = updateAiSettings(await readJson<AiSettingsPatch>(request));
@@ -1,3 +1,4 @@
import { refreshUsage } from "@/lib/ai-usage";
import { defaultModelFor, defaultProviderFor, startRun } from "@/lib/agents";
import { characterFileRel, getCharacter } from "@/lib/characters";
import { errorResponse, readJson } from "@/lib/http";
@@ -12,6 +13,7 @@ export async function POST(request: Request, ctx: Ctx) {
const character = getCharacter(id);
if (!character) throw new UserError("Personagem não encontrado.");
const body = await readJson<{ note?: string }>(request).catch(() => ({} as { note?: string }));
await refreshUsage({ maxAgeMs: 60_000 }); // uso das IAs fresco antes de escolher (Configurações → IA)
const provider = defaultProviderFor("character");
const run = startRun({
provider, model: defaultModelFor("character", provider), kind: "character",
+2
View File
@@ -1,6 +1,7 @@
// Criar história com IA pela API (o mesmo que o formulário "Nova história com IA"): cria a história
// e o primeiro episódio e põe o agente para escrever. { text, title?, kind?, provider?, model? }
// → { storyId, episodeId, runId }. Útil para automação (o coordenador dispara o agente do painel).
import { refreshUsage } from "@/lib/ai-usage";
import { defaultModelFor, defaultProviderFor, startRun } from "@/lib/agents";
import { errorResponse } from "@/lib/http";
import { slugify } from "@/lib/paths";
@@ -20,6 +21,7 @@ export async function POST(request: Request) {
for (let n = 2; getStory(id); n++) id = `${base}-${n}`;
const story = createStory({ title, id, logline: "", kind, branchCount: 2 });
const ep = createEpisode(story.id, { title: kind === "documentary" ? "" : "Abertura" });
await refreshUsage({ maxAgeMs: 60_000 }); // uso das IAs fresco antes de escolher (Configurações → IA)
const provider: Provider = PROVIDERS.includes(body.provider as Provider) ? (body.provider as Provider) : defaultProviderFor("story");
const model = String(body.model ?? "") || defaultModelFor("story", provider);
const run = startRun({ provider, model, kind: "story", request: text, storyId: story.id, episodeId: ep.id });
+3 -3
View File
@@ -27,8 +27,8 @@ const KINDS: { id: AgentKind; label: string; description: string; icon: Componen
{ id: "free", label: "Pedido livre", description: "Ajustes no projeto, testes, iluminação", icon: ChatIcon },
];
export const PROVIDER_LABEL: Record<Provider, string> = { claude: "Claude Code", codex: "GPT · Codex", gemini: "Gemini" };
const PROVIDER_SHORT: Record<Provider, string> = { claude: "Claude", codex: "GPT", gemini: "Gemini" };
export const PROVIDER_LABEL: Record<Provider, string> = { claude: "Claude Code", codex: "GPT · Codex", antigravity: "Antigravity" };
const PROVIDER_SHORT: Record<Provider, string> = { claude: "Claude", codex: "GPT", antigravity: "Antigravity" };
const PLACEHOLDER: Record<AgentKind, string> = {
story: "Ex.: Um entregador recebe um pacote sem remetente; toda vez que tenta entregar, o endereço muda. Suspense leve com humor.",
@@ -254,7 +254,7 @@ export function AgentConsole(props: {
{/* 4. Pedido */}
<div className="grid gap-4 border-t border-line bg-surface p-5">
<div className="grid gap-3 md:grid-cols-3">
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
<Field label="História">
<Select value={storyId} onChange={(e) => { setStoryId(e.target.value); setEpisodeId(""); }}>
<option value="">Nenhuma</option>
+98 -12
View File
@@ -1,12 +1,12 @@
"use client";
// Configurações → IA: as três CLIs (Claude Code, Codex/GPT e Gemini) num cartão cada — instalar/atualizar, ligar,
// Configurações → IA: as três CLIs (Claude Code, Codex/GPT e Antigravity) num cartão cada — instalar/atualizar, ligar,
// entrar com a conta (OAuth, num terminal) ou colar a chave de API (cofre DPAPI), testar — e a IA reserva
// (troca sozinha quando uma cair, pausa e ordem). API: GET/PUT /api/ai e POST/PUT/DELETE /api/ai/[provider].
import { useCallback, useEffect, useState, type ReactNode } from "react";
import type { AiSettings, AuthMode, ProviderStatus, TestResult } from "@/lib/ai";
import type { AiSettings, AuthMode, ProviderStatus, ProviderUsage, TestResult } from "@/lib/ai";
import type { Provider } from "@/lib/types";
import { CopyButton } from "./copy-button";
import { AlertIcon, ArrowLeftIcon, CheckIcon, CpuIcon, DownloadIcon, KeyIcon, LinkIcon, PauseIcon, PlayIcon, RefreshIcon, TrashIcon, UsersIcon } from "./icons";
import { AlertIcon, ArrowLeftIcon, ChartIcon, CheckIcon, CpuIcon, DownloadIcon, KeyIcon, LinkIcon, PauseIcon, PlayIcon, RefreshIcon, TrashIcon, UsersIcon } from "./icons";
import { Badge, Button, Card, ChoiceGroup, Feedback, Field, Input, Select, Spinner, Switch, cx, type Tone } from "./ui";
type Payload = { settings: AiSettings; providers: ProviderStatus[]; test?: TestResult };
@@ -28,10 +28,11 @@ async function aiCall<T = Payload>(path: string, method = "GET", body?: unknown)
}
const COOLDOWN_OPTIONS = [5, 15, 30, 60, 120];
const LIMIT_OPTIONS = [70, 80, 90, 95, 100];
const PROVIDER_TAGLINE: Record<Provider, string> = {
claude: "Cena, Godot e ajustes no projeto. Mostra o custo em US$.",
codex: "GPT: enredo e roteiro por padrão. Usa a conta do ChatGPT.",
gemini: "Google. Boa reserva com chave do AI Studio (tem cota gratuita).",
antigravity: "Google, pela conta (sem chave): Gemini 4 e 3.8 Flash. Cota de 5 h e semanal.",
};
const time = (iso: string) => new Date(iso).toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" });
@@ -40,8 +41,10 @@ const time = (iso: string) => new Date(iso).toLocaleTimeString("pt-BR", { hour:
function statusBadge(p: ProviderStatus): { tone: Tone; text: string } {
if (!p.settings.enabled) return { tone: "neutral", text: "desligada" };
if (!p.installed) return { tone: "warning", text: "não instalada" };
if (!p.ready) return { tone: "warning", text: p.settings.authMode === "apiKey" ? "falta a chave" : "falta entrar" };
if (!p.ready && p.lastTest && !p.lastTest.ok) return { tone: "danger", text: "falhou no teste" };
if (!p.ready) return { tone: "warning", text: p.settings.authMode === "apiKey" ? "falta a chave" : p.oauth.state === "unknown" ? "falta testar" : "falta entrar" };
if (p.cooldown) return { tone: "danger", text: `em pausa até ${time(p.cooldown.until)}` };
if (p.overLimit) return { tone: "warning", text: p.usage?.blocked ? "bateu o limite" : "perto do limite" };
return { tone: "success", text: "pronta" };
}
@@ -94,7 +97,7 @@ export function AiSettings() {
<Button variant="ghost" size="sm" onClick={() => void load(true)}><RefreshIcon size={15} />Procurar de novo</Button>
</div>
<div className="grid gap-5 xl:grid-cols-3">
{data.settings.order.map((id) => <ProviderCard key={id} status={byId[id]} onChange={setData} />)}
{data.settings.order.map((id) => <ProviderCard key={id} status={byId[id]} limit={data.settings.fallback.usageLimitPercent} onChange={setData} />)}
</div>
</section>
</div>
@@ -132,6 +135,13 @@ function FallbackCard({ data, onChange }: { data: Payload; onChange: (next: Payl
<Switch label="Trocar de IA sozinho" checked={settings.fallback.enabled} busy={busy === "enabled"}
hint={settings.fallback.enabled ? "Ligado: a tarefa continua na próxima IA, que confere o que a anterior já fez." : "Desligado: a tarefa para com erro e você escolhe outra IA."}
onChange={(enabled) => void save("enabled", { fallback: { enabled } }, enabled ? "Reserva ligada." : "Reserva desligada.")} />
<Field label="Sair da frente com o uso em" hint="Quando a sessão de 5 h ou a semana chega aqui, a tarefa já começa na próxima IA, para não gastar o limite inteiro (sobra para você usar no terminal).">
<Select value={settings.fallback.usageLimitPercent} disabled={busy === "limit"}
onChange={(e) => void save("limit", { fallback: { usageLimitPercent: Number(e.target.value) } }, "Limite de uso salvo.")}>
{[...new Set([...LIMIT_OPTIONS, settings.fallback.usageLimitPercent])].sort((a, b) => a - b)
.map((v) => <option key={v} value={v}>{v === 100 ? "100% (só quando bater)" : `${v}%`}</option>)}
</Select>
</Field>
<Field label="Depois de cair, pular a IA por" hint="Evita insistir numa IA sem cota. Dá para tirar da pausa no cartão dela.">
<Select value={settings.fallback.cooldownMin} disabled={busy === "cooldown"}
onChange={(e) => void save("cooldown", { fallback: { cooldownMin: Number(e.target.value) } }, "Pausa salva.")}>
@@ -149,7 +159,10 @@ function FallbackCard({ data, onChange }: { data: Payload; onChange: (next: Payl
return (
<li key={id} className={cx("flex items-center gap-3 rounded-control border border-line bg-sunken/60 px-3 py-2", !p.ready && "opacity-70")}>
<span className="grid size-6 shrink-0 place-items-center rounded-full bg-overlay text-xs font-semibold tabular-nums text-fg-muted">{index + 1}</span>
<span className="min-w-0 flex-1 truncate text-sm font-medium text-fg">{p.label}</span>
<span className="min-w-0 flex-1 truncate text-sm font-medium text-fg">
{p.label}
{peak(p.usage) !== null && <span className="ml-2 text-xs font-normal tabular-nums text-fg-subtle">{Math.round(peak(p.usage)!)}% usado</span>}
</span>
<Badge tone={badge.tone}>{badge.text}</Badge>
<span className="flex gap-1">
<Button variant="ghost" size="sm" aria-label={`Subir ${p.label}`} disabled={index === 0 || busy !== null}
@@ -171,7 +184,7 @@ function FallbackCard({ data, onChange }: { data: Payload; onChange: (next: Payl
/* ---------- Cartão de cada IA ---------- */
function ProviderCard({ status: p, onChange }: { status: ProviderStatus; onChange: (next: Payload) => void }) {
function ProviderCard({ status: p, limit, onChange }: { status: ProviderStatus; limit: number; onChange: (next: Payload) => void }) {
const [busy, setBusy] = useState<string | null>(null);
const [message, setMessage] = useState<Message>(null);
const [key, setKey] = useState("");
@@ -209,6 +222,10 @@ function ProviderCard({ status: p, onChange }: { status: ProviderStatus; onChang
<InstallSection p={p} busy={busy} onInstall={() => void act("install", post("install"))} />
{p.installed && p.settings.enabled && (
<UsageSection p={p} limit={limit} busy={busy} onRefresh={() => void act("usage", post("usage"))} />
)}
{p.installed && (
<section className="grid gap-3 border-t border-line pt-4" aria-label={`Como o ${p.label} entra`}>
<ChoiceGroup<AuthMode> name={`auth-${p.id}`} legend="Como entra" value={p.settings.authMode}
@@ -238,7 +255,7 @@ function ProviderCard({ status: p, onChange }: { status: ProviderStatus; onChang
</div>
)}
<div className="flex flex-wrap items-center gap-3">
<Button variant="secondary" size="sm" disabled={busy !== null || !p.ready}
<Button variant="secondary" size="sm" disabled={busy !== null || (p.settings.authMode === "apiKey" && !p.apiKey.saved)}
onClick={() => void act("test", post("test"))}>
{busy === "test" ? <><Spinner className="size-3.5" />Testando…</> : <><CheckIcon size={15} />Testar</>}
</Button>
@@ -257,6 +274,71 @@ function ProviderCard({ status: p, onChange }: { status: ProviderStatus; onChang
);
}
/** Maior uso entre as janelas ainda valendo (null = sem leitura). */
function peak(usage: ProviderUsage | null): number | null {
const live = (usage?.windows ?? []).filter((w) => !w.resetsAt || Date.parse(w.resetsAt) > Date.now());
return live.length ? Math.max(...live.map((w) => w.usedPercent)) : null;
}
const ago = (iso: string) => {
const minutes = Math.round((Date.now() - Date.parse(iso)) / 60_000);
return minutes < 1 ? "agora" : minutes < 60 ? `há ${minutes} min` : `às ${time(iso)}`;
};
const when = (iso: string) => {
const date = new Date(iso);
const sameDay = date.toDateString() === new Date().toDateString();
return sameDay ? time(iso) : `${date.toLocaleDateString("pt-BR", { weekday: "short", day: "2-digit", month: "2-digit" })} ${time(iso)}`;
};
function UsageSection({ p, limit, busy, onRefresh }: { p: ProviderStatus; limit: number; busy: string | null; onRefresh: () => void }) {
const usage = p.usage;
const canRead = p.settings.authMode === "oauth";
return (
<section className="grid gap-3 border-t border-line pt-4" aria-label={`Uso do ${p.label}`}>
<div className="flex items-center justify-between gap-2">
<span className="flex items-center gap-1.5 text-[0.8125rem] font-medium text-fg-muted"><ChartIcon size={14} />Uso do limite</span>
{canRead && (
<Button variant="ghost" size="sm" disabled={busy !== null} onClick={onRefresh} aria-label={`Atualizar o uso do ${p.label}`}>
{busy === "usage" ? <Spinner className="size-3.5" /> : <RefreshIcon size={14} />}{usage ? ago(usage.at) : "Ler agora"}
</Button>
)}
</div>
{!canRead ? (
<p className="text-xs leading-relaxed text-fg-subtle">
Na chave de API a cobrança é por uso: não há janela de limite para mostrar.
</p>
) : !usage ? (
<p className="text-xs text-fg-subtle">Ainda não lido. A leitura não gasta tokens.</p>
) : (
<div className="grid gap-2.5">
{usage.windows.map((w) => {
const expired = !!w.resetsAt && Date.parse(w.resetsAt) <= Date.now();
const value = expired ? 0 : w.usedPercent;
const tone = value >= 100 ? "bg-danger" : value >= limit ? "bg-warning" : value >= limit - 20 ? "bg-accent" : "bg-success";
return (
<div key={w.id} className="grid gap-1">
<div className="flex items-baseline justify-between gap-2 text-xs">
<span className="text-fg-muted">{w.label}</span>
<span className="tabular-nums text-fg">{expired ? "zerou" : `${Math.round(w.usedPercent)}%`}
{w.resetsAt && !expired && <span className="text-fg-subtle"> · zera {when(w.resetsAt)}</span>}</span>
</div>
<div className="relative h-1.5 overflow-hidden rounded-full bg-overlay" role="meter" aria-valuemin={0} aria-valuemax={100}
aria-valuenow={Math.round(value)} aria-label={`${w.label}: ${Math.round(value)}% usado`}>
<span className={cx("absolute inset-y-0 left-0 rounded-full", tone)} style={{ width: `${Math.min(100, value)}%` }} />
<span aria-hidden="true" className="absolute inset-y-0 w-px bg-fg-subtle/60" style={{ left: `${limit}%` }} />
</div>
</div>
);
})}
{p.overLimit && <p className="text-xs text-warning">{p.overLimit}: as tarefas novas começam na próxima IA da ordem.</p>}
{usage.note && <p className="text-xs text-fg-subtle">{usage.note}</p>}
{usage.error && <p className="text-xs text-danger">{usage.error}</p>}
</div>
)}
</section>
);
}
function InstallSection({ p, busy, onInstall }: { p: ProviderStatus; busy: string | null; onInstall: () => void }) {
const job = p.install;
const running = job?.status === "running";
@@ -279,9 +361,13 @@ function InstallSection({ p, busy, onInstall }: { p: ProviderStatus; busy: strin
<code className="min-w-0 flex-1 truncate font-mono text-xs text-fg-muted">{p.meta.installCommand}</code>
<CopyButton text={p.meta.installCommand} label="Copiar comando" variant="ghost" size="sm" />
</div>
<Button variant="flame" size="sm" className="justify-self-start" disabled={running || busy !== null} onClick={onInstall}>
{running ? <><Spinner className="size-3.5" />Instalando…</> : <><DownloadIcon size={15} />Instalar {p.label}</>}
</Button>
{p.meta.canInstall ? (
<Button variant="flame" size="sm" className="justify-self-start" disabled={running || busy !== null} onClick={onInstall}>
{running ? <><Spinner className="size-3.5" />Instalando…</> : <><DownloadIcon size={15} />Instalar {p.label}</>}
</Button>
) : (
<p className="text-xs text-fg-subtle">Depois de instalar, clique em &quot;Procurar de novo&quot;.</p>
)}
</div>
)}
{job && (job.status !== "success" || !p.installed) && (
+10 -2
View File
@@ -60,6 +60,7 @@ export function SourcesPage() {
<tbody>
{channels.map((c) => (
<SourceRow key={c.id} channel={c} accounts={channelAccounts[c.id] ?? []} showEmotes={games !== null} onChanged={reload}
recording={sessions.find((s) => s.channelId === c.id && (s.status === "recording" || s.status === "starting")) ?? null}
onConfigure={() => setCutScope({
kind: "channel", channel: c,
// Sessões vêm da mais nova para a mais antiga: a primeira da fonte dá o quadro de referência.
@@ -131,8 +132,10 @@ function languageOptions(current: string | undefined) {
/* ---------- Linha da fonte ---------- */
function SourceRow({ channel: c, accounts, showEmotes, onChanged, onConfigure }: {
function SourceRow({ channel: c, accounts, showEmotes, onChanged, onConfigure, recording }: {
channel: ClipperChannel; accounts: { id: string; name: string }[]; showEmotes: boolean; onChanged: () => void; onConfigure: () => void;
/** Sessão gravando AGORA desta fonte (a coluna "Ao vivo" mostra ela, não a última checagem do monitor). */
recording: ClipperSession | null;
}) {
const { pending, message, setMessage, run } = useClipperAction(onChanged);
const [renaming, setRenaming] = useState(false);
@@ -141,6 +144,8 @@ function SourceRow({ channel: c, accounts, showEmotes, onChanged, onConfigure }:
const base = `channels/${encodeURIComponent(c.id)}`;
const name = c.displayName || c.channel;
const isLive = checked ? checked.live : c.lastStatus === "ao vivo";
// A última checagem do monitor envelhece (monitor pausado/desligado): "ao vivo" de 2 h atrás não é "ao vivo agora".
const staleCheck = !checked && Boolean(c.lastCheckAt) && Date.now() - Date.parse(c.lastCheckAt ?? "") > 10 * 60_000;
const paused = c.monitor && Boolean(c.monitorPausedAt);
const busy = pending !== null;
const emotesId = useId();
@@ -206,7 +211,10 @@ function SourceRow({ channel: c, accounts, showEmotes, onChanged, onConfigure }:
</Td>
<Td>
{isLive ? <Badge tone="danger" pulse>ao vivo</Badge> : c.lastStatus === "offline" || checked ? <Badge>offline</Badge> : <span className="text-fg-subtle">—</span>}
{recording ? <Badge tone="danger" pulse>gravando #{recording.id}</Badge>
: isLive && staleCheck ? <span className="text-xs text-fg-subtle" title="Resultado da última checagem do monitor; use “Checar agora”.">ao vivo {formatRelative(c.lastCheckAt ?? "")}</span>
: isLive ? <Badge tone="danger" pulse>ao vivo</Badge>
: c.lastStatus === "offline" || checked ? <Badge>offline</Badge> : <span className="text-fg-subtle">—</span>}
</Td>
<Td>
+21 -2
View File
@@ -104,7 +104,8 @@ export type ClipperSession = {
};
export type GameSource = "platform" | "screen" | "user" | "";
export type MemoryEntry = { fromS: number; toS: number; summary: string };
/** `summaryPt`: fonte em inglês — o resumo em português para o painel (`summary` é o inglês que vai à IA). */
export type MemoryEntry = { fromS: number; toS: number; summary: string; summaryPt?: string };
export type CamDetect = {
hasWebcam: boolean; cam: Rect | null; gameOnScreen?: boolean; frame?: string; at?: string;
/** Quem achou: yunet = local (rosto no quadro, sem IA) · ai = IA olhando quadros · manual = você marcou. */
@@ -133,10 +134,22 @@ export type ClipAnalysis = {
action_start_s: number;
reaction_end_s: number;
hook: string;
/** Fonte em inglês: os textos traduzidos para o painel (o vídeo usa os originais, em inglês). */
pt?: { what_happened: string; screen: string; speech: string; chat_meaning: string; hook: string };
};
/** Fonte em inglês: a fala do corte em frases (tempo da sessão) com a tradução em português. */
export type ClipTranslation = {
language: string; startS: number; endS: number; model?: string;
lines: { s: number; e: number; text: string; pt: string }[];
};
export type ClipJudge = null
| { model: string; keep: boolean; score: number; reason: string; analysis?: ClipAnalysis | null; analystModel?: string }
| {
model: string; keep: boolean; score: number; reason: string; analysis?: ClipAnalysis | null; analystModel?: string;
/** Fonte em inglês: título, legenda e motivo em português (só para ler; o post sai em inglês). */
pt?: { title?: string; caption?: string; reason?: string };
}
| { error: string };
export type ClipTags = { risada?: number; susto?: number; hype?: number; clip?: number };
@@ -156,6 +169,8 @@ export type Clip = {
emotes?: Record<string, number>;
// Cortes da varredura da IA (source "ai").
proposalTitle?: string; proposalScore?: number; proposalReason?: string; scanFromS?: number; scanToS?: number;
/** Fonte em inglês: a proposta da varredura em português. */
proposalTitlePt?: string; proposalReasonPt?: string;
/** Reação no rosto do streamer dentro do trecho (opcional: só com câmera e rastreio ligado). */
face?: FaceReaction;
/** Corte de fonte "face": o apoio do áudio (sinal suavizado) e do chat (mensagens de reação) que deixou o rosto virar corte. */
@@ -165,6 +180,8 @@ export type Clip = {
title: string;
caption: string;
transcript: string;
/** Fonte em inglês: fala traduzida por frase; null = sessão em português ou ainda não traduzida. */
translation?: ClipTranslation | null;
status: ClipStatus;
file: string | null;
thumb: string | null;
@@ -195,6 +212,8 @@ export type CutSettings = {
caption: {
enabled: boolean; font: string; size: number; color: string; highlight: string; outline: string;
outlineWidth: number; y: number | null; uppercase: boolean; maxWords: number;
/** Só para desenvolver (fonte em inglês): a tradução em português embaixo da legenda. Nunca publicar ligado. */
translation?: boolean;
};
credit: { enabled: boolean; position: "top" | "bottom"; size: number };
duration: { minS: number; maxS: number; backtrackS: number };
+47 -1
View File
@@ -141,9 +141,11 @@ function ClipBody({ clip, onChanged, publishJobs }: { clip: Clip; onChanged: ()
)}
</form>
<Portuguese clip={clip} pending={pending} run={run} />
{editable && <TrimControl clip={clip} pending={pending} run={run} />}
{clip.transcript && (
{clip.transcript && !clip.translation?.lines.length && (
<details className="group rounded-control border border-line bg-sunken/30 px-3 py-2 text-[0.8125rem]">
<summary className="cursor-pointer text-fg-muted select-none hover:text-fg">Transcrição</summary>
<p className="mt-2 leading-relaxed text-fg-muted">{clip.transcript}</p>
@@ -156,6 +158,50 @@ function ClipBody({ clip, onChanged, publishJobs }: { clip: Clip; onChanged: ()
);
}
/** Fonte em inglês (doc/clipador/IDIOMAS.md): o vídeo, o título e a legenda do post saem em inglês; aqui a equipe lê
* a tradução — título, legenda e a fala frase a frase. Some em sessão em português. */
function Portuguese({ clip, pending, run }: {
clip: Clip;
pending: string | null;
run: ReturnType<typeof useClipperAction>["run"];
}) {
const pt = clip.judge && "pt" in clip.judge ? clip.judge.pt : undefined;
const lines = clip.translation?.lines ?? [];
const english = (clip.language ?? "").toLowerCase().startsWith("en");
if (!english && !pt && !lines.length) return null;
const translate = () => run("translate", () => clipperCall<Clip>(`clips/${clip.id}/translate`, "POST"), "Fala traduzida.");
return (
<section aria-label="Tradução para o português" className="grid gap-2.5 rounded-control border border-info/25 bg-info-soft/30 px-3.5 py-3">
<p className="flex flex-wrap items-center gap-2 text-xs">
<span className="font-semibold text-info">Em português</span>
<span className="text-fg-subtle">só para entender — o vídeo, o título e a legenda do post saem em inglês</span>
</p>
{pt?.title && <p className="text-[0.875rem] font-medium text-fg">{pt.title}</p>}
{pt?.caption && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{pt.caption}</p>}
{lines.length > 0 ? (
<details className="text-[0.8125rem]">
<summary className="cursor-pointer text-fg-muted select-none hover:text-fg">O que ele fala ({lines.length} frases)</summary>
<ol className="mt-2 grid gap-2">
{lines.map((line, i) => (
<li key={i} className="grid grid-cols-[3.25rem_minmax(0,1fr)] gap-2">
<span className="pt-px font-mono text-[0.6875rem] text-fg-subtle tabular-nums">{formatClock(line.s - clip.startS)}</span>
<span className="grid gap-0.5">
<span className="text-fg">{line.pt}</span>
<span className="text-xs text-fg-subtle italic">{line.text}</span>
</span>
</li>
))}
</ol>
</details>
) : english && clip.transcript ? (
<Button type="button" variant="ghost" size="sm" className="justify-self-start" disabled={pending !== null} onClick={() => void translate()}>
{pending === "translate" && <Spinner className="size-3.5" />}Traduzir a fala
</Button>
) : null}
</section>
);
}
/** Rodapé: anterior/próximo à esquerda, ações da etapa no meio, apagar à direita. */
function ClipFooter({ clip, position, onPrev, onNext, onClose, onChanged, publishJobs, onPublished, deleting, onDelete }: {
clip: Clip; position: { index: number; total: number } | null; onPrev: (() => void) | null; onNext: (() => void) | null; onClose: () => void;
+13 -5
View File
@@ -149,7 +149,7 @@ export function JudgeVerdict({ clip }: { clip: Clip }) {
<Badge tone={judge.keep ? "success" : "warning"} dot={false}>{judge.keep ? "manteve" : "descartou"}</Badge>
<span className="font-mono text-[0.6875rem] text-fg-subtle">{judge.model}</span>
</p>
{judge.reason && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{judge.reason}</p>}
{(judge.pt?.reason || judge.reason) && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{judge.pt?.reason || judge.reason}</p>}
</div>
</>
);
@@ -159,6 +159,9 @@ export function JudgeVerdict({ clip }: { clip: Clip }) {
export function Proposal({ clip }: { clip: Clip }) {
const r = clip.reasons ?? {};
if (clip.source !== "ai" || !(r.proposalTitle || r.proposalReason)) return null;
// Fonte em inglês: mostra o português (a proposta original, em inglês, fica no title do parágrafo).
const title = r.proposalTitlePt || r.proposalTitle;
const reason = r.proposalReasonPt || r.proposalReason;
return (
<div className="grid gap-1 rounded-control border border-info/20 bg-info-soft/40 px-3.5 py-2.5 text-xs">
<p className="flex flex-wrap items-center gap-2">
@@ -166,8 +169,8 @@ export function Proposal({ clip }: { clip: Clip }) {
{r.proposalScore !== undefined && <Badge tone="info" dot={false}>proposta {formatScore(r.proposalScore)}/10</Badge>}
{r.scanFromS !== undefined && r.scanToS !== undefined && <span className="text-fg-subtle">janela {formatClock(r.scanFromS)}–{formatClock(r.scanToS)}</span>}
</p>
{r.proposalTitle && <p className="font-medium text-fg">{r.proposalTitle}</p>}
{r.proposalReason && <p className="leading-relaxed text-fg-muted">{r.proposalReason}</p>}
{title && <p className="font-medium text-fg" title={r.proposalTitlePt ? r.proposalTitle : undefined}>{title}</p>}
{reason && <p className="leading-relaxed text-fg-muted">{reason}</p>}
</div>
);
}
@@ -175,8 +178,13 @@ export function Proposal({ clip }: { clip: Clip }) {
/** O que o ANALISTA (1º juiz) entendeu: situação, o que aconteceu, confiança; tela/fala/chat expansíveis. */
export function AnalysisView({ analysis: a, model }: { analysis: ClipAnalysis; model?: string }) {
const confidence = Math.round(Math.min(1, Math.max(0, a.confidence ?? 0)) * 100);
// Fonte em inglês: a IA trabalhou em inglês e mandou a tradução em `pt`; o gancho vai no vídeo em inglês.
const pt = a.pt;
const details = [
{ label: "Tela", text: a.screen }, { label: "Fala", text: a.speech }, { label: "Chat", text: a.chat_meaning }, { label: "Gancho", text: a.hook },
{ label: "Tela", text: pt?.screen || a.screen }, { label: "Fala", text: pt?.speech || a.speech },
{ label: "Chat", text: pt?.chat_meaning || a.chat_meaning },
{ label: "Gancho", text: pt ? `${a.hook}${pt.hook ? ` (${pt.hook})` : ""}` : a.hook },
...(pt && a.what_happened ? [{ label: "Original", text: a.what_happened }] : []),
].filter((d) => d.text);
return (
<div className="grid gap-2 rounded-control border border-line bg-sunken/40 px-3.5 py-2.5">
@@ -188,7 +196,7 @@ export function AnalysisView({ analysis: a, model }: { analysis: ClipAnalysis; m
</span>
{model && <span className="font-mono text-[0.6875rem] text-fg-subtle">analista {model}</span>}
</p>
{a.what_happened && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{a.what_happened}</p>}
{(pt?.what_happened || a.what_happened) && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{pt?.what_happened || a.what_happened}</p>}
{details.length > 0 && (
<details className="text-xs">
<summary className="cursor-pointer text-fg-subtle select-none hover:text-fg">Tela, fala e chat</summary>
@@ -117,6 +117,10 @@ function ClipRow({ clip, sessions, stage, nameOf, defaultLanguage, publishing, o
<Td>
<div className="grid min-w-0 max-w-[36rem] gap-0.5">
<p className="truncate font-medium text-fg" title={clip.title || undefined}>{title}</p>
{/* Fonte em inglês: o título do post é o inglês acima; a tradução é só para a equipe entender. */}
{clip.judge && "pt" in clip.judge && clip.judge.pt?.title && (
<p className="truncate text-xs text-fg-muted" title="Tradução do título (o post sai em inglês)">🇧🇷 {clip.judge.pt.title}</p>
)}
<p className="flex flex-wrap items-center gap-x-2 text-xs text-fg-subtle">
<span className="text-fg-muted">{name}</span>
<span aria-hidden="true">·</span>
@@ -510,6 +510,9 @@ function CutSettingsEditor({ scope, onDirty, onClose, onSaved }: {
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Ritmo e posição</h4>
<RangeField label="Palavras por vez" min={1} max={6} step={1} value={draft.caption.maxWords} onChange={(maxWords) => update("caption", { maxWords })} />
<Switch label="Caixa alta" checked={draft.caption.uppercase} onChange={(uppercase) => update("caption", { uppercase })} />
<Switch label="Tradução em português embaixo (teste)" checked={draft.caption.translation ?? false}
onChange={(translation) => update("caption", { translation })}
hint="Só para desenvolver, em fonte em inglês: a fala traduzida aparece embaixo da legenda. Desligue antes de publicar." />
<Switch label="Posição automática" checked={draft.caption.y === null}
onChange={(auto) => update("caption", { y: auto ? null : 0.74 })}
hint={horizontal ? "O serviço escolhe a altura no quadro horizontal." : "Na emenda entre câmera e jogo, ou a cerca de 74% da altura."} />
+3 -4
View File
@@ -1,5 +1,5 @@
"use client";
// Juiz (IA) do Clipador: provedor (Codex/GPT, Claude, Gemini ou desligado), os dois juízes (analista e editor),
// Juiz (IA) do Clipador: provedor (Codex/GPT, Claude ou desligado), os dois juízes (analista e editor),
// nota mínima e as opções da IA (varredura, visão, achar câmera). Roda pela CLI do PC; login, chave de API e IA
// reserva ficam em Configurações → IA (/settings/ai, contrato em doc/ia.md).
import Link from "next/link";
@@ -59,7 +59,7 @@ export function JudgeForm({ judge, onSaved }: { judge: JudgeConfig; onSaved: (ne
: !judge.available ? <Badge tone="danger">CLI não encontrada</Badge>
: judge.unavailableReason ? <Badge tone="warning">indisponível</Badge> : <Badge tone="success">disponível</Badge>}
</span>}
description={<>A IA confirma o momento, dá nota de 0 a 10 e escreve título e legenda. Roda pela CLI do Codex, do Claude ou do Gemini
description={<>A IA confirma o momento, dá nota de 0 a 10 e escreve título e legenda. Roda pela CLI do Codex ou do Claude
no PC; login ou chave de API e a IA reserva (se a escolhida cair, a próxima assume) se configuram
em <Link href="/settings/ai" className="font-medium text-accent underline-offset-2 hover:underline">Configurações → IA</Link>.</>}>
<form className="grid gap-7" onSubmit={(e) => { e.preventDefault(); void save(); }}>
@@ -67,7 +67,6 @@ export function JudgeForm({ judge, onSaved }: { judge: JudgeConfig; onSaved: (ne
options={[
{ value: "codex", label: "Codex (GPT)", hint: "padrão" },
{ value: "claude", label: "Claude" },
{ value: "gemini", label: "Gemini", hint: "chave de API" },
{ value: "off", label: "Desligado", hint: "só heurística" },
]} />
@@ -136,7 +135,7 @@ export function JudgeForm({ judge, onSaved }: { judge: JudgeConfig; onSaved: (ne
{judge.provider !== "off" && !judge.available && (
<Feedback ok={false}>
A CLI do {PROVIDER_LABEL[judge.provider]} não foi encontrada. Instale e faça login no terminal ({judge.provider === "codex" ? <code>codex login</code> : judge.provider === "gemini" ? <code>npm install -g @google/gemini-cli</code> : <code>claude</code>}), ou escolha outro provedor.
A CLI do {PROVIDER_LABEL[judge.provider]} não foi encontrada. Instale e faça login no terminal ({judge.provider === "codex" ? <code>codex login</code> : <code>claude</code>}), ou escolha outro provedor.
</Feedback>
)}
{judge.provider !== "off" && judge.available && judge.unavailableReason && (
@@ -163,13 +163,13 @@ function SessionDetail({ session: s, name, clips, games, onChanged, onGamesChang
{/* 3. O que está acontecendo: resumo da IA + jogo */}
{showNow && (
<section aria-label="O que está acontecendo" className="grid rounded-card border border-line bg-surface shadow-card">
{lastMemory?.summary && (
{(lastMemory?.summaryPt || lastMemory?.summary) && (
<div className="flex items-start gap-2.5 px-5 py-3.5">
<SparkIcon size={15} className="mt-0.5 shrink-0 text-violet" />
<p className="line-clamp-3 min-h-[2lh] min-w-0 flex-1 text-[0.875rem] leading-relaxed text-fg-muted" title={lastMemory.summary}>
<p className="line-clamp-3 min-h-[2lh] min-w-0 flex-1 text-[0.875rem] leading-relaxed text-fg-muted" title={lastMemory.summaryPt || lastMemory.summary}>
<span className="font-semibold text-violet">{live ? "Agora na live" : "Último resumo da IA"}</span>
<span className="text-fg-subtle tabular-nums"> · {formatClock(lastMemory.fromS)}–{formatClock(lastMemory.toS)}</span>
<span className="text-fg-subtle">: </span>{lastMemory.summary}
<span className="text-fg-subtle">: </span>{lastMemory.summaryPt || lastMemory.summary}
</p>
<SummaryCadence clock={clock} live={live} scannedUntilS={s.scannedUntilS ?? null} intervalS={scanIntervalS} />
</div>
+1 -1
View File
@@ -10,7 +10,7 @@ import { PageHeader, cx } from "./ui";
export type SettingsSection = { href: string; label: string; hint: string; description: string; icon: ComponentType<{ size?: number }> };
export const SETTINGS_SECTIONS: SettingsSection[] = [
{ href: "/settings/ai", label: "IA", hint: "Claude, GPT e Gemini", icon: CpuIcon,
{ href: "/settings/ai", label: "IA", hint: "Claude, GPT e Antigravity", icon: CpuIcon,
description: "Quais IAs o CenaForge usa, como cada uma entra (conta ou chave de API) e a ordem da reserva quando uma cair." },
{ href: "/settings/publishing", label: "Publicação", hint: "Horários e pausa", icon: ClockIcon,
description: "Pausar tudo, os horários bons de cada rede, o fuso e de quanto em quanto tempo ler os números dos posts." },
+1 -1
View File
@@ -40,7 +40,7 @@ const NAV: NavItem[] = [
{ href: "/characters", label: "Personagens", hint: "Elenco reaproveitável", icon: UsersIcon },
{ href: "/assets", label: "Assets", hint: "Biblioteca e envios", icon: CubeIcon },
{ href: "/voices", label: "Vozes", hint: "Narração e legenda", icon: MicIcon },
{ href: "/agent", label: "Agente", hint: "Claude, GPT e Gemini", icon: TerminalIcon },
{ href: "/agent", label: "Agente", hint: "Claude, GPT e Antigravity", icon: TerminalIcon },
];
/** Depois do estúdio: onde as histórias vão ao ar. */
+2 -2
View File
@@ -13,7 +13,7 @@ import { Button, ChoiceGroup, Feedback, Input, Kbd, Select, Spinner, Textarea, c
const MIN_CHARS = 20;
const MAX_CHARS = 20_000;
const PROVIDER_NAME: Record<Provider, string> = { codex: "GPT · Codex", claude: "Claude", gemini: "Gemini" };
const PROVIDER_NAME: Record<Provider, string> = { codex: "GPT · Codex", claude: "Claude", antigravity: "Antigravity" };
export function StoryComposer({ autoProvider, available, models }: {
/** Agente que o modo automático vai usar agora (Codex, se estiver instalado). */
@@ -87,7 +87,7 @@ export function StoryComposer({ autoProvider, available, models }: {
onChange={(next) => { setProvider(next); setModel(""); }}
options={[
{ value: "", label: `Automático (${PROVIDER_NAME[autoProvider]})` },
...(["claude", "codex", "gemini"] as const).filter((p) => p !== autoProvider)
...(["claude", "codex", "antigravity"] as const).filter((p) => p !== autoProvider)
.map((p) => ({ value: p, label: PROVIDER_NAME[p], disabled: !available[p] })),
]} />
<label className="grid content-start gap-2">
+96 -62
View File
@@ -1,4 +1,4 @@
// Agentes de código (Claude Code, Codex e Gemini) chamados pela CLI, como no VS Code.
// Agentes de código (Claude Code, Codex e Antigravity) chamados pela CLI, como no VS Code.
// Instalação, login/chave e a IA reserva ficam em lib/ai.ts (Configurações → IA).
//
// Segurança (decisão do usuário: "edita sozinho no projeto"):
@@ -14,8 +14,10 @@ import { all, get, now, run } from "./db";
import { DATA_DIR, REPO_ROOT, rel } from "./paths";
import { buildPrompt } from "./prompts";
import {
PROVIDER_META, geminiModels, isAvailabilityError, markUnavailable, nextFallback, providerEnv, providerStatus, readyChain, resolvedFor,
PROVIDER_META, antigravityModels, isAvailabilityError, markUnavailable, nextFallback, overLimit, providerEnv, providerStatus, readAiSettings,
readyChain, resolvedFor,
} from "./ai";
import { recordClaudeRateLimit, refreshUsage } from "./ai-usage";
import { killTree, lineSplitter } from "./proc";
import { onAgentRunClosed } from "./branches";
import { UserError, getEpisodeById, getStory, syncStoryMeta } from "./stories";
@@ -96,7 +98,7 @@ function codexModels(): ModelOption[] {
/** Modelos que o seletor oferece por agente. */
export function models(): Record<Provider, ModelOption[]> {
return { claude: CLAUDE_MODELS, codex: codexModels(), gemini: [{ id: "", label: "Padrão da CLI (automático)" }, ...geminiModels()] };
return { claude: CLAUDE_MODELS, codex: codexModels(), antigravity: [{ id: "", label: "Padrão da CLI" }, ...antigravityModels()] };
}
/** Modelo sugerido por tipo de tarefa (economia de tokens). */
@@ -117,7 +119,7 @@ export function defaultProviderFor(kind: AgentKind): Provider {
/** Modelo padrão: o do tipo de tarefa só vale para o Claude; no Codex, o do config.toml. */
export function defaultModelFor(kind: AgentKind, provider: Provider): string {
if (provider === "gemini") return "";
if (provider === "antigravity") return "";
return provider === "claude" ? DEFAULT_MODEL[kind] : CODEX_DEFAULT_MODEL[kind];
}
@@ -155,7 +157,7 @@ export function busy(): boolean {
const PROVIDER_NOTE: Record<Provider, string> = {
claude: "Claude Code CLI em modo não interativo (-p, stream-json); edição automática dentro do projeto e comandos liberados.",
codex: "Codex CLI (codex exec --json) com sandbox workspace-write: escreve só dentro do projeto.",
gemini: "Gemini CLI (-p, stream-json) com edição automática; comandos de shell só os liberados (render e testes).",
antigravity: "Antigravity CLI (agy -p, stream-json) pela conta Google: edição automática; de shell, só os comandos exatos liberados (testes e verificação).",
};
/** As três IAs para o console: o estado vem de lib/ai.ts (instalada, ligada, login/chave, pausa da reserva). */
@@ -185,6 +187,17 @@ export function startRun(input: {
/** Execução que caiu por indisponibilidade e que esta continua com a IA reserva. */
fallbackOfRunId?: number | null;
}): AgentRun {
// Perto do limite de uso (Configurações → IA): começa já na próxima IA livre, para não gastar o limite inteiro.
// Continuação de conversa fica na mesma IA (a sessão é dela).
let limitNote: string | null = null;
const hot = !input.resumeRunId && readAiSettings().fallback.enabled ? overLimit(input.provider) : null;
if (hot) {
const alternative = readyChain(input.provider).find((id) => id !== input.provider && !overLimit(id));
if (alternative) {
limitNote = `${PROVIDER_META[input.provider].label} está com ${hot}: a tarefa vai com ${PROVIDER_META[alternative].label}.`;
input = { ...input, provider: alternative, model: defaultModelFor(input.kind, alternative) };
}
}
const info = providers().find((p) => p.id === input.provider);
const resolved = resolvedFor(input.provider);
if (!info?.available || !resolved) {
@@ -232,7 +245,7 @@ export function startRun(input: {
"--allowedTools", CLAUDE_ALLOWED_TOOLS]
: input.provider === "codex"
? codexArgs(prompt, input.model, resume?.session_id ?? null, input.kind)
: geminiArgs(prompt, input.model, resume?.session_id ?? null);
: antigravityArgs(prompt, input.model, resume?.session_id ?? null);
// providerEnv: chave de API só nesta chamada (modo "chave") ou nenhuma (modo "conta"); ver doc/ia.md.
const child = spawn(resolved.command, [...resolved.prefixArgs, ...args], {
@@ -240,7 +253,7 @@ export function startRun(input: {
});
const listeners = new Set<(e: AgentEvent | null) => void>();
const log = fs.createWriteStream(logPath);
const gemini: GeminiState = { text: "" };
const textBuffer: TextBuffer = { text: "" };
const emit = (e: Omit<AgentEvent, "at">) => {
if (e.kind !== "system" && e.kind !== "stderr" && e.kind !== "error") entry.progressed = true;
if (e.kind === "stderr" || e.kind === "error" || (e.kind === "result" && e.isError)) {
@@ -255,6 +268,7 @@ export function startRun(input: {
active.set(id, entry);
emit({ kind: "system", text: `${input.provider}${input.model ? ` · ${input.model}` : ""} · tarefa "${input.kind}"` +
`${resume ? ` · continua a execução #${resume.id}` : ""}${fallbackOf ? ` · reserva da execução #${fallbackOf.id}` : ""}` });
if (limitNote) emit({ kind: "system", text: limitNote });
child.stdout.setEncoding("utf8").on("data", lineSplitter((line) => {
let obj: Record<string, unknown>;
@@ -265,7 +279,8 @@ export function startRun(input: {
return;
}
const events = input.provider === "claude" ? normalizeClaude(obj, id)
: input.provider === "codex" ? normalizeCodex(obj, id) : normalizeGemini(obj, id, gemini);
: input.provider === "codex" ? normalizeCodex(obj, id)
: normalizeAntigravity(obj, id, textBuffer);
events.forEach(emit);
}));
child.stderr.setEncoding("utf8").on("data", lineSplitter((line) => {
@@ -273,7 +288,7 @@ export function startRun(input: {
}));
child.on("error", (error) => emit({ kind: "error", text: `não iniciou: ${error.message}`, isError: true }));
child.on("close", (code) => {
if (input.provider === "gemini") flushGemini(gemini, id).forEach(emit);
if (input.provider === "antigravity") flushText(textBuffer, id).forEach(emit);
// Tarefa "criar história": a IA grava meta.json com título e premissa definitivos.
if (input.kind === "story" && story && code === 0) syncStoryMeta(story.id);
const current = getRun(id);
@@ -356,6 +371,8 @@ function startFallback(id: number, entry: ActiveRun): number | null {
if (!closed || closed.status !== "error") return null;
if (!isAvailabilityError([closed.error ?? "", ...entry.errors].join("\n"))) return null;
markUnavailable(closed.provider, closed.error ?? entry.errors.at(-1) ?? "indisponível");
// Relê o uso da IA que caiu: a tela mostra quanto ela usou e quando zera.
void refreshUsage({ only: closed.provider });
// IAs já tentadas nesta cadeia (segue fallback_of para trás).
const tried: Provider[] = [];
for (let cursor: AgentRun | undefined = closed; cursor; cursor = cursor.fallback_of ? getRun(cursor.fallback_of) : undefined) {
@@ -460,26 +477,10 @@ const STDERR_NOISE = [/no stdin data received/, /Reading additional input from s
// O Claude Code avisa de id fora da lista interna dele, mas roda o modelo normalmente (testado com claude-fable-5-2).
/\[claude-code:unrecognized_model\]/];
// --- Gemini ---------------------------------------------------------------------
/** O texto do Antigravity chega em pedaços (`text_delta`): junta e solta um bloco só quando chega outro tipo de evento. */
export type TextBuffer = { text: string };
/**
* Gemini CLI 0.68.0 sem interação (doc/ia.md). `auto_edit` aprova as edições sozinho; de shell, só os comandos
* abaixo (no modo não interativo o resto é recusado). `--skip-trust`: confia na pasta só nesta execução.
*/
const GEMINI_ALLOWED_SHELL = [
"pnpm render", "pnpm verify", "pnpm test", "pnpm typecheck", "pnpm.cmd render", "pnpm.cmd verify", "pnpm.cmd test", SKILL_SCRIPTS,
].map((command) => `run_shell_command(${command})`);
export function geminiArgs(prompt: string, model: string, sessionId: string | null): string[] {
return ["-p", prompt, "-o", "stream-json", "--approval-mode", "auto_edit", "--skip-trust",
...(model ? ["-m", model] : []), ...(sessionId ? ["--resume", sessionId] : []),
"--allowed-tools", ...GEMINI_ALLOWED_SHELL];
}
/** O texto do Gemini chega em pedaços (`delta`): junta e solta um bloco só quando chega outro tipo de evento. */
export type GeminiState = { text: string };
function flushGemini(state: GeminiState, runId: number): Omit<AgentEvent, "at">[] {
function flushText(state: TextBuffer, runId: number): Omit<AgentEvent, "at">[] {
const text = state.text.trim();
state.text = "";
if (!text) return [];
@@ -487,43 +488,72 @@ function flushGemini(state: GeminiState, runId: number): Omit<AgentEvent, "at">[
return [{ kind: "text", text }];
}
/** Eventos JSONL do `gemini -o stream-json` (formato lido no código do gemini-cli 0.68.0). */
export function normalizeGemini(o: Record<string, unknown>, runId: number, state: GeminiState): Omit<AgentEvent, "at">[] {
if (o.type === "message") {
if (o.role === "assistant") state.text += String(o.content ?? "");
return [];
}
const pending = flushGemini(state, runId);
switch (o.type) {
case "init":
run("UPDATE agent_runs SET session_id = ? WHERE id = ?", String(o.session_id), runId);
return [...pending, { kind: "system", text: `sessão iniciada · modelo ${o.model}` }];
case "tool_use":
return [...pending, { kind: "tool", text: `${o.tool_name} ${summarizeInput(o.parameters as Record<string, unknown> | undefined)}` }];
case "tool_result": {
const error = o.error as { message?: string } | undefined;
return [...pending, { kind: "tool_result", text: truncate(String(o.output ?? error?.message ?? ""), 1500) || "(sem saída)", isError: o.status === "error" }];
// --- Antigravity ----------------------------------------------------------------
/**
* Antigravity CLI 1.5.10 sem interação (testado em 18/11/2026; doc/ia.md). `--mode accept-edits` aprova as edições;
* comando de shell só com regra `command(<linha exata>)` em `permissions.allow`. O agy NÃO aceita prefixo nem
* curinga (testado), então só entram comandos sem argumentos variáveis; o resto é recusado em silêncio (aviso no
* stderr). `--settings` vale só para esta execução: a configuração global do usuário não muda.
*/
const ANTIGRAVITY_ALLOWED_COMMANDS = [
"pnpm typecheck", "pnpm.cmd typecheck", "pnpm test", "pnpm.cmd test", "pnpm run doctor", "pnpm.cmd run doctor",
"pnpm prepare-assets", "pnpm.cmd prepare-assets",
];
export function antigravityArgs(prompt: string, model: string, conversationId: string | null): string[] {
const settings = { permissions: { allow: ANTIGRAVITY_ALLOWED_COMMANDS.map((c) => `command(${c})`) } };
return ["-p", prompt, "--output-format", "stream-json", "--mode", "accept-edits", "--settings", JSON.stringify(settings),
...(model ? ["--model", model] : []), ...(conversationId ? ["--conversation", conversationId] : [])];
}
type AgyStep = {
step_type?: string; state?: string; text_delta?: string; tool_name?: string;
tool_info?: { parameters?: Record<string, unknown> };
};
/** Eventos JSONL do `agy -p --output-format stream-json`: init → step_update (texto em pedaços, ferramentas) → result. */
export function normalizeAntigravity(o: Record<string, unknown>, runId: number, state: TextBuffer): Omit<AgentEvent, "at">[] {
if (o.event === "step_update") {
const step = (o.step_update ?? {}) as AgyStep;
if (step.step_type === "agent_response") {
state.text += step.text_delta ?? "";
return [];
}
case "error":
return [...pending, o.severity === "error"
? { kind: "error", text: truncate(String(o.message ?? ""), 500), isError: true }
: { kind: "system", text: truncate(String(o.message ?? ""), 300) }];
case "result": {
const stats = (o.stats ?? {}) as { input_tokens?: number; output_tokens?: number; tool_calls?: number };
const error = o.error as { message?: string } | undefined;
const failed = o.status === "error";
run("UPDATE agent_runs SET num_turns = COALESCE(num_turns, 0) + 1, error = COALESCE(error, ?) WHERE id = ?",
failed ? String(error?.message ?? "erro").slice(0, 2000) : null, runId);
return [...pending, {
kind: "result", isError: failed,
text: failed
? `Terminou com erro: ${truncate(String(error?.message ?? "falha"), 300)}`
: `Concluído · ${stats.input_tokens ?? 0} tokens de entrada · ${stats.output_tokens ?? 0} de saída · ${stats.tool_calls ?? 0} ferramentas · Gemini não informa custo em US$`,
}];
if (step.step_type !== "tool") return [];
const pending = flushText(state, runId);
// Parâmetros chegam com inicial maiúscula (Path, CommandLine): normaliza para o resumo de sempre.
const params = step.tool_info?.parameters
? Object.fromEntries(Object.entries(step.tool_info.parameters).map(([k, v]) => [k === "CommandLine" ? "command" : k.charAt(0).toLowerCase() + k.slice(1), v]))
: undefined;
if (step.state === "ACTIVE") return [...pending, { kind: "tool", text: `${step.tool_name ?? "ferramenta"} ${summarizeInput(params)}` }];
if (step.state === "ERROR") {
return [...pending, { kind: "tool_result", text: `${step.tool_name} recusada ou falhou (de shell, só os comandos liberados)`, isError: true }];
}
default:
return pending;
return pending;
}
const pending = flushText(state, runId);
if (o.event === "init") {
run("UPDATE agent_runs SET session_id = ? WHERE id = ?", String(o.conversation_id ?? ""), runId);
return [...pending, { kind: "system", text: "sessão iniciada · Antigravity" }];
}
if (o.event === "result") {
const r = (o.result ?? {}) as {
status?: string; response?: string; num_turns?: number; error?: unknown;
usage?: { input_tokens?: number; output_tokens?: number; cache_read_tokens?: number };
};
const failed = (r.status ?? "SUCCESS") !== "SUCCESS";
const message = failed ? String(typeof r.error === "string" ? r.error : JSON.stringify(r.error ?? r.status)).slice(0, 2000) : null;
run("UPDATE agent_runs SET num_turns = COALESCE(num_turns, 0) + ?, result = COALESCE(?, result), error = COALESCE(error, ?) WHERE id = ?",
Number(r.num_turns ?? 1), r.response ? r.response.slice(0, 20_000) : null, message, runId);
const u = r.usage ?? {};
return [...pending, {
kind: "result", isError: failed,
text: failed ? `Terminou com erro: ${truncate(message ?? "falha", 300)}`
: `Concluído · ${u.input_tokens ?? 0} tokens de entrada (${u.cache_read_tokens ?? 0} em cache) · ${u.output_tokens ?? 0} de saída · conta Google, sem custo em US$`,
}];
}
return pending;
}
// --- normalização ---------------------------------------------------------------
@@ -538,6 +568,10 @@ function normalizeClaude(o: Record<string, unknown>, runId: number): Omit<AgentE
return [{ kind: "system", text: `sessão iniciada · modelo ${o.model}` }];
}
return [];
case "rate_limit_event":
// Uso da assinatura (janela de 5 h e semanal) que vem em toda execução: alimenta o monitor de uso.
recordClaudeRateLimit(o.rate_limit_info);
return [];
case "assistant":
return ((o.message as { content?: Block[] })?.content ?? []).flatMap((c): Omit<AgentEvent, "at">[] => {
if (c.type === "text" && c.text?.trim()) return [{ kind: "text", text: c.text }];
+261
View File
@@ -0,0 +1,261 @@
// Uso e limites de cada IA, lidos pela própria CLI SEM gastar tokens (estudo em doc/ia.md, "Estudo: uso e limites"):
// Claude — `claude -p "/usage"` (resposta local, modelo <synthetic>, US$ 0) e o evento `rate_limit_event` que vem
// em toda execução do agente (o mais preciso: utilização 0–1 e reset em epoch);
// Codex — `codex app-server` (JSON-RPC por stdin): `account/rateLimits/read`, sem rodar modelo;
// Antigravity — `agy -p "/usage"` (resposta local, sem cota): fração restante das janelas de 5 h e semanal;
// O monitor relê a cada 5 min e antes de cada tarefa; o resultado fica em lib/ai.ts (getUsage/overLimit).
import { spawn } from "node:child_process";
import os from "node:os";
import { getUsage, providerEnv, providerStatus, resolvedFor, setUsage, type ProviderUsage, type UsageWindow } from "./ai";
import { killTree, lineSplitter } from "./proc";
import type { Provider } from "./types";
const MONITOR_MS = 5 * 60_000;
const READ_TIMEOUT_MS = 45_000;
const g = globalThis as unknown as { __cenaforgeUsageMonitor?: NodeJS.Timeout; __cenaforgeUsageReading?: Map<Provider, Promise<void>> };
const reading = () => (g.__cenaforgeUsageReading ??= new Map());
/* ---------------------------------------------------------------- Claude */
const MONTHS: Record<string, number> = { jan: 0, feb: 1, mar: 2, apr: 3, may: 4, jun: 5, jul: 6, aug: 7, sep: 8, oct: 9, nov: 10, dec: 11 };
/** "Nov 18, 7:10am" / "7:10am" / "2pm" (horário local) → ISO. Sem data: hoje, ou amanhã se a hora já passou. */
export function parseClaudeReset(text: string, now = new Date()): string | null {
const m = /(?:([A-Za-z]{3})[a-z]*\s+(\d{1,2}),?\s+)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)/i.exec(text);
if (!m) return null;
let hour = Number(m[3]) % 12;
if (m[5].toLowerCase() === "pm") hour += 12;
const date = new Date(now);
date.setSeconds(0, 0);
date.setHours(hour, Number(m[4] ?? 0));
if (m[1] && MONTHS[m[1].toLowerCase()] !== undefined) {
date.setMonth(MONTHS[m[1].toLowerCase()], Number(m[2]));
// Virada de ano: "Jan 2" lido em dezembro é do ano que vem.
if (date.getTime() < now.getTime() - 86_400_000 * 180) date.setFullYear(date.getFullYear() + 1);
} else if (date.getTime() < now.getTime()) {
date.setDate(date.getDate() + 1);
}
return date.toISOString();
}
/** Texto do `/usage` → janelas. Ex.: "Current session: 2% used · resets Nov 18, 7:10am (America/Sao_Paulo)". */
export function parseClaudeUsageText(text: string, now = new Date()): { windows: UsageWindow[]; subscription: boolean } {
const windows: UsageWindow[] = [];
for (const line of text.split(/\r?\n/)) {
const m = /^\s*Current (session|week)(?:\s*\(([^)]+)\))?:\s*(\d+(?:\.\d+)?)%\s*used(?:\s*·\s*resets\s+(.+))?$/i.exec(line);
if (!m) continue;
const scope = m[2]?.trim() ?? "";
const session = m[1].toLowerCase() === "session";
const allModels = !scope || /all models/i.test(scope);
windows.push({
id: session ? "five_hour" : allModels ? "seven_day" : `seven_day_${scope.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`,
label: session ? "Sessão (5 h)" : allModels ? "Semana" : `Semana (${scope})`,
usedPercent: Number(m[3]),
resetsAt: m[4] ? parseClaudeReset(m[4], now) : null,
});
}
return { windows, subscription: /using your subscription/i.test(text) };
}
/** `rate_limit_event.rate_limit_info` de uma execução do agente (formato verificado no claude 2.1.314). */
export function recordClaudeRateLimit(info: unknown): void {
const i = (info ?? {}) as {
status?: string; overageStatus?: string; isUsingOverage?: boolean;
unifiedWindows?: Record<string, { utilization?: number; resetsAt?: number; status?: string }>;
};
const labels: Record<string, string> = { five_hour: "Sessão (5 h)", seven_day: "Semana" };
const windows = Object.entries(i.unifiedWindows ?? {}).map(([id, w]): UsageWindow => ({
id, label: labels[id] ?? id.replace(/_/g, " "),
usedPercent: Math.round(Number(w.utilization ?? 0) * 1000) / 10,
resetsAt: w.resetsAt ? new Date(w.resetsAt * 1000).toISOString() : null,
}));
if (!windows.length && !i.status) return;
// Janelas por modelo (ex.: "Semana (Fable)") só vêm no /usage: mantém as que já estavam.
const previous = getUsage("claude")?.windows.filter((w) => !windows.some((n) => n.id === w.id)) ?? [];
setUsage("claude", {
at: new Date().toISOString(), source: "run", windows: [...windows, ...previous],
blocked: !!i.status && i.status !== "allowed" && i.status !== "allowed_warning",
plan: null, note: i.isUsingOverage ? "Usando crédito extra (além do plano)." : null, error: null,
});
}
async function readClaude(): Promise<ProviderUsage> {
const resolved = resolvedFor("claude");
if (!resolved) throw new Error("CLI não encontrada");
// Fora do repositório e sem configurações do usuário: o /usage é local, mas a CLI ainda carrega o resto ao abrir.
const out = await runCollect(resolved.command, [...resolved.prefixArgs, "-p", "/usage", "--output-format", "stream-json", "--verbose",
"--setting-sources", "project,local", "--strict-mcp-config"], providerEnv("claude"));
let text = "";
for (const line of out.split(/\r?\n/)) {
try {
const o = JSON.parse(line) as { type?: string; result?: string; total_cost_usd?: number };
if (o.type === "result" && typeof o.result === "string") text = o.result;
} catch { /* linha que não é JSON */ }
}
const { windows, subscription } = parseClaudeUsageText(text);
// Chave de API: cobrança por uso, sem janelas de 5 h/semana.
if (!windows.length) {
return { at: new Date().toISOString(), source: "cli", windows: [], blocked: false, plan: subscription ? "assinatura" : null,
note: subscription ? null : "Chave de API: cobrança por uso, sem janela de limite.", error: text ? null : "O /usage não respondeu." };
}
const previous = getUsage("claude");
return { at: new Date().toISOString(), source: "cli", windows, plan: "assinatura", error: null,
blocked: windows.some((w) => w.usedPercent >= 100), note: previous?.note ?? null };
}
/* ---------------------------------------------------------------- Codex */
type CodexWindow = { usedPercent?: number; windowDurationMins?: number; resetsAt?: number } | null;
type CodexLimits = {
ordinaryUsageAllowed?: boolean;
rateLimits?: { primary?: CodexWindow; secondary?: CodexWindow; planType?: string | null; rateLimitReachedType?: string | null; credits?: { hasCredits?: boolean; balance?: string } };
rateLimitResetCredits?: { availableCount?: number };
};
const windowLabel = (mins: number | undefined) =>
!mins ? "Janela" : mins <= 60 * 6 ? `Sessão (${Math.round(mins / 60)} h)` : mins >= 60 * 24 * 6 ? "Semana" : `Janela de ${Math.round(mins / 60)} h`;
/** Resposta do `account/rateLimits/read` (codex-cli 0.169.0) → uso. Exportada para teste. */
export function parseCodexLimits(result: CodexLimits, at = new Date()): ProviderUsage {
const limits = result.rateLimits ?? {};
const windows = ([["primary", limits.primary], ["secondary", limits.secondary]] as const)
.filter(([, w]) => w && typeof w.usedPercent === "number")
.map(([id, w]): UsageWindow => ({
id: id === "primary" ? "five_hour" : "seven_day", label: windowLabel(w!.windowDurationMins),
usedPercent: Number(w!.usedPercent), resetsAt: w!.resetsAt ? new Date(w!.resetsAt * 1000).toISOString() : null,
}));
const resets = result.rateLimitResetCredits?.availableCount ?? 0;
return {
at: at.toISOString(), source: "cli", windows,
blocked: result.ordinaryUsageAllowed === false || !!limits.rateLimitReachedType,
plan: limits.planType ?? null,
note: resets > 0 ? `${resets} reset${resets > 1 ? "s" : ""} grátis de limite na conta (use no app do Codex).` : null,
error: null,
};
}
async function readCodex(): Promise<ProviderUsage> {
const resolved = resolvedFor("codex");
if (!resolved) throw new Error("CLI não encontrada");
const result = await new Promise<CodexLimits>((resolve, reject) => {
const child = spawn(resolved.command, [...resolved.prefixArgs, "app-server"], {
cwd: os.homedir(), shell: false, windowsHide: true, stdio: ["pipe", "pipe", "ignore"], env: providerEnv("codex"),
});
const finish = (error: Error | null, value?: CodexLimits) => {
clearTimeout(timer);
killTree(child);
if (error) reject(error); else resolve(value!);
};
const timer = setTimeout(() => finish(new Error("o app-server do Codex não respondeu")), READ_TIMEOUT_MS);
child.on("error", (e) => finish(e));
child.stdout.setEncoding("utf8").on("data", lineSplitter((line) => {
let msg: { id?: number; result?: CodexLimits; error?: { message?: string } };
try { msg = JSON.parse(line); } catch { return; }
if (msg.id === 1) {
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "initialized" }) + "\n");
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "account/rateLimits/read" }) + "\n");
} else if (msg.id === 2) {
finish(msg.error ? new Error(msg.error.message ?? "erro do app-server") : null, msg.result);
}
}));
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { clientInfo: { name: "cenaforge-panel", version: "1.0" } } }) + "\n");
});
return parseCodexLimits(result);
}
/* ---------------------------------------------------------------- Antigravity */
type AgyBucket = { id?: string; name?: string; window?: string; remaining_fraction?: number; reset_time?: string };
type AgyUsage = { groups?: { name?: string; buckets?: AgyBucket[] }[] };
/**
* `agy -p "/usage" --output-format stream-json` → evento `command_result` (agy 1.5.10, sem gastar cota). Os modelos
* dividem a cota em grupos; o padrão do agente é o grupo "Gemini Models" — é ele que decide. Exportada para teste.
*/
export function parseAgyUsage(data: AgyUsage, at = new Date()): ProviderUsage {
const groups = data.groups ?? [];
const main = groups.find((g) => /gemini/i.test(g.name ?? "")) ?? groups[0];
const windows = (main?.buckets ?? []).filter((b) => typeof b.remaining_fraction === "number").map((b): UsageWindow => ({
id: b.window === "5h" ? "five_hour" : b.window === "weekly" ? "seven_day" : String(b.id ?? b.window),
label: b.window === "5h" ? "Sessão (5 h)" : b.window === "weekly" ? "Semana" : String(b.name ?? b.window),
usedPercent: Math.round((1 - Number(b.remaining_fraction)) * 1000) / 10,
resetsAt: b.reset_time ?? null,
}));
const others = groups.filter((g) => g !== main).map((g) => {
const used = Math.max(0, ...(g.buckets ?? []).map((b) => 1 - Number(b.remaining_fraction ?? 1)));
return `${g.name}: ${Math.round(used * 100)}% usado`;
});
return {
at: at.toISOString(), source: "cli", windows, plan: "conta Google",
blocked: windows.some((w) => w.usedPercent >= 100),
note: others.length ? `Outra cota da conta (não usada pelo agente padrão) · ${others.join(" · ")}.` : null,
error: null,
};
}
async function readAntigravity(): Promise<ProviderUsage> {
const resolved = resolvedFor("antigravity");
if (!resolved) throw new Error("CLI não encontrada");
const out = await runCollect(resolved.command, [...resolved.prefixArgs, "-p", "/usage", "--output-format", "stream-json"], providerEnv("antigravity"));
for (const line of out.split(/\r?\n/)) {
try {
const o = JSON.parse(line) as { event?: string; command?: { name?: string; data?: AgyUsage } };
if (o.event === "command_result" && o.command?.name === "usage" && o.command.data) return parseAgyUsage(o.command.data);
} catch { /* linha que não é JSON */ }
}
throw new Error("o /usage do Antigravity não respondeu");
}
/* ---------------------------------------------------------------- leitura e monitor */
function runCollect(command: string, args: string[], env: NodeJS.ProcessEnv): Promise<string> {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { cwd: os.homedir(), shell: false, windowsHide: true, stdio: ["ignore", "pipe", "ignore"], env });
let out = "";
const timer = setTimeout(() => { killTree(child); reject(new Error("a CLI não respondeu a tempo")); }, READ_TIMEOUT_MS);
child.stdout.setEncoding("utf8").on("data", (c: string) => { out += c; });
child.on("error", (e) => { clearTimeout(timer); reject(e); });
child.on("close", () => { clearTimeout(timer); resolve(out); });
});
}
const READERS: Partial<Record<Provider, () => Promise<ProviderUsage>>> = { claude: readClaude, codex: readCodex, antigravity: readAntigravity };
/** Relê o uso de uma IA (uma leitura por vez por IA). Erro fica registrado na própria leitura. */
function refreshOne(id: Provider): Promise<void> {
const running = reading().get(id);
if (running) return running;
const reader = READERS[id];
if (!reader) return Promise.resolve();
const job = reader()
.then((usage) => setUsage(id, usage))
.catch((error: Error) => {
const previous = getUsage(id);
setUsage(id, { ...(previous ?? { windows: [], blocked: false, plan: null, note: null, source: "cli" as const }),
at: previous?.at ?? new Date().toISOString(), error: `Não deu para ler o uso: ${error.message}` });
})
.finally(() => reading().delete(id));
reading().set(id, job);
return job;
}
/**
* Relê o uso das IAs ligadas e instaladas (no modo conta; na chave não há janela). `maxAgeMs`: só as leituras mais
* velhas que isso. Chamado antes de cada tarefa (maxAge 60 s), pelo monitor (5 min) e pelo botão da tela.
*/
export async function refreshUsage(options: { maxAgeMs?: number; only?: Provider } = {}): Promise<void> {
const maxAge = options.maxAgeMs ?? 0;
const targets = providerStatus().filter((p) => p.installed && p.settings.enabled && p.settings.authMode === "oauth" && READERS[p.id]
&& (!options.only || p.id === options.only)
&& (!p.usage || Date.now() - Date.parse(p.usage.at) >= maxAge));
await Promise.all(targets.map((p) => refreshOne(p.id)));
}
/** Liga o monitor de 5 min (uma vez por processo; sobrevive ao recarregamento do código no `pnpm dev`). */
export function ensureUsageMonitor(): void {
if (g.__cenaforgeUsageMonitor) return;
g.__cenaforgeUsageMonitor = setInterval(() => void refreshUsage({ maxAgeMs: MONITOR_MS - 10_000 }), MONITOR_MS);
g.__cenaforgeUsageMonitor.unref?.();
void refreshUsage({ maxAgeMs: MONITOR_MS });
}
+122 -41
View File
@@ -1,5 +1,5 @@
// IA: configuração (data/ai/settings.json), classificador de indisponibilidade, ambiente por modo de login, cofre
// DPAPI (só no Windows) e o normalizador do Gemini. Tudo numa pasta TEMPORÁRIA (CENAFORGE_ROOT); nenhuma CLI real é
// DPAPI (só no Windows), uso e limites e o Antigravity. Tudo numa pasta TEMPORÁRIA (CENAFORGE_ROOT); nenhuma CLI real é
// chamada. Rodar: pnpm --filter cenaforge-panel test:panel
import assert from "node:assert/strict";
import fs from "node:fs";
@@ -25,20 +25,22 @@ before(async () => {
});
describe("configuração da IA", () => {
it("sem arquivo usa o padrão: Claude e Codex ligados na conta, Gemini desligado", () => {
it("sem arquivo usa o padrão: Claude e Codex ligados na conta, Antigravity desligado", () => {
const s = ai.readAiSettings();
assert.deepEqual(s.order, ["claude", "codex", "gemini"]);
assert.deepEqual(s.order, ["claude", "codex", "antigravity"]);
assert.equal(s.providers.antigravity.enabled, false);
assert.equal(s.providers.antigravity.authMode, "oauth");
assert.equal(s.fallback.usageLimitPercent, 90);
assert.equal(s.providers.claude.enabled, true);
assert.equal(s.providers.gemini.enabled, false);
assert.equal(s.providers.gemini.authMode, "apiKey");
assert.equal(s.fallback.enabled, true);
});
it("normaliza arquivo estragado: ordem sem repetição e completa, pausa dentro do limite", () => {
fs.mkdirSync(path.dirname(SETTINGS()), { recursive: true });
fs.writeFileSync(SETTINGS(), JSON.stringify({ order: ["gemini", "gemini", "x"], providers: { codex: { enabled: "sim", authMode: "nada" } }, fallback: { cooldownMin: 9999 } }));
fs.writeFileSync(SETTINGS(), JSON.stringify({ order: ["antigravity", "antigravity", "gemini", "x"], providers: { codex: { enabled: "sim", authMode: "nada" }, gemini: { enabled: true } }, fallback: { cooldownMin: 9999 } }));
const s = ai.readAiSettings();
assert.deepEqual(s.order, ["gemini", "claude", "codex"]);
assert.deepEqual(s.order, ["antigravity", "claude", "codex"], "o \"gemini\" de um arquivo antigo é ignorado");
assert.equal("gemini" in s.providers, false);
assert.equal(s.providers.codex.enabled, true);
assert.equal(s.providers.codex.authMode, "oauth");
assert.equal(s.fallback.cooldownMin, 240);
@@ -46,12 +48,13 @@ describe("configuração da IA", () => {
});
it("salva só o que veio e recusa ordem inválida", () => {
const s = ai.updateAiSettings({ providers: { gemini: { enabled: true } }, order: ["codex", "gemini", "claude"], fallback: { cooldownMin: 30 } });
assert.equal(s.providers.gemini.enabled, true);
assert.deepEqual(JSON.parse(fs.readFileSync(SETTINGS(), "utf8")).order, ["codex", "gemini", "claude"]);
const s = ai.updateAiSettings({ providers: { antigravity: { enabled: true } }, order: ["codex", "antigravity", "claude"], fallback: { cooldownMin: 30 } });
assert.equal(s.providers.antigravity.enabled, true);
assert.deepEqual(JSON.parse(fs.readFileSync(SETTINGS(), "utf8")).order, ["codex", "antigravity", "claude"]);
assert.throws(() => ai.updateAiSettings({ order: ["codex", "codex", "claude"] }), /cada IA uma vez/);
assert.throws(() => ai.updateAiSettings({ order: ["codex", "gemini", "claude"] }), /cada IA uma vez/);
assert.throws(() => ai.updateAiSettings({ fallback: { cooldownMin: 0 } }), /entre 1 e 240/);
assert.throws(() => ai.updateAiSettings({ providers: { gemini: { authMode: "senha" as never } } }), /Modo de login/);
assert.throws(() => ai.updateAiSettings({ providers: { antigravity: { authMode: "senha" as never } } }), /Modo de login/);
assert.equal(ai.readAiSettings().fallback.cooldownMin, 30);
});
});
@@ -68,15 +71,13 @@ describe("indisponibilidade (dispara a reserva)", () => {
});
describe("ambiente de cada chamada", () => {
it("modo conta tira a chave do ambiente; Gemini na conta liga GOOGLE_GENAI_USE_GCA", () => {
ai.updateAiSettings({ providers: { claude: { authMode: "oauth" }, gemini: { authMode: "oauth" } } });
it("modo conta tira a chave do ambiente (a CLI usaria a chave em vez da conta)", () => {
ai.updateAiSettings({ providers: { claude: { authMode: "oauth" }, antigravity: { authMode: "oauth" } } });
const base = { ANTHROPIC_API_KEY: "sk-ant-velha", GEMINI_API_KEY: "AIza-velha", PATH: "x" };
const claude = ai.providerEnv("claude", base);
assert.equal(claude.ANTHROPIC_API_KEY, undefined);
assert.equal(claude.PATH, "x");
const gemini = ai.providerEnv("gemini", base);
assert.equal(gemini.GEMINI_API_KEY, undefined);
assert.equal(gemini.GOOGLE_GENAI_USE_GCA, "true");
assert.equal(ai.providerEnv("antigravity", base).GEMINI_API_KEY, undefined);
});
it("modo chave sem chave salva não vaza a do ambiente do painel", () => {
@@ -96,32 +97,112 @@ describe("ambiente de cada chamada", () => {
});
});
describe("Gemini: eventos do stream-json", () => {
it("junta o texto em pedaços, registra sessão, ferramenta e resultado", () => {
const id = Number(dbm.run(`INSERT INTO agent_runs (provider, model, kind, prompt, status, log_path, started_at)
VALUES ('gemini', '', 'free', 'oi', 'running', '', ?)`, dbm.now()).lastInsertRowid);
const state: import("./agents").GeminiState = { text: "" };
const n = (o: Record<string, unknown>) => agents.normalizeGemini(o, id, state);
assert.deepEqual(n({ type: "init", session_id: "abc-123", model: "gemini-3.5-flash" }).map((e) => e.kind), ["system"]);
assert.deepEqual(n({ type: "message", role: "user", content: "oi" }), []);
assert.deepEqual(n({ type: "message", role: "assistant", content: "Vou ", delta: true }), []);
assert.deepEqual(n({ type: "message", role: "assistant", content: "ler.", delta: true }), []);
const tool = n({ type: "tool_use", tool_name: "read_file", tool_id: "t1", parameters: { file_path: "README.md" } });
assert.deepEqual(tool.map((e) => [e.kind, e.text]), [["text", "Vou ler."], ["tool", "read_file README.md"]]);
assert.equal(n({ type: "tool_result", tool_id: "t1", status: "error", error: { message: "sem permissão" } })[0].isError, true);
const done = n({ type: "result", status: "error", error: { type: "API", message: "429 quota exceeded" }, stats: {} });
assert.equal(done[0].isError, true);
const row = dbm.get<{ session_id: string; error: string; num_turns: number }>("SELECT session_id, error, num_turns FROM agent_runs WHERE id = ?", id)!;
assert.equal(row.session_id, "abc-123");
assert.match(row.error, /429/);
assert.equal(ai.isAvailabilityError(row.error), true);
describe("uso e limites", () => {
type Usage = typeof import("./ai-usage");
let usage: Usage;
before(async () => { usage = await import("./ai-usage"); });
const NOW = new Date(2026, 10, 18, 2, 30); // 18/11/2026 02:30, horário local
it("lê o texto do /usage do Claude (sessão, semana e semana por modelo)", () => {
const text = "You are currently using your subscription to power your Claude Code usage\n\n" +
"Current session: 2% used · resets Nov 18, 7:10am (America/Sao_Paulo)\n" +
"Current week (all models): 67% used · resets Nov 21, 2pm (America/Sao_Paulo)\n" +
"Current week (Fable): 24% used · resets Nov 21, 2pm (America/Sao_Paulo)\n\nWhat's contributing to your usage?";
const r = usage.parseClaudeUsageText(text, NOW);
assert.equal(r.subscription, true);
assert.deepEqual(r.windows.map((w) => [w.id, w.usedPercent]), [["five_hour", 2], ["seven_day", 67], ["seven_day_fable", 24]]);
assert.equal(new Date(r.windows[0].resetsAt!).getTime(), new Date(2026, 10, 18, 7, 10).getTime());
assert.equal(new Date(r.windows[1].resetsAt!).getTime(), new Date(2026, 10, 21, 14, 0).getTime());
});
it("argumentos: modo headless, edição automática, retomada e shell só o liberado", () => {
const args = agents.geminiArgs("faça X", "gemini-2.5-pro", "sess-1");
assert.deepEqual(args.slice(0, 7), ["-p", "faça X", "-o", "stream-json", "--approval-mode", "auto_edit", "--skip-trust"]);
assert.ok(args.includes("--resume") && args.includes("sess-1"));
assert.ok(args.some((a) => a.startsWith("run_shell_command(pnpm render")));
assert.equal(args.includes("--yolo"), false);
it("reset só com a hora: hoje, ou amanhã se já passou; virada de ano", () => {
assert.equal(new Date(usage.parseClaudeReset("5pm", NOW)!).getDate(), 18);
assert.equal(new Date(usage.parseClaudeReset("1:15am", NOW)!).getDate(), 19);
assert.equal(new Date(usage.parseClaudeReset("Jan 2, 9am", new Date(2026, 11, 30))!).getFullYear(), 2027);
});
it("lê o account/rateLimits/read do Codex e marca quando bateu", () => {
const u = usage.parseCodexLimits({
ordinaryUsageAllowed: false,
rateLimits: { primary: { usedPercent: 100, windowDurationMins: 300, resetsAt: 1794979788 },
secondary: { usedPercent: 29, windowDurationMins: 10080, resetsAt: 1795530834 }, planType: "plus", rateLimitReachedType: "rate_limit_reached" },
rateLimitResetCredits: { availableCount: 2 },
});
assert.deepEqual(u.windows.map((w) => [w.label, w.usedPercent]), [["Sessão (5 h)", 100], ["Semana", 29]]);
assert.equal(u.blocked, true);
assert.equal(u.plan, "plus");
assert.match(u.note!, /2 resets/);
});
it("evento rate_limit_event do agente Claude vira uso (0–1 → %)", () => {
usage.recordClaudeRateLimit({ status: "allowed", unifiedWindows: {
five_hour: { utilization: 0.93, resetsAt: Math.floor(Date.now() / 1000) + 3600 },
seven_day: { utilization: 0.4, resetsAt: Math.floor(Date.now() / 1000) + 86400 } } });
const u = ai.getUsage("claude")!;
assert.equal(u.windows[0].usedPercent, 93);
assert.equal(u.source, "run");
assert.ok(fs.existsSync(path.join(ROOT, "data", "ai", "usage.json")), "o Clipador lê o uso deste arquivo");
});
it("limite: 90% tira da frente; janela que já zerou e leitura velha não contam", () => {
ai.updateAiSettings({ fallback: { usageLimitPercent: 90 } });
assert.match(ai.overLimit("claude")!, /Sessão \(5 h\) em 93%/);
ai.updateAiSettings({ fallback: { usageLimitPercent: 95 } });
assert.equal(ai.overLimit("claude"), null);
const base = { source: "cli" as const, plan: null, note: null, error: null };
ai.setUsage("codex", { ...base, at: new Date().toISOString(), blocked: true,
windows: [{ id: "five_hour", label: "Sessão (5 h)", usedPercent: 100, resetsAt: new Date(Date.now() - 60_000).toISOString() }] });
assert.equal(ai.overLimit("codex"), null, "a janela já zerou");
ai.setUsage("codex", { ...base, at: new Date(Date.now() - 3_600_000).toISOString(), blocked: true,
windows: [{ id: "five_hour", label: "Sessão (5 h)", usedPercent: 100, resetsAt: new Date(Date.now() + 60_000).toISOString() }] });
assert.equal(ai.overLimit("codex"), null, "leitura de 1 h atrás não decide");
assert.throws(() => ai.updateAiSettings({ fallback: { usageLimitPercent: 30 } }), /entre 50% e 100%/);
});
});
describe("Antigravity (agy 1.5.10)", () => {
it("argumentos: headless, edição automática e shell só com regra exata (sem curinga)", () => {
const args = agents.antigravityArgs("faça X", "gemini-3.8-flash-medium", "conv-1");
assert.deepEqual(args.slice(0, 6), ["-p", "faça X", "--output-format", "stream-json", "--mode", "accept-edits"]);
const settings = JSON.parse(args[args.indexOf("--settings") + 1]) as { permissions: { allow: string[] } };
assert.ok(settings.permissions.allow.includes("command(pnpm typecheck)"));
assert.equal(settings.permissions.allow.some((r) => r.includes("*")), false);
assert.ok(args.includes("--conversation") && args.includes("conv-1"));
assert.equal(args.includes("--dangerously-skip-permissions"), false);
});
it("eventos: conversa, texto em pedaços, ferramenta (ativa e recusada) e resultado", () => {
const id = Number(dbm.run(`INSERT INTO agent_runs (provider, model, kind, prompt, status, log_path, started_at)
VALUES ('antigravity', '', 'free', 'oi', 'running', '', ?)`, dbm.now()).lastInsertRowid);
const state: import("./agents").TextBuffer = { text: "" };
const n = (o: Record<string, unknown>) => agents.normalizeAntigravity(o, id, state);
n({ event: "init", conversation_id: "c-9", init: { permission_mode: "request-review" } });
assert.deepEqual(n({ event: "step_update", step_update: { step_type: "agent_response", state: "ACTIVE", text_delta: "Vou " } }), []);
n({ event: "step_update", step_update: { step_type: "agent_response", state: "DONE", text_delta: "criar." } });
const tool = n({ event: "step_update", step_update: { step_type: "tool", state: "ACTIVE", tool_name: "write_file", tool_info: { parameters: { Path: "teste.txt" } } } });
assert.deepEqual(tool.map((e) => [e.kind, e.text]), [["text", "Vou criar."], ["tool", "write_file teste.txt"]]);
const denied = n({ event: "step_update", step_update: { step_type: "tool", state: "ERROR", tool_name: "run_command", tool_info: { parameters: { CommandLine: "whoami" } } } });
assert.equal(denied[0].isError, true);
const done = n({ event: "result", result: { status: "SUCCESS", response: "feito", num_turns: 1, usage: { input_tokens: 11199, output_tokens: 247, cache_read_tokens: 6791 } } });
assert.match(done[0].text, /11199 tokens de entrada \(6791 em cache\)/);
const row = dbm.get<{ session_id: string; result: string }>("SELECT session_id, result FROM agent_runs WHERE id = ?", id)!;
assert.deepEqual([row.session_id, row.result], ["c-9", "feito"]);
});
it("uso (/usage): fração restante → % usado, do grupo Gemini; o outro grupo vira nota", async () => {
const { parseAgyUsage } = await import("./ai-usage");
const u = parseAgyUsage({ groups: [
{ name: "Gemini Models", buckets: [
{ id: "gemini-weekly", window: "weekly", remaining_fraction: 0.949576735496521, reset_time: "2026-11-25T03:53:32Z" },
{ id: "gemini-5h", window: "5h", remaining_fraction: 0.8792469501495361, reset_time: "2026-11-18T08:53:32Z" }] },
{ name: "Claude and GPT models", buckets: [{ id: "3p-5h", window: "5h", remaining_fraction: 1 }] }] });
assert.deepEqual(u.windows.map((w) => [w.label, w.usedPercent]), [["Semana", 5], ["Sessão (5 h)", 12.1]]);
assert.equal(u.blocked, false);
assert.match(u.note!, /Claude and GPT models: 0% usado/);
});
it("modelos: lê `agy models` (id + tab + nome) e ignora a linha de aviso", () => {
const list = ai.parseAgyModels("Fetching available models...\ngemini-4-carbon-medium\tGemini 4 Carbon (Medium)\ngemini-3.8-flash-medium\tGemini 3.8 Flash (Medium)\n");
assert.deepEqual(list, [{ id: "gemini-4-carbon-medium", label: "Gemini 4 Carbon (Medium)" }, { id: "gemini-3.8-flash-medium", label: "Gemini 3.8 Flash (Medium)" }]);
});
});
+141 -51
View File
@@ -1,4 +1,4 @@
// IA do painel: as três CLIs (Claude Code, Codex e Gemini), login com a conta (OAuth) ou chave de API,
// IA do painel: as três CLIs (Claude Code, Codex e Antigravity), login com a conta (OAuth) ou chave de API,
// instalação pelo painel e a IA reserva (se uma cair, a próxima da ordem assume).
//
// Contrato com o Clipador (Python), que lê os mesmos arquivos: doc/ia.md.
@@ -21,11 +21,14 @@ export type AiSettings = {
providers: Record<Provider, ProviderSettings>;
/** Prioridade da reserva. */
order: Provider[];
fallback: { enabled: boolean; cooldownMin: number };
/** `usageLimitPercent`: com uma janela de uso nesse ponto, a IA sai da frente e a próxima assume (padrão 90). */
fallback: { enabled: boolean; cooldownMin: number; usageLimitPercent: number };
};
const AI_DIR = path.join(DATA_DIR, "ai");
const SETTINGS_PATH = path.join(AI_DIR, "settings.json");
/** Retrato do uso de cada IA (escrito pelo painel, lido pelo Clipador). Ver doc/ia.md, "Estudo: uso e limites". */
const USAGE_PATH = path.join(AI_DIR, "usage.json");
const VAULT_PATH = path.join(AI_DIR, "vault.bin");
const HOME = os.homedir();
const IS_WINDOWS = process.platform === "win32";
@@ -35,10 +38,10 @@ export const DEFAULT_AI_SETTINGS: AiSettings = {
providers: {
claude: { enabled: true, authMode: "oauth" },
codex: { enabled: true, authMode: "oauth" },
gemini: { enabled: false, authMode: "apiKey" },
antigravity: { enabled: false, authMode: "oauth" },
},
order: ["claude", "codex", "gemini"],
fallback: { enabled: true, cooldownMin: 15 },
order: ["claude", "codex", "antigravity"],
fallback: { enabled: true, cooldownMin: 15, usageLimitPercent: 90 },
};
/* ---------------------------------------------------------------- catálogo das CLIs */
@@ -55,7 +58,10 @@ export type ProviderMeta = {
binEnv: string;
/** No Windows o npm instala um `.cmd` (o Node não o executa sem shell): rodamos o `.js` do pacote pelo Node. */
npmEntry: string | null;
install: { display: string; command: Command };
/** `command` null = não há instalador por linha de comando: a tela mostra `display` (site oficial). */
install: { display: string; command: Command | null };
/** Atualizar a CLI já instalada, quando é diferente de reinstalar (ex.: `agy update`). */
updateArgs?: string[];
/** Argumentos do login com a conta, abertos num terminal visível. */
loginArgs: string[];
oauthLabel: string;
@@ -89,13 +95,15 @@ export const PROVIDER_META: Record<Provider, ProviderMeta> = {
oauthNote: null,
apiKeyEnv: "CODEX_API_KEY", apiKeyUrl: "https://platform.openai.com/api-keys", apiKeyLabel: "Chave da API da OpenAI (sk-…)",
},
gemini: {
id: "gemini", label: "Gemini CLI", vendor: "Google", bin: "gemini", binEnv: "GEMINI_BIN", npmEntry: path.join("@google", "gemini-cli", "bundle", "gemini.js"),
install: npmInstall("@google/gemini-cli@latest"),
antigravity: {
// Antigravity CLI (substituto do Gemini CLI para conta pessoal). Testado em 18/11/2026 com agy 1.5.10: doc/ia.md.
id: "antigravity", label: "Antigravity", vendor: "Google", bin: "agy", binEnv: "AGY_BIN", npmEntry: null,
install: { display: "Instale o Antigravity CLI pelo site oficial: https://antigravity.google/docs/install", command: null },
updateArgs: ["update"],
// `agy` sem argumentos abre a sessão interativa, que pede o login do Google na primeira vez.
loginArgs: [],
oauthLabel: "Conta Google",
// Verificado em 18/11/2026 (gemini-cli 0.68.0): IneligibleTierError UNSUPPORTED_CLIENT no plano gratuito.
oauthNote: "O Google encerrou o login gratuito do Gemini CLI para contas pessoais. Só planos pagos elegíveis (Code Assist Standard/Enterprise, Workspace) entram com a conta. Para conta pessoal, use a chave de API do AI Studio.",
oauthLabel: "Conta Google (a mesma do app Antigravity)",
oauthNote: "Termos do Google: a FAQ do Antigravity diz que usar o agy dentro de outro programa \"não é suportado\" nos planos pessoais. O painel chama a CLI oficial sem modificação, mas o uso é por sua conta e risco.",
apiKeyEnv: "GEMINI_API_KEY", apiKeyUrl: "https://aistudio.google.com/apikey", apiKeyLabel: "Chave do Google AI Studio (AIza…)",
},
};
@@ -124,11 +132,13 @@ export function readAiSettings(): AiSettings {
const order = [...new Set((Array.isArray(raw.order) ? raw.order : []).filter(isProvider))];
for (const id of DEFAULT_AI_SETTINGS.order) if (!order.includes(id)) order.push(id);
const cooldown = Number(raw.fallback?.cooldownMin);
const limit = Number(raw.fallback?.usageLimitPercent);
return {
version: 1, providers, order,
fallback: {
enabled: typeof raw.fallback?.enabled === "boolean" ? raw.fallback.enabled : true,
cooldownMin: Number.isFinite(cooldown) ? Math.min(240, Math.max(1, Math.round(cooldown))) : DEFAULT_AI_SETTINGS.fallback.cooldownMin,
usageLimitPercent: Number.isFinite(limit) ? Math.min(100, Math.max(50, Math.round(limit))) : DEFAULT_AI_SETTINGS.fallback.usageLimitPercent,
},
};
}
@@ -149,6 +159,7 @@ export function updateAiSettings(patch: AiSettingsPatch): AiSettings {
}
if (change.authMode !== undefined) {
if (change.authMode !== "oauth" && change.authMode !== "apiKey") throw new UserError("Modo de login inválido.");
if (next.providers[id].authMode !== change.authMode) tests().delete(id);
next.providers[id].authMode = change.authMode;
}
}
@@ -168,6 +179,11 @@ export function updateAiSettings(patch: AiSettingsPatch): AiSettings {
if (!Number.isInteger(minutes) || minutes < 1 || minutes > 240) throw new UserError("A pausa precisa ficar entre 1 e 240 minutos.");
next.fallback.cooldownMin = minutes;
}
if (patch.fallback?.usageLimitPercent !== undefined) {
const percent = Number(patch.fallback.usageLimitPercent);
if (!Number.isInteger(percent) || percent < 50 || percent > 100) throw new UserError("O limite de uso precisa ficar entre 50% e 100%.");
next.fallback.usageLimitPercent = percent;
}
writeAtomic(SETTINGS_PATH, JSON.stringify(next, null, 2) + "\n");
invalidateStatus();
return next;
@@ -190,7 +206,8 @@ const g = globalThis as unknown as {
__cenaforgeAiInstalls?: Map<Provider, InstallJob>;
__cenaforgeAiCooldown?: Map<Provider, { until: number; reason: string }>;
__cenaforgeAiTests?: Map<Provider, TestResult>;
__cenaforgeGeminiModels?: { at: number; list: { id: string; label: string }[]; loading: boolean };
__cenaforgeAiUsage?: Map<Provider, ProviderUsage>;
__cenaforgeAgyModels?: { at: number; list: { id: string; label: string }[]; loading: boolean };
};
/** DPAPI pelo PowerShell (System.Security.ProtectedData), escopo do usuário. O Clipador abre com ctypes. */
@@ -257,7 +274,8 @@ export type ResolvedCommand = { path: string; command: string; prefixArgs: strin
/** Pastas onde os instaladores costumam pôr as CLIs (o PATH do painel é o de quando ele abriu). */
function extraDirs(): string[] {
const dirs = [path.join(HOME, ".local", "bin")];
// .gemini/bin: onde o instalador do Antigravity põe o agy.exe (fora do PATH até rodar `agy install`).
const dirs = [path.join(HOME, ".local", "bin"), path.join(HOME, ".gemini", "bin")];
if (process.env.APPDATA) dirs.push(path.join(process.env.APPDATA, "npm"));
return dirs;
}
@@ -291,10 +309,6 @@ export function providerEnv(id: Provider, base: Record<string, string | undefine
const variable = PROVIDER_META[id].apiKeyEnv;
if (key) env[variable] = key;
else delete env[variable];
if (id === "gemini") {
if (mode === "oauth") env.GOOGLE_GENAI_USE_GCA = "true";
else delete env.GOOGLE_GENAI_USE_GCA;
}
return env;
}
@@ -308,6 +322,20 @@ type ProviderRuntime = { id: Provider; resolved: ResolvedCommand | null; version
export type InstallJob = { status: "running" | "success" | "error"; log: string[]; startedAt: string; finishedAt: string | null };
export type TestResult = { ok: boolean; text: string; at: string; ms: number };
/** Uma janela de limite (sessão de 5 h, semana…): quanto já foi usado e quando zera. */
export type UsageWindow = { id: string; label: string; usedPercent: number; resetsAt: string | null };
export type ProviderUsage = {
at: string;
/** cli = leitura própria (claude /usage, codex app-server); run = veio junto de uma execução. */
source: "cli" | "run";
windows: UsageWindow[];
/** A própria CLI diz que bateu o limite (não aceita mais pedidos até o reset). */
blocked: boolean;
plan: string | null;
note: string | null;
error: string | null;
};
export type ProviderStatus = {
id: Provider; label: string; vendor: string;
installed: boolean; version: string | null; path: string | null;
@@ -321,7 +349,10 @@ export type ProviderStatus = {
cooldown: { until: string; reason: string } | null;
install: InstallJob | null;
lastTest: TestResult | null;
meta: { installCommand: string; oauthLabel: string; oauthNote: string | null; apiKeyEnv: string; apiKeyUrl: string; apiKeyLabel: string; canLogin: boolean };
usage: ProviderUsage | null;
/** Passou do limite de uso (ou bateu): fica atrás das outras na escolha. */
overLimit: string | null;
meta: { installCommand: string; canInstall: boolean; oauthLabel: string; oauthNote: string | null; apiKeyEnv: string; apiKeyUrl: string; apiKeyLabel: string; canLogin: boolean };
};
function run(resolved: ResolvedCommand, args: string[], timeout = 20_000) {
@@ -347,10 +378,14 @@ function detectOAuth(id: Provider, resolved: ResolvedCommand | null): OAuthState
if (/logged in/i.test(text) && !/not logged in/i.test(text)) return { state: "yes", detail: text.split(/\r?\n/)[0].replace(/^Logged in using/i, "Logado com") };
return { state: "no", detail: "Não está logado." };
}
// Gemini: não há comando de status; a credencial do Google fica em ~/.gemini/oauth_creds.json.
return fs.existsSync(path.join(HOME, ".gemini", "oauth_creds.json"))
? { state: "unknown", detail: "Há uma credencial do Google salva; use \"Testar\" para ver se a conta é aceita." }
: { state: "no", detail: "Nenhuma credencial do Google salva." };
if (id === "antigravity") {
// `agy models` só lista com a conta logada (sem gastar cota).
const r = run(resolved, ["models"], 30_000);
return r.status === 0 && r.stdout.trim()
? { state: "yes", detail: "Logado com a conta Google." }
: { state: "no", detail: "Não está logado (abra \"Entrar com a conta\")." };
}
return { state: "unknown", detail: "" };
}
function runtimes(force = false): ProviderRuntime[] {
@@ -393,6 +428,10 @@ export function providerStatus(options: { refresh?: boolean } = {}): ProviderSta
else if (own.authMode === "apiKey" && vaultError) problem = vaultError;
else if (own.authMode === "apiKey" && !key) problem = "Falta a chave de API.";
else if (own.authMode === "oauth" && rt.oauth.state === "no") problem = "Falta entrar com a conta.";
// O último teste falhou por login, chave ou cota: não está pronta até passar num teste novo.
else if (tests().get(rt.id) && !tests().get(rt.id)!.ok && isAvailabilityError(tests().get(rt.id)!.text)) {
problem = `O último teste falhou: ${tests().get(rt.id)!.text.slice(0, 160)}`;
}
const cooldown = activeCooldown(rt.id);
return {
id: rt.id, label: meta.label, vendor: meta.vendor,
@@ -403,8 +442,11 @@ export function providerStatus(options: { refresh?: boolean } = {}): ProviderSta
cooldown: cooldown ? { until: new Date(cooldown.until).toISOString(), reason: cooldown.reason } : null,
install: installs().get(rt.id) ?? null,
lastTest: tests().get(rt.id) ?? null,
usage: usageStore().get(rt.id) ?? null,
overLimit: overLimit(rt.id),
meta: {
installCommand: meta.install.display, oauthLabel: meta.oauthLabel, oauthNote: meta.oauthNote,
installCommand: rt.resolved && meta.updateArgs ? `${meta.bin} ${meta.updateArgs.join(" ")}` : meta.install.display,
canInstall: !!meta.install.command || !!(rt.resolved && meta.updateArgs), oauthLabel: meta.oauthLabel, oauthNote: meta.oauthNote,
apiKeyEnv: meta.apiKeyEnv, apiKeyUrl: meta.apiKeyUrl, apiKeyLabel: meta.apiKeyLabel, canLogin: IS_WINDOWS,
},
};
@@ -456,13 +498,54 @@ export function readyChain(first?: Provider): Provider[] {
const settings = readAiSettings();
const ready = new Set(providerStatus().filter((p) => p.ready).map((p) => p.id));
const order = [...new Set([...(first ? [first] : []), ...settings.order])].filter((id) => ready.has(id));
return [...order.filter((id) => !activeCooldown(id)), ...order.filter((id) => activeCooldown(id))];
// Ordem: livres; perto do limite de uso; em pausa (caíram há pouco). Sobrar só as últimas é melhor do que parar.
const free = order.filter((id) => !activeCooldown(id) && !overLimit(id));
const limited = order.filter((id) => !activeCooldown(id) && overLimit(id));
return [...free, ...limited, ...order.filter((id) => activeCooldown(id))];
}
/** Próxima IA para continuar uma tarefa que falhou por indisponibilidade (null = reserva desligada ou nenhuma). */
export function nextFallback(tried: Provider[]): Provider | null {
if (!readAiSettings().fallback.enabled) return null;
return readyChain().find((id) => !tried.includes(id) && !activeCooldown(id)) ?? null;
const candidates = readyChain().filter((id) => !tried.includes(id) && !activeCooldown(id));
return candidates.find((id) => !overLimit(id)) ?? candidates[0] ?? null;
}
/* ---------------------------------------------------------------- uso e limites */
const usageStore = () => (g.__cenaforgeAiUsage ??= new Map<Provider, ProviderUsage>());
/** Leitura mais velha que isso não decide nada (o monitor relê a cada 5 min). */
const USAGE_STALE_MS = 30 * 60_000;
export function getUsage(id: Provider): ProviderUsage | null {
return usageStore().get(id) ?? null;
}
/** Guarda a leitura e regrava data/ai/usage.json (o Clipador lê para também pular a IA perto do limite). */
export function setUsage(id: Provider, usage: ProviderUsage): void {
usageStore().set(id, usage);
const providers: Record<string, ProviderUsage> = {};
for (const [key, value] of usageStore()) providers[key] = value;
try {
writeAtomic(USAGE_PATH, JSON.stringify({ updatedAt: new Date().toISOString(), limitPercent: readAiSettings().fallback.usageLimitPercent, providers }, null, 2) + "\n");
} catch (error) {
console.warn(`uso das IAs: não gravei ${USAGE_PATH}: ${(error as Error).message}`);
}
}
/**
* Motivo para a IA sair da frente (null = livre): a CLI disse que bateu o limite, ou alguma janela ainda valendo
* está em `usageLimitPercent` ou mais. Leitura velha (> 30 min) não conta.
*/
export function overLimit(id: Provider, now = Date.now()): string | null {
const usage = usageStore().get(id);
if (!usage || now - Date.parse(usage.at) > USAGE_STALE_MS) return null;
const live = usage.windows.filter((w) => !w.resetsAt || Date.parse(w.resetsAt) > now);
if (usage.blocked && live.some((w) => w.usedPercent >= 100)) return `bateu o limite (${live.filter((w) => w.usedPercent >= 100).map((w) => w.label).join(", ")})`;
if (usage.blocked && live.length === 0 && usage.windows.length === 0) return "a CLI recusou por limite de uso";
const limit = readAiSettings().fallback.usageLimitPercent;
const hot = live.filter((w) => w.usedPercent >= limit).sort((a, b) => b.usedPercent - a.usedPercent)[0];
return hot ? `${hot.label} em ${Math.round(hot.usedPercent)}% (limite ${limit}%)` : null;
}
/* ---------------------------------------------------------------- instalação */
@@ -473,8 +556,15 @@ const installs = () => (g.__cenaforgeAiInstalls ??= new Map());
export function startInstall(id: Provider): InstallJob {
if (!isProvider(id)) throw new UserError("IA desconhecida.");
if (installs().get(id)?.status === "running") throw new UserError("A instalação já está em andamento.");
const { command } = PROVIDER_META[id].install;
const job: InstallJob = { status: "running", log: [`$ ${PROVIDER_META[id].install.display}`], startedAt: new Date().toISOString(), finishedAt: null };
const meta = PROVIDER_META[id];
const installed = resolvedFor(id);
// Já instalada e com comando próprio de atualização (agy update); senão, o instalador.
const command: Command | null = installed && meta.updateArgs
? { file: installed.command, args: [...installed.prefixArgs, ...meta.updateArgs] }
: meta.install.command;
if (!command) throw new UserError(meta.install.display);
const display = installed && meta.updateArgs ? `${meta.bin} ${meta.updateArgs.join(" ")}` : meta.install.display;
const job: InstallJob = { status: "running", log: [`$ ${display}`], startedAt: new Date().toISOString(), finishedAt: null };
installs().set(id, job);
const push = (line: string) => {
job.log.push(line.slice(0, 400));
@@ -510,8 +600,8 @@ export function openLoginTerminal(id: Provider): void {
if (!resolved) throw new UserError("Instale a CLI antes de entrar com a conta.");
const quoted = [resolved.command, ...resolved.prefixArgs].map((part) => `"${part}"`).join(" ");
const cmdline = [quoted, ...PROVIDER_META[id].loginArgs].join(" ");
const banner = id === "gemini"
? "echo No Gemini, escolha \"Login with Google\". Depois de logar, feche esta janela com /quit. &&"
const banner = id === "antigravity"
? "echo Escolha o login com a conta Google. Depois de logar, feche esta janela e clique em Verificar no painel. &&"
: "echo Siga o login no navegador. Depois feche esta janela e clique em Verificar no painel. &&";
// cmd /k "<linha>": as aspas externas caem e as dos caminhos ficam. Caminhos vêm da detecção, não do usuário.
const child = spawn("cmd.exe", ["/d", "/c", "start", `"CenaForge - login ${PROVIDER_META[id].label}"`, "cmd.exe", "/k", `"${banner} ${cmdline}"`],
@@ -524,7 +614,6 @@ export function openLoginTerminal(id: Provider): void {
function providerEnvForLogin(id: Provider): NodeJS.ProcessEnv {
const env = { ...process.env };
delete env[PROVIDER_META[id].apiKeyEnv];
if (id === "gemini") delete env.GOOGLE_GENAI_USE_GCA;
return env;
}
@@ -545,7 +634,7 @@ export async function testProvider(id: Provider): Promise<TestResult> {
? ["-p", question, "--output-format", "json", "--max-turns", "1", "--setting-sources", "project,local", "--strict-mcp-config"]
: id === "codex"
? ["exec", "--json", "--skip-git-repo-check", "--sandbox", "read-only", "-C", cwd, question]
: ["-p", question, "-o", "json", "--approval-mode", "plan", "--skip-trust"];
: ["-p", question, "--output-format", "json", "--mode", "plan"];
const started = Date.now();
const output = await new Promise<{ code: number | null; out: string; err: string }>((resolve) => {
const child = spawn(resolved.command, [...resolved.prefixArgs, ...args], { cwd, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: providerEnv(id) });
@@ -573,9 +662,11 @@ function readTestAnswer(id: Provider, out: string): { ok: boolean; text: string
const r = JSON.parse(out) as { is_error?: boolean; result?: string };
return { ok: !r.is_error, text: String(r.result ?? "").trim().slice(0, 200) };
}
if (id === "gemini") {
const r = JSON.parse(out.slice(out.indexOf("{"))) as { response?: string; error?: { message?: string } };
return r.error ? { ok: false, text: String(r.error.message ?? "erro") } : { ok: true, text: String(r.response ?? "").trim().slice(0, 200) };
if (id === "antigravity") {
// `--output-format json`: o objeto `result` do stream-json ({status, response, …}), direto ou embrulhado.
const parsed = JSON.parse(out.slice(out.indexOf("{"))) as { status?: string; response?: string; result?: { status?: string; response?: string }; error?: unknown };
const r = parsed.result ?? parsed;
return { ok: (r.status ?? "SUCCESS") === "SUCCESS" && !!r.response, text: String(r.response ?? JSON.stringify(parsed.error ?? "")).trim().slice(0, 200) };
}
// Codex: JSONL; a resposta é o último agent_message; falha vem em turn.failed/error.
let text = "";
@@ -597,32 +688,31 @@ function summarizeFailure(text: string): string {
return useful.slice(0, 400);
}
/* ---------------------------------------------------------------- modelos do Gemini */
/* ---------------------------------------------------------------- modelos do Antigravity */
const GEMINI_FALLBACK_MODELS = [
{ id: "gemini-3.5-flash", label: "Gemini 3.5 Flash: rápido e barato" },
{ id: "gemini-2.5-pro", label: "Gemini 2.5 Pro: mais capaz" },
{ id: "gemini-3.1-flash-lite", label: "Gemini 3.1 Flash-Lite: o mais barato" },
];
/** Linhas do `agy models` (texto com tab: id e nome). Exportada para teste. */
export function parseAgyModels(text: string): { id: string; label: string }[] {
return text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
.map((line) => line.split(/\t+|\s{2,}/).map((part) => part.trim()).filter(Boolean))
.filter((parts) => parts.length >= 1 && /^[a-z0-9][\w.-]*$/i.test(parts[0]) && !/^(id|model|name)$/i.test(parts[0]))
.map((parts) => ({ id: parts[0], label: parts[1] ?? parts[0] }));
}
/** Modelos do `gemini models -o json` (não exige login). Devolve o cache na hora e atualiza em segundo plano (1 h). */
export function geminiModels(): { id: string; label: string }[] {
const cache = (g.__cenaforgeGeminiModels ??= { at: 0, list: GEMINI_FALLBACK_MODELS, loading: false });
const resolved = resolvedFor("gemini");
/** Modelos do Antigravity (`agy models`, exige a conta logada); cache de 1 h, atualizado em segundo plano. */
export function antigravityModels(): { id: string; label: string }[] {
const cache = (g.__cenaforgeAgyModels ??= { at: 0, list: [], loading: false });
const resolved = resolvedFor("antigravity");
if (resolved && !cache.loading && Date.now() - cache.at > 3_600_000) {
cache.loading = true;
const child = spawn(resolved.command, [...resolved.prefixArgs, "models", "-o", "json"], { cwd: HOME, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
const child = spawn(resolved.command, [...resolved.prefixArgs, "models"], { cwd: HOME, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "ignore"], env: providerEnv("antigravity") });
let out = "";
child.stdout.setEncoding("utf8").on("data", (c: string) => { out += c; });
child.on("error", () => { cache.loading = false; });
child.on("close", () => {
cache.loading = false;
cache.at = Date.now();
try {
const parsed = JSON.parse(out.slice(out.indexOf("["))) as { id?: unknown; displayName?: unknown }[];
const list = parsed.filter((m) => typeof m.id === "string" && m.id !== "auto").map((m) => ({ id: String(m.id), label: String(m.displayName ?? m.id) }));
if (list.length) cache.list = list;
} catch { /* mantém a lista anterior */ }
const list = parseAgyModels(out);
if (list.length) cache.list = list;
});
}
return cache.list;
+1 -1
View File
@@ -63,7 +63,7 @@ export function buildPrompt(input: { kind: AgentKind; provider: Provider; reques
"Não acione os subagentes `cenaforge-skill-updater` nem `cenaforge-token-auditor` (100–150 mil tokens cada): isso é feito fora do painel. " +
"Ao terminar, liste os arquivos criados ou alterados e o que ficou pendente.",
provider !== "claude"
? `Você é o ${provider === "codex" ? "Codex" : "Gemini"}. ` +
? `Você é o ${{ codex: "Codex", antigravity: "Antigravity" }[provider]}. ` +
"Arquivos em `.claude/agents/` são subagentes do Claude: você não os aciona; quando o CLAUDE.md mandar delegar a um deles, faça o trabalho você mesmo. " +
"No PowerShell, leia texto com `Get-Content -Raw -Encoding UTF8` (sem isso os acentos saem quebrados) e rode o pnpm como `pnpm.cmd` " +
"(o `pnpm.ps1` é bloqueado pela política de execução): `pnpm.cmd render -- --config <json> --profile preview`."
+2 -2
View File
@@ -123,8 +123,8 @@ export type Decision = {
snapshot_json: string;
};
export type Provider = "claude" | "codex" | "gemini";
export const PROVIDERS: Provider[] = ["claude", "codex", "gemini"];
export type Provider = "claude" | "codex" | "antigravity";
export const PROVIDERS: Provider[] = ["claude", "codex", "antigravity"];
// godot: o agente constrói uma cena nova na biblioteca do Godot (godot/library/, doc/godot/cenas.md).
export type AgentKind = "free" | "story" | "script" | "scene" | "branches" | "godot" | "character";
export const AGENT_KINDS: AgentKind[] = ["free", "story", "script", "scene", "branches", "godot", "character"];