Spaces:
Runtime error
Runtime error
Uanderson Silva commited on
Commit ·
fc99222
1
Parent(s): 48c7a9b
create new frontend interface
Browse filesFiles changed (14)
- frontend/index.html+21-1
- frontend/src/App.tsx+125-362
- frontend/src/components/ArtifactPanel.tsxAdded+523
- frontend/src/components/ControlPanel.tsxAdded+443
- frontend/src/types.tsAdded+48
- frontend/src/utils/diff.tsAdded+54
- frontend/src/utils/status.tsAdded+100
- src/agents/auditor/agent.ts+10
- src/agents/coder/agent.ts+14-1
- src/agents/tester/agent.ts+11-1
- src/agents/tester/index.tsDeleted-28
- src/config/llm.ts+1-1
- src/logger.ts+23
- src/server.ts+3-1
2 unmodified lines34567892 unmodified lines<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Multi-Agent Smart Contracts</title></head><body><div id="root"></div>2 unmodified lines345678910111213141516171819202122232425262728292 unmodified lines<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>TALP1 — Smart Contract Agents</title><link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,400;0,500;0,600;0,700;1,400&display=swap" rel="stylesheet" /><style>*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }html, body { height: 100%; }body { overflow: hidden; background: #070c10; font-family: 'JetBrains Mono', 'Fira Code', monospace; }#root { height: 100%; }::-webkit-scrollbar { width: 5px; height: 5px; }::-webkit-scrollbar-track { background: transparent; }::-webkit-scrollbar-thumb { background: #21262d; border-radius: 3px; }::-webkit-scrollbar-thumb:hover { background: #30363d; }* { scrollbar-width: thin; scrollbar-color: #21262d transparent; }@keyframes spin { to { transform: rotate(360deg); } }@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }@keyframes fadein { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: translateY(0); } }@keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }</style></head><body><div id="root"></div>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555615 unmodified lines727374757677787980818283848586878889909192939495969798991001011 unmodified line103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430import { useState, useRef, useCallback } from "react";interface Finding {title: string;description: string;recommendation: string;severity: "high" | "medium" | "low";codeSnippet: string;location: string;path: string;judgeReview: {review: string;confidence: number;exploitablePaths: string[];};}interface AgentResult {contract?: string;compilationErrors?: string[];reviewSummary?: string;findings?: Finding[];// Tester fieldsstatus?: string;pocCode?: string;executionLogs?: string[];iterations?: number;}export function App() {const [requirements, setRequirements] = useState("");const [logs, setLogs] = useState<string[]>([]);const [coderResult, setCoderResult] = useState<AgentResult | null>(null);const [auditorResult, setAuditorResult] = useState<AgentResult | null>(null);const [testerResult, setTesterResult] = useState<AgentResult | null>(null);const [running, setRunning] = useState(false);const logsEndRef = useRef<HTMLDivElement>(null);const appendLog = useCallback((msg: string) => {setLogs((prev) => [...prev, msg]);setTimeout(() => logsEndRef.current?.scrollIntoView({ behavior: "smooth" }), 50);}, []);const handleSubmit = async (e: React.FormEvent) => {e.preventDefault();if (!requirements.trim() || running) return;setRunning(true);setLogs([]);setCoderResult(null);setAuditorResult(null);setTesterResult(null);appendLog("Iniciando pipeline...");try {const res = await fetch("/api/run", {15 unmodified linesbuffer += decoder.decode(value, { stream: true });const lines = buffer.split("\n");buffer = lines.pop() || "";for (const line of lines) {if (line.startsWith("event:")) {currentEvent = line.slice(6).trim();console.log("event", currentEvent);} else if (line.startsWith("data:")) {const data = line.slice(5).trim();console.log("data", data);switch (currentEvent) {case "log":appendLog(data);break;case "coder":setCoderResult(JSON.parse(data));break;case "auditor":setAuditorResult(JSON.parse(data));break;case "tester":setTesterResult(JSON.parse(data));break;case "error":appendLog(`❌ ERRO: ${data}`);break;}currentEvent = "";1 unmodified line}}} catch (err) {appendLog(`❌ Erro de conexão: ${err instanceof Error ? err.message : String(err)}`);} finally {setRunning(false);}};return (<div style={styles.container}><header style={styles.header}><h1 style={styles.title}>Multi-Agent: Geração, Auditoria e Teste de Smart Contracts</h1><p style={styles.subtitle}>Descreva um cenário ou requisito cuja solução seja um smart contract em Solidity. O sistema irá gerar,compilar, auditar e testar o contrato automaticamente.</p></header><form onSubmit={handleSubmit} style={styles.form}><textareavalue={requirements}onChange={(e) => setRequirements(e.target.value)}placeholder={"Ex: Crie um token ERC20 com as seguintes características:\n- Nome: MeuToken, Símbolo: MTK\n- Supply inicial de 1.000.000 tokens\n- Funções de mint (apenas owner) e burn\n- Pausável pelo owner"}style={styles.textarea}rows={6}disabled={running}/><buttontype="submit"disabled={running || !requirements.trim()}style={{...styles.button,opacity: running || !requirements.trim() ? 0.5 : 1,}}>{running ? "Executando pipeline..." : "Executar Pipeline"}</button></form>{/* Logs */}{logs.length > 0 && (<section style={styles.section}><h2 style={styles.sectionTitle}>📋 Log de Execução</h2><div style={styles.logBox}>{logs.map((log, i) => (<div key={i} style={styles.logLine}>{log}</div>))}<div ref={logsEndRef} /></div></section>)}{/* Coder */}{coderResult && (<section style={styles.section}><h2 style={styles.sectionTitle}>🔨 Agente Coder</h2><h3 style={styles.subTitle}>Contrato Gerado</h3><div style={styles.codeBox}><pre style={styles.code}>{coderResult.contract}</pre></div>{coderResult.compilationErrors && coderResult.compilationErrors.length > 0 && (<><h3 style={{ ...styles.subTitle, color: "#ef4444" }}>Erros de Compilação</h3><div style={{ ...styles.codeBox, borderColor: "#ef4444" }}><pre style={styles.code}>{coderResult.compilationErrors.join("\n")}</pre></div></>)}{coderResult.reviewSummary && (<><h3 style={styles.subTitle}>Revisão de Segurança</h3><div style={styles.resultBox}><p style={styles.resultText}>{coderResult.reviewSummary}</p></div></>)}</section>)}{/* Auditor */}{auditorResult && (<section style={styles.section}><h2 style={styles.sectionTitle}>🔍 Agente Auditor</h2>{auditorResult.findings && auditorResult.findings.length > 0 ? (auditorResult.findings.map((f, i) => (<div key={i} style={{ ...styles.findingCard, borderColor: severityColor(f.severity) }}><div style={styles.findingHeader}><span style={{ ...styles.severityBadge, background: severityColor(f.severity) }}>{f.severity.toUpperCase()}</span><span style={styles.findingTitle}>{f.title}</span></div><p style={styles.findingText}>{f.description}</p><p style={{ ...styles.findingText, color: "#94a3b8" }}><strong>Localização:</strong> {f.location ?? "-"}</p>{f.codeSnippet && <pre style={styles.code}>{f.codeSnippet}</pre>}<p style={{ ...styles.findingText, color: "#94a3b8" }}><strong>Recomendação:</strong> {f.recommendation}</p><p style={{ ...styles.findingText, color: "#64748b", fontSize: 12 }}>Confiança: {Math.round(f.judgeReview.confidence)}% — {f.judgeReview.review}</p></div>))) : (<div style={styles.resultBox}><p style={styles.resultText}>Nenhuma vulnerabilidade encontrada.</p></div>)}</section>)}{/* Tester */}{testerResult && (<section style={styles.section}><h2 style={styles.sectionTitle}>🧪 Agente Tester</h2><div style={styles.resultBox}><p style={styles.resultText}><strong>Status:</strong>{" "}<span style={{ color: testerResult.status === "success" ? "#22c55e" : "#ef4444" }}>{testerResult.status?.toUpperCase()}</span><br /><strong>Iterações:</strong> {testerResult.iterations}</p></div>{testerResult.pocCode && (<><h3 style={styles.subTitle}>Proof of Concept (Exploit)</h3><div style={styles.codeBox}><pre style={styles.code}>{testerResult.pocCode}</pre></div></>)}{testerResult.executionLogs && testerResult.executionLogs.length > 0 && (<><h3 style={styles.subTitle}>Logs de Execução (Foundry)</h3><div style={styles.logBox}>{testerResult.executionLogs.map((log, i) => (<div key={i} style={styles.logLine}>{log}</div>))}</div></>)}</section>)}</div>);}const severityColor = (severity: string) => {switch (severity) {case "high":return "#ef4444";case "medium":return "#f97316";case "low":return "#eab308";default:return "#64748b";}};const styles: Record<string, React.CSSProperties> = {container: {maxWidth: 900,margin: "0 auto",padding: "32px 20px",fontFamily: "'Segoe UI', system-ui, -apple-system, sans-serif",color: "#e2e8f0",background: "#0f172a",minHeight: "100vh",},header: {textAlign: "center",marginBottom: 32,},title: {fontSize: 28,fontWeight: 700,color: "#f8fafc",margin: "0 0 12px",lineHeight: 1.3,},subtitle: {fontSize: 15,color: "#94a3b8",margin: 0,lineHeight: 1.6,},form: {display: "flex",flexDirection: "column",gap: 12,marginBottom: 32,},textarea: {width: "100%",padding: 16,fontSize: 14,fontFamily: "inherit",borderRadius: 8,border: "1px solid #334155",background: "#1e293b",color: "#e2e8f0",resize: "vertical",outline: "none",boxSizing: "border-box",lineHeight: 1.6,},button: {padding: "12px 24px",fontSize: 15,fontWeight: 600,borderRadius: 8,border: "none",background: "#3b82f6",color: "#fff",cursor: "pointer",transition: "background 0.2s",},section: {marginBottom: 28,},sectionTitle: {fontSize: 18,fontWeight: 600,color: "#f8fafc",marginBottom: 10,},subTitle: {fontSize: 14,fontWeight: 600,color: "#94a3b8",marginTop: 14,marginBottom: 6,},logBox: {background: "#1e293b",border: "1px solid #334155",borderRadius: 8,padding: 16,maxHeight: 220,overflowY: "auto",fontSize: 13,fontFamily: "'JetBrains Mono', 'Fira Code', monospace",},logLine: {padding: "2px 0",color: "#a5f3fc",whiteSpace: "pre-wrap",wordBreak: "break-word",},codeBox: {background: "#1e293b",border: "1px solid #334155",borderRadius: 8,padding: 16,maxHeight: 400,overflowY: "auto",},code: {margin: 0,fontSize: 13,fontFamily: "'JetBrains Mono', 'Fira Code', monospace",color: "#a5f3fc",whiteSpace: "pre-wrap",wordBreak: "break-word",},resultBox: {background: "#1e293b",border: "1px solid #334155",borderRadius: 8,padding: 16,},resultText: {margin: 0,fontSize: 14,lineHeight: 1.6,color: "#cbd5e1",whiteSpace: "pre-wrap",},findingCard: {background: "#1e293b",border: "1px solid",borderRadius: 8,padding: 16,marginBottom: 12,},findingHeader: {display: "flex",alignItems: "center",gap: 10,marginBottom: 8,},severityBadge: {fontSize: 11,fontWeight: 700,color: "#fff",padding: "2px 8px",borderRadius: 4,letterSpacing: "0.05em",},findingTitle: {fontSize: 15,fontWeight: 600,color: "#f8fafc",},findingText: {margin: "4px 0",fontSize: 13,lineHeight: 1.6,color: "#cbd5e1",},};1234567891011121314151617181920212223242526272829303132333435363738394041424344454615 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491 unmodified line151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193import { useState, useRef, useCallback } from "react";import type { CoderResult, AuditorResult, TesterResult, AgentState } from "./types";import { computeDiff, type DiffLine } from "./utils/diff";import { INITIAL_AGENT_STATES, applyStepEvent, type StepEvent } from "./utils/status";import { ArtifactPanel } from "./components/ArtifactPanel";import { ControlPanel } from "./components/ControlPanel";export type ArtifactTab = "contract" | "findings" | "poc";export function App() {const [requirements, setRequirements] = useState("");const [running, setRunning] = useState(false);const [logs, setLogs] = useState<string[]>([]);const [coder, setCoder] = useState<CoderResult | null>(null);const [auditor, setAuditor] = useState<AuditorResult | null>(null);const [tester, setTester] = useState<TesterResult | null>(null);const [agentStates, setAgentStates] = useState<AgentState[]>(INITIAL_AGENT_STATES);const [selectedTab, setSelectedTab] = useState<ArtifactTab>("contract");const [contractDiff, setContractDiff] = useState<DiffLine[] | null>(null);const [pocDiff, setPocDiff] = useState<DiffLine[] | null>(null);const [diffMode, setDiffMode] = useState<Record<string, boolean>>({});const prevContract = useRef<string | null>(null);const prevPoc = useRef<string | null>(null);const appendLog = useCallback((msg: string) => {setLogs((prev) => [...prev, msg]);}, []);const handleRun = async (e: React.FormEvent) => {e.preventDefault();if (!requirements.trim() || running) return;setRunning(true);setLogs([]);setCoder(null);setAuditor(null);setTester(null);setAgentStates(INITIAL_AGENT_STATES);setContractDiff(null);setPocDiff(null);setSelectedTab("contract");try {const res = await fetch("/api/run", {15 unmodified linesbuffer += decoder.decode(value, { stream: true });const lines = buffer.split("\n");buffer = lines.pop() ?? "";for (const line of lines) {if (line.startsWith("event:")) {currentEvent = line.slice(6).trim();} else if (line.startsWith("data:")) {const data = line.slice(5).trim();switch (currentEvent) {case "log":appendLog(data);break;case "step": {const event: StepEvent = JSON.parse(data);setAgentStates((prev) => applyStepEvent(prev, event));break;}case "coder": {const result: CoderResult = JSON.parse(data);const hasPrev = prevContract.current !== null;const diff = computeDiff(prevContract.current, result.contract);prevContract.current = result.contract;setContractDiff(diff);setDiffMode((prev) => ({ ...prev, contract: hasPrev }));setCoder(result);setSelectedTab("contract");setAgentStates((prev) => {const s = prev.map((a) => ({ ...a, steps: a.steps.map((st) => ({ ...st })) }));const a = s.find((x) => x.id === "coder")!;a.status = "done";a.steps.forEach((st) => {if (st.status !== "error") st.status = "done";});return s;});break;}case "auditor": {const result: AuditorResult = JSON.parse(data);setAuditor(result);if (result.findings.length > 0) setSelectedTab("findings");setAgentStates((prev) => {const s = prev.map((a) => ({ ...a, steps: a.steps.map((st) => ({ ...st })) }));const a = s.find((x) => x.id === "auditor")!;a.status = "done";a.steps.forEach((st) => {if (st.status !== "error") st.status = "done";});return s;});break;}case "tester": {const result: TesterResult = JSON.parse(data);if (result.pocCode) {const hasPrev = prevPoc.current !== null;const diff = computeDiff(prevPoc.current, result.pocCode);prevPoc.current = result.pocCode;setPocDiff(diff);setDiffMode((prev) => ({ ...prev, poc: hasPrev }));setSelectedTab("poc");}setTester(result);setAgentStates((prev) => {const s = prev.map((a) => ({ ...a, steps: a.steps.map((st) => ({ ...st })) }));const a = s.find((x) => x.id === "tester")!;if (result.status === "skipped") {a.status = "skipped";a.steps.forEach((st) => {st.status = "skipped";});} else {a.status = result.status === "success" ? "done" : "error";a.steps.forEach((st) => {if (st.status !== "error") st.status = "done";});}return s;});break;}case "error":appendLog(`[ERRO] ${data}`);break;}currentEvent = "";1 unmodified line}}} catch (err) {appendLog(`[ERRO] ${err instanceof Error ? err.message : String(err)}`);} finally {setRunning(false);}};const toggleDiffMode = (key: string) => setDiffMode((prev) => ({ ...prev, [key]: !prev[key] }));return (<divstyle={{display: "flex",height: "100vh",background: "#070c10",overflow: "hidden",color: "#c9d1d9",}}><ControlPanelrequirements={requirements}onRequirementsChange={setRequirements}onRun={handleRun}running={running}agentStates={agentStates}logs={logs}/><ArtifactPanelcoder={coder}auditor={auditor}tester={tester}contractDiff={contractDiff}pocDiff={pocDiff}selectedTab={selectedTab}onSelectTab={setSelectedTab}diffMode={diffMode}onToggleDiff={toggleDiffMode}/></div>);}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523import type { CoderResult, AuditorResult, TesterResult, Finding } from "../types";import type { DiffLine } from "../utils/diff";import type { ArtifactTab } from "../App";
const C = { bg: "#0d1117", surface: "#161b22", border: "#21262d", text: "#c9d1d9", muted: "#8b949e", dim: "#484f58", accent: "#58a6ff", green: "#3fb950", red: "#f85149", yellow: "#d29922", orange: "#db6d28", addedBg: "rgba(46, 160, 67, 0.1)", removedBg: "rgba(248, 81, 73, 0.09)",};
const SEVERITY_COLOR: Record<string, string> = { high: C.red, medium: C.yellow, low: "#58a6ff",};
interface Props { coder: CoderResult | null; auditor: AuditorResult | null; tester: TesterResult | null; contractDiff: DiffLine[] | null; pocDiff: DiffLine[] | null; selectedTab: ArtifactTab; onSelectTab: (tab: ArtifactTab) => void; diffMode: Record<string, boolean>; onToggleDiff: (key: string) => void;}
export function ArtifactPanel({ coder, auditor, tester, contractDiff, pocDiff, selectedTab, onSelectTab, diffMode, onToggleDiff,}: Props) { const findingCount = auditor?.findings?.length ?? 0; const hasPoc = !!tester?.pocCode;
const treeItems: { id: ArtifactTab; icon: string; name: string; badge?: string; badgeColor?: string; available: boolean; }[] = [ { id: "contract", icon: "◈", name: "Contract.sol", badge: coder ? "sol" : undefined, badgeColor: C.accent, available: !!coder, }, { id: "findings", icon: "⚑", name: "findings/", badge: auditor ? (findingCount > 0 ? `${findingCount} issue${findingCount > 1 ? "s" : ""}` : "clean") : undefined, badgeColor: auditor ? (findingCount > 0 ? C.red : C.green) : C.dim, available: !!auditor, }, { id: "poc", icon: "◈", name: "ExploitTest.t.sol", badge: tester ? tester.status : undefined, badgeColor: tester?.status === "success" ? C.green : tester?.status === "failed" ? C.red : C.yellow, available: hasPoc, }, ];
return ( <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", overflow: "hidden", borderLeft: `1px solid ${C.border}`, background: C.bg, }} > {/* Panel titlebar */} <div style={{ height: 38, display: "flex", alignItems: "center", gap: 8, padding: "0 16px", borderBottom: `1px solid ${C.border}`, flexShrink: 0, }} > <span style={{ fontSize: 10, color: C.dim, letterSpacing: "0.12em", textTransform: "uppercase" }}> explorer </span> </div>
{/* File tree */} <div style={{ flexShrink: 0, borderBottom: `1px solid ${C.border}`, padding: "6px 0", }} > <div style={{ padding: "3px 16px 4px", display: "flex", alignItems: "center", gap: 6 }}> <span style={{ fontSize: 10, color: C.dim, letterSpacing: "0.08em" }}>▾</span> <span style={{ fontSize: 11, color: C.muted, letterSpacing: "0.05em" }}>artifacts</span> </div> {treeItems.map((item) => { const selected = selectedTab === item.id; return ( <button key={item.id} onClick={() => item.available && onSelectTab(item.id)} disabled={!item.available} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "4px 16px 4px 28px", background: selected ? "rgba(88, 166, 255, 0.08)" : "transparent", border: "none", borderLeft: selected ? `2px solid ${C.accent}` : "2px solid transparent", cursor: item.available ? "pointer" : "default", textAlign: "left", color: selected ? C.text : item.available ? C.muted : C.dim, fontSize: 13, transition: "background 0.1s", }} > <span style={{ fontSize: 10, color: selected ? C.accent : item.available ? C.dim : "#2d333b" }}> {item.icon} </span> <span style={{ flex: 1 }}>{item.name}</span> {item.badge && ( <span style={{ fontSize: 10, color: item.badgeColor, padding: "1px 5px", borderRadius: 3, border: `1px solid ${item.badgeColor}30`, background: `${item.badgeColor}12`, }} > {item.badge} </span> )} </button> ); })} </div>
{/* Content area */} <div style={{ flex: 1, overflow: "hidden", display: "flex", flexDirection: "column" }}> {selectedTab === "contract" && coder && contractDiff ? ( <CodeViewer title="Contract.sol" diff={contractDiff} showDiff={diffMode["contract"] ?? false} onToggleDiff={() => onToggleDiff("contract")} /> ) : selectedTab === "findings" && auditor ? ( <FindingsViewer findings={auditor.findings} reviewSummary={coder?.reviewSummary} /> ) : selectedTab === "poc" && tester?.pocCode && pocDiff ? ( <CodeViewer title="ExploitTest.t.sol" diff={pocDiff} showDiff={diffMode["poc"] ?? false} onToggleDiff={() => onToggleDiff("poc")} status={tester.status} iterations={tester.iterations} /> ) : ( <EmptyState /> )} </div> </div> );}
function CodeViewer({ title, diff, showDiff, onToggleDiff, status, iterations,}: { title: string; diff: DiffLine[]; showDiff: boolean; onToggleDiff: () => void; status?: string; iterations?: number;}) { const addedCount = diff.filter((l) => l.type === "added").length; const removedCount = diff.filter((l) => l.type === "removed").length; const totalLines = diff.filter((l) => l.type !== "removed").length; const hasDiff = addedCount > 0 || removedCount > 0; const hasChanges = diff.some((l) => l.type === "removed") || diff.some((l) => l.type === "added" && diff.some((x) => x.type === "unchanged"));
return ( <div style={{ display: "flex", flexDirection: "column", height: "100%", overflow: "hidden" }}> {/* Toolbar */} <div style={{ height: 36, display: "flex", alignItems: "center", padding: "0 16px", borderBottom: `1px solid ${C.border}`, gap: 10, flexShrink: 0, background: C.bg, }} > <span style={{ fontSize: 12, color: C.muted }}>{title}</span> {status && ( <span style={{ fontSize: 10, color: status === "success" ? C.green : status === "failed" ? C.red : C.yellow, padding: "1px 6px", border: `1px solid currentColor`, borderRadius: 3, opacity: 0.8, }} > {status} </span> )} {iterations !== undefined && iterations > 0 && ( <span style={{ fontSize: 10, color: C.dim }}>{iterations} iter</span> )} <span style={{ flex: 1 }} /> {hasDiff && ( <> {hasChanges && ( <span style={{ fontSize: 10, color: C.dim }}> <span style={{ color: C.green }}>+{addedCount}</span>{" "} <span style={{ color: C.red }}>-{removedCount}</span> </span> )} <button onClick={onToggleDiff} style={{ padding: "2px 8px", fontSize: 11, background: showDiff ? "rgba(88, 166, 255, 0.12)" : "transparent", border: `1px solid ${showDiff ? C.accent : C.border}`, color: showDiff ? C.accent : C.muted, cursor: "pointer", borderRadius: 3, fontFamily: "inherit", }} > diff </button> </> )} <span style={{ fontSize: 10, color: C.dim }}>{totalLines}L</span> </div>
{/* Code */} <div style={{ flex: 1, overflow: "auto", background: "#0a0e14" }}> <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5, lineHeight: 1.65, }} > <tbody> {diff.map((dl, idx) => { if (!showDiff && dl.type === "removed") return null; const isAdded = showDiff && dl.type === "added"; const isRemoved = showDiff && dl.type === "removed"; return ( <tr key={idx} style={{ background: isAdded ? C.addedBg : isRemoved ? C.removedBg : "transparent", }} > {showDiff && ( <td style={{ width: 18, textAlign: "center", color: isAdded ? C.green : isRemoved ? C.red : "transparent", fontSize: 11, userSelect: "none", paddingLeft: 8, paddingRight: 4, }} > {isAdded ? "+" : isRemoved ? "−" : " "} </td> )} <td style={{ width: 44, textAlign: "right", paddingRight: 14, paddingLeft: 8, color: isRemoved ? "#5e3535" : C.dim, userSelect: "none", fontSize: 11, }} > {dl.lineNo > 0 ? dl.lineNo : ""} </td> <td style={{ padding: "0 16px 0 0", color: isAdded ? "#b5e3b5" : isRemoved ? "#e5a0a0" : C.text, whiteSpace: "pre", fontFamily: "inherit", }} > {dl.line} </td> </tr> ); })} </tbody> </table> </div> </div> );}
function FindingsViewer({ findings, reviewSummary }: { findings: Finding[]; reviewSummary?: string }) { return ( <div style={{ flex: 1, overflow: "auto", padding: 20 }}> {/* Review summary */} {reviewSummary && ( <div style={{ marginBottom: 20 }}> <div style={{ fontSize: 10, color: C.dim, letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 8, }} > coder / security-review </div> <div style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: 6, padding: 14, fontSize: 12.5, color: C.muted, lineHeight: 1.7, whiteSpace: "pre-wrap", }} > {reviewSummary} </div> </div> )}
{/* Findings */} <div style={{ fontSize: 10, color: C.dim, letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 8, }} > auditor / findings — {findings.length} issue{findings.length !== 1 ? "s" : ""} </div>
{findings.length === 0 ? ( <div style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: 6, padding: 16, color: C.green, fontSize: 13, }} > ✓ Nenhuma vulnerabilidade encontrada. </div> ) : ( findings.map((f, i) => <FindingCard key={i} finding={f} index={i} />) )} </div> );}
function FindingCard({ finding, index }: { finding: Finding; index: number }) { const color = SEVERITY_COLOR[finding.severity] ?? C.muted;
return ( <div style={{ background: C.surface, border: `1px solid ${C.border}`, borderLeft: `3px solid ${color}`, borderRadius: 6, marginBottom: 12, overflow: "hidden", animation: "fadein 0.2s ease", }} > {/* Header */} <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", borderBottom: `1px solid ${C.border}`, }} > <span style={{ fontSize: 9, fontWeight: 700, color: color, padding: "2px 6px", border: `1px solid ${color}`, borderRadius: 3, letterSpacing: "0.1em", background: `${color}15`, }} > {finding.severity.toUpperCase()} </span> <span style={{ fontSize: 13, color: C.text, fontWeight: 600 }}> [{index + 1}] {finding.title} </span> {finding.location && <span style={{ marginLeft: "auto", fontSize: 10, color: C.dim }}>{finding.location}</span>} </div>
{/* Body */} <div style={{ padding: 14 }}> <p style={{ fontSize: 12.5, color: C.muted, lineHeight: 1.7, marginBottom: 10 }}>{finding.description}</p>
{finding.codeSnippet && ( <div style={{ background: "#0a0e14", border: `1px solid ${C.border}`, borderRadius: 4, padding: "8px 12px", marginBottom: 10, fontSize: 12, color: "#b5c0cc", whiteSpace: "pre", overflow: "auto", maxHeight: 140, fontFamily: "inherit", }} > {finding.codeSnippet} </div> )}
<div style={{ fontSize: 12, color: C.muted, marginBottom: 6 }}> <span style={{ color: C.dim }}>recomendação: </span> {finding.recommendation} </div>
<div style={{ fontSize: 11, color: C.dim, marginTop: 8 }}> confiança: {Math.round(finding.judgeReview.confidence)}% — {finding.judgeReview.review} </div> </div> </div> );}
function EmptyState() { return ( <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", color: C.dim, gap: 12, }} > <div style={{ fontSize: 28, opacity: 0.3 }}>◈</div> <div style={{ fontSize: 12, letterSpacing: "0.05em" }}>aguardando execução do pipeline</div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443import { useEffect, useRef } from "react";
import type { AgentState, StepStatus } from "../types";
const C = { bg: "#0d1117", surface: "#161b22", border: "#21262d", text: "#c9d1d9", muted: "#8b949e", dim: "#484f58", accent: "#58a6ff", green: "#3fb950", red: "#f85149", yellow: "#d29922",};
const AGENT_COLORS: Record<string, string> = { coder: "#58a6ff", auditor: "#d29922", tester: "#3fb950",};
const DEFAULT_REQUIREMENT = `Crie um contrato de staking com as seguintes características:- Usuários podem depositar ETH e receber créditos proporcionais ao valor- O owner pode pausar e retomar os depósitos- Função de saque que devolve ETH proporcional ao crédito do usuário- Acumula recompensas de 1% ao dia sobre o saldo depositado- Emite eventos para depósito, saque e distribuição de recompensas`;
interface Props { requirements: string; onRequirementsChange: (v: string) => void; onRun: (e: React.FormEvent) => void; running: boolean; agentStates: AgentState[]; logs: string[];}
export function ControlPanel({ requirements, onRequirementsChange, onRun, running, agentStates, logs }: Props) { return ( <div style={{ width: 400, flexShrink: 0, display: "flex", flexDirection: "column", background: C.bg, overflow: "hidden", }} > <Header /> <InputForm requirements={requirements} onChange={onRequirementsChange} onRun={onRun} running={running} /> <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden", minHeight: 0 }}> <PipelineStatus agents={agentStates} running={running} /> <TerminalLog logs={logs} /> </div> </div> );}
function Header() { return ( <div style={{ padding: "14px 18px 10px", borderBottom: `1px solid ${C.border}`, flexShrink: 0, }} > <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 3 }}> <span style={{ fontSize: 15, fontWeight: 700, color: C.accent, letterSpacing: "0.05em" }}>TALP1</span> <span style={{ fontSize: 10, color: C.dim }}>v0.1</span> </div> <div style={{ fontSize: 11, color: C.dim, lineHeight: 1.5 }}>multi-agent smart contract pipeline</div> </div> );}
function InputForm({ requirements, onChange, onRun, running,}: { requirements: string; onChange: (v: string) => void; onRun: (e: React.FormEvent) => void; running: boolean;}) { const canRun = !running && requirements.trim().length > 0;
return ( <form onSubmit={onRun} style={{ padding: "12px 18px", borderBottom: `1px solid ${C.border}`, flexShrink: 0, display: "flex", flexDirection: "column", gap: 8, }} > <div style={{ fontSize: 10, color: C.dim, letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 2 }}> requisitos </div> <textarea value={requirements} onChange={(e) => onChange(e.target.value)} disabled={running} rows={5} placeholder="Descreva o smart contract a ser gerado, auditado e testado..." style={{ width: "100%", padding: "10px 12px", fontSize: 12, fontFamily: "inherit", background: C.surface, border: `1px solid ${C.border}`, borderRadius: 5, color: C.text, resize: "none", outline: "none", lineHeight: 1.65, transition: "border-color 0.15s", }} onFocus={(e) => (e.target.style.borderColor = `${C.accent}60`)} onBlur={(e) => (e.target.style.borderColor = C.border)} /> <div style={{ display: "flex", gap: 8 }}> <button type="button" onClick={() => onChange(DEFAULT_REQUIREMENT)} disabled={running} style={{ padding: "7px 10px", fontSize: 11, fontFamily: "inherit", background: "transparent", border: `1px solid ${C.border}`, borderRadius: 4, color: C.muted, cursor: running ? "default" : "pointer", opacity: running ? 0.4 : 1, whiteSpace: "nowrap", }} > usar exemplo </button> <button type="submit" disabled={!canRun} style={{ flex: 1, padding: "7px 14px", fontSize: 12, fontFamily: "inherit", fontWeight: 600, background: canRun ? C.accent : "transparent", border: `1px solid ${canRun ? C.accent : C.border}`, borderRadius: 4, color: canRun ? "#fff" : C.dim, cursor: canRun ? "pointer" : "default", transition: "all 0.15s", display: "flex", alignItems: "center", justifyContent: "center", gap: 7, }} > {running && ( <span style={{ width: 10, height: 10, borderRadius: "50%", border: "1.5px solid rgba(255,255,255,0.3)", borderTopColor: "#fff", display: "inline-block", animation: "spin 0.7s linear infinite", flexShrink: 0, }} /> )} {running ? "executando..." : "▶ executar"} </button> </div> </form> );}
function PipelineStatus({ agents, running }: { agents: AgentState[]; running: boolean }) { const anyActive = agents.some((a) => a.status === "running");
return ( <div style={{ flexShrink: 0, borderBottom: `1px solid ${C.border}`, padding: "10px 0", maxHeight: 280, overflow: "auto", }} > <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "0 18px 6px", }} > <span style={{ fontSize: 10, color: C.dim, letterSpacing: "0.1em", textTransform: "uppercase" }}>pipeline</span> {anyActive && ( <span style={{ width: 6, height: 6, borderRadius: "50%", background: C.accent, animation: "pulse 1.2s ease-in-out infinite", flexShrink: 0, }} /> )} </div>
{agents.map((agent) => ( <AgentBlock key={agent.id} agent={agent} /> ))} </div> );}
function AgentBlock({ agent }: { agent: AgentState }) { const color = AGENT_COLORS[agent.id] ?? C.muted; const isRunning = agent.status === "running"; const isDone = agent.status === "done"; const isError = agent.status === "error"; const isSkipped = agent.status === "skipped";
return ( <div style={{ padding: "4px 18px" }}> {/* Agent header */} <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}> <AgentDot status={agent.status} color={color} /> <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.08em", color: isDone || isRunning ? color : C.dim, }} > {agent.label} </span> <span style={{ marginLeft: "auto", fontSize: 10, color: isDone ? C.green : isError ? C.red : isSkipped ? C.dim : isRunning ? color : C.dim, opacity: isDone || isError || isSkipped || isRunning ? 1 : 0.5, }} > {isDone ? "done" : isError ? "error" : isSkipped ? "skip" : isRunning ? "running" : "pending"} </span> </div>
{/* Steps */} <div style={{ paddingLeft: 20 }}> {agent.steps.map((step) => ( <StepRow key={step.id} step={step} agentColor={color} /> ))} </div> </div> );}
function AgentDot({ status, color }: { status: StepStatus; color: string }) { if (status === "running") { return ( <span style={{ width: 8, height: 8, borderRadius: "50%", border: `1.5px solid ${color}40`, borderTopColor: color, display: "inline-block", animation: "spin 0.7s linear infinite", flexShrink: 0, }} /> ); } if (status === "done") { return <span style={{ color, fontSize: 10, lineHeight: 1 }}>✓</span>; } if (status === "error") { return <span style={{ color: C.red, fontSize: 10, lineHeight: 1 }}>✗</span>; } if (status === "skipped") { return <span style={{ color: C.dim, fontSize: 10, lineHeight: 1 }}>–</span>; } return <span style={{ color: C.dim, fontSize: 10, lineHeight: 1 }}>○</span>;}
function StepRow({ step, agentColor,}: { step: { label: string; status: StepStatus; detail?: string }; agentColor: string;}) { const isRunning = step.status === "running"; const isDone = step.status === "done"; const isError = step.status === "error"; const isSkipped = step.status === "skipped";
return ( <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "2px 0", fontSize: 11, color: isDone ? C.muted : isRunning ? C.text : C.dim, animation: isRunning ? "fadein 0.15s ease" : undefined, }} > <span style={{ width: 10, flexShrink: 0, textAlign: "center" }}> {isDone ? ( <span style={{ color: C.green, fontSize: 9 }}>✓</span> ) : isRunning ? ( <span style={{ width: 6, height: 6, borderRadius: "50%", border: `1px solid ${agentColor}40`, borderTopColor: agentColor, display: "inline-block", animation: "spin 0.7s linear infinite", }} /> ) : isError ? ( <span style={{ color: C.red, fontSize: 9 }}>✗</span> ) : isSkipped ? ( <span style={{ color: C.dim, fontSize: 9 }}>–</span> ) : ( <span style={{ color: C.dim, fontSize: 9 }}>·</span> )} </span> <span>{step.label}</span> {step.detail && <span style={{ color: agentColor, fontSize: 10, opacity: 0.8 }}>{step.detail}</span>} </div> );}
function logColor(log: string): string { if (log.includes("[Coder]")) return "#58a6ff"; if (log.includes("[Auditor]")) return "#d29922"; if (log.includes("[Tester]")) return "#3fb950"; if (log.includes("[ERRO]") || log.toLowerCase().startsWith("error")) return "#f85149"; if (log === "Pipeline concluído.") return "#3fb950"; return "#6e7681";}
function TerminalLog({ logs }: { logs: string[] }) { const endRef = useRef<HTMLDivElement>(null);
useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [logs]);
return ( <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden", minHeight: 0 }}> <div style={{ padding: "6px 18px 4px", borderBottom: `1px solid ${C.border}`, flexShrink: 0, display: "flex", alignItems: "center", gap: 8, }} > <span style={{ fontSize: 10, color: C.dim, letterSpacing: "0.1em", textTransform: "uppercase" }}>terminal</span> {logs.length > 0 && <span style={{ fontSize: 10, color: C.dim }}>{logs.length} lines</span>} </div> <div style={{ flex: 1, overflow: "auto", padding: "10px 18px", background: "#070c10", fontSize: 11.5, lineHeight: 1.7, }} > {logs.length === 0 ? ( <span style={{ color: C.dim }}> <BlinkCursor /> </span> ) : ( logs.map((log, i) => ( <div key={i} style={{ color: logColor(log), display: "flex", gap: 8, animation: "fadein 0.1s ease", }} > <span style={{ color: C.dim, userSelect: "none", flexShrink: 0 }}>›</span> <span style={{ wordBreak: "break-word", whiteSpace: "pre-wrap" }}>{log}</span> </div> )) )} <div ref={endRef} /> </div> </div> );}
function BlinkCursor() { return ( <span style={{ display: "inline-block", width: 7, height: 13, background: C.dim, verticalAlign: "middle", animation: "blink 1.2s step-end infinite", borderRadius: 1, }} /> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748export interface Finding { title: string; description: string; recommendation: string; severity: "high" | "medium" | "low"; codeSnippet: string; location: string; path: string; judgeReview: { review: string; confidence: number; exploitablePaths: string[]; };}
export interface CoderResult { contract: string; compilationErrors: string[]; reviewSummary: string;}
export interface AuditorResult { findings: Finding[];}
export interface TesterResult { status: "success" | "failed" | "timeout" | "skipped" | "running"; pocCode?: string; executionLogs?: string[]; iterations: number;}
export type StepStatus = "pending" | "running" | "done" | "error" | "skipped";
export interface PipelineStep { id: string; label: string; status: StepStatus; detail?: string;}
export interface AgentState { id: "coder" | "auditor" | "tester"; label: string; color: string; status: StepStatus; steps: PipelineStep[];}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354export interface DiffLine { type: "added" | "removed" | "unchanged"; line: string; lineNo: number;}
export function computeDiff(prev: string | null, next: string): DiffLine[] { const nextLines = next.split("\n");
if (!prev) { return nextLines.map((line, i) => ({ type: "added", line, lineNo: i + 1 })); } if (prev === next) { return nextLines.map((line, i) => ({ type: "unchanged", line, lineNo: i + 1 })); }
const prevLines = prev.split("\n"); const m = prevLines.length; const n = nextLines.length;
if (m > 600 || n > 600) { return nextLines.map((line, i) => ({ type: "added", line, lineNo: i + 1 })); }
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0) as number[]); for (let i = 1; i <= m; i++) { for (let j = 1; j <= n; j++) { dp[i][j] = prevLines[i - 1] === nextLines[j - 1] ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]); } }
const result: DiffLine[] = []; let i = m; let j = n; while (i > 0 || j > 0) { if (i > 0 && j > 0 && prevLines[i - 1] === nextLines[j - 1]) { result.unshift({ type: "unchanged", line: nextLines[j - 1], lineNo: j }); i--; j--; } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) { result.unshift({ type: "added", line: nextLines[j - 1], lineNo: j }); j--; } else { result.unshift({ type: "removed", line: prevLines[i - 1], lineNo: 0 }); i--; } }
return result;}
export function diffHasChanges(lines: DiffLine[]): boolean { return lines.some((l) => l.type !== "unchanged");}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import type { AgentState, StepStatus } from "../types";
export interface StepEvent { agent: "coder" | "auditor" | "tester"; step: string; status: "running" | "done" | "error" | "skipped"; detail?: string;}
export const INITIAL_AGENT_STATES: AgentState[] = [ { id: "coder", label: "CODER", color: "#58a6ff", status: "pending", steps: [ { id: "coder.gen", label: "Gerando contrato", status: "pending" }, { id: "coder.compile", label: "Compilando", status: "pending" }, { id: "coder.review", label: "Revisando segurança", status: "pending" }, ], }, { id: "auditor", label: "AUDITOR", color: "#d29922", status: "pending", steps: [ { id: "audit.scope", label: "Mapeando escopo", status: "pending" }, { id: "audit.ctx", label: "Coletando contexto", status: "pending" }, { id: "audit.find", label: "Analisando vulnerabilidades", status: "pending" }, { id: "audit.judge", label: "Julgando findings", status: "pending" }, ], }, { id: "tester", label: "TESTER", color: "#3fb950", status: "pending", steps: [ { id: "test.oracle", label: "Preparando scaffold", status: "pending" }, { id: "test.gen", label: "Gerando PoC", status: "pending" }, { id: "test.run", label: "Executando Foundry", status: "pending" }, { id: "test.reflect", label: "Analisando falha", status: "pending" }, ], },];
const AGENT_ORDER = ["coder", "auditor", "tester"] as const;
const STEP_PREFIX: Record<string, string> = { coder: "coder.", auditor: "audit.", tester: "test.",};
export function applyStepEvent(states: AgentState[], event: StepEvent): AgentState[] { const s = states.map((a) => ({ ...a, steps: a.steps.map((st) => ({ ...st })) }));
const fullStepId = STEP_PREFIX[event.agent] + event.step;
if (event.status === "running") { // Mark all preceding agents as done when a new agent starts its first step const agentIndex = AGENT_ORDER.indexOf(event.agent); for (let i = 0; i < agentIndex; i++) { const prev = s.find((a) => a.id === AGENT_ORDER[i]); if (prev && prev.status !== "done" && prev.status !== "error") { prev.status = "done"; prev.steps.forEach((st) => { if (st.status === "pending") st.status = "done"; }); } }
const agent = s.find((a) => a.id === event.agent); if (agent && agent.status === "pending") agent.status = "running"; }
// Update the step const step = s.flatMap((a) => a.steps).find((st) => st.id === fullStepId); if (step) { step.status = event.status; if (event.detail !== undefined) step.detail = event.detail; }
// When a step finishes, check if all steps are settled → update agent status if (event.status !== "running") { const agent = s.find((a) => a.id === event.agent); if (agent) { const settled: StepStatus[] = ["done", "error", "skipped"]; const allSettled = agent.steps.every((st) => settled.includes(st.status)); if (allSettled) { const hasError = agent.steps.some((st) => st.status === "error"); const allSkipped = agent.steps.every((st) => st.status === "skipped"); agent.status = hasError ? "error" : allSkipped ? "skipped" : "done"; } } }
return s;}6 unmodified lines78910111244 unmodified lines5758596061628 unmodified lines7172737475767778798046 unmodified lines12712812913013113213 unmodified lines14614714814915015129 unmodified lines18118218318418518618718818919019119244 unmodified lines2372382392402412426 unmodified linesimport { logger } from "../../logger.ts";import { createLLM } from "../../config/llm.ts";import { JUDGE_FINDINGS_PROMPT, FIND_VULNERABILITIES_PROMPT, GATHER_CONTEXT_PROMPT } from "./prompts.ts";import { AuditorState, JudgeReviewSchema, CandidateFindingSchema } from "./state.ts";import { analyzeSolidityFile } from "./tools/solidity-analyzer-tool.ts";44 unmodified lines};const defineScope: GraphNode<typeof AuditorState> = async (state) => {logger.info(`[Auditor] defineScope: percorrendo repositório em ${state.repoPath}`);const solFiles: string[] = [];8 unmodified lineslogger.debug(`[Auditor] defineScope: arquivos de documentação: ${JSON.stringify(docFiles)}`);logger.debug(`[Auditor] defineScope: árvore de arquivos:\n${fileTree}`);return { scope: solFiles, docs: docFiles, fileTree };};const gatherContext: GraphNode<typeof AuditorState> = async (state) => {logger.info(`[Auditor] gatherContext: processando ${state.scope.length} arquivo(s) Solidity e ${state.docs.length} arquivo(s) de documentação`);const readFile = (filePath: string): string => {46 unmodified lineslogger.info(`[Auditor] gatherContext: contexto construído (${parts.join("\n\n").length} caracteres)`);logger.debug(`[Auditor] gatherContext: contexto completo:\n${parts.join("\n\n")}`);return { repoContext: result.context };};13 unmodified lineslogger.info(`[Auditor] findVulnerabilities: invocando LLM para ${state.scope.length} arquivo(s) em paralelo (iteração ${state.reflectionCount + 1})`,);const allFindings = await Promise.all(state.scope.map(async (filePath) => {29 unmodified lineslogger.info(`[Auditor] findVulnerabilities: LLM retornou ${candidateFindings.length} finding(s) candidato(s) no total`);logger.debug(`[Auditor] findVulnerabilities: findings:\n${JSON.stringify(candidateFindings, null, 2)}`);return { candidateFindings };};const judgeFindings: GraphNode<typeof AuditorState> = async (state) => {if (state.candidateFindings.length === 0) {logger.info("[Auditor] judgeFindings: sem findings candidatos para revisar, pulando chamada ao LLM");return {judgeReviews: [],findings: [],44 unmodified lineslogger.info(`[Auditor] judgeFindings: ${findings.length} confirmado(s), ${falsePositiveCount} falso(s) positivo(s)`);logger.debug(`[Auditor] judgeFindings: revisões:\n${JSON.stringify(reviews, null, 2)}`);return {judgeReviews: reviews,findings,6 unmodified lines7891011121344 unmodified lines585960616263648 unmodified lines73747576777879808182838446 unmodified lines13113213313413513613713 unmodified lines15115215315415515615729 unmodified lines18718818919019119219319419519619719819920020144 unmodified lines2462472482492502512526 unmodified linesimport { logger } from "../../logger.ts";import { createLLM } from "../../config/llm.ts";import { emitStep } from "../../logger.ts";import { JUDGE_FINDINGS_PROMPT, FIND_VULNERABILITIES_PROMPT, GATHER_CONTEXT_PROMPT } from "./prompts.ts";import { AuditorState, JudgeReviewSchema, CandidateFindingSchema } from "./state.ts";import { analyzeSolidityFile } from "./tools/solidity-analyzer-tool.ts";44 unmodified lines};const defineScope: GraphNode<typeof AuditorState> = async (state) => {emitStep({ agent: "auditor", step: "scope", status: "running" });logger.info(`[Auditor] defineScope: percorrendo repositório em ${state.repoPath}`);const solFiles: string[] = [];8 unmodified lineslogger.debug(`[Auditor] defineScope: arquivos de documentação: ${JSON.stringify(docFiles)}`);logger.debug(`[Auditor] defineScope: árvore de arquivos:\n${fileTree}`);emitStep({ agent: "auditor", step: "scope", status: "done" });return { scope: solFiles, docs: docFiles, fileTree };};const gatherContext: GraphNode<typeof AuditorState> = async (state) => {emitStep({ agent: "auditor", step: "ctx", status: "running" });logger.info(`[Auditor] gatherContext: processando ${state.scope.length} arquivo(s) Solidity e ${state.docs.length} arquivo(s) de documentação`);const readFile = (filePath: string): string => {46 unmodified lineslogger.info(`[Auditor] gatherContext: contexto construído (${parts.join("\n\n").length} caracteres)`);logger.debug(`[Auditor] gatherContext: contexto completo:\n${parts.join("\n\n")}`);emitStep({ agent: "auditor", step: "ctx", status: "done" });return { repoContext: result.context };};13 unmodified lineslogger.info(`[Auditor] findVulnerabilities: invocando LLM para ${state.scope.length} arquivo(s) em paralelo (iteração ${state.reflectionCount + 1})`,);emitStep({ agent: "auditor", step: "find", status: "running", detail: `iter ${state.reflectionCount + 1}` });const allFindings = await Promise.all(state.scope.map(async (filePath) => {29 unmodified lineslogger.info(`[Auditor] findVulnerabilities: LLM retornou ${candidateFindings.length} finding(s) candidato(s) no total`);logger.debug(`[Auditor] findVulnerabilities: findings:\n${JSON.stringify(candidateFindings, null, 2)}`);emitStep({ agent: "auditor", step: "find", status: "done" });return { candidateFindings };};const judgeFindings: GraphNode<typeof AuditorState> = async (state) => {emitStep({ agent: "auditor", step: "judge", status: "running" });if (state.candidateFindings.length === 0) {logger.info("[Auditor] judgeFindings: sem findings candidatos para revisar, pulando chamada ao LLM");emitStep({ agent: "auditor", step: "judge", status: "done" });return {judgeReviews: [],findings: [],44 unmodified lineslogger.info(`[Auditor] judgeFindings: ${findings.length} confirmado(s), ${falsePositiveCount} falso(s) positivo(s)`);logger.debug(`[Auditor] judgeFindings: revisões:\n${JSON.stringify(reviews, null, 2)}`);emitStep({ agent: "auditor", step: "judge", status: "done" });return {judgeReviews: reviews,findings,
3 unmodified lines45678911 unmodified lines2122232425266 unmodified lines3334353637381 unmodified line40414243444546474849501 unmodified line52535455565715 unmodified lines7374757677787 unmodified lines8687888990918 unmodified lines1001011021031041051063 unmodified linesimport { solidityCoderPrompt, solidityFixPrompt, solidityReviewPrompt } from "./prompts.ts";import { compileSolidityTool } from "./tools/compile-solidity.ts";import { createLLM } from "../../config/llm.ts";const MAX_FIX_ATTEMPTS = 3;11 unmodified lines* Nó 1: Gera o smart contract a partir dos requisitos.*/const generateContract: GraphNode<typeof CoderState> = async (state) => {const llm = createLLM();const chain = solidityCoderPrompt.pipe(llm);6 unmodified linestypeof result.content === "string" ? result.content : JSON.stringify(result.content),);return { contract: code, compilationErrors: [] };};1 unmodified line* Nó 2: Compila o contrato e armazena erros (se houver).*/const compileContract: GraphNode<typeof CoderState> = async (state) => {const result = await compileSolidityTool.invoke({sourceCode: state.contract,filename: "Contract.sol",});return { compilationErrors: result.errors };};1 unmodified line* Nó 3: Corrige o contrato com base nos erros de compilação.*/const fixContract: GraphNode<typeof CoderState> = async (state) => {const llm = createLLM();const chain = solidityFixPrompt.pipe(llm);15 unmodified lines* Nó 4: Revisa o contrato compilado quanto a segurança e boas práticas.*/const reviewContract: GraphNode<typeof CoderState> = async (state) => {const llm = createLLM();const chain = solidityReviewPrompt.pipe(llm);7 unmodified linesconst summary =typeof result.content === "string" ? result.content : JSON.stringify(result.content);return { reviewSummary: summary };};8 unmodified linesfixAttempts++;return "fixContract";}fixAttempts = 0; // reset para próxima execuçãoreturn "reviewContract";}3 unmodified lines4567891011 unmodified lines222324252627286 unmodified lines353637383940411 unmodified line4344454647484950515253545556571 unmodified line5960616263646515 unmodified lines818283848586877 unmodified lines95969798991001018 unmodified lines1101111121131141151161171181193 unmodified linesimport { solidityCoderPrompt, solidityFixPrompt, solidityReviewPrompt } from "./prompts.ts";import { compileSolidityTool } from "./tools/compile-solidity.ts";import { createLLM } from "../../config/llm.ts";import { emitStep } from "../../logger.ts";const MAX_FIX_ATTEMPTS = 3;11 unmodified lines* Nó 1: Gera o smart contract a partir dos requisitos.*/const generateContract: GraphNode<typeof CoderState> = async (state) => {emitStep({ agent: "coder", step: "gen", status: "running" });const llm = createLLM();const chain = solidityCoderPrompt.pipe(llm);6 unmodified linestypeof result.content === "string" ? result.content : JSON.stringify(result.content),);emitStep({ agent: "coder", step: "gen", status: "done" });return { contract: code, compilationErrors: [] };};1 unmodified line* Nó 2: Compila o contrato e armazena erros (se houver).*/const compileContract: GraphNode<typeof CoderState> = async (state) => {emitStep({ agent: "coder", step: "compile", status: "running" });const result = await compileSolidityTool.invoke({sourceCode: state.contract,filename: "Contract.sol",});if (result.errors.length === 0) {emitStep({ agent: "coder", step: "compile", status: "done" });}return { compilationErrors: result.errors };};1 unmodified line* Nó 3: Corrige o contrato com base nos erros de compilação.*/const fixContract: GraphNode<typeof CoderState> = async (state) => {emitStep({ agent: "coder", step: "compile", status: "running", detail: `fix ${fixAttempts}/${MAX_FIX_ATTEMPTS}` });const llm = createLLM();const chain = solidityFixPrompt.pipe(llm);15 unmodified lines* Nó 4: Revisa o contrato compilado quanto a segurança e boas práticas.*/const reviewContract: GraphNode<typeof CoderState> = async (state) => {emitStep({ agent: "coder", step: "review", status: "running" });const llm = createLLM();const chain = solidityReviewPrompt.pipe(llm);7 unmodified linesconst summary =typeof result.content === "string" ? result.content : JSON.stringify(result.content);emitStep({ agent: "coder", step: "review", status: "done" });return { reviewSummary: summary };};8 unmodified linesfixAttempts++;return "fixContract";}if (state.compilationErrors.length > 0) {emitStep({ agent: "coder", step: "compile", status: "error" });}fixAttempts = 0;return "reviewContract";}
7 unmodified lines89101112131415161718192021222324252628 unmodified lines5556575859602 unmodified lines636465666768697071727374757635 unmodified lines1121131141151161172 unmodified lines12012112212312412512 unmodified lines1381391401411421437 unmodified linesimport { extractSolidity } from "./utils/extractSolidity.js";import { runFoundry } from "./tools/foundryRunner.js";import { analyzeFoundryLog } from "./utils/logAnalyzer.js";import { logger } from "../../logger.ts";const MAX_ITERATIONS = 5;const llm = createLLM();async function oracleNode(state: PoCState): Promise<Partial<PoCState>> {logger.info(`[Tester] oracleNode: gerando scaffold para: ${state.report.title}`);const solidityScaffold = generateLocalScaffold(state.report);const oracleContext: OracleContext = { solidityScaffold };logger.info(`[Tester] oracleNode: scaffold gerado, tamanho: ${solidityScaffold.length} chars`);return { oracleContext };}28 unmodified lines\`\`\``;logger.info(`[Tester] generatePoCNode: iteração ${iterations + 1}, isRetry=${isRetry}`);try {const response = await llm.invoke([2 unmodified lines]);const solidityCode = extractSolidity(response.content as string);logger.info(`[Tester] generatePoCNode: Solidity extraído, tamanho: ${solidityCode.length}`);return { pocCode: solidityCode, iterations: 1 };} catch (err) {logger.error(`[Tester] generatePoCNode: falha na geração: ${(err as Error).message}`);return { iterations: 1, lastError: `Erro na geração/extração: ${(err as Error).message}` };}}async function runFoundryNode(state: PoCState): Promise<Partial<PoCState>> {logger.info("[Tester] runFoundryNode: executando...");const trimmedCode = state.pocCode.trim();35 unmodified lineslogger.info(`[Tester] runFoundryNode: falha detectada: ${analysis.summary}`);}return {executionLogs: [result.combined], // reducer appendlastError: summary,2 unmodified lines}async function reflectNode(state: PoCState): Promise<Partial<PoCState>> {const lastLog = state.executionLogs[state.executionLogs.length - 1];if (!lastLog) {return { lastError: "Sem logs disponíveis para análise." };12 unmodified lineslogger.info(`[Tester] reflectNode: categoria: ${analysis.category}`);logger.info(`[Tester] reflectNode: resumo: ${analysis.summary}`);return {lastError: `[${analysis.category.toUpperCase()}] ${analysis.summary}\n\nLinhas relevantes:\n${analysis.relevantLines.join("\n")}`,};7 unmodified lines891011121314151617181920212223242526272828 unmodified lines575859606162632 unmodified lines666768697071727374757677787980818235 unmodified lines1181191201211221231241252 unmodified lines12812913013113213313412 unmodified lines1471481491501511521537 unmodified linesimport { extractSolidity } from "./utils/extractSolidity.js";import { runFoundry } from "./tools/foundryRunner.js";import { analyzeFoundryLog } from "./utils/logAnalyzer.js";import { logger, emitStep } from "../../logger.ts";const MAX_ITERATIONS = 5;const llm = createLLM();async function oracleNode(state: PoCState): Promise<Partial<PoCState>> {emitStep({ agent: "tester", step: "oracle", status: "running" });logger.info(`[Tester] oracleNode: gerando scaffold para: ${state.report.title}`);const solidityScaffold = generateLocalScaffold(state.report);const oracleContext: OracleContext = { solidityScaffold };logger.info(`[Tester] oracleNode: scaffold gerado, tamanho: ${solidityScaffold.length} chars`);emitStep({ agent: "tester", step: "oracle", status: "done" });return { oracleContext };}28 unmodified lines\`\`\``;logger.info(`[Tester] generatePoCNode: iteração ${iterations + 1}, isRetry=${isRetry}`);emitStep({ agent: "tester", step: "gen", status: "running", detail: `iter ${iterations + 1}` });try {const response = await llm.invoke([2 unmodified lines]);const solidityCode = extractSolidity(response.content as string);logger.info(`[Tester] generatePoCNode: Solidity extraído, tamanho: ${solidityCode.length}`);emitStep({ agent: "tester", step: "gen", status: "done" });return { pocCode: solidityCode, iterations: 1 };} catch (err) {logger.error(`[Tester] generatePoCNode: falha na geração: ${(err as Error).message}`);emitStep({ agent: "tester", step: "gen", status: "error" });return { iterations: 1, lastError: `Erro na geração/extração: ${(err as Error).message}` };}}async function runFoundryNode(state: PoCState): Promise<Partial<PoCState>> {emitStep({ agent: "tester", step: "run", status: "running" });logger.info("[Tester] runFoundryNode: executando...");const trimmedCode = state.pocCode.trim();35 unmodified lineslogger.info(`[Tester] runFoundryNode: falha detectada: ${analysis.summary}`);}emitStep({ agent: "tester", step: "run", status: passed ? "done" : result.timedOut ? "error" : "done" });return {executionLogs: [result.combined], // reducer appendlastError: summary,2 unmodified lines}async function reflectNode(state: PoCState): Promise<Partial<PoCState>> {emitStep({ agent: "tester", step: "reflect", status: "running" });const lastLog = state.executionLogs[state.executionLogs.length - 1];if (!lastLog) {return { lastError: "Sem logs disponíveis para análise." };12 unmodified lineslogger.info(`[Tester] reflectNode: categoria: ${analysis.category}`);logger.info(`[Tester] reflectNode: resumo: ${analysis.summary}`);emitStep({ agent: "tester", step: "reflect", status: "done" });return {lastError: `[${analysis.category.toUpperCase()}] ${analysis.summary}\n\nLinhas relevantes:\n${analysis.relevantLines.join("\n")}`,};
12345678910111213141516171819202122232425262728import { testerAgent } from "./agent.js";import { VulnerabilityReport, PoCResult } from "./types.js";import { logger } from "../../logger.js";
/** * Entry point para o Agente Gerador de PoCs. * @param report O relatório de vulnerabilidade (mapeado a partir do Finding do Auditor). * @returns PoCResult contendo o código do exploit e o status da execução. */export async function runPoCGenerator(report: VulnerabilityReport): Promise<PoCResult> { logger.info(`[Tester] runPoCGenerator: iniciando para: ${report.id} — ${report.title}`);
const finalState = await testerAgent.invoke({ report });
const result: PoCResult = { reportId: report.id, status: finalState.status === "running" ? "failed" : finalState.status, solidityCode: finalState.pocCode, executionLogs: finalState.executionLogs, iterations: finalState.iterations, };
logger.info(`[Tester] runPoCGenerator: concluído — status=${result.status}, iterações=${result.iterations}`); return result;}
export type { VulnerabilityReport, PoCResult, Finding, OracleContext } from "./types.js";export { testerAgent } from "./agent.js";17 unmodified lines1819202122232417 unmodified lines});case "anthropic":return new ChatAnthropic({model: process.env.ANTHROPIC_MODEL || "claude-sonnet-4-6",temperature: 0.2,maxTokens: 4096,});17 unmodified lines1819202122232417 unmodified lines});case "anthropic":return new ChatAnthropic({model: process.env.ANTHROPIC_MODEL || "claude-haiku-4-5",temperature: 0.2,maxTokens: 4096,});
36 unmodified lines37383940414236 unmodified lines},});export const logger = winston.createLogger({level: "debug",transports: [36 unmodified lines373839404142434445464748495051525354555657585960616263646536 unmodified lines},});export interface StepEvent {agent: "coder" | "auditor" | "tester";step: string;status: "running" | "done" | "error" | "skipped";detail?: string;}type StepSink = (event: StepEvent) => void | Promise<void>;let activeStepSink: StepSink | null = null;export function setStepSink(sink: StepSink): void {activeStepSink = sink;}export function clearStepSink(): void {activeStepSink = null;}export function emitStep(event: StepEvent): void {if (activeStepSink) void activeStepSink(event);}export const logger = winston.createLogger({level: "debug",transports: [
12 unmodified lines1314151617181917 unmodified lines37383940414265 unmodified lines10810911011111211312 unmodified linesimport { auditorAgent } from "./agents/auditor/agent.ts";import { testerAgent } from "./agents/tester/agent.ts";import { mapFindingToReport } from "./utils/mapFinding.js";import { logger, setLogSink, clearLogSink } from "./logger.ts";const app = new Hono();17 unmodified linestry {setLogSink((msg) => send("log", msg));// === CODER ===logger.info("[Coder] Gerando smart contract a partir dos requisitos...");65 unmodified linesawait send("error", message);} finally {clearLogSink();}});});12 unmodified lines1314151617181917 unmodified lines3738394041424365 unmodified lines10911011111211311411512 unmodified linesimport { auditorAgent } from "./agents/auditor/agent.ts";import { testerAgent } from "./agents/tester/agent.ts";import { mapFindingToReport } from "./utils/mapFinding.js";import { logger, setLogSink, clearLogSink, setStepSink, clearStepSink } from "./logger.ts";const app = new Hono();17 unmodified linestry {setLogSink((msg) => send("log", msg));setStepSink((event) => send("step", JSON.stringify(event)));// === CODER ===logger.info("[Coder] Gerando smart contract a partir dos requisitos...");65 unmodified linesawait send("error", message);} finally {clearLogSink();clearStepSink();}});});
frontend/index.html+21-1
frontend/src/App.tsx+125-362
frontend/src/components/ArtifactPanel.tsxAdded+523
frontend/src/components/ControlPanel.tsxAdded+443
frontend/src/types.tsAdded+48
frontend/src/utils/diff.tsAdded+54
frontend/src/utils/status.tsAdded+100
src/agents/auditor/agent.ts+10
src/agents/coder/agent.ts+14-1
src/agents/tester/agent.ts+11-1
src/agents/tester/index.tsDeleted-28
src/config/llm.ts+1-1
src/logger.ts+23
src/server.ts+3-1