IA: Claude, Codex e Gemini com login, chave de API e IA reserva; Configurações em subpáginas
- Configurações → IA (/settings/ai): um cartão por IA para instalar/atualizar a CLI pelo painel, ligar, entrar com a conta (OAuth pela própria CLI, num terminal) ou colar a chave de API, e testar. Chaves cifradas com a DPAPI do Windows em data/ai/vault.bin; só vão para a CLI no ambiente da chamada. - Gemini CLI como terceiro agente do painel (stream-json, edição automática, shell só o liberado). - IA reserva: execução que cai por indisponibilidade (cota, 429, login, chave, rede) pausa a IA e recomeça a mesma tarefa na próxima pronta da ordem; migração v10 (agent_runs.fallback_of). - Configurações viraram subpáginas (IA, Publicação, Apps das redes, Navegador, Sobre os modos), também no menu lateral; links antigos apontam para a subpágina certa. - Contrato com o Clipador em doc/ia.md; skill do CenaForge atualizada até a 1.51.0. O login gratuito do Gemini CLI para conta pessoal foi encerrado pelo Google (IneligibleTierError): para conta pessoal, use a chave do AI Studio. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -31,7 +31,7 @@ export default async function AccountsPage({ searchParams }: { searchParams: Pro
|
||||
description="Cada canal reúne os seus perfis no YouTube, no TikTok e no Instagram. Ligue histórias e fontes de corte a ele: o que você aprovar sai nas redes do canal."
|
||||
meta={<>
|
||||
<Meta icon={<PublishIcon size={15} />}>Fila e horários em <Link href="/publishing" className="text-fg-muted underline underline-offset-2 hover:text-fg">Publicações</Link></Meta>
|
||||
<Meta icon={<SettingsIcon size={15} />}>Apps das redes e horários bons em <Link href="/settings" className="text-fg-muted underline underline-offset-2 hover:text-fg">Configurações</Link></Meta>
|
||||
<Meta icon={<SettingsIcon size={15} />}>Apps das redes e horários bons em <Link href="/settings/publishing" className="text-fg-muted underline underline-offset-2 hover:text-fg">Configurações</Link></Meta>
|
||||
</>} />
|
||||
|
||||
<div className="grid gap-6">
|
||||
|
||||
@@ -7,7 +7,7 @@ import { addManualComments, closeDecision, decisionVotes } from "@/lib/decisions
|
||||
import { defaultModelFor, defaultProviderFor, startRun } from "@/lib/agents";
|
||||
import { slugify } from "@/lib/paths";
|
||||
import { UserError, createEpisode, createStory, deleteStory, getEpisodeById, getStory, provisionalTitle } from "@/lib/stories";
|
||||
import { CHOICES, type Choice, type Provider, type StoryKind } from "@/lib/types";
|
||||
import { CHOICES, PROVIDERS, type Choice, type Provider, type StoryKind } from "@/lib/types";
|
||||
|
||||
export type FormState = { error?: string; message?: string } | null;
|
||||
|
||||
@@ -55,7 +55,7 @@ export async function createStoryFromTextAction(_prev: FormState, form: FormData
|
||||
// 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" });
|
||||
const chosen = String(form.get("provider") ?? "");
|
||||
const provider: Provider = chosen === "claude" || chosen === "codex" ? chosen : defaultProviderFor("story");
|
||||
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.
|
||||
const model = String(form.get("model") ?? "") || defaultModelFor("story", provider);
|
||||
const run = startRun({
|
||||
|
||||
@@ -24,13 +24,13 @@ 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") })),
|
||||
model: map((k) => ({ claude: defaultModelFor(k, "claude"), codex: defaultModelFor(k, "codex"), gemini: defaultModelFor(k, "gemini") })),
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Agentes de código" title="Console do agente"
|
||||
description="Peça uma história, um roteiro, uma cena ou um ajuste. Enredo e roteiro saem com o GPT (Codex); a cena, com o Claude. Um agente roda por vez, sempre dentro do projeto." />
|
||||
description="Peça uma história, um roteiro, uma cena ou um ajuste. Enredo e roteiro saem com o GPT (Codex); a cena, com o Claude. Se uma IA cair, a reserva assume (Configurações → IA). Um agente roda por vez, sempre dentro do projeto." />
|
||||
<div className="grid items-start gap-8 xl:grid-cols-[minmax(0,1fr)_20rem] 2xl:grid-cols-[minmax(0,1fr)_26rem]">
|
||||
<AgentConsole
|
||||
key={runId ?? "novo"}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { clearCooldown, openLoginTerminal, providerStatus, readAiSettings, setApiKey, startInstall, testProvider } from "@/lib/ai";
|
||||
import { errorResponse, readJson } from "@/lib/http";
|
||||
import { UserError } from "@/lib/stories";
|
||||
import { PROVIDERS, type Provider } from "@/lib/types";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Ctx = { params: Promise<{ provider: string }> };
|
||||
|
||||
async function mustProvider(ctx: Ctx): Promise<Provider> {
|
||||
const id = (await ctx.params).provider;
|
||||
if (!(PROVIDERS as string[]).includes(id)) throw new UserError("IA desconhecida.");
|
||||
return id as Provider;
|
||||
}
|
||||
|
||||
const payload = (refresh = false) => ({ settings: readAiSettings(), providers: providerStatus({ refresh }) });
|
||||
|
||||
/**
|
||||
* Ações de uma IA: {action: "install" | "login" | "verify" | "test" | "resume"}.
|
||||
* 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.
|
||||
*/
|
||||
export async function POST(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const id = await mustProvider(ctx);
|
||||
const { action } = await readJson<{ action: string }>(request);
|
||||
switch (action) {
|
||||
case "install":
|
||||
startInstall(id);
|
||||
return Response.json(payload());
|
||||
case "login":
|
||||
openLoginTerminal(id);
|
||||
return Response.json(payload());
|
||||
case "verify":
|
||||
return Response.json(payload(true));
|
||||
case "test": {
|
||||
const test = await testProvider(id);
|
||||
return Response.json({ ...payload(), test });
|
||||
}
|
||||
case "resume":
|
||||
clearCooldown(id);
|
||||
return Response.json(payload());
|
||||
default:
|
||||
throw new UserError("Ação inválida.");
|
||||
}
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Guarda a chave de API no cofre (DPAPI): {apiKey}. A resposta nunca traz a chave, só os 4 últimos caracteres. */
|
||||
export async function PUT(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const id = await mustProvider(ctx);
|
||||
const { apiKey } = await readJson<{ apiKey: string }>(request);
|
||||
if (typeof apiKey !== "string") throw new UserError("Cole a chave de API.");
|
||||
setApiKey(id, apiKey);
|
||||
return Response.json(payload());
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apaga a chave de API desta IA do cofre. */
|
||||
export async function DELETE(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
setApiKey(await mustProvider(ctx), null);
|
||||
return Response.json(payload());
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { providerStatus, readAiSettings, updateAiSettings, type AiSettingsPatch } from "@/lib/ai";
|
||||
import { errorResponse, readJson } from "@/lib/http";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Estado das IAs: {settings, providers}. `?refresh=1` refaz a detecção (instalada, versão, login) na hora. */
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const refresh = new URL(request.url).searchParams.get("refresh") === "1";
|
||||
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?}}. */
|
||||
export async function PUT(request: Request) {
|
||||
try {
|
||||
const settings = updateAiSettings(await readJson<AiSettingsPatch>(request));
|
||||
return Response.json({ settings, providers: providerStatus() });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { defaultModelFor, defaultProviderFor, startRun } from "@/lib/agents";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { slugify } from "@/lib/paths";
|
||||
import { UserError, createEpisode, createStory, getStory, provisionalTitle } from "@/lib/stories";
|
||||
import { STORY_KINDS, type Provider, type StoryKind } from "@/lib/types";
|
||||
import { PROVIDERS, STORY_KINDS, type Provider, type StoryKind } from "@/lib/types";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
@@ -20,7 +20,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" });
|
||||
const provider: Provider = body.provider === "claude" || body.provider === "codex" ? body.provider : defaultProviderFor("story");
|
||||
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 });
|
||||
return Response.json({ storyId: story.id, episodeId: ep.id, runId: run.id });
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "@/components/ui";
|
||||
import { defaultProviderFor, models, providers } from "@/lib/agents";
|
||||
import { listEpisodes, listStories } from "@/lib/stories";
|
||||
import type { EpisodeView, Story } from "@/lib/types";
|
||||
import type { EpisodeView, Provider, Story } from "@/lib/types";
|
||||
|
||||
export default async function HomePage() {
|
||||
await connection();
|
||||
@@ -18,7 +18,7 @@ export default async function HomePage() {
|
||||
const totalEpisodes = stories.reduce((sum, s) => sum + s.episodes.length, 0);
|
||||
const rendered = stories.reduce((sum, s) => sum + s.episodes.filter((e) => e.stage === "renderizado" || e.stage === "decidido").length, 0);
|
||||
const openVotes = stories.reduce((sum, s) => sum + (s.story.kind === "interactive" ? s.episodes.filter((e) => e.stage === "renderizado").length : 0), 0);
|
||||
const available = Object.fromEntries(providers().map((p) => [p.id, p.available])) as Record<"claude" | "codex", boolean>;
|
||||
const available = Object.fromEntries(providers().map((p) => [p.id, p.available])) as Record<Provider, boolean>;
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -16,7 +16,7 @@ export default function PublishingPage() {
|
||||
description="Tudo o que vai para as redes: o que espera a sua aprovação, o que está agendado, o que está saindo agora e o que já foi publicado."
|
||||
meta={<>
|
||||
<Meta icon={<PublishIcon size={15} />}>Redes e regras em <Link href="/accounts" className="text-fg-muted underline underline-offset-2 hover:text-fg">Canais de publicação</Link></Meta>
|
||||
<Meta icon={<ClockIcon size={15} />}>Horários bons em <Link href="/settings" className="text-fg-muted underline underline-offset-2 hover:text-fg">Configurações</Link></Meta>
|
||||
<Meta icon={<ClockIcon size={15} />}>Horários bons em <Link href="/settings/publishing" className="text-fg-muted underline underline-offset-2 hover:text-fg">Configurações</Link></Meta>
|
||||
<Meta icon={<SettingsIcon size={15} />}>O painel precisa estar aberto para publicar</Meta>
|
||||
</>} />
|
||||
<PublishingBoard />
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { AiSettings } from "@/components/ai-settings";
|
||||
|
||||
export const metadata = { title: "IA · Configurações" };
|
||||
|
||||
export default function Page() {
|
||||
return <AiSettings />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { AppsTab } from "@/components/settings-panel";
|
||||
|
||||
export const metadata = { title: "Apps das redes · Configurações" };
|
||||
|
||||
export default function Page() {
|
||||
return <AppsTab />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { BrowserTab } from "@/components/settings-panel";
|
||||
|
||||
export const metadata = { title: "Navegador · Configurações" };
|
||||
|
||||
export default function Page() {
|
||||
return <BrowserTab />;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { SettingsShell } from "@/components/settings-shell";
|
||||
|
||||
export const metadata = { title: "Configurações" };
|
||||
|
||||
/** Moldura comum das subpáginas de Configurações (IA, Publicação, Apps das redes, Navegador, Sobre os modos). */
|
||||
export default function SettingsLayout({ children }: { children: ReactNode }) {
|
||||
return <SettingsShell>{children}</SettingsShell>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { ModesTab } from "@/components/settings-panel";
|
||||
|
||||
export const metadata = { title: "Sobre os modos · Configurações" };
|
||||
|
||||
export default function Page() {
|
||||
return <ModesTab />;
|
||||
}
|
||||
@@ -1,15 +1,6 @@
|
||||
import { SettingsPanel } from "@/components/settings-panel";
|
||||
import { PageHeader } from "@/components/ui";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export const metadata = { title: "Configurações" };
|
||||
|
||||
/** Configurações do painel: publicação, apps das redes, navegador da sessão logada e a explicação dos modos. */
|
||||
/** /settings abre a primeira seção (IA); cada seção tem a própria página. */
|
||||
export default function SettingsPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Painel" title="Configurações"
|
||||
description="Horários de publicação, os apps de cada rede e o navegador usado na sessão logada. Tudo fica só neste computador." />
|
||||
<SettingsPanel />
|
||||
</>
|
||||
);
|
||||
redirect("/settings/ai");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { PublishingTab } from "@/components/settings-panel";
|
||||
|
||||
export const metadata = { title: "Publicação · Configurações" };
|
||||
|
||||
export default function Page() {
|
||||
return <PublishingTab />;
|
||||
}
|
||||
@@ -308,7 +308,7 @@ export function PublishingRulesCard({ account, className }: { account: AccountVi
|
||||
{ value: "best_slot", label: "No próximo horário bom", hint: "Mais gente vendo" },
|
||||
]} />
|
||||
<p className="text-[0.8125rem] leading-relaxed text-fg-subtle">
|
||||
Os horários bons de cada rede ficam em <TextLink href="/settings">Configurações</TextLink>. Entre dois vídeos na mesma rede fica pelo menos 1 hora.
|
||||
Os horários bons de cada rede ficam em <TextLink href="/settings/publishing">Configurações</TextLink>. Entre dois vídeos na mesma rede fica pelo menos 1 hora.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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" };
|
||||
const PROVIDER_SHORT: Record<Provider, string> = { claude: "Claude", codex: "GPT" };
|
||||
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" };
|
||||
|
||||
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.",
|
||||
@@ -210,7 +210,7 @@ export function AgentConsole(props: {
|
||||
{/* 2. Agente */}
|
||||
<fieldset className="grid gap-3">
|
||||
<legend className="mb-3 text-eyebrow font-semibold uppercase text-fg-subtle">2 · Agente</legend>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
{props.providers.map((p) => (
|
||||
<ProviderCard key={p.id} info={p} selected={provider === p.id} recommended={preferred === p.id}
|
||||
onSelect={() => chooseProvider(p.id)} />
|
||||
@@ -334,7 +334,7 @@ function ProviderCard({ info, selected, recommended, onSelect }:
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-sm font-semibold text-fg">{PROVIDER_LABEL[info.id]}</span>
|
||||
{recommended && <Badge tone="accent" dot={false}>padrão desta tarefa</Badge>}
|
||||
{!info.available && <Badge tone="warning" dot={false}>não instalado</Badge>}
|
||||
{!info.available && <Badge tone="warning" dot={false}>não está pronto</Badge>}
|
||||
</span>
|
||||
<span id={hintId} className="grid gap-1 text-xs leading-relaxed text-fg-subtle">
|
||||
{info.version && <span className="font-mono text-[0.6875rem] text-fg-muted">{info.version}</span>}
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
"use client";
|
||||
// Configurações → IA: as três CLIs (Claude Code, Codex/GPT e Gemini) 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 { 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 { Badge, Button, Card, ChoiceGroup, Feedback, Field, Input, Select, Spinner, Switch, cx, type Tone } from "./ui";
|
||||
|
||||
type Payload = { settings: AiSettings; providers: ProviderStatus[]; test?: TestResult };
|
||||
type Result<T> = { ok: true; data: T } | { ok: false; error: string };
|
||||
type Message = { ok: boolean; text: string } | null;
|
||||
|
||||
async function aiCall<T = Payload>(path: string, method = "GET", body?: unknown): Promise<Result<T>> {
|
||||
try {
|
||||
const response = await fetch(`/api/ai${path}`, {
|
||||
method, cache: "no-store",
|
||||
headers: body === undefined ? undefined : { "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const data = (await response.json().catch(() => ({}))) as T & { error?: string };
|
||||
return response.ok ? { ok: true, data } : { ok: false, error: data.error ?? `Erro ${response.status}` };
|
||||
} catch {
|
||||
return { ok: false, error: "O painel não respondeu." };
|
||||
}
|
||||
}
|
||||
|
||||
const COOLDOWN_OPTIONS = [5, 15, 30, 60, 120];
|
||||
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).",
|
||||
};
|
||||
|
||||
const time = (iso: string) => new Date(iso).toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
/** Situação em uma palavra (badge do cartão e da ordem). */
|
||||
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.cooldown) return { tone: "danger", text: `em pausa até ${time(p.cooldown.until)}` };
|
||||
return { tone: "success", text: "pronta" };
|
||||
}
|
||||
|
||||
export function AiSettings() {
|
||||
const [data, setData] = useState<Payload | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async (refresh = false) => {
|
||||
const r = await aiCall(refresh ? "?refresh=1" : "");
|
||||
if (r.ok) { setData(r.data); setError(null); } else setError(r.error);
|
||||
}, []);
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
|
||||
// Instalação em andamento: relê a cada 2 s para mostrar o log.
|
||||
const installing = data?.providers.some((p) => p.install?.status === "running") ?? false;
|
||||
useEffect(() => {
|
||||
if (!installing) return;
|
||||
const timer = setInterval(() => void load(), 2000);
|
||||
return () => clearInterval(timer);
|
||||
}, [installing, load]);
|
||||
|
||||
if (error && !data) {
|
||||
return (
|
||||
<div className="grid justify-items-start gap-3">
|
||||
<Feedback ok={false}>Não deu para ler as IAs: {error}</Feedback>
|
||||
<Button variant="secondary" size="sm" onClick={() => void load()}><RefreshIcon size={15} />Tentar de novo</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!data) return <p role="status" className="flex items-center gap-2 text-sm text-fg-muted"><Spinner />Procurando as CLIs neste computador…</p>;
|
||||
|
||||
const readyCount = data.providers.filter((p) => p.ready).length;
|
||||
const byId = Object.fromEntries(data.providers.map((p) => [p.id, p])) as Record<Provider, ProviderStatus>;
|
||||
|
||||
return (
|
||||
<div className="grid gap-8">
|
||||
{readyCount === 0 && (
|
||||
<Feedback ok={false}>Nenhuma IA está pronta. Instale pelo menos uma abaixo e entre com a conta (ou cole uma chave de API).</Feedback>
|
||||
)}
|
||||
<FallbackCard data={data} onChange={setData} />
|
||||
<section aria-labelledby="ias" className="grid gap-4">
|
||||
<div className="flex flex-wrap items-end justify-between gap-3">
|
||||
<div>
|
||||
<h2 id="ias" className="text-base font-semibold text-fg">As IAs deste computador</h2>
|
||||
<p className="mt-1 max-w-[75ch] text-sm text-fg-subtle">
|
||||
Cada uma roda pela CLI oficial. <strong className="font-medium text-fg-muted">Conta</strong> usa a assinatura em que você já paga
|
||||
(login no navegador); <strong className="font-medium text-fg-muted">chave de API</strong> cobra por uso e fica cifrada neste PC.
|
||||
</p>
|
||||
</div>
|
||||
<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} />)}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Reserva ---------- */
|
||||
|
||||
function FallbackCard({ data, onChange }: { data: Payload; onChange: (next: Payload) => void }) {
|
||||
const { settings } = data;
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<Message>(null);
|
||||
const byId = Object.fromEntries(data.providers.map((p) => [p.id, p])) as Record<Provider, ProviderStatus>;
|
||||
|
||||
async function save(key: string, patch: Partial<{ order: Provider[]; fallback: Partial<AiSettings["fallback"]> }>, ok: string) {
|
||||
setBusy(key);
|
||||
setMessage(null);
|
||||
const r = await aiCall("", "PUT", patch);
|
||||
setBusy(null);
|
||||
if (r.ok) { onChange(r.data); setMessage({ ok: true, text: ok }); } else setMessage({ ok: false, text: r.error });
|
||||
}
|
||||
|
||||
function move(index: number, delta: -1 | 1) {
|
||||
const order = [...settings.order];
|
||||
const [item] = order.splice(index, 1);
|
||||
order.splice(index + delta, 0, item);
|
||||
void save(`move-${item}`, { order }, "Ordem salva.");
|
||||
}
|
||||
|
||||
return (
|
||||
<Card eyebrow={<><RefreshIcon size={13} />IA reserva</>} title="Se uma IA cair, a próxima assume"
|
||||
description="Vale para os agentes do painel e para o juiz do Clipador. A tarefa começa na IA escolhida (ou na preferida dela); se falhar por limite de uso, login, chave ou rede, recomeça na próxima pronta desta lista. Erro do pedido em si não troca de IA.">
|
||||
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)]">
|
||||
<div className="grid content-start gap-5">
|
||||
<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="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.")}>
|
||||
{[...new Set([...COOLDOWN_OPTIONS, settings.fallback.cooldownMin])].sort((a, b) => a - b)
|
||||
.map((m) => <option key={m} value={m}>{m < 60 ? `${m} minutos` : `${m / 60} hora${m > 60 ? "s" : ""}`}</option>)}
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
<div className="grid content-start gap-2">
|
||||
<span className="text-[0.8125rem] font-medium text-fg-muted">Ordem de uso</span>
|
||||
<ol className="grid gap-2">
|
||||
{settings.order.map((id, index) => {
|
||||
const p = byId[id];
|
||||
const badge = statusBadge(p);
|
||||
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>
|
||||
<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}
|
||||
onClick={() => move(index, -1)} className="px-2"><ArrowLeftIcon size={14} className="rotate-90" /></Button>
|
||||
<Button variant="ghost" size="sm" aria-label={`Descer ${p.label}`} disabled={index === settings.order.length - 1 || busy !== null}
|
||||
onClick={() => move(index, 1)} className="px-2"><ArrowLeftIcon size={14} className="-rotate-90" /></Button>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
<p className="text-xs text-fg-subtle">IA desligada ou sem login/chave é pulada.</p>
|
||||
</div>
|
||||
</div>
|
||||
{message && <div className="mt-5"><Feedback ok={message.ok}>{message.text}</Feedback></div>}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Cartão de cada IA ---------- */
|
||||
|
||||
function ProviderCard({ status: p, onChange }: { status: ProviderStatus; onChange: (next: Payload) => void }) {
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<Message>(null);
|
||||
const [key, setKey] = useState("");
|
||||
const badge = statusBadge(p);
|
||||
|
||||
async function act(name: string, call: () => Promise<Result<Payload>>, ok?: (data: Payload) => string) {
|
||||
setBusy(name);
|
||||
setMessage(null);
|
||||
const r = await call();
|
||||
setBusy(null);
|
||||
if (!r.ok) { setMessage({ ok: false, text: r.error }); return false; }
|
||||
onChange(r.data);
|
||||
if (ok) setMessage({ ok: true, text: ok(r.data) });
|
||||
return true;
|
||||
}
|
||||
const post = (action: string) => () => aiCall(`/${p.id}`, "POST", { action });
|
||||
|
||||
return (
|
||||
<article aria-labelledby={`ia-${p.id}`}
|
||||
className={cx("grid content-start gap-5 rounded-card border border-line bg-surface p-5 shadow-card", !p.settings.enabled && "opacity-80")}>
|
||||
<header className="grid gap-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h3 id={`ia-${p.id}`} className="flex flex-wrap items-center gap-2 text-base font-semibold text-fg">
|
||||
<CpuIcon size={17} />{p.label}<span className="text-xs font-normal text-fg-subtle">{p.vendor}</span>
|
||||
</h3>
|
||||
<p className="mt-1 text-xs leading-relaxed text-fg-subtle">{PROVIDER_TAGLINE[p.id]}</p>
|
||||
</div>
|
||||
<Badge tone={badge.tone}>{badge.text}</Badge>
|
||||
</div>
|
||||
<Switch label="Usar esta IA" checked={p.settings.enabled} busy={busy === "enabled"}
|
||||
hint={p.settings.enabled ? "Pode ser escolhida e entra na reserva." : "Nunca é chamada, nem como reserva."}
|
||||
onChange={(enabled) => void act("enabled", () => aiCall("", "PUT", { providers: { [p.id]: { enabled } } }))} />
|
||||
</header>
|
||||
|
||||
<InstallSection p={p} busy={busy} onInstall={() => void act("install", post("install"))} />
|
||||
|
||||
{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}
|
||||
onChange={(authMode) => void act("auth", () => aiCall("", "PUT", { providers: { [p.id]: { authMode } } }))}
|
||||
options={[
|
||||
{ value: "oauth", label: <span className="inline-flex items-center gap-1.5"><UsersIcon size={14} />Conta</span> },
|
||||
{ value: "apiKey", label: <span className="inline-flex items-center gap-1.5"><KeyIcon size={14} />Chave de API</span> },
|
||||
]} />
|
||||
{p.settings.authMode === "oauth"
|
||||
? <OAuthSection p={p} busy={busy}
|
||||
onLogin={() => void act("login", post("login"), () => "Abrimos um terminal com o login. Termine no navegador e clique em Verificar.")}
|
||||
onVerify={() => void act("verify", post("verify"), (d) => d.providers.find((x) => x.id === p.id)?.oauth.detail || "Verificado.")} />
|
||||
: <ApiKeySection p={p} busy={busy} value={key} onValue={setKey}
|
||||
onSave={() => void act("key", () => aiCall(`/${p.id}`, "PUT", { apiKey: key }), () => "Chave salva no cofre deste PC.").then((ok) => ok && setKey(""))}
|
||||
onRemove={() => void act("remove", () => aiCall(`/${p.id}`, "DELETE"), () => "Chave apagada.")} />}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{p.installed && p.settings.enabled && (
|
||||
<footer className="grid gap-3 border-t border-line pt-4">
|
||||
{p.cooldown && (
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-control border border-danger/30 bg-danger-soft/50 px-3 py-2 text-xs text-danger">
|
||||
<PauseIcon size={14} /><span className="min-w-0 flex-1">Em pausa até {time(p.cooldown.until)}: {p.cooldown.reason}</span>
|
||||
<Button variant="ghost" size="sm" disabled={busy !== null} onClick={() => void act("resume", post("resume"), () => "Saiu da pausa.")}>
|
||||
<PlayIcon size={14} />Tirar da pausa
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button variant="secondary" size="sm" disabled={busy !== null || !p.ready}
|
||||
onClick={() => void act("test", post("test"))}>
|
||||
{busy === "test" ? <><Spinner className="size-3.5" />Testando…</> : <><CheckIcon size={15} />Testar</>}
|
||||
</Button>
|
||||
<span className="text-xs text-fg-subtle">Faz uma pergunta mínima (poucos tokens) fora do projeto.</span>
|
||||
</div>
|
||||
{p.lastTest && (
|
||||
<p className={cx("text-xs", p.lastTest.ok ? "text-success" : "text-danger")} role="status">
|
||||
{p.lastTest.ok ? "Funcionou" : "Falhou"} às {time(p.lastTest.at)} · {(p.lastTest.ms / 1000).toFixed(1)} s · {p.lastTest.text}
|
||||
</p>
|
||||
)}
|
||||
</footer>
|
||||
)}
|
||||
|
||||
{message && <Feedback ok={message.ok}>{message.text}</Feedback>}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function InstallSection({ p, busy, onInstall }: { p: ProviderStatus; busy: string | null; onInstall: () => void }) {
|
||||
const job = p.install;
|
||||
const running = job?.status === "running";
|
||||
return (
|
||||
<section className="grid gap-3 border-t border-line pt-4" aria-label={`Instalação do ${p.label}`}>
|
||||
{p.installed ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="grid min-w-0 gap-0.5">
|
||||
<span className="flex items-center gap-1.5 text-sm text-fg"><CheckIcon size={14} className="text-success" />Instalada</span>
|
||||
<span className="truncate font-mono text-[0.6875rem] text-fg-subtle" title={p.path ?? undefined}>{p.version}</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" disabled={running || busy !== null} onClick={onInstall}>
|
||||
{running ? <><Spinner className="size-3.5" />Atualizando…</> : <><DownloadIcon size={14} />Atualizar</>}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3">
|
||||
<p className="text-sm text-fg-muted">A CLI não foi encontrada neste computador.</p>
|
||||
<div className="flex items-center gap-2 rounded-control border border-line bg-sunken px-3 py-2">
|
||||
<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>
|
||||
</div>
|
||||
)}
|
||||
{job && (job.status !== "success" || !p.installed) && (
|
||||
<details open={job.status !== "success"} className="rounded-control border border-line bg-sunken">
|
||||
<summary className="cursor-pointer px-3 py-2 text-xs text-fg-muted">
|
||||
{job.status === "running" ? "Instalando…" : job.status === "success" ? "Instalação concluída" : "A instalação falhou"} · log
|
||||
</summary>
|
||||
<pre className="max-h-48 overflow-auto px-3 pb-3 font-mono text-[0.6875rem] leading-relaxed whitespace-pre-wrap text-fg-subtle">{job.log.slice(-40).join("\n")}</pre>
|
||||
</details>
|
||||
)}
|
||||
{job?.status === "success" && !p.installed && (
|
||||
<Feedback ok={false}>Instalou, mas o painel ainda não acha a CLI (o PATH dele é o de quando abriu). Clique em "Procurar de novo" ou reinicie o <code>pnpm panel</code>.</Feedback>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function OAuthSection({ p, busy, onLogin, onVerify }: { p: ProviderStatus; busy: string | null; onLogin: () => void; onVerify: () => void }) {
|
||||
const tone = p.oauth.state === "yes" ? "text-success" : p.oauth.state === "no" ? "text-warning" : "text-fg-muted";
|
||||
return (
|
||||
<div className="grid gap-3">
|
||||
<p className="text-xs text-fg-subtle">{p.meta.oauthLabel}. O login é feito pela própria CLI: o painel nunca vê a senha.</p>
|
||||
{p.oauth.detail && <p className={cx("text-sm", tone)}>{p.oauth.detail}</p>}
|
||||
{p.meta.oauthNote && (
|
||||
<p className="flex gap-2 rounded-control border border-warning/30 bg-warning-soft/40 px-3 py-2 text-xs leading-relaxed text-warning">
|
||||
<AlertIcon size={14} className="mt-0.5 shrink-0" />{p.meta.oauthNote}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{p.meta.canLogin && (
|
||||
<Button variant={p.oauth.state === "yes" ? "ghost" : "primary"} size="sm" disabled={busy !== null} onClick={onLogin}>
|
||||
{busy === "login" ? <Spinner className="size-3.5" /> : <LinkIcon size={14} />}{p.oauth.state === "yes" ? "Trocar de conta" : "Entrar com a conta"}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="secondary" size="sm" disabled={busy !== null} onClick={onVerify}>
|
||||
{busy === "verify" ? <Spinner className="size-3.5" /> : <RefreshIcon size={14} />}Verificar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ApiKeySection({ p, busy, value, onValue, onSave, onRemove }: {
|
||||
p: ProviderStatus; busy: string | null; value: string; onValue: (v: string) => void; onSave: () => void; onRemove: () => void;
|
||||
}) {
|
||||
return (
|
||||
<form className="grid gap-3" onSubmit={(e) => { e.preventDefault(); onSave(); }}>
|
||||
{p.apiKey.saved && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-sm">
|
||||
<span className="flex items-center gap-1.5 text-success"><KeyIcon size={14} />Chave salva <span className="font-mono text-xs text-fg-subtle">{p.apiKey.hint}</span></span>
|
||||
<Button type="button" variant="ghost" size="sm" disabled={busy !== null} onClick={onRemove}><TrashIcon size={14} />Apagar</Button>
|
||||
</div>
|
||||
)}
|
||||
<Field label={p.apiKey.saved ? "Trocar a chave" : p.meta.apiKeyLabel}
|
||||
hint={<>Fica cifrada neste PC (DPAPI do Windows) e nunca volta para a tela. Vai para a CLI como <code>{p.meta.apiKeyEnv}</code> só na hora da chamada.</>}>
|
||||
<Input type="password" autoComplete="off" spellCheck={false} value={value} onChange={(e) => onValue(e.target.value)} placeholder="Cole a chave aqui" />
|
||||
</Field>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button type="submit" size="sm" disabled={busy !== null || value.trim().length < 16}>
|
||||
{busy === "key" ? <Spinner className="size-3.5" /> : <KeyIcon size={14} />}Salvar chave
|
||||
</Button>
|
||||
<ExternalLink href={p.meta.apiKeyUrl}>Criar uma chave</ExternalLink>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function ExternalLink({ href, children }: { href: string; children: ReactNode }) {
|
||||
return (
|
||||
<a href={href} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-xs text-fg-muted underline underline-offset-2 hover:text-fg">
|
||||
{children}<LinkIcon size={12} />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -341,7 +341,7 @@ export function ConnectWizard({ accountId, accountName, platform, network, recon
|
||||
)}
|
||||
|
||||
<div aria-live="assertive" className="empty:hidden">
|
||||
{error && <Feedback ok={false}>{error}{/app|client/i.test(error) && <> Veja <Link className="underline" href="/settings?tab=apps">Configurações › Apps das redes</Link>.</>}</Feedback>}
|
||||
{error && <Feedback ok={false}>{error}{/app|client/i.test(error) && <> Veja <Link className="underline" href="/settings/apps">Configurações › Apps das redes</Link>.</>}</Feedback>}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
@@ -417,7 +417,7 @@ function ModeCard({ platform, mode, checked, appMissing, onSelect }: {
|
||||
{appMissing && (
|
||||
<span className="ml-8 flex gap-2 rounded-control border border-info/30 bg-info-soft px-3 py-2 text-[0.8125rem] leading-relaxed text-info">
|
||||
<AlertIcon size={15} className="mt-0.5" />
|
||||
<span>O app do {label} ainda não foi configurado. Faça isso antes em <Link href="/settings?tab=apps" className="font-semibold underline">Configurações › Apps das redes</Link>.</span>
|
||||
<span>O app do {label} ainda não foi configurado. Faça isso antes em <Link href="/settings/apps" className="font-semibold underline">Configurações › Apps das redes</Link>.</span>
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
|
||||
@@ -132,7 +132,7 @@ export function MetricsSyncControls({ syncs, accountId, everyHours, showAccount
|
||||
<h2 className="text-sm font-semibold text-fg">Números das redes</h2>
|
||||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||||
{everyHours > 0 ? `O painel lê sozinho a cada ${everyHours} h (com o painel aberto).` : "Leitura automática desligada: só pelo botão."}{" "}
|
||||
Muda em <Link href="/settings" className="underline underline-offset-2 hover:text-fg">Configurações</Link>.
|
||||
Muda em <Link href="/settings/publishing" className="underline underline-offset-2 hover:text-fg">Configurações</Link>.
|
||||
TikTok e Instagram abrem a janela do navegador por alguns segundos.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -251,7 +251,7 @@ export function PublishingBoard() {
|
||||
action={<Button size="sm" onClick={() => void resume()} disabled={resumeBusy}>
|
||||
{resumeBusy ? <Spinner className="size-3.5" /> : <PublishIcon size={15} />}Retomar
|
||||
</Button>}>
|
||||
Nada sai para as redes até você retomar. Dá para aprovar e agendar normalmente. A pausa também fica em <TextLink href="/settings">Configurações</TextLink>.
|
||||
Nada sai para as redes até você retomar. Dá para aprovar e agendar normalmente. A pausa também fica em <TextLink href="/settings/publishing">Configurações</TextLink>.
|
||||
</NoticeBar>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"use client";
|
||||
// Configurações do painel (por enquanto, tudo da publicação nas redes), em abas:
|
||||
// Publicação — pausar tudo, horários bons por rede, fuso e de quanto em quanto tempo ler os números dos posts
|
||||
// (GET/PUT /api/settings);
|
||||
// Apps das redes — passo a passo para criar o app de cada rede e os campos Client ID/Secret
|
||||
// (GET/PUT/DELETE /api/settings/apps/[platform]); o segredo nunca volta para a tela;
|
||||
// Navegador — navegador encontrado pelo Publicador (modo sessão) e onde ficam as sessões;
|
||||
// Sobre os modos — comparação simples entre "Conta oficial (API)" e "Sessão logada".
|
||||
// Seções de Configurações da publicação nas redes, cada uma numa subpágina (/settings/<seção>, ver settings-shell.tsx):
|
||||
// PublishingTab — pausar tudo, horários bons por rede, fuso e de quanto em quanto tempo ler os números dos posts
|
||||
// (GET/PUT /api/settings);
|
||||
// AppsTab — passo a passo para criar o app de cada rede e os campos Client ID/Secret
|
||||
// (GET/PUT/DELETE /api/settings/apps/[platform]); o segredo nunca volta para a tela;
|
||||
// BrowserTab — navegador encontrado pelo Publicador (modo sessão) e onde ficam as sessões;
|
||||
// ModesTab — comparação simples entre "Conta oficial (API)" e "Sessão logada".
|
||||
// A seção de IA fica em ai-settings.tsx.
|
||||
import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from "react";
|
||||
import type { Platform } from "@/lib/types";
|
||||
import { askConfirm } from "./confirm-dialog";
|
||||
@@ -17,10 +18,8 @@ import {
|
||||
type AppState, type PublisherStatus, type AppSettings,
|
||||
} from "./publishing-client";
|
||||
import { NoticeBar, PlatformName, TextLink } from "./publishing-ui";
|
||||
import { Tabs } from "./tabs";
|
||||
import { Badge, Button, Card, Feedback, Field, Input, Select, Spinner, Switch, Table, Td, Th, THead, Tr, cx } from "./ui";
|
||||
|
||||
type TabId = "publicacao" | "apps" | "navegador" | "modos";
|
||||
type Message = { ok: boolean; text: string } | null;
|
||||
|
||||
/** Ordem de exibição das redes nestas telas (a mais usada primeiro). */
|
||||
@@ -35,27 +34,9 @@ const TIMEZONES: { value: string; label: string }[] = [
|
||||
{ value: "UTC", label: "UTC" },
|
||||
];
|
||||
|
||||
export function SettingsPanel() {
|
||||
return (
|
||||
<Tabs<TabId> label="Seções das configurações"
|
||||
items={[
|
||||
{ id: "publicacao", label: "Publicação", icon: <ClockIcon size={16} /> },
|
||||
{ id: "apps", label: "Apps das redes", icon: <KeyIcon size={16} /> },
|
||||
{ id: "navegador", label: "Navegador", icon: <GlobeIcon size={16} /> },
|
||||
{ id: "modos", label: "Sobre os modos", icon: <InfoIcon size={16} /> },
|
||||
]}
|
||||
panels={{
|
||||
publicacao: <PublishingTab />,
|
||||
apps: <AppsTab />,
|
||||
navegador: <BrowserTab />,
|
||||
modos: <ModesTab />,
|
||||
}} />
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Publicação ---------- */
|
||||
|
||||
function PublishingTab() {
|
||||
export function PublishingTab() {
|
||||
const [settings, setSettings] = useState<AppSettings | null>(null);
|
||||
const [draft, setDraft] = useState<AppSettings | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -244,7 +225,7 @@ const GUIDES: Record<"youtube" | "tiktok", Guide> = {
|
||||
},
|
||||
};
|
||||
|
||||
function AppsTab() {
|
||||
export function AppsTab() {
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<p className="max-w-[75ch] text-sm leading-relaxed text-fg-muted">
|
||||
@@ -403,7 +384,7 @@ function ExternalLink({ href, children }: { href: string; children: ReactNode })
|
||||
|
||||
/* ---------- Navegador ---------- */
|
||||
|
||||
function BrowserTab() {
|
||||
export function BrowserTab() {
|
||||
const [status, setStatus] = useState<PublisherStatus | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const load = useCallback(async () => {
|
||||
@@ -474,7 +455,7 @@ const MODES_TABLE: Record<Platform, { official: string[]; session: string[] }> =
|
||||
},
|
||||
};
|
||||
|
||||
function ModesTab() {
|
||||
export function ModesTab() {
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<Card title="Os dois jeitos de conectar uma rede"
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
// Moldura das subpáginas de Configurações: cabeçalho + sub-navegação (a barra lateral usa a mesma lista).
|
||||
// Cada seção é uma página própria (/settings/<seção>), para dar link direto (ex.: "Configurações → IA").
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { ClockIcon, CpuIcon, GlobeIcon, InfoIcon, KeyIcon } from "./icons";
|
||||
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,
|
||||
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." },
|
||||
{ href: "/settings/apps", label: "Apps das redes", hint: "Client ID e Secret", icon: KeyIcon,
|
||||
description: "O app de cada rede para publicar pela conta oficial (API). O segredo fica no cofre e nunca volta para a tela." },
|
||||
{ href: "/settings/browser", label: "Navegador", hint: "Sessão logada", icon: GlobeIcon,
|
||||
description: "O navegador que o Publicador usa no modo sessão logada e onde ficam as sessões." },
|
||||
{ href: "/settings/modes", label: "Sobre os modos", hint: "API × sessão logada", icon: InfoIcon,
|
||||
description: "Comparação simples entre publicar pela conta oficial (API) e pela sessão logada." },
|
||||
];
|
||||
|
||||
export function activeSettingsSection(pathname: string): SettingsSection | null {
|
||||
return SETTINGS_SECTIONS.find((s) => pathname === s.href || pathname.startsWith(`${s.href}/`)) ?? null;
|
||||
}
|
||||
|
||||
export function SettingsShell({ children }: { children: ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
const current = activeSettingsSection(pathname);
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<PageHeader eyebrow="Painel" title={current ? `Configurações · ${current.label}` : "Configurações"}
|
||||
description={current?.description ?? "Tudo fica só neste computador."} />
|
||||
<nav aria-label="Seções das configurações" className="flex flex-wrap items-center gap-1 border-b border-line">
|
||||
{SETTINGS_SECTIONS.map((s) => {
|
||||
const active = current?.href === s.href;
|
||||
const Icon = s.icon;
|
||||
return (
|
||||
<Link key={s.href} href={s.href} aria-current={active ? "page" : undefined}
|
||||
className={cx("group relative flex h-11 items-center gap-2 rounded-t-control px-3 text-sm font-medium transition-colors",
|
||||
"focus-visible:outline-2 focus-visible:outline-accent",
|
||||
active ? "text-fg" : "text-fg-muted hover:bg-raised/70 hover:text-fg")}>
|
||||
<span className={cx("flex", active ? "text-accent" : "text-fg-subtle group-hover:text-fg-muted")}><Icon size={16} /></span>
|
||||
<span className="max-sm:sr-only">{s.label}</span>
|
||||
{active && <span aria-hidden="true" className="absolute inset-x-2 -bottom-px h-0.5 rounded-full bg-accent" />}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { CLIPPER_SECTIONS, activeSection } from "./clipper-shell";
|
||||
import { ChartIcon, CubeIcon, FilmIcon, MicIcon, PublishIcon, ScissorsIcon, SettingsIcon, SparkIcon, TerminalIcon, UsersIcon } from "./icons";
|
||||
import { LogoMark, Wordmark } from "./logo";
|
||||
import { getSummary } from "./publishing-client";
|
||||
import { SETTINGS_SECTIONS, activeSettingsSection } from "./settings-shell";
|
||||
import { cx } from "./ui";
|
||||
|
||||
type SubItem = { href: string; label: string; icon?: ComponentType<{ size?: number }> };
|
||||
@@ -39,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 e Codex", icon: TerminalIcon },
|
||||
{ href: "/agent", label: "Agente", hint: "Claude, GPT e Gemini", icon: TerminalIcon },
|
||||
];
|
||||
|
||||
/** Depois do estúdio: onde as histórias vão ao ar. */
|
||||
@@ -48,7 +49,11 @@ const DISTRIBUTION: NavItem[] = [
|
||||
{ href: "/publishing", label: "Publicações", hint: "Aprovar, agendar, acompanhar", icon: PublishIcon },
|
||||
];
|
||||
|
||||
const SETTINGS: NavItem = { href: "/settings", label: "Configurações", hint: "Horários, apps e navegador", icon: SettingsIcon };
|
||||
const SETTINGS: NavItem = {
|
||||
href: "/settings", label: "Configurações", hint: "IA, publicação e navegador", icon: SettingsIcon,
|
||||
children: SETTINGS_SECTIONS.map((s) => ({ href: s.href, label: s.label, icon: s.icon })),
|
||||
activeChild: (pathname) => activeSettingsSection(pathname)?.href ?? null,
|
||||
};
|
||||
|
||||
function useAwaitingCount(pathname: string): number | null {
|
||||
const [count, setCount] = useState<number | null>(null);
|
||||
|
||||
@@ -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" };
|
||||
const PROVIDER_NAME: Record<Provider, string> = { codex: "GPT · Codex", claude: "Claude", gemini: "Gemini" };
|
||||
|
||||
export function StoryComposer({ autoProvider, available, models }: {
|
||||
/** Agente que o modo automático vai usar agora (Codex, se estiver instalado). */
|
||||
@@ -24,11 +24,12 @@ export function StoryComposer({ autoProvider, available, models }: {
|
||||
}) {
|
||||
const [state, action, pending] = useActionState(createStoryFromTextAction, null);
|
||||
const [length, setLength] = useState(0);
|
||||
const [provider, setProvider] = useState<"" | "claude">("");
|
||||
const [provider, setProvider] = useState<"" | Provider>("");
|
||||
const [kind, setKind] = useState<StoryKind>(DEFAULT_STORY_FORMAT);
|
||||
const [model, setModel] = useState("");
|
||||
const short = length > 0 && length < MIN_CHARS;
|
||||
const engine: Provider = provider === "claude" ? "claude" : autoProvider;
|
||||
const engine: Provider = provider || autoProvider;
|
||||
const noneReady = !Object.values(available).some(Boolean);
|
||||
const documentary = kind === "documentary";
|
||||
|
||||
return (
|
||||
@@ -85,8 +86,9 @@ export function StoryComposer({ autoProvider, available, models }: {
|
||||
<ChoiceGroup name="provider" legend="Quem escreve" value={provider}
|
||||
onChange={(next) => { setProvider(next); setModel(""); }}
|
||||
options={[
|
||||
{ value: "", label: autoProvider === "codex" ? "GPT · Codex" : "Automático" },
|
||||
{ value: "claude", label: "Claude", disabled: !available.claude },
|
||||
{ value: "", label: `Automático (${PROVIDER_NAME[autoProvider]})` },
|
||||
...(["claude", "codex", "gemini"] as const).filter((p) => p !== autoProvider)
|
||||
.map((p) => ({ value: p, label: PROVIDER_NAME[p], disabled: !available[p] })),
|
||||
]} />
|
||||
<label className="grid content-start gap-2">
|
||||
<span className="text-[0.8125rem] font-medium text-fg-muted">Modelo</span>
|
||||
@@ -96,8 +98,10 @@ export function StoryComposer({ autoProvider, available, models }: {
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{!available.codex && (
|
||||
<p className="text-xs text-warning">O Codex não está instalado aqui: o modo automático vai usar o Claude. Instale com <code>npm install -g @openai/codex</code> e rode <code>codex login</code>.</p>
|
||||
{noneReady ? (
|
||||
<p className="text-xs text-warning">Nenhuma IA está pronta neste computador. Instale e entre com a conta (ou cole uma chave) em <a href="/settings/ai" className="underline">Configurações → IA</a>.</p>
|
||||
) : !available.codex && (
|
||||
<p className="text-xs text-fg-subtle">O Codex não está pronto: o automático usa {PROVIDER_NAME[autoProvider]}. Ajuste em <a href="/settings/ai" className="underline">Configurações → IA</a>.</p>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-x-5 gap-y-3 border-t border-line pt-6">
|
||||
|
||||
+173
-68
@@ -1,4 +1,5 @@
|
||||
// Agentes de código (Claude Code e Codex) chamados pela CLI, como no VS Code.
|
||||
// Agentes de código (Claude Code, Codex e Gemini) 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"):
|
||||
// - roda com cwd = raiz do repositório; edições automáticas só dentro dele;
|
||||
@@ -6,13 +7,16 @@
|
||||
// - o pedido vai como argumento (sem shell); stdin fechado;
|
||||
// - um agente por vez; cancelar encerra a árvore de processos.
|
||||
// Comentários do público NUNCA entram no prompt: só a decisão A/B já fechada.
|
||||
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { all, get, now, run } from "./db";
|
||||
import { DATA_DIR, REPO_ROOT, rel } from "./paths";
|
||||
import { buildPrompt } from "./prompts";
|
||||
import { findOnPath, killTree, lineSplitter } from "./proc";
|
||||
import {
|
||||
PROVIDER_META, geminiModels, isAvailabilityError, markUnavailable, nextFallback, providerEnv, providerStatus, readyChain, resolvedFor,
|
||||
} from "./ai";
|
||||
import { killTree, lineSplitter } from "./proc";
|
||||
import { onAgentRunClosed } from "./branches";
|
||||
import { UserError, getEpisodeById, getStory, syncStoryMeta } from "./stories";
|
||||
import { AGENT_KINDS, type AgentEvent, type AgentKind, type AgentRun, type Provider } from "./types";
|
||||
@@ -92,7 +96,7 @@ function codexModels(): ModelOption[] {
|
||||
|
||||
/** Modelos que o seletor oferece por agente. */
|
||||
export function models(): Record<Provider, ModelOption[]> {
|
||||
return { claude: CLAUDE_MODELS, codex: codexModels() };
|
||||
return { claude: CLAUDE_MODELS, codex: codexModels(), gemini: [{ id: "", label: "Padrão da CLI (automático)" }, ...geminiModels()] };
|
||||
}
|
||||
|
||||
/** Modelo sugerido por tipo de tarefa (economia de tokens). */
|
||||
@@ -106,15 +110,14 @@ export const DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "", s
|
||||
*/
|
||||
export const PREFERRED_PROVIDER: Record<AgentKind, Provider> = { free: "claude", story: "codex", script: "codex", scene: "claude", branches: "codex", godot: "claude", character: "claude" };
|
||||
|
||||
/** A preferida da tarefa se estiver pronta (e fora de pausa); senão a próxima da ordem da reserva. */
|
||||
export function defaultProviderFor(kind: AgentKind): Provider {
|
||||
const list = providers();
|
||||
const preferred = PREFERRED_PROVIDER[kind];
|
||||
if (list.find((p) => p.id === preferred)?.available) return preferred;
|
||||
return list.find((p) => p.available)?.id ?? preferred;
|
||||
return readyChain(PREFERRED_PROVIDER[kind])[0] ?? PREFERRED_PROVIDER[kind];
|
||||
}
|
||||
|
||||
/** 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 "";
|
||||
return provider === "claude" ? DEFAULT_MODEL[kind] : CODEX_DEFAULT_MODEL[kind];
|
||||
}
|
||||
|
||||
@@ -125,11 +128,8 @@ export function defaultModelFor(kind: AgentKind, provider: Provider): string {
|
||||
*/
|
||||
const CODEX_DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "gpt-6.1-sol", script: "gpt-6.1-sol", branches: "gpt-6.1-sol", scene: "", godot: "", character: "" };
|
||||
|
||||
/** `command` + `prefixArgs` é o que de fato executamos (ex.: node + codex.js no Windows). */
|
||||
type ProviderInfo = {
|
||||
id: Provider; available: boolean; path: string | null; version: string | null; note: string;
|
||||
command: string | null; prefixArgs: string[];
|
||||
};
|
||||
/** Uma IA como o console do agente a vê. `available` = pronta (ligada, instalada e com login ou chave). */
|
||||
type ProviderInfo = { id: Provider; available: boolean; path: string | null; version: string | null; note: string };
|
||||
/**
|
||||
* Execução em andamento. `followUp`: mensagem do usuário enviada durante a execução; quando ela
|
||||
* fecha (sozinha ou interrompida), a mesma sessão é retomada com essa mensagem.
|
||||
@@ -141,8 +141,10 @@ type ActiveRun = {
|
||||
followUp: string | null;
|
||||
/** O agente já deu um passo (texto ou ferramenta). Antes disso a sessão ainda não guardou o pedido. */
|
||||
progressed: boolean;
|
||||
/** Últimas linhas de erro (stderr e eventos de erro): decidem se a falha foi indisponibilidade. */
|
||||
errors: string[];
|
||||
};
|
||||
const g = globalThis as unknown as { __cenaforgeAgents?: Map<number, ActiveRun>; __cenaforgeProviders?: { at: number; list: ProviderInfo[] } };
|
||||
const g = globalThis as unknown as { __cenaforgeAgents?: Map<number, ActiveRun> };
|
||||
const active = (g.__cenaforgeAgents ??= new Map());
|
||||
|
||||
/** Há um agente trabalhando? (o executor roda um por vez) */
|
||||
@@ -150,52 +152,23 @@ export function busy(): boolean {
|
||||
return active.size > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executável de um provedor. No Windows o npm instala o Codex como `codex.cmd` (que o Node
|
||||
* não executa sem shell); nesse caso rodamos o `codex.js` do pacote diretamente pelo Node.
|
||||
*/
|
||||
function resolveCommand(id: Provider, envVar: string): { path: string; command: string; prefixArgs: string[] } | null {
|
||||
const fromEnv = process.env[envVar];
|
||||
if (fromEnv) {
|
||||
return fromEnv.endsWith(".js")
|
||||
? { path: fromEnv, command: process.execPath, prefixArgs: [fromEnv] }
|
||||
: { path: fromEnv, command: fromEnv, prefixArgs: [] };
|
||||
}
|
||||
const exe = findOnPath(id);
|
||||
if (exe) return { path: exe, command: exe, prefixArgs: [] };
|
||||
if (id === "codex") {
|
||||
for (const dir of (process.env.PATH ?? "").split(path.delimiter).filter(Boolean)) {
|
||||
const js = path.join(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
|
||||
if (fs.existsSync(path.join(dir, "codex.cmd")) && fs.existsSync(js)) {
|
||||
return { path: js, command: process.execPath, prefixArgs: [js] };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
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).",
|
||||
};
|
||||
|
||||
/** As três IAs para o console: o estado vem de lib/ai.ts (instalada, ligada, login/chave, pausa da reserva). */
|
||||
export function providers(): ProviderInfo[] {
|
||||
// Cache curto: instalar ou remover uma CLI aparece sem reiniciar o painel.
|
||||
if (g.__cenaforgeProviders && Date.now() - g.__cenaforgeProviders.at < 60_000) return g.__cenaforgeProviders.list;
|
||||
const detect = (id: Provider, envVar: string, note: string): ProviderInfo => {
|
||||
const resolved = resolveCommand(id, envVar);
|
||||
let version: string | null = null;
|
||||
if (resolved) {
|
||||
const r = spawnSync(resolved.command, [...resolved.prefixArgs, "--version"], { encoding: "utf8", timeout: 20_000, windowsHide: true, shell: false });
|
||||
version = r.status === 0 ? r.stdout.trim().split(/\r?\n/)[0] : null;
|
||||
}
|
||||
return providerStatus().map((p) => {
|
||||
const pause = p.cooldown
|
||||
? ` Em pausa até ${new Date(p.cooldown.until).toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" })} (${p.cooldown.reason}).`
|
||||
: "";
|
||||
return {
|
||||
id, available: !!resolved && version !== null, path: resolved?.path ?? null, version,
|
||||
note: resolved ? note : `${note} Não encontrado: instale e faça login${id === "codex" ? " (npm install -g @openai/codex; codex login)" : ""}.`,
|
||||
command: resolved?.command ?? null, prefixArgs: resolved?.prefixArgs ?? [],
|
||||
id: p.id, available: p.ready, path: p.path, version: p.version,
|
||||
note: p.ready ? `${PROVIDER_NOTE[p.id]}${pause}` : `${PROVIDER_NOTE[p.id]} ${p.problem} Ajuste em Configurações → IA.`,
|
||||
};
|
||||
};
|
||||
const list = [
|
||||
detect("claude", "CLAUDE_BIN", "Claude Code CLI em modo não interativo (-p, stream-json); edição automática dentro do projeto e comandos liberados."),
|
||||
detect("codex", "CODEX_BIN", "Codex CLI (codex exec --json) com sandbox workspace-write: escreve só dentro do projeto."),
|
||||
];
|
||||
g.__cenaforgeProviders = { at: Date.now(), list };
|
||||
return list;
|
||||
});
|
||||
}
|
||||
|
||||
export function listRuns(limit = 30): AgentRun[] {
|
||||
@@ -209,9 +182,14 @@ export function getRun(id: number): AgentRun | undefined {
|
||||
export function startRun(input: {
|
||||
provider: Provider; model: string; kind: AgentKind; request: string;
|
||||
storyId?: string | null; episodeId?: number | null; resumeRunId?: number | null;
|
||||
/** Execução que caiu por indisponibilidade e que esta continua com a IA reserva. */
|
||||
fallbackOfRunId?: number | null;
|
||||
}): AgentRun {
|
||||
const info = providers().find((p) => p.id === input.provider);
|
||||
if (!info?.available || !info.command) throw new UserError(`${input.provider} não está disponível neste computador.`);
|
||||
const resolved = resolvedFor(input.provider);
|
||||
if (!info?.available || !resolved) {
|
||||
throw new UserError(`${PROVIDER_META[input.provider]?.label ?? input.provider} não está pronto neste computador. ${info?.note ?? ""}`.trim());
|
||||
}
|
||||
if (active.size > 0) throw new UserError("Já existe um agente trabalhando. Aguarde ou cancele antes de enviar outro pedido.");
|
||||
const request = input.request.trim();
|
||||
if (request.length < 2) throw new UserError("Escreva o pedido.");
|
||||
@@ -230,12 +208,18 @@ export function startRun(input: {
|
||||
throw new UserError("Só é possível continuar uma conversa do mesmo agente, com sessão registrada.");
|
||||
}
|
||||
|
||||
const prompt = resume ? request : buildPrompt({ kind: input.kind, provider: input.provider, request, story, episode });
|
||||
const fallbackOf = input.fallbackOfRunId ? getRun(input.fallbackOfRunId) : undefined;
|
||||
const basePrompt = resume ? request : buildPrompt({ kind: input.kind, provider: input.provider, request, story, episode });
|
||||
// Reserva: a IA anterior pode ter deixado arquivos pela metade; a nova confere antes de refazer.
|
||||
const prompt = fallbackOf
|
||||
? `${basePrompt}\n\nObservação: esta tarefa começou com outra IA (${PROVIDER_META[fallbackOf.provider].label}), que parou por indisponibilidade. ` +
|
||||
"Confira o estado atual dos arquivos citados antes de criar ou refazer algo e continue de onde ela parou."
|
||||
: basePrompt;
|
||||
const logDir = path.join(DATA_DIR, "logs", "agents");
|
||||
fs.mkdirSync(logDir, { recursive: true });
|
||||
const row = run(`INSERT INTO agent_runs (provider, model, kind, prompt, story_id, episode_id, resume_of, status, log_path, started_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'running', '', ?)`,
|
||||
input.provider, input.model, input.kind, request, story?.id ?? null, episode?.id ?? null, resume?.id ?? null, now());
|
||||
const row = run(`INSERT INTO agent_runs (provider, model, kind, prompt, story_id, episode_id, resume_of, fallback_of, status, log_path, started_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'running', '', ?)`,
|
||||
input.provider, input.model, input.kind, request, story?.id ?? null, episode?.id ?? null, resume?.id ?? null, fallbackOf?.id ?? null, now());
|
||||
const id = Number(row.lastInsertRowid);
|
||||
const logPath = path.join(logDir, `${id}.jsonl`);
|
||||
run("UPDATE agent_runs SET log_path = ? WHERE id = ?", rel(logPath), id);
|
||||
@@ -246,20 +230,31 @@ export function startRun(input: {
|
||||
...(resume?.session_id ? ["--resume", resume.session_id] : []),
|
||||
...CLAUDE_LEAN_FLAGS, "--max-budget-usd", String(CLAUDE_BUDGET_USD[input.kind]),
|
||||
"--allowedTools", CLAUDE_ALLOWED_TOOLS]
|
||||
: codexArgs(prompt, input.model, resume?.session_id ?? null, input.kind);
|
||||
: input.provider === "codex"
|
||||
? codexArgs(prompt, input.model, resume?.session_id ?? null, input.kind)
|
||||
: geminiArgs(prompt, input.model, resume?.session_id ?? null);
|
||||
|
||||
const child = spawn(info.command, [...info.prefixArgs, ...args], { cwd: REPO_ROOT, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
||||
// 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], {
|
||||
cwd: REPO_ROOT, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: providerEnv(input.provider),
|
||||
});
|
||||
const listeners = new Set<(e: AgentEvent | null) => void>();
|
||||
const log = fs.createWriteStream(logPath);
|
||||
const gemini: GeminiState = { 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)) {
|
||||
entry.errors.push(e.text);
|
||||
if (entry.errors.length > 20) entry.errors.shift();
|
||||
}
|
||||
const event = { ...e, at: now() } as AgentEvent;
|
||||
log.write(JSON.stringify(event) + "\n");
|
||||
for (const l of listeners) l(event);
|
||||
};
|
||||
const entry: ActiveRun = { child, listeners, emit, followUp: null, progressed: false };
|
||||
const entry: ActiveRun = { child, listeners, emit, followUp: null, progressed: false, errors: [] };
|
||||
active.set(id, entry);
|
||||
emit({ kind: "system", text: `${input.provider}${input.model ? ` · ${input.model}` : ""} · tarefa "${input.kind}"${resume ? ` · continua a execução #${resume.id}` : ""}` });
|
||||
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}` : ""}` });
|
||||
|
||||
child.stdout.setEncoding("utf8").on("data", lineSplitter((line) => {
|
||||
let obj: Record<string, unknown>;
|
||||
@@ -269,7 +264,8 @@ export function startRun(input: {
|
||||
emit({ kind: "text", text: line.slice(0, 2000) });
|
||||
return;
|
||||
}
|
||||
const events = input.provider === "claude" ? normalizeClaude(obj, id) : normalizeCodex(obj, id);
|
||||
const events = input.provider === "claude" ? normalizeClaude(obj, id)
|
||||
: input.provider === "codex" ? normalizeCodex(obj, id) : normalizeGemini(obj, id, gemini);
|
||||
events.forEach(emit);
|
||||
}));
|
||||
child.stderr.setEncoding("utf8").on("data", lineSplitter((line) => {
|
||||
@@ -277,6 +273,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);
|
||||
// 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);
|
||||
@@ -286,6 +283,12 @@ export function startRun(input: {
|
||||
ok ? "success" : "error", ok ? null : `saiu com código ${code}`, now(), id);
|
||||
}
|
||||
active.delete(id);
|
||||
// IA reserva: caiu por indisponibilidade (cota, login, rede…) e ninguém mandou mensagem → a próxima IA assume.
|
||||
// Começa antes das vertentes e dos ouvintes: o preparo passa a esperar a reserva e o "end" já leva o id dela.
|
||||
const fallbackRunId = entry.followUp ? null : startFallback(id, entry);
|
||||
if (fallbackRunId) {
|
||||
run("UPDATE episodes SET branches_run_id = ? WHERE branches_run_id = ? AND branches_status = 'running'", fallbackRunId, id);
|
||||
}
|
||||
// Vertentes: fecha o preparo desta execução e começa o próximo da fila (o executor já está livre).
|
||||
try {
|
||||
onAgentRunClosed(id, getRun(id)?.status === "success");
|
||||
@@ -339,9 +342,45 @@ export function sendFollowUp(id: number, text: string, mode: "now" | "queue"): v
|
||||
}
|
||||
}
|
||||
|
||||
/** A execução que continuou esta (mensagem enviada durante ela ou "Continuar esta conversa"). */
|
||||
/** A execução que continuou esta (mensagem enviada durante ela, "Continuar esta conversa" ou a IA reserva). */
|
||||
export function followUpRunOf(id: number): number | null {
|
||||
return get<{ id: number }>("SELECT id FROM agent_runs WHERE resume_of = ? ORDER BY id DESC LIMIT 1", id)?.id ?? null;
|
||||
return get<{ id: number }>("SELECT id FROM agent_runs WHERE resume_of = ? OR fallback_of = ? ORDER BY id DESC LIMIT 1", id, id)?.id ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Se a execução terminou com erro de indisponibilidade, põe a IA em pausa e começa a mesma tarefa na próxima IA
|
||||
* pronta da ordem (Configurações → IA). Cada IA é tentada uma vez por cadeia. Devolve o id da nova execução.
|
||||
*/
|
||||
function startFallback(id: number, entry: ActiveRun): number | null {
|
||||
const closed = getRun(id);
|
||||
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");
|
||||
// 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) {
|
||||
tried.push(cursor.provider);
|
||||
}
|
||||
const next = nextFallback(tried);
|
||||
if (!next) {
|
||||
entry.emit({ kind: "system", text: `${PROVIDER_META[closed.provider].label} ficou indisponível e não há outra IA pronta para assumir (Configurações → IA).` });
|
||||
return null;
|
||||
}
|
||||
// Numa continuação, o prompt guardado é só a mensagem nova: o pedido original vem da primeira execução da conversa.
|
||||
let root: AgentRun = closed;
|
||||
for (let parent = root.resume_of ? getRun(root.resume_of) : undefined; parent; parent = parent.resume_of ? getRun(parent.resume_of) : undefined) root = parent;
|
||||
const request = root.id === closed.id ? closed.prompt : `${root.prompt}\n\nMensagem seguinte do usuário:\n${closed.prompt}`;
|
||||
try {
|
||||
const started = startRun({
|
||||
provider: next, model: defaultModelFor(closed.kind, next), kind: closed.kind, request: request.slice(0, 20_000),
|
||||
storyId: closed.story_id, episodeId: closed.episode_id, fallbackOfRunId: id,
|
||||
});
|
||||
entry.emit({ kind: "system", text: `${PROVIDER_META[closed.provider].label} indisponível: a tarefa continua com ${PROVIDER_META[next].label} (execução #${started.id}).` });
|
||||
return started.id;
|
||||
} catch (error) {
|
||||
entry.emit({ kind: "error", text: `A IA reserva não começou: ${(error as Error).message}`, isError: true });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function cancelRun(id: number): void {
|
||||
@@ -421,6 +460,72 @@ 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 ---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 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">[] {
|
||||
const text = state.text.trim();
|
||||
state.text = "";
|
||||
if (!text) return [];
|
||||
run("UPDATE agent_runs SET result = ? WHERE id = ?", text.slice(0, 20_000), runId);
|
||||
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" }];
|
||||
}
|
||||
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$`,
|
||||
}];
|
||||
}
|
||||
default:
|
||||
return pending;
|
||||
}
|
||||
}
|
||||
|
||||
// --- normalização ---------------------------------------------------------------
|
||||
|
||||
type Block = { type?: string; text?: string; name?: string; input?: Record<string, unknown>; content?: unknown; is_error?: boolean };
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// 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 é
|
||||
// chamada. Rodar: pnpm --filter cenaforge-panel test:panel
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { before, describe, it } from "node:test";
|
||||
|
||||
const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "cenaforge-ai-"));
|
||||
process.env.CENAFORGE_ROOT = ROOT;
|
||||
|
||||
type Ai = typeof import("./ai");
|
||||
type Agents = typeof import("./agents");
|
||||
type Db = typeof import("./db");
|
||||
let ai: Ai;
|
||||
let agents: Agents;
|
||||
let dbm: Db;
|
||||
const SETTINGS = () => path.join(ROOT, "data", "ai", "settings.json");
|
||||
|
||||
before(async () => {
|
||||
ai = await import("./ai");
|
||||
agents = await import("./agents");
|
||||
dbm = await import("./db");
|
||||
});
|
||||
|
||||
describe("configuração da IA", () => {
|
||||
it("sem arquivo usa o padrão: Claude e Codex ligados na conta, Gemini desligado", () => {
|
||||
const s = ai.readAiSettings();
|
||||
assert.deepEqual(s.order, ["claude", "codex", "gemini"]);
|
||||
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 } }));
|
||||
const s = ai.readAiSettings();
|
||||
assert.deepEqual(s.order, ["gemini", "claude", "codex"]);
|
||||
assert.equal(s.providers.codex.enabled, true);
|
||||
assert.equal(s.providers.codex.authMode, "oauth");
|
||||
assert.equal(s.fallback.cooldownMin, 240);
|
||||
fs.rmSync(SETTINGS());
|
||||
});
|
||||
|
||||
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"]);
|
||||
assert.throws(() => ai.updateAiSettings({ order: ["codex", "codex", "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.equal(ai.readAiSettings().fallback.cooldownMin, 30);
|
||||
});
|
||||
});
|
||||
|
||||
describe("indisponibilidade (dispara a reserva)", () => {
|
||||
for (const text of [
|
||||
"API Error: 429 rate_limit_error", "You've hit your usage limit", "Credit balance is too low", "Overloaded (529)",
|
||||
"IneligibleTierError: This client is no longer supported", "Not logged in · Please run /login", "getaddrinfo ENOTFOUND api.openai.com",
|
||||
"não iniciou: spawn ENOENT", "Invalid API key",
|
||||
]) it(`troca de IA: ${text}`, () => assert.equal(ai.isAvailabilityError(text), true));
|
||||
for (const text of ["saiu com código 1", "SyntaxError: Unexpected token in JSON", "Parou no teto de gasto desta tarefa", ""]) {
|
||||
it(`não troca: ${text || "(vazio)"}`, () => assert.equal(ai.isAvailabilityError(text), false));
|
||||
}
|
||||
});
|
||||
|
||||
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" } } });
|
||||
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");
|
||||
});
|
||||
|
||||
it("modo chave sem chave salva não vaza a do ambiente do painel", () => {
|
||||
ai.updateAiSettings({ providers: { codex: { authMode: "apiKey" } } });
|
||||
assert.equal(ai.providerEnv("codex", { CODEX_API_KEY: "sk-do-sistema" }).CODEX_API_KEY, undefined);
|
||||
});
|
||||
|
||||
it("cofre DPAPI: guarda, injeta só na chamada e apaga", { skip: process.platform !== "win32" && "DPAPI só existe no Windows" }, () => {
|
||||
assert.throws(() => ai.setApiKey("codex", "curta"), /não parece válida/);
|
||||
ai.setApiKey("codex", "sk-test-0123456789abcdefWXYZ");
|
||||
const bytes = fs.readFileSync(path.join(ROOT, "data", "ai", "vault.bin"));
|
||||
assert.equal(bytes.includes(Buffer.from("sk-test")), false, "a chave não pode ficar em texto claro");
|
||||
assert.equal(ai.providerEnv("codex", {}).CODEX_API_KEY, "sk-test-0123456789abcdefWXYZ");
|
||||
ai.setApiKey("codex", null);
|
||||
assert.equal(fs.existsSync(path.join(ROOT, "data", "ai", "vault.bin")), false);
|
||||
assert.equal(ai.providerEnv("codex", {}).CODEX_API_KEY, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,629 @@
|
||||
// IA do painel: as três CLIs (Claude Code, Codex e Gemini), 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.
|
||||
// data/ai/settings.json — ligada/desligada, modo de login e ordem da reserva (sem segredo);
|
||||
// data/ai/vault.bin — chaves de API cifradas com a DPAPI do Windows (só esta conta, nesta máquina).
|
||||
// A chave nunca volta para a tela: a API só diz se existe e os 4 últimos caracteres.
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { DATA_DIR } from "./paths";
|
||||
import { findOnPath, lineSplitter } from "./proc";
|
||||
import { UserError } from "./stories";
|
||||
import { PROVIDERS, type Provider } from "./types";
|
||||
|
||||
export type AuthMode = "oauth" | "apiKey";
|
||||
export type ProviderSettings = { enabled: boolean; authMode: AuthMode };
|
||||
export type AiSettings = {
|
||||
version: 1;
|
||||
providers: Record<Provider, ProviderSettings>;
|
||||
/** Prioridade da reserva. */
|
||||
order: Provider[];
|
||||
fallback: { enabled: boolean; cooldownMin: number };
|
||||
};
|
||||
|
||||
const AI_DIR = path.join(DATA_DIR, "ai");
|
||||
const SETTINGS_PATH = path.join(AI_DIR, "settings.json");
|
||||
const VAULT_PATH = path.join(AI_DIR, "vault.bin");
|
||||
const HOME = os.homedir();
|
||||
const IS_WINDOWS = process.platform === "win32";
|
||||
|
||||
export const DEFAULT_AI_SETTINGS: AiSettings = {
|
||||
version: 1,
|
||||
providers: {
|
||||
claude: { enabled: true, authMode: "oauth" },
|
||||
codex: { enabled: true, authMode: "oauth" },
|
||||
gemini: { enabled: false, authMode: "apiKey" },
|
||||
},
|
||||
order: ["claude", "codex", "gemini"],
|
||||
fallback: { enabled: true, cooldownMin: 15 },
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- catálogo das CLIs */
|
||||
|
||||
type Command = { file: string; args: string[] };
|
||||
|
||||
export type ProviderMeta = {
|
||||
id: Provider;
|
||||
label: string;
|
||||
vendor: string;
|
||||
/** Nome do executável no PATH. */
|
||||
bin: string;
|
||||
/** Variável que aponta o executável manualmente (ex.: CLAUDE_BIN). */
|
||||
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 };
|
||||
/** Argumentos do login com a conta, abertos num terminal visível. */
|
||||
loginArgs: string[];
|
||||
oauthLabel: string;
|
||||
oauthNote: string | null;
|
||||
apiKeyEnv: string;
|
||||
apiKeyUrl: string;
|
||||
apiKeyLabel: string;
|
||||
};
|
||||
|
||||
const npmInstall = (pkg: string): ProviderMeta["install"] => ({
|
||||
display: `npm install -g ${pkg}`,
|
||||
command: IS_WINDOWS ? { file: "cmd.exe", args: ["/d", "/s", "/c", `npm install -g ${pkg}`] } : { file: "npm", args: ["install", "-g", pkg] },
|
||||
});
|
||||
|
||||
export const PROVIDER_META: Record<Provider, ProviderMeta> = {
|
||||
claude: {
|
||||
id: "claude", label: "Claude Code", vendor: "Anthropic", bin: "claude", binEnv: "CLAUDE_BIN", npmEntry: null,
|
||||
install: IS_WINDOWS
|
||||
? { display: "irm https://claude.ai/install.ps1 | iex", command: { file: "powershell.exe", args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", "irm https://claude.ai/install.ps1 | iex"] } }
|
||||
: { display: "curl -fsSL https://claude.ai/install.sh | bash", command: { file: "bash", args: ["-lc", "curl -fsSL https://claude.ai/install.sh | bash"] } },
|
||||
loginArgs: ["auth", "login"],
|
||||
oauthLabel: "Conta Claude (Pro/Max) ou Console",
|
||||
oauthNote: null,
|
||||
apiKeyEnv: "ANTHROPIC_API_KEY", apiKeyUrl: "https://console.anthropic.com/settings/keys", apiKeyLabel: "Chave da API da Anthropic (sk-ant-…)",
|
||||
},
|
||||
codex: {
|
||||
id: "codex", label: "Codex", vendor: "OpenAI", bin: "codex", binEnv: "CODEX_BIN", npmEntry: path.join("@openai", "codex", "bin", "codex.js"),
|
||||
install: npmInstall("@openai/codex@latest"),
|
||||
loginArgs: ["login"],
|
||||
oauthLabel: "Conta ChatGPT (Plus/Pro/Team)",
|
||||
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"),
|
||||
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.",
|
||||
apiKeyEnv: "GEMINI_API_KEY", apiKeyUrl: "https://aistudio.google.com/apikey", apiKeyLabel: "Chave do Google AI Studio (AIza…)",
|
||||
},
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- configuração */
|
||||
|
||||
function isProvider(value: unknown): value is Provider {
|
||||
return typeof value === "string" && (PROVIDERS as string[]).includes(value);
|
||||
}
|
||||
|
||||
/** Lê e normaliza: campo inválido volta ao padrão; a ordem sempre tem as três IAs, uma vez cada. */
|
||||
export function readAiSettings(): AiSettings {
|
||||
let raw: Partial<AiSettings> = {};
|
||||
try {
|
||||
raw = JSON.parse(fs.readFileSync(SETTINGS_PATH, "utf8")) as Partial<AiSettings>;
|
||||
} catch { /* ausente ou inválido: padrão */ }
|
||||
const providers = {} as Record<Provider, ProviderSettings>;
|
||||
for (const id of PROVIDERS) {
|
||||
const item = (raw.providers as Record<string, Partial<ProviderSettings>> | undefined)?.[id] ?? {};
|
||||
const fallback = DEFAULT_AI_SETTINGS.providers[id];
|
||||
providers[id] = {
|
||||
enabled: typeof item.enabled === "boolean" ? item.enabled : fallback.enabled,
|
||||
authMode: item.authMode === "oauth" || item.authMode === "apiKey" ? item.authMode : fallback.authMode,
|
||||
};
|
||||
}
|
||||
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);
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type AiSettingsPatch = {
|
||||
providers?: Partial<Record<Provider, Partial<ProviderSettings>>>;
|
||||
order?: unknown;
|
||||
fallback?: Partial<AiSettings["fallback"]>;
|
||||
};
|
||||
|
||||
export function updateAiSettings(patch: AiSettingsPatch): AiSettings {
|
||||
const next = readAiSettings();
|
||||
for (const [id, change] of Object.entries(patch.providers ?? {})) {
|
||||
if (!isProvider(id) || !change) throw new UserError("IA desconhecida.");
|
||||
if (change.enabled !== undefined) {
|
||||
if (typeof change.enabled !== "boolean") throw new UserError("\"Ligada\" precisa ser verdadeiro ou falso.");
|
||||
next.providers[id].enabled = change.enabled;
|
||||
}
|
||||
if (change.authMode !== undefined) {
|
||||
if (change.authMode !== "oauth" && change.authMode !== "apiKey") throw new UserError("Modo de login inválido.");
|
||||
next.providers[id].authMode = change.authMode;
|
||||
}
|
||||
}
|
||||
if (patch.order !== undefined) {
|
||||
const order = Array.isArray(patch.order) ? patch.order : [];
|
||||
if (order.length !== PROVIDERS.length || !order.every(isProvider) || new Set(order).size !== PROVIDERS.length) {
|
||||
throw new UserError("A ordem precisa ter cada IA uma vez.");
|
||||
}
|
||||
next.order = order as Provider[];
|
||||
}
|
||||
if (patch.fallback?.enabled !== undefined) {
|
||||
if (typeof patch.fallback.enabled !== "boolean") throw new UserError("Reserva: valor inválido.");
|
||||
next.fallback.enabled = patch.fallback.enabled;
|
||||
}
|
||||
if (patch.fallback?.cooldownMin !== undefined) {
|
||||
const minutes = Number(patch.fallback.cooldownMin);
|
||||
if (!Number.isInteger(minutes) || minutes < 1 || minutes > 240) throw new UserError("A pausa precisa ficar entre 1 e 240 minutos.");
|
||||
next.fallback.cooldownMin = minutes;
|
||||
}
|
||||
writeAtomic(SETTINGS_PATH, JSON.stringify(next, null, 2) + "\n");
|
||||
invalidateStatus();
|
||||
return next;
|
||||
}
|
||||
|
||||
function writeAtomic(file: string, data: string | Buffer): void {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const tmp = `${file}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(tmp, data);
|
||||
fs.renameSync(tmp, file);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- cofre (DPAPI) */
|
||||
|
||||
const VAULT_ENTROPY = "CenaForge.AI.vault.v1";
|
||||
type VaultData = Partial<Record<Provider, string>>;
|
||||
const g = globalThis as unknown as {
|
||||
__cenaforgeAiVault?: { mtimeMs: number; data: VaultData };
|
||||
__cenaforgeAiStatus?: { at: number; list: ProviderRuntime[] };
|
||||
__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 };
|
||||
};
|
||||
|
||||
/** DPAPI pelo PowerShell (System.Security.ProtectedData), escopo do usuário. O Clipador abre com ctypes. */
|
||||
function dpapi(op: "Protect" | "Unprotect", data: Buffer): Buffer {
|
||||
if (!IS_WINDOWS) throw new UserError("O cofre de chaves usa a DPAPI do Windows; este sistema não tem.");
|
||||
const script = "Add-Type -AssemblyName System.Security; $i = [Console]::In.ReadToEnd().Trim(); " +
|
||||
`$e = [Text.Encoding]::UTF8.GetBytes('${VAULT_ENTROPY}'); ` +
|
||||
`[Console]::Out.Write([Convert]::ToBase64String([Security.Cryptography.ProtectedData]::${op}([Convert]::FromBase64String($i), $e, 'CurrentUser')))`;
|
||||
const r = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],
|
||||
{ input: data.toString("base64"), encoding: "utf8", windowsHide: true, timeout: 30_000 });
|
||||
if (r.status !== 0 || !r.stdout.trim()) {
|
||||
throw new UserError("O cofre de chaves não abriu (arquivo de outro usuário do Windows ou corrompido). Apague data/ai/vault.bin e salve as chaves de novo.");
|
||||
}
|
||||
return Buffer.from(r.stdout.trim(), "base64");
|
||||
}
|
||||
|
||||
function readVault(): VaultData {
|
||||
let stat: fs.Stats;
|
||||
try {
|
||||
stat = fs.statSync(VAULT_PATH);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
if (g.__cenaforgeAiVault?.mtimeMs === stat.mtimeMs) return g.__cenaforgeAiVault.data;
|
||||
const parsed = JSON.parse(dpapi("Unprotect", fs.readFileSync(VAULT_PATH)).toString("utf8")) as Record<string, unknown>;
|
||||
const data: VaultData = {};
|
||||
for (const id of PROVIDERS) if (typeof parsed[id] === "string" && parsed[id]) data[id] = parsed[id] as string;
|
||||
g.__cenaforgeAiVault = { mtimeMs: stat.mtimeMs, data };
|
||||
return data;
|
||||
}
|
||||
|
||||
function apiKeyOf(id: Provider): string | null {
|
||||
try {
|
||||
return readVault()[id] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Guarda (ou apaga, com null) a chave de uma IA. Validação leve: sem espaços e tamanho plausível. */
|
||||
export function setApiKey(id: Provider, key: string | null): void {
|
||||
if (!isProvider(id)) throw new UserError("IA desconhecida.");
|
||||
const data = { ...readVault() };
|
||||
if (key === null) {
|
||||
delete data[id];
|
||||
} else {
|
||||
const clean = key.trim();
|
||||
if (clean.length < 16 || clean.length > 400 || /\s/.test(clean)) throw new UserError("Essa chave não parece válida: cole a chave inteira, sem espaços.");
|
||||
data[id] = clean;
|
||||
}
|
||||
if (Object.keys(data).length === 0) {
|
||||
fs.rmSync(VAULT_PATH, { force: true });
|
||||
} else {
|
||||
writeAtomic(VAULT_PATH, dpapi("Protect", Buffer.from(JSON.stringify(data), "utf8")));
|
||||
}
|
||||
g.__cenaforgeAiVault = undefined;
|
||||
g.__cenaforgeAiTests?.delete(id);
|
||||
invalidateStatus();
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- executável e ambiente */
|
||||
|
||||
export type ResolvedCommand = { path: string; command: string; prefixArgs: string[] };
|
||||
|
||||
/** 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")];
|
||||
if (process.env.APPDATA) dirs.push(path.join(process.env.APPDATA, "npm"));
|
||||
return dirs;
|
||||
}
|
||||
|
||||
export function resolveCommand(id: Provider): ResolvedCommand | null {
|
||||
const meta = PROVIDER_META[id];
|
||||
const fromEnv = process.env[meta.binEnv];
|
||||
if (fromEnv) {
|
||||
return fromEnv.endsWith(".js") ? { path: fromEnv, command: process.execPath, prefixArgs: [fromEnv] } : { path: fromEnv, command: fromEnv, prefixArgs: [] };
|
||||
}
|
||||
const exe = findOnPath(meta.bin);
|
||||
if (exe) return { path: exe, command: exe, prefixArgs: [] };
|
||||
const dirs = [...(process.env.PATH ?? "").split(path.delimiter).filter(Boolean), ...extraDirs()];
|
||||
for (const dir of dirs) {
|
||||
if (!IS_WINDOWS) break;
|
||||
const native = path.join(dir, `${meta.bin}.exe`);
|
||||
if (fs.existsSync(native)) return { path: native, command: native, prefixArgs: [] };
|
||||
if (meta.npmEntry) {
|
||||
const js = path.join(dir, "node_modules", meta.npmEntry);
|
||||
if (fs.existsSync(path.join(dir, `${meta.bin}.cmd`)) && fs.existsSync(js)) return { path: js, command: process.execPath, prefixArgs: [js] };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Variáveis de ambiente de uma chamada: o modo chave só vale para ela; o login global da CLI não muda. */
|
||||
export function providerEnv(id: Provider, base: Record<string, string | undefined> = process.env): NodeJS.ProcessEnv {
|
||||
const env = { ...base } as NodeJS.ProcessEnv;
|
||||
const mode = readAiSettings().providers[id].authMode;
|
||||
const key = mode === "apiKey" ? apiKeyOf(id) : null;
|
||||
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;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- estado de cada IA */
|
||||
|
||||
export type OAuthState = { state: "yes" | "no" | "unknown"; detail: string };
|
||||
|
||||
/** Parte cara do estado (processos): fica em cache por 60 s. */
|
||||
type ProviderRuntime = { id: Provider; resolved: ResolvedCommand | null; version: string | null; oauth: OAuthState };
|
||||
|
||||
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 };
|
||||
|
||||
export type ProviderStatus = {
|
||||
id: Provider; label: string; vendor: string;
|
||||
installed: boolean; version: string | null; path: string | null;
|
||||
settings: ProviderSettings;
|
||||
oauth: OAuthState;
|
||||
apiKey: { saved: boolean; hint: string | null };
|
||||
/** Ligada, instalada e com login (ou chave) — pode ser chamada agora. */
|
||||
ready: boolean;
|
||||
/** Por que não está pronta (null = pronta). */
|
||||
problem: string | null;
|
||||
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 };
|
||||
};
|
||||
|
||||
function run(resolved: ResolvedCommand, args: string[], timeout = 20_000) {
|
||||
return spawnSync(resolved.command, [...resolved.prefixArgs, ...args], { encoding: "utf8", timeout, windowsHide: true, shell: false, env: process.env });
|
||||
}
|
||||
|
||||
function detectOAuth(id: Provider, resolved: ResolvedCommand | null): OAuthState {
|
||||
if (!resolved) return { state: "unknown", detail: "" };
|
||||
if (id === "claude") {
|
||||
const r = run(resolved, ["auth", "status", "--json"]);
|
||||
try {
|
||||
const s = JSON.parse(r.stdout) as { loggedIn?: boolean; authMethod?: string; subscriptionType?: string };
|
||||
if (!s.loggedIn) return { state: "no", detail: "Não está logado." };
|
||||
const plan = s.subscriptionType ? ` · plano ${s.subscriptionType}` : "";
|
||||
return { state: "yes", detail: `Logado (${s.authMethod ?? "conta"}${plan}).` };
|
||||
} catch {
|
||||
return { state: "unknown", detail: "Não deu para ler o login do Claude Code." };
|
||||
}
|
||||
}
|
||||
if (id === "codex") {
|
||||
const r = run(resolved, ["login", "status"]);
|
||||
const text = `${r.stdout ?? ""}\n${r.stderr ?? ""}`.trim();
|
||||
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." };
|
||||
}
|
||||
|
||||
function runtimes(force = false): ProviderRuntime[] {
|
||||
const cached = g.__cenaforgeAiStatus;
|
||||
if (!force && cached && Date.now() - cached.at < 60_000) return cached.list;
|
||||
const list = PROVIDERS.map((id): ProviderRuntime => {
|
||||
const resolved = resolveCommand(id);
|
||||
let version: string | null = null;
|
||||
if (resolved) {
|
||||
const r = run(resolved, ["--version"]);
|
||||
version = r.status === 0 ? r.stdout.trim().split(/\r?\n/)[0] : null;
|
||||
}
|
||||
return { id, resolved: version !== null ? resolved : null, version, oauth: detectOAuth(id, version !== null ? resolved : null) };
|
||||
});
|
||||
g.__cenaforgeAiStatus = { at: Date.now(), list };
|
||||
return list;
|
||||
}
|
||||
|
||||
export function invalidateStatus(): void {
|
||||
g.__cenaforgeAiStatus = undefined;
|
||||
}
|
||||
|
||||
export function providerStatus(options: { refresh?: boolean } = {}): ProviderStatus[] {
|
||||
const settings = readAiSettings();
|
||||
let vault: VaultData = {};
|
||||
let vaultError: string | null = null;
|
||||
try {
|
||||
vault = readVault();
|
||||
} catch (error) {
|
||||
vaultError = (error as Error).message;
|
||||
}
|
||||
return runtimes(options.refresh).map((rt): ProviderStatus => {
|
||||
const meta = PROVIDER_META[rt.id];
|
||||
const own = settings.providers[rt.id];
|
||||
const key = vault[rt.id];
|
||||
const installed = rt.resolved !== null;
|
||||
let problem: string | null = null;
|
||||
if (!own.enabled) problem = "Desligada.";
|
||||
else if (!installed) problem = "CLI não instalada.";
|
||||
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.";
|
||||
const cooldown = activeCooldown(rt.id);
|
||||
return {
|
||||
id: rt.id, label: meta.label, vendor: meta.vendor,
|
||||
installed, version: rt.version, path: rt.resolved?.path ?? null,
|
||||
settings: own, oauth: rt.oauth,
|
||||
apiKey: { saved: !!key, hint: key ? `…${key.slice(-4)}` : null },
|
||||
ready: problem === null, problem,
|
||||
cooldown: cooldown ? { until: new Date(cooldown.until).toISOString(), reason: cooldown.reason } : null,
|
||||
install: installs().get(rt.id) ?? null,
|
||||
lastTest: tests().get(rt.id) ?? null,
|
||||
meta: {
|
||||
installCommand: meta.install.display, oauthLabel: meta.oauthLabel, oauthNote: meta.oauthNote,
|
||||
apiKeyEnv: meta.apiKeyEnv, apiKeyUrl: meta.apiKeyUrl, apiKeyLabel: meta.apiKeyLabel, canLogin: IS_WINDOWS,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function resolvedFor(id: Provider): ResolvedCommand | null {
|
||||
return runtimes().find((r) => r.id === id)?.resolved ?? null;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- reserva */
|
||||
|
||||
const cooldowns = () => (g.__cenaforgeAiCooldown ??= new Map());
|
||||
|
||||
/** Falha que não é culpa do pedido: cota, sobrecarga, login/chave, rede, CLI fora. Ver doc/ia.md. */
|
||||
const AVAILABILITY_PATTERNS = [
|
||||
/rate.?limit/i, /\b429\b/, /quota/i, /usage limit/i, /limit (reached|exceeded)/i, /credit balance/i, /hit your limit/i,
|
||||
/overloaded/i, /\b529\b/, /\b503\b/, /\b502\b/, /unavailable/i, /capacity/i,
|
||||
/\b401\b/, /\b403\b/, /unauthori[sz]ed/i, /not logged in/i, /please (run|log)/i, /login/i, /invalid.{0,12}api.?key/i, /authentication/i, /IneligibleTier/i, /auth method/i,
|
||||
/ECONN/i, /ETIMEDOUT/i, /ENOTFOUND/i, /EAI_AGAIN/i, /network/i, /socket hang up/i, /fetch failed/i,
|
||||
/não iniciou/i, /não encontrad/i, /não está disponível/i, /timed? ?out/i, /passou de \d+ s/i,
|
||||
];
|
||||
|
||||
export function isAvailabilityError(text: string | null | undefined): boolean {
|
||||
return !!text && AVAILABILITY_PATTERNS.some((re) => re.test(text));
|
||||
}
|
||||
|
||||
export function markUnavailable(id: Provider, reason: string): void {
|
||||
const minutes = readAiSettings().fallback.cooldownMin;
|
||||
cooldowns().set(id, { until: Date.now() + minutes * 60_000, reason: reason.slice(0, 300) });
|
||||
}
|
||||
|
||||
export function clearCooldown(id: Provider): void {
|
||||
cooldowns().delete(id);
|
||||
}
|
||||
|
||||
function activeCooldown(id: Provider): { until: number; reason: string } | null {
|
||||
const entry = cooldowns().get(id);
|
||||
if (!entry) return null;
|
||||
if (entry.until <= Date.now()) {
|
||||
cooldowns().delete(id);
|
||||
return null;
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/** IAs prontas na ordem de uso: `first` (a escolhida/preferida) e depois a ordem da reserva. As em pausa vão para o fim. */
|
||||
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))];
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- instalação */
|
||||
|
||||
const installs = () => (g.__cenaforgeAiInstalls ??= new Map());
|
||||
|
||||
/** Instala ou atualiza a CLI em segundo plano; o log aparece na tela (GET /api/ai). */
|
||||
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 };
|
||||
installs().set(id, job);
|
||||
const push = (line: string) => {
|
||||
job.log.push(line.slice(0, 400));
|
||||
if (job.log.length > 200) job.log.splice(1, job.log.length - 200);
|
||||
};
|
||||
const child = spawn(command.file, command.args, { cwd: HOME, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: process.env });
|
||||
child.stdout.setEncoding("utf8").on("data", lineSplitter(push));
|
||||
child.stderr.setEncoding("utf8").on("data", lineSplitter(push));
|
||||
child.on("error", (error) => {
|
||||
push(`não iniciou: ${error.message}`);
|
||||
job.status = "error";
|
||||
job.finishedAt = new Date().toISOString();
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
if (job.status === "running") job.status = code === 0 ? "success" : "error";
|
||||
push(code === 0 ? "Instalação concluída." : `Saiu com código ${code}.`);
|
||||
job.finishedAt = new Date().toISOString();
|
||||
invalidateStatus();
|
||||
});
|
||||
return job;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- login (OAuth) */
|
||||
|
||||
/**
|
||||
* Abre um terminal visível com o login da CLI (o navegador abre a página da conta). O painel não vê a senha:
|
||||
* o login é da própria CLI. Depois o usuário clica em "Verificar".
|
||||
*/
|
||||
export function openLoginTerminal(id: Provider): void {
|
||||
if (!isProvider(id)) throw new UserError("IA desconhecida.");
|
||||
if (!IS_WINDOWS) throw new UserError(`Rode no terminal: ${PROVIDER_META[id].bin} ${PROVIDER_META[id].loginArgs.join(" ")}`);
|
||||
const resolved = resolvedFor(id) ?? resolveCommand(id);
|
||||
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. &&"
|
||||
: "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}"`],
|
||||
{ cwd: HOME, detached: true, stdio: "ignore", windowsVerbatimArguments: true, env: providerEnvForLogin(id) });
|
||||
child.unref();
|
||||
invalidateStatus();
|
||||
}
|
||||
|
||||
/** No login com a conta, nenhuma chave de API pode estar no ambiente (a CLI usaria a chave em vez da conta). */
|
||||
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;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- teste rápido */
|
||||
|
||||
const tests = () => (g.__cenaforgeAiTests ??= new Map());
|
||||
|
||||
/** Pergunta mínima, fora do repositório (não carrega CLAUDE.md nem skills): confirma login, chave e cota. */
|
||||
export async function testProvider(id: Provider): Promise<TestResult> {
|
||||
if (!isProvider(id)) throw new UserError("IA desconhecida.");
|
||||
const resolved = resolvedFor(id) ?? resolveCommand(id);
|
||||
if (!resolved) throw new UserError("Instale a CLI antes de testar.");
|
||||
const status = providerStatus().find((p) => p.id === id);
|
||||
if (status?.settings.authMode === "apiKey" && !status.apiKey.saved) throw new UserError("Salve a chave de API antes de testar.");
|
||||
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "cenaforge-ai-test-"));
|
||||
const question = "Responda apenas com a palavra: ok";
|
||||
const args = id === "claude"
|
||||
? ["-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"];
|
||||
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) });
|
||||
let out = "";
|
||||
let err = "";
|
||||
const timer = setTimeout(() => { err += "\ntempo esgotado (90 s)"; child.kill(); }, 90_000);
|
||||
child.stdout.setEncoding("utf8").on("data", (c: string) => { out += c; });
|
||||
child.stderr.setEncoding("utf8").on("data", (c: string) => { err += c; });
|
||||
child.on("error", (e) => { err += `\nnão iniciou: ${e.message}`; });
|
||||
child.on("close", (code) => { clearTimeout(timer); resolve({ code, out, err }); });
|
||||
});
|
||||
fs.rmSync(cwd, { recursive: true, force: true });
|
||||
const answer = readTestAnswer(id, output.out);
|
||||
const ok = output.code === 0 && answer.ok;
|
||||
const text = ok ? `Respondeu: "${answer.text}"` : summarizeFailure(answer.text || output.err || output.out);
|
||||
const result: TestResult = { ok, text, at: new Date().toISOString(), ms: Date.now() - started };
|
||||
tests().set(id, result);
|
||||
if (ok) clearCooldown(id);
|
||||
return result;
|
||||
}
|
||||
|
||||
function readTestAnswer(id: Provider, out: string): { ok: boolean; text: string } {
|
||||
try {
|
||||
if (id === "claude") {
|
||||
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) };
|
||||
}
|
||||
// Codex: JSONL; a resposta é o último agent_message; falha vem em turn.failed/error.
|
||||
let text = "";
|
||||
for (const line of out.split(/\r?\n/).filter(Boolean)) {
|
||||
const e = JSON.parse(line) as { type?: string; item?: { type?: string; text?: string }; error?: { message?: string }; message?: string };
|
||||
if (e.type === "item.completed" && e.item?.type === "agent_message") text = String(e.item.text ?? "");
|
||||
if (e.type === "turn.failed" || e.type === "error") return { ok: false, text: String(e.error?.message ?? e.message ?? "erro") };
|
||||
}
|
||||
return { ok: !!text, text: text.trim().slice(0, 200) };
|
||||
} catch {
|
||||
return { ok: false, text: "" };
|
||||
}
|
||||
}
|
||||
|
||||
/** Primeira linha útil do erro, sem pilha de chamadas. */
|
||||
function summarizeFailure(text: string): string {
|
||||
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !/^at /.test(l) && !/True color/i.test(l) && !/Ripgrep/i.test(l));
|
||||
const useful = lines.find((l) => /error|erro|limit|auth|login|key|quota|denied|inválid|unsupported/i.test(l)) ?? lines[0] ?? "Falhou sem mensagem.";
|
||||
return useful.slice(0, 400);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- modelos do Gemini */
|
||||
|
||||
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" },
|
||||
];
|
||||
|
||||
/** 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");
|
||||
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"] });
|
||||
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 */ }
|
||||
});
|
||||
}
|
||||
return cache.list;
|
||||
}
|
||||
@@ -401,6 +401,10 @@ export const MIGRATIONS: string[] = [
|
||||
`
|
||||
ALTER TABLE accounts ADD COLUMN language TEXT NOT NULL DEFAULT 'pt-BR';
|
||||
`,
|
||||
// v10: IA reserva — a execução que continuou outra que caiu por indisponibilidade (lib/ai.ts, doc/ia.md).
|
||||
`
|
||||
ALTER TABLE agent_runs ADD COLUMN fallback_of INTEGER REFERENCES agent_runs(id);
|
||||
`,
|
||||
];
|
||||
|
||||
const g = globalThis as unknown as { __cenaforgeDb?: DatabaseSync };
|
||||
|
||||
@@ -62,8 +62,9 @@ export function buildPrompt(input: { kind: AgentKind; provider: Provider; reques
|
||||
"Trabalhe só dentro do repositório. Seja econômico: Grep antes de ler, leia por intervalo de linhas, filtre saídas longas (`| Select-Object -Last 20` / `| tail -n 20`). " +
|
||||
"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 === "codex"
|
||||
? "Você é o Codex. 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. " +
|
||||
provider !== "claude"
|
||||
? `Você é o ${provider === "codex" ? "Codex" : "Gemini"}. ` +
|
||||
"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`."
|
||||
: null,
|
||||
|
||||
@@ -61,7 +61,7 @@ describe("migração v5", () => {
|
||||
it("migra com backup, preserva ids e não quebra chaves estrangeiras", () => {
|
||||
const version = dbm.get<{ user_version: number }>("PRAGMA user_version")!.user_version;
|
||||
assert.equal(version, dbm.MIGRATIONS.length);
|
||||
assert.equal(version, 9);
|
||||
assert.equal(version, 10);
|
||||
assert.equal(fs.readdirSync(path.join(ROOT, "data", "backups")).filter((f) => f.startsWith("cenaforge-v4-")).length, 1);
|
||||
assert.deepEqual(dbm.all("PRAGMA foreign_key_check"), []);
|
||||
});
|
||||
|
||||
@@ -123,7 +123,8 @@ export type Decision = {
|
||||
snapshot_json: string;
|
||||
};
|
||||
|
||||
export type Provider = "claude" | "codex";
|
||||
export type Provider = "claude" | "codex" | "gemini";
|
||||
export const PROVIDERS: Provider[] = ["claude", "codex", "gemini"];
|
||||
// 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"];
|
||||
@@ -138,6 +139,8 @@ export type AgentRun = {
|
||||
story_id: string | null;
|
||||
episode_id: number | null;
|
||||
resume_of: number | null;
|
||||
/** Execução que falhou por indisponibilidade e que esta continuou com a IA reserva. */
|
||||
fallback_of: number | null;
|
||||
status: AgentStatus;
|
||||
session_id: string | null;
|
||||
cost_usd: number | null;
|
||||
|
||||
Reference in New Issue
Block a user