Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
540 lines
29 KiB
TypeScript
540 lines
29 KiB
TypeScript
// Agentes de código (Claude Code e Codex) chamados pela CLI, como no VS Code.
|
||
//
|
||
// 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;
|
||
// - Bash só para os comandos liberados abaixo (render, testes, scripts da skill);
|
||
// - 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 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 { onAgentRunClosed } from "./branches";
|
||
import { UserError, getEpisodeById, getStory, syncStoryMeta } from "./stories";
|
||
import { AGENT_KINDS, type AgentEvent, type AgentKind, type AgentRun, type Provider } from "./types";
|
||
|
||
const SKILL_SCRIPTS = "python .claude/skills/cenaforge/scripts";
|
||
export const CLAUDE_ALLOWED_TOOLS = [
|
||
"Read", "Edit", "Write", "Glob", "Grep", "Agent", "Skill", "TodoWrite",
|
||
"Bash(pnpm render:*)", "Bash(pnpm verify:*)", "Bash(pnpm test:*)", "Bash(pnpm typecheck)",
|
||
"Bash(pnpm run doctor)", "Bash(pnpm prepare-assets)",
|
||
`Bash(${SKILL_SCRIPTS}/new_scene.py:*)`, `Bash(${SKILL_SCRIPTS}/runs_summary.py:*)`,
|
||
`Bash(${SKILL_SCRIPTS}/inspect_strip.py:*)`, `Bash(${SKILL_SCRIPTS}/check_skill.py:*)`, `Bash(${SKILL_SCRIPTS}/godot_api.py:*)`,
|
||
`Bash(${SKILL_SCRIPTS}/frame_check.py:*)`, `Bash(${SKILL_SCRIPTS}/check_script.py:*)`,
|
||
].join(",");
|
||
|
||
/**
|
||
* Economia de tokens: sem estas flags, o `claude -p` do painel carregava a cada turno os plugins,
|
||
* MCPs, hooks, skills e agentes da instalação do usuário (61 ferramentas, 310 skills, 78 agentes).
|
||
* Medido com o mesmo prompt trivial (17/11/2026): 62,4 mil → 14,9 mil tokens de entrada no 1º turno,
|
||
* partida de 8,0 s → 4,3 s. Valem só para os agentes do painel; a config global não muda.
|
||
* - `--setting-sources project,local`: ignora ~/.claude/settings.json (plugins e hooks do usuário).
|
||
* O login não depende dele. O .claude/ do projeto (skills, subagentes) continua valendo.
|
||
* - `--strict-mcp-config` sem `--mcp-config`: nenhum servidor MCP.
|
||
* - `--tools`: só as ferramentas que as tarefas usam (Agent = subagente roteirista; Skill = cenaforge).
|
||
*/
|
||
const CLAUDE_TOOLS = "Read,Edit,Write,Glob,Grep,Bash,Agent,Skill,TodoWrite";
|
||
const CLAUDE_LEAN_FLAGS = ["--setting-sources", "project,local", "--strict-mcp-config", "--tools", CLAUDE_TOOLS];
|
||
|
||
/**
|
||
* Teto de gasto por execução do Claude (US$), proteção contra laço. Folgado: a cena no Godot
|
||
* custou US$ 3,09 no Opus e o padrão agora é o Sonnet. Ao atingir, a CLI encerra a execução e o
|
||
* usuário pode continuar a conversa pelo painel.
|
||
*/
|
||
export const CLAUDE_BUDGET_USD: Record<AgentKind, number> = { story: 1.5, script: 1.5, branches: 2.5, scene: 1, godot: 3, free: 3 };
|
||
|
||
export type ModelOption = { id: string; label: string };
|
||
|
||
/** Modelos do Claude Code (ids aceitos por `claude --model`). "" = o padrão configurado na CLI. */
|
||
const CLAUDE_MODELS: ModelOption[] = [
|
||
{ id: "", label: "Padrão da CLI" },
|
||
{ id: "claude-fable-5-2", label: "Fable 5.2" },
|
||
{ id: "claude-opus-5-5", label: "Opus 5.5: mais capaz, mais caro" },
|
||
{ id: "claude-sonnet-5-5", label: "Sonnet 5.5: equilíbrio entre roteiro e cena" },
|
||
{ id: "claude-haiku-5-5", label: "Haiku 5.5: mais barato, para variações e resumos" },
|
||
];
|
||
/** Apelidos que execuções antigas gravaram; continuam aceitos ao retomar uma conversa. */
|
||
const CLAUDE_ALIASES = ["opus", "sonnet", "haiku"];
|
||
|
||
const CODEX_HOME = process.env.CODEX_HOME || path.join(process.env.USERPROFILE || process.env.HOME || "", ".codex");
|
||
|
||
/**
|
||
* Modelos do Codex: a própria CLI guarda em ~/.codex/models_cache.json os modelos que a conta
|
||
* enxerga (atualizado a cada uso da CLI). Só os visíveis no seletor da CLI ("list"), na ordem dela.
|
||
* O padrão é o `model = "..."` do config.toml.
|
||
*/
|
||
function codexModels(): ModelOption[] {
|
||
let configured = "";
|
||
try {
|
||
configured = /^\s*model\s*=\s*"([^"]+)"/m.exec(fs.readFileSync(path.join(CODEX_HOME, "config.toml"), "utf8"))?.[1] ?? "";
|
||
} catch { /* sem config: a CLI usa o padrão dela */ }
|
||
type CachedModel = { slug?: unknown; display_name?: unknown; description?: unknown; visibility?: unknown; priority?: unknown };
|
||
let cached: CachedModel[] = [];
|
||
try {
|
||
const parsed = JSON.parse(fs.readFileSync(path.join(CODEX_HOME, "models_cache.json"), "utf8")) as { models?: unknown };
|
||
if (Array.isArray(parsed.models)) cached = parsed.models as CachedModel[];
|
||
} catch { /* cache ausente: só o padrão */ }
|
||
const listed = cached
|
||
.filter((m) => typeof m.slug === "string" && m.visibility === "list")
|
||
.sort((a, b) => Number(a.priority ?? 99) - Number(b.priority ?? 99))
|
||
.map((m) => {
|
||
const name = typeof m.display_name === "string" ? m.display_name : String(m.slug);
|
||
const about = typeof m.description === "string" && m.description ? `: ${m.description}` : "";
|
||
return { id: String(m.slug), label: `${name}${about}` };
|
||
});
|
||
const defaultName = listed.find((m) => m.id === configured)?.label.split(":")[0] ?? configured;
|
||
return [{ id: "", label: defaultName ? `Padrão da CLI (${defaultName})` : "Padrão da CLI" }, ...listed];
|
||
}
|
||
|
||
/** Modelos que o seletor oferece por agente. */
|
||
export function models(): Record<Provider, ModelOption[]> {
|
||
return { claude: CLAUDE_MODELS, codex: codexModels() };
|
||
}
|
||
|
||
/** Modelo sugerido por tipo de tarefa (economia de tokens). */
|
||
// Vertentes: roteiro + cena de 2–4 episódios numa execução só → Sonnet (qualidade de roteiro sem o custo do Opus).
|
||
// Cena no Godot: Sonnet (a cena dos náufragos no Opus custou US$ 3,09 e esgotou o limite de 5 h em 11 min).
|
||
export const DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "", script: "", scene: "claude-sonnet-5-5", branches: "claude-sonnet-5-5", godot: "claude-sonnet-5-5" };
|
||
|
||
/**
|
||
* Agente preferido por tarefa (decisão do usuário: enredo e roteiro com GPT, via Codex).
|
||
* Se o preferido não estiver disponível, cai para o outro.
|
||
*/
|
||
export const PREFERRED_PROVIDER: Record<AgentKind, Provider> = { free: "claude", story: "codex", script: "codex", scene: "claude", branches: "codex", godot: "claude" };
|
||
|
||
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;
|
||
}
|
||
|
||
/** 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 {
|
||
return provider === "claude" ? DEFAULT_MODEL[kind] : CODEX_DEFAULT_MODEL[kind];
|
||
}
|
||
|
||
/**
|
||
* Codex por tarefa (economia): texto e roteiro com o modelo de uso geral (GPT-6.1-Sol), não o
|
||
* "frontier" do config.toml (GPT-6-Astra, o mais caro). "" = o padrão do config.toml. Só vale se o
|
||
* modelo existir na lista da CLI; senão cai no padrão.
|
||
*/
|
||
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: "" };
|
||
|
||
/** `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[];
|
||
};
|
||
/**
|
||
* 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.
|
||
*/
|
||
type ActiveRun = {
|
||
child: ChildProcess;
|
||
listeners: Set<(e: AgentEvent | null) => void>;
|
||
emit: (e: Omit<AgentEvent, "at">) => void;
|
||
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;
|
||
};
|
||
const g = globalThis as unknown as { __cenaforgeAgents?: Map<number, ActiveRun>; __cenaforgeProviders?: { at: number; list: ProviderInfo[] } };
|
||
const active = (g.__cenaforgeAgents ??= new Map());
|
||
|
||
/** Há um agente trabalhando? (o executor roda um por vez) */
|
||
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;
|
||
}
|
||
|
||
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 {
|
||
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 ?? [],
|
||
};
|
||
};
|
||
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[] {
|
||
return all<AgentRun>("SELECT * FROM agent_runs ORDER BY id DESC LIMIT ?", limit);
|
||
}
|
||
|
||
export function getRun(id: number): AgentRun | undefined {
|
||
return get<AgentRun>("SELECT * FROM agent_runs WHERE id = ?", id);
|
||
}
|
||
|
||
export function startRun(input: {
|
||
provider: Provider; model: string; kind: AgentKind; request: string;
|
||
storyId?: string | null; episodeId?: number | null; resumeRunId?: 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.`);
|
||
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.");
|
||
if (request.length > 20_000) throw new UserError("Pedido longo demais (máx. 20 mil caracteres).");
|
||
if (!AGENT_KINDS.includes(input.kind)) throw new UserError("Tipo de tarefa inválido.");
|
||
const knownModel = models()[input.provider].some((m) => m.id === input.model) ||
|
||
(input.provider === "claude" && CLAUDE_ALIASES.includes(input.model));
|
||
if (input.model && !knownModel) throw new UserError("Modelo inválido para este agente.");
|
||
|
||
const story = input.storyId ? getStory(input.storyId) : undefined;
|
||
if (input.storyId && !story) throw new UserError("História não encontrada.");
|
||
const episode = input.episodeId ? getEpisodeById(input.episodeId) : undefined;
|
||
if (input.episodeId && (!episode || episode.story_id !== story?.id)) throw new UserError("Episódio não pertence à história.");
|
||
const resume = input.resumeRunId ? getRun(input.resumeRunId) : undefined;
|
||
if (input.resumeRunId && (!resume?.session_id || resume.provider !== input.provider)) {
|
||
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 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 id = Number(row.lastInsertRowid);
|
||
const logPath = path.join(logDir, `${id}.jsonl`);
|
||
run("UPDATE agent_runs SET log_path = ? WHERE id = ?", rel(logPath), id);
|
||
|
||
const args = input.provider === "claude"
|
||
? ["-p", prompt, "--output-format", "stream-json", "--verbose", "--permission-mode", "acceptEdits",
|
||
...(input.model ? ["--model", input.model] : []),
|
||
...(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);
|
||
|
||
const child = spawn(info.command, [...info.prefixArgs, ...args], { cwd: REPO_ROOT, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
||
const listeners = new Set<(e: AgentEvent | null) => void>();
|
||
const log = fs.createWriteStream(logPath);
|
||
const emit = (e: Omit<AgentEvent, "at">) => {
|
||
if (e.kind !== "system" && e.kind !== "stderr" && e.kind !== "error") entry.progressed = true;
|
||
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 };
|
||
active.set(id, entry);
|
||
emit({ kind: "system", text: `${input.provider}${input.model ? ` · ${input.model}` : ""} · tarefa "${input.kind}"${resume ? ` · continua a execução #${resume.id}` : ""}` });
|
||
|
||
child.stdout.setEncoding("utf8").on("data", lineSplitter((line) => {
|
||
let obj: Record<string, unknown>;
|
||
try {
|
||
obj = JSON.parse(line);
|
||
} catch {
|
||
emit({ kind: "text", text: line.slice(0, 2000) });
|
||
return;
|
||
}
|
||
const events = input.provider === "claude" ? normalizeClaude(obj, id) : normalizeCodex(obj, id);
|
||
events.forEach(emit);
|
||
}));
|
||
child.stderr.setEncoding("utf8").on("data", lineSplitter((line) => {
|
||
if (!STDERR_NOISE.some((re) => re.test(line))) emit({ kind: "stderr", text: line.slice(0, 1000) });
|
||
}));
|
||
child.on("error", (error) => emit({ kind: "error", text: `não iniciou: ${error.message}`, isError: true }));
|
||
child.on("close", (code) => {
|
||
// 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);
|
||
if (current?.status === "running") {
|
||
const ok = code === 0 && !current.error;
|
||
run("UPDATE agent_runs SET status = ?, error = COALESCE(error, ?), finished_at = ? WHERE id = ?",
|
||
ok ? "success" : "error", ok ? null : `saiu com código ${code}`, now(), id);
|
||
}
|
||
active.delete(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");
|
||
} catch (error) {
|
||
console.warn(`vertentes após a execução #${id}: ${(error as Error).message}`);
|
||
}
|
||
// Mensagem enviada durante a execução: retoma a mesma sessão com ela. Começa ANTES de avisar
|
||
// os ouvintes, para o evento "end" já levar o id da continuação (o console segue para ela).
|
||
if (entry.followUp) {
|
||
const closed = getRun(id);
|
||
try {
|
||
if (!closed?.session_id) throw new UserError("o agente não registrou a sessão, então não dá para continuar a conversa");
|
||
startRun({
|
||
provider: closed.provider, model: closed.model, kind: closed.kind, request: entry.followUp,
|
||
storyId: closed.story_id, episodeId: closed.episode_id, resumeRunId: id,
|
||
});
|
||
} catch (error) {
|
||
emit({ kind: "error", text: `Sua mensagem não foi enviada: ${(error as Error).message}. Copie-a e envie de novo.`, isError: true });
|
||
}
|
||
}
|
||
for (const l of listeners) l(null);
|
||
log.end();
|
||
});
|
||
return getRun(id)!;
|
||
}
|
||
|
||
/**
|
||
* Mensagem do usuário durante a execução.
|
||
* - "now": interrompe o agente e retoma a mesma sessão com a correção (ele vê o que já fez);
|
||
* - "queue": espera o agente terminar e então continua a conversa com a mensagem.
|
||
* Uma mensagem por vez: a nova substitui a que estava na fila.
|
||
*/
|
||
export function sendFollowUp(id: number, text: string, mode: "now" | "queue"): void {
|
||
const entry = active.get(id);
|
||
if (!entry) throw new UserError("Esta execução já terminou. Use \"Continuar esta conversa\".");
|
||
const message = text.trim();
|
||
if (message.length < 2) throw new UserError("Escreva a mensagem.");
|
||
if (message.length > 20_000) throw new UserError("Mensagem longa demais (máx. 20 mil caracteres).");
|
||
const current = getRun(id);
|
||
// Testado com o Codex: interrompido antes do primeiro passo, a sessão retomada não tem o pedido original.
|
||
if (mode === "now" && (!current?.session_id || !entry.progressed)) {
|
||
throw new UserError("O agente ainda está começando. Aguarde o primeiro passo dele ou use \"Enviar ao terminar\".");
|
||
}
|
||
entry.followUp = mode === "now"
|
||
? `O usuário interrompeu você para corrigir o rumo. Considere o que já foi feito até aqui e siga esta orientação:\n\n${message}`
|
||
: `Mensagem do usuário enviada enquanto você trabalhava:\n\n${message}`;
|
||
entry.emit({ kind: "system", text: mode === "now" ? "Interrompido para receber sua correção." : "Sua mensagem será enviada quando o agente terminar." });
|
||
if (mode === "now") {
|
||
run("UPDATE agent_runs SET status = 'cancelled', error = COALESCE(error, ?), finished_at = ? WHERE id = ?", "interrompida para correção", now(), id);
|
||
killTree(entry.child);
|
||
}
|
||
}
|
||
|
||
/** A execução que continuou esta (mensagem enviada durante ela ou "Continuar esta conversa"). */
|
||
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;
|
||
}
|
||
|
||
export function cancelRun(id: number): void {
|
||
const entry = active.get(id);
|
||
if (!entry) throw new UserError("Esta execução não está em andamento.");
|
||
run("UPDATE agent_runs SET status = 'cancelled', finished_at = ? WHERE id = ?", now(), id);
|
||
killTree(entry.child);
|
||
}
|
||
|
||
export function isActive(id: number): boolean {
|
||
return active.has(id);
|
||
}
|
||
|
||
/** Inscreve-se nos eventos ao vivo; o callback recebe null quando termina. */
|
||
export function subscribe(id: number, listener: (e: AgentEvent | null) => void): () => void {
|
||
const entry = active.get(id);
|
||
if (!entry) return () => {};
|
||
entry.listeners.add(listener);
|
||
return () => entry.listeners.delete(listener);
|
||
}
|
||
|
||
export function readEvents(id: number): AgentEvent[] {
|
||
const r = getRun(id);
|
||
if (!r) return [];
|
||
try {
|
||
return fs.readFileSync(path.join(REPO_ROOT, r.log_path), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l) as AgentEvent);
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
// --- Codex ----------------------------------------------------------------------
|
||
|
||
/**
|
||
* Esforço de raciocínio por tarefa (o config.toml do usuário usa "high"). Medido: o roteiro (#6)
|
||
* gastou só 857 tokens de raciocínio, então "low" quase não economizaria e arriscaria a pesquisa
|
||
* de fatos; fica "medium". A cena no Godot (#8) gastou 14,5 mil: "medium". A cena JSON só roda
|
||
* um script: "low". "" = o do config.toml.
|
||
*/
|
||
const CODEX_EFFORT: Record<AgentKind, string> = { story: "medium", script: "medium", branches: "medium", godot: "medium", scene: "low", free: "" };
|
||
|
||
/** Plugins do Codex que não servem ao repositório: o de computer-use põe a ferramenta `cua_repl` (~6,5 mil caracteres) em todo turno. */
|
||
const CODEX_UNUSED_PLUGINS = ["computer-use@openai-bundled", "unified-computer-use@openai-bundled"];
|
||
|
||
/**
|
||
* Overrides `-c` só para as execuções do painel (a config global não muda): esforço por tarefa,
|
||
* servidores MCP pessoais do config.toml desligados e plugins de computer-use fora.
|
||
* Obs.: `-c mcp_servers={}` não funciona (o Codex mescla tabelas); é preciso `enabled=false` por servidor.
|
||
*/
|
||
function codexLeanOverrides(kind: AgentKind): string[] {
|
||
const overrides: string[] = [];
|
||
if (CODEX_EFFORT[kind]) overrides.push(`model_reasoning_effort="${CODEX_EFFORT[kind]}"`);
|
||
let config = "";
|
||
try { config = fs.readFileSync(path.join(CODEX_HOME, "config.toml"), "utf8"); } catch { /* sem config: nada a desligar */ }
|
||
const servers = new Set([...config.matchAll(/^\s*\[mcp_servers\.("?)([A-Za-z0-9_-]+)\1\]\s*$/gm)].map((m) => m[2]));
|
||
for (const name of servers) overrides.push(`mcp_servers.${name}.enabled=false`);
|
||
for (const plugin of CODEX_UNUSED_PLUGINS) {
|
||
if (config.includes(`[plugins."${plugin}"]`)) overrides.push(`plugins."${plugin}".enabled=false`);
|
||
}
|
||
return overrides.flatMap((o) => ["-c", o]);
|
||
}
|
||
|
||
/**
|
||
* Flags reais do codex-cli 0.169.0. O repositório não é Git, por isso --skip-git-repo-check.
|
||
* A retomada (`exec resume`) não aceita --sandbox nem -C: o sandbox vai por -c e o diretório
|
||
* é o cwd do processo (raiz do repositório).
|
||
*/
|
||
function codexArgs(prompt: string, model: string, sessionId: string | null, kind: AgentKind): string[] {
|
||
const common = ["--json", "--skip-git-repo-check", ...(model ? ["-m", model] : []), ...codexLeanOverrides(kind)];
|
||
return sessionId
|
||
? ["exec", "resume", ...common, "-c", 'sandbox_mode="workspace-write"', sessionId, prompt]
|
||
: ["exec", ...common, "--sandbox", "workspace-write", "-C", REPO_ROOT, prompt];
|
||
}
|
||
|
||
/** Linhas de stderr que não ajudam o usuário (aviso de stdin, MCP pessoal do Codex fora do ar, config pessoal do Codex). */
|
||
const STDERR_NOISE = [/no stdin data received/, /Reading additional input from stdin/, /rmcp::transport/, /Codex is ignoring \d+ unrecognized configuration setting/,
|
||
// 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\]/];
|
||
|
||
// --- normalização ---------------------------------------------------------------
|
||
|
||
type Block = { type?: string; text?: string; name?: string; input?: Record<string, unknown>; content?: unknown; is_error?: boolean };
|
||
|
||
function normalizeClaude(o: Record<string, unknown>, runId: number): Omit<AgentEvent, "at">[] {
|
||
switch (o.type) {
|
||
case "system":
|
||
if (o.subtype === "init") {
|
||
run("UPDATE agent_runs SET session_id = ? WHERE id = ?", String(o.session_id), runId);
|
||
return [{ kind: "system", text: `sessão iniciada · modelo ${o.model}` }];
|
||
}
|
||
return [];
|
||
case "assistant":
|
||
return ((o.message as { content?: Block[] })?.content ?? []).flatMap((c): Omit<AgentEvent, "at">[] => {
|
||
if (c.type === "text" && c.text?.trim()) return [{ kind: "text", text: c.text }];
|
||
if (c.type === "tool_use") return [{ kind: "tool", text: `${c.name} ${summarizeInput(c.input)}` }];
|
||
return [];
|
||
});
|
||
case "user":
|
||
return ((o.message as { content?: Block[] | string })?.content instanceof Array
|
||
? (o.message as { content: Block[] }).content : [])
|
||
.filter((c) => c.type === "tool_result")
|
||
.map((c) => ({ kind: "tool_result" as const, text: truncate(stringify(c.content), 1500), isError: !!c.is_error }));
|
||
case "result": {
|
||
const denials = (o.permission_denials as unknown[] | undefined)?.length ?? 0;
|
||
run(`UPDATE agent_runs SET cost_usd = ?, num_turns = ?, result = ?, error = ?, session_id = COALESCE(session_id, ?)
|
||
WHERE id = ?`, Number(o.total_cost_usd ?? 0), Number(o.num_turns ?? 0), String(o.result ?? "").slice(0, 20_000),
|
||
// Erro com subtype "success" (ex.: limite de uso) traz o motivo em "result": guarde o texto.
|
||
o.is_error
|
||
? (o.subtype === "error_max_budget_usd"
|
||
? "Parou no teto de gasto desta tarefa (--max-budget-usd). Continue a conversa para seguir."
|
||
: o.subtype && o.subtype !== "success" ? String(o.subtype) : String(o.result ?? "erro").slice(0, 500))
|
||
: null,
|
||
String(o.session_id ?? ""), runId);
|
||
return [{
|
||
kind: "result", text: `${o.is_error ? "Terminou com erro" : "Concluído"} · ${o.num_turns} turnos · US$ ${Number(o.total_cost_usd ?? 0).toFixed(4)}` +
|
||
(denials ? ` · ${denials} ação(ões) bloqueada(s) pelas permissões` : ""),
|
||
isError: !!o.is_error, costUsd: Number(o.total_cost_usd ?? 0), turns: Number(o.num_turns ?? 0),
|
||
}];
|
||
}
|
||
default:
|
||
return [];
|
||
}
|
||
}
|
||
|
||
type CodexItem = {
|
||
type?: string; text?: string; message?: string; command?: string; aggregated_output?: string;
|
||
exit_code?: number | null; status?: string; changes?: { path?: string; kind?: string }[];
|
||
server?: string; tool?: string; query?: string;
|
||
};
|
||
|
||
/** Eventos JSONL do `codex exec --json` (formato verificado com codex-cli 0.169.0). */
|
||
function normalizeCodex(o: Record<string, unknown>, runId: number): Omit<AgentEvent, "at">[] {
|
||
const item = (o.item ?? {}) as CodexItem;
|
||
switch (o.type) {
|
||
case "thread.started":
|
||
run("UPDATE agent_runs SET session_id = ? WHERE id = ?", String(o.thread_id), runId);
|
||
return [{ kind: "system", text: "sessão iniciada" }];
|
||
case "item.started":
|
||
return item.type === "command_execution" ? [{ kind: "tool", text: `$ ${truncate(stripShell(item.command ?? ""), 200)}` }] : [];
|
||
case "item.completed":
|
||
switch (item.type) {
|
||
case "agent_message":
|
||
run("UPDATE agent_runs SET result = ? WHERE id = ?", String(item.text ?? "").slice(0, 20_000), runId);
|
||
return item.text?.trim() ? [{ kind: "text", text: item.text }] : [];
|
||
case "command_execution":
|
||
return [{ kind: "tool_result", text: truncate(item.aggregated_output ?? "", 1500) || "(sem saída)", isError: (item.exit_code ?? 0) !== 0 }];
|
||
case "file_change":
|
||
return [{ kind: "tool", text: `arquivos: ${(item.changes ?? []).map((c) => `${c.kind ?? "edit"} ${String(c.path ?? "").replace(REPO_ROOT, ".")}`).join(", ")}` }];
|
||
case "mcp_tool_call":
|
||
return [{ kind: "tool", text: `MCP ${item.server ?? ""} ${item.tool ?? ""}` }];
|
||
case "web_search":
|
||
return [{ kind: "tool", text: `busca: ${item.query ?? ""}` }];
|
||
case "error":
|
||
// Avisos de configuração do usuário chegam como "error" mas não interrompem.
|
||
return [{ kind: "system", text: truncate(item.message ?? "", 300) }];
|
||
default:
|
||
return [];
|
||
}
|
||
case "turn.completed": {
|
||
const u = (o.usage ?? {}) as { input_tokens?: number; cached_input_tokens?: number; output_tokens?: number };
|
||
run("UPDATE agent_runs SET num_turns = COALESCE(num_turns, 0) + 1 WHERE id = ?", runId);
|
||
return [{ kind: "result", text: `Concluído · ${u.input_tokens ?? 0} tokens de entrada (${u.cached_input_tokens ?? 0} em cache) · ${u.output_tokens ?? 0} de saída · Codex não informa custo em US$` }];
|
||
}
|
||
case "turn.failed":
|
||
case "error": {
|
||
const message = String((o.error as { message?: string } | undefined)?.message ?? o.message ?? "falha");
|
||
run("UPDATE agent_runs SET error = ? WHERE id = ?", message.slice(0, 2000), runId);
|
||
return [{ kind: "result", text: `Terminou com erro: ${truncate(message, 300)}`, isError: true }];
|
||
}
|
||
default:
|
||
return [];
|
||
}
|
||
}
|
||
|
||
function stripShell(command: string): string {
|
||
// `"...powershell.exe" -Command '...'` → só o comando interno
|
||
const m = /-Command '([\s\S]*)'$/.exec(command);
|
||
return m ? m[1] : command;
|
||
}
|
||
|
||
function summarizeInput(input: Record<string, unknown> | undefined): string {
|
||
if (!input) return "";
|
||
const v = input.file_path ?? input.path ?? input.pattern ?? input.command ?? input.description ?? input.skill;
|
||
return v ? truncate(String(v).replace(REPO_ROOT, "."), 200) : truncate(JSON.stringify(input), 200);
|
||
}
|
||
|
||
function stringify(content: unknown): string {
|
||
if (typeof content === "string") return content;
|
||
if (Array.isArray(content)) return content.map((c) => (typeof c === "object" && c && "text" in c ? String((c as { text: unknown }).text) : "")).join("\n");
|
||
return JSON.stringify(content ?? "");
|
||
}
|
||
|
||
function truncate(s: string, n: number): string {
|
||
return s.length > n ? s.slice(0, n) + "…" : s;
|
||
}
|