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:
@@ -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.
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 "Procurar de novo".</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{job && (job.status !== "success" || !p.installed) && (
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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."} />
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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." },
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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
@@ -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 }];
|
||||
|
||||
@@ -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
@@ -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
@@ -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;
|
||||
|
||||
@@ -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`."
|
||||
|
||||
@@ -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"];
|
||||
|
||||
Reference in New Issue
Block a user