Open-source release for Alpha version

This commit is contained in:
Ahmed Allam
2025-08-08 20:36:44 -07:00
commit 81ac98e8b9
105 changed files with 22125 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
from .main import main
__all__ = ["main"]
+1122
View File
File diff suppressed because it is too large Load Diff
+680
View File
@@ -0,0 +1,680 @@
Screen {
background: #1a1a1a;
color: #d4d4d4;
}
#splash_screen {
height: 100%;
width: 100%;
background: #1a1a1a;
color: #22c55e;
content-align: center middle;
text-align: center;
}
#splash_content {
width: auto;
height: auto;
background: transparent;
text-align: center;
padding: 2;
}
#main_container {
height: 100%;
padding: 0;
margin: 0;
background: #1a1a1a;
}
#content_container {
height: 1fr;
padding: 0;
background: transparent;
}
#agents_tree {
width: 20%;
background: transparent;
border: round #262626;
border-title-color: #a8a29e;
border-title-style: bold;
margin-left: 1;
padding: 1;
}
#chat_area_container {
width: 80%;
background: transparent;
}
#chat_history {
height: 1fr;
background: transparent;
border: round #1a1a1a;
padding: 0;
margin-bottom: 0;
margin-right: 0;
scrollbar-background: #0f0f0f;
scrollbar-color: #262626;
scrollbar-corner-color: #0f0f0f;
scrollbar-size: 1 1;
}
#agent_status_display {
height: 1;
background: transparent;
margin: 0;
padding: 0 1;
}
#agent_status_display.hidden {
display: none;
}
#status_text {
width: 1fr;
height: 100%;
background: transparent;
color: #a3a3a3;
text-align: left;
content-align: left middle;
text-style: italic;
margin: 0;
padding: 0;
}
#keymap_indicator {
width: auto;
height: 100%;
background: transparent;
color: #737373;
text-align: right;
content-align: right middle;
text-style: none;
margin: 0;
padding: 0;
}
#chat_input_container {
height: 3;
background: transparent;
border: round #525252;
margin-right: 0;
padding: 0;
layout: horizontal;
align-vertical: middle;
}
#chat_input_container:focus-within {
border: round #22c55e;
}
#chat_input_container:focus-within #chat_prompt {
color: #22c55e;
text-style: bold;
}
#chat_prompt {
width: auto;
height: 100%;
padding: 0 0 0 1;
color: #737373;
content-align-vertical: middle;
}
#chat_history:focus {
border: round #22c55e;
}
#chat_input {
width: 1fr;
height: 100%;
background: #121212;
border: none;
color: #d4d4d4;
padding: 0;
margin: 0;
}
#chat_input:focus {
border: none;
}
#chat_input > .text-area--placeholder {
color: #525252;
text-style: italic;
}
#chat_input > .text-area--cursor {
color: #22c55e;
background: #22c55e;
}
.chat-placeholder {
width: 100%;
height: 100%;
content-align: center middle;
text-align: center;
color: #737373;
text-style: italic;
}
.chat-content {
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
padding: 0 1;
background: transparent;
width: 100%;
}
.chat-message {
margin-bottom: 0;
padding: 0;
background: transparent;
width: 100%;
}
.user-message {
color: #e5e5e5;
border-left: thick #3b82f6;
padding-left: 1;
margin-bottom: 1;
}
.tool-call {
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
padding: 0 1;
background: #0a0a0a;
border: round #1a1a1a;
border-left: thick #f59e0b;
width: 100%;
}
.tool-call.status-completed {
border-left: thick #22c55e;
background: #0d1f12;
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
.tool-call.status-running {
border-left: thick #f59e0b;
background: #1f1611;
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
.tool-call.status-failed,
.tool-call.status-error {
border-left: thick #ef4444;
background: #1f0d0d;
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
.browser-tool,
.terminal-tool,
.python-tool,
.agents-graph-tool,
.file-edit-tool,
.proxy-tool,
.notes-tool,
.thinking-tool,
.web-search-tool,
.finish-tool,
.reporting-tool,
.scan-info-tool,
.subagent-info-tool {
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
.browser-tool {
border-left: thick #06b6d4;
}
.browser-tool.status-completed {
border-left: thick #06b6d4;
background: transparent;
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
.browser-tool.status-running {
border-left: thick #0891b2;
background: transparent;
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
.terminal-tool {
border-left: thick #22c55e;
}
.terminal-tool.status-completed {
border-left: thick #22c55e;
background: transparent;
}
.terminal-tool.status-running {
border-left: thick #16a34a;
background: transparent;
}
.python-tool {
border-left: thick #3b82f6;
}
.python-tool.status-completed {
border-left: thick #3b82f6;
background: transparent;
}
.python-tool.status-running {
border-left: thick #2563eb;
background: transparent;
}
.agents-graph-tool {
border-left: thick #fbbf24;
}
.agents-graph-tool.status-completed {
border-left: thick #fbbf24;
background: transparent;
}
.agents-graph-tool.status-running {
border-left: thick #f59e0b;
background: transparent;
}
.file-edit-tool {
border-left: thick #10b981;
}
.file-edit-tool.status-completed {
border-left: thick #10b981;
background: transparent;
}
.file-edit-tool.status-running {
border-left: thick #059669;
background: transparent;
}
.proxy-tool {
border-left: thick #06b6d4;
}
.proxy-tool.status-completed {
border-left: thick #06b6d4;
background: transparent;
}
.proxy-tool.status-running {
border-left: thick #0891b2;
background: transparent;
}
.notes-tool {
border-left: thick #fbbf24;
}
.notes-tool.status-completed {
border-left: thick #fbbf24;
background: transparent;
}
.notes-tool.status-running {
border-left: thick #f59e0b;
background: transparent;
}
.thinking-tool {
border-left: thick #a855f7;
}
.thinking-tool.status-completed {
border-left: thick #a855f7;
background: transparent;
}
.thinking-tool.status-running {
border-left: thick #9333ea;
background: transparent;
}
.web-search-tool {
border-left: thick #22c55e;
}
.web-search-tool.status-completed {
border-left: thick #22c55e;
background: transparent;
}
.web-search-tool.status-running {
border-left: thick #16a34a;
background: transparent;
}
.finish-tool {
border-left: thick #dc2626;
}
.finish-tool.status-completed {
border-left: thick #dc2626;
background: transparent;
}
.finish-tool.status-running {
border-left: thick #b91c1c;
background: transparent;
}
.reporting-tool {
border-left: thick #ea580c;
}
.reporting-tool.status-completed {
border-left: thick #ea580c;
background: transparent;
}
.reporting-tool.status-running {
border-left: thick #c2410c;
background: transparent;
}
.scan-info-tool {
border-left: thick #22c55e;
background: transparent;
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
.scan-info-tool.status-completed {
border-left: thick #22c55e;
background: transparent;
}
.scan-info-tool.status-running {
border-left: thick #16a34a;
background: transparent;
}
.subagent-info-tool {
border-left: thick #22c55e;
background: transparent;
margin: 0 !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
.subagent-info-tool.status-completed {
border-left: thick #22c55e;
background: transparent;
}
.subagent-info-tool.status-running {
border-left: thick #16a34a;
background: transparent;
}
Tree {
background: transparent;
color: #e7e5e4;
scrollbar-background: transparent;
scrollbar-color: #404040;
scrollbar-corner-color: transparent;
scrollbar-size: 1 1;
}
Tree > .tree--label {
text-style: bold;
color: #a8a29e;
background: transparent;
padding: 0 1;
margin-bottom: 1;
border-bottom: solid #262626;
text-align: center;
}
.tree--node {
height: 1;
padding: 0;
margin: 0;
}
.tree--node-label {
color: #d6d3d1;
background: transparent;
text-style: none;
padding: 0 1;
margin: 0 1;
}
.tree--node:hover .tree--node-label {
background: transparent;
color: #fafaf9;
text-style: bold;
border-left: solid #a8a29e;
}
.tree--node.-selected .tree--node-label {
background: transparent;
color: #fafaf9;
text-style: bold;
border-left: heavy #d6d3d1;
}
.tree--node.-expanded .tree--node-label {
text-style: bold;
color: #fafaf9;
background: transparent;
border-left: solid #78716c;
}
Tree:focus {
border: round #262626;
}
Tree:focus > .tree--label {
color: #fafaf9;
text-style: bold;
background: transparent;
}
.tree--node .tree--node .tree--node-label {
color: #a8a29e;
padding-left: 2;
border: none;
background: transparent;
margin-left: 1;
}
.tree--node .tree--node:hover .tree--node-label {
background: transparent;
color: #e7e5e4;
}
.tree--node .tree--node .tree--node .tree--node-label {
color: #78716c;
padding-left: 3;
text-style: none;
border: none;
background: transparent;
margin-left: 2;
}
StopAgentScreen {
align: center middle;
background: $background 0%;
}
#stop_agent_dialog {
grid-size: 1;
grid-gutter: 1;
grid-rows: auto auto;
padding: 1;
width: 30;
height: auto;
border: round #a3a3a3;
background: #1a1a1a 98%;
}
#stop_agent_title {
color: #a3a3a3;
text-style: bold;
text-align: center;
width: 100%;
margin-bottom: 0;
}
#stop_agent_buttons {
grid-size: 2;
grid-gutter: 1;
grid-columns: 1fr 1fr;
width: 100%;
height: 1;
}
#stop_agent_buttons Button {
height: 1;
min-height: 1;
border: none;
text-style: bold;
}
#stop_agent {
background: transparent;
color: #ef4444;
border: none;
}
#stop_agent:hover, #stop_agent:focus {
background: #ef4444;
color: #ffffff;
border: none;
}
#cancel_stop {
background: transparent;
color: #737373;
border: none;
}
#cancel_stop:hover, #cancel_stop:focus {
background:rgb(54, 54, 54);
color: #ffffff;
border: none;
}
QuitScreen {
align: center middle;
background: $background 0%;
}
#quit_dialog {
grid-size: 1;
grid-gutter: 1;
grid-rows: auto auto;
padding: 1;
width: 24;
height: auto;
border: round #525252;
background: #1a1a1a 98%;
}
#quit_title {
color: #d4d4d4;
text-style: bold;
text-align: center;
width: 100%;
margin-bottom: 0;
}
#quit_buttons {
grid-size: 2;
grid-gutter: 1;
grid-columns: 1fr 1fr;
width: 100%;
height: 1;
}
#quit_buttons Button {
height: 1;
min-height: 1;
border: none;
text-style: bold;
}
#quit {
background: transparent;
color: #ef4444;
border: none;
}
#quit:hover, #quit:focus {
background: #ef4444;
color: #ffffff;
border: none;
}
#cancel {
background: transparent;
color: #737373;
border: none;
}
#cancel:hover, #cancel:focus {
background:rgb(54, 54, 54);
color: #ffffff;
border: none;
}
HelpScreen {
align: center middle;
background: $background 0%;
}
#dialog {
grid-size: 1;
grid-gutter: 0 1;
grid-rows: auto auto;
padding: 1 2;
width: 40;
height: auto;
border: round #22c55e;
background: #1a1a1a 98%;
}
#help_title {
color: #22c55e;
text-style: bold;
text-align: center;
width: 100%;
margin-bottom: 1;
}
#help_content {
color: #d4d4d4;
text-align: left;
width: 100%;
margin-bottom: 1;
padding: 0;
background: transparent;
text-style: none;
}
+542
View File
@@ -0,0 +1,542 @@
#!/usr/bin/env python3
"""
Strix Agent Command Line Interface
"""
import argparse
import asyncio
import logging
import os
import secrets
import sys
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
import docker
import litellm
from docker.errors import DockerException
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from strix.cli.app import run_strix_cli
from strix.cli.tracer import get_global_tracer
from strix.runtime.docker_runtime import STRIX_IMAGE
logging.getLogger().setLevel(logging.ERROR)
def format_token_count(count: float) -> str:
count = int(count)
if count >= 1_000_000:
return f"{count / 1_000_000:.1f}M"
if count >= 1_000:
return f"{count / 1_000:.1f}K"
return str(count)
def validate_environment() -> None:
console = Console()
missing_required_vars = []
missing_optional_vars = []
if not os.getenv("STRIX_LLM"):
missing_required_vars.append("STRIX_LLM")
if not os.getenv("LLM_API_KEY"):
missing_required_vars.append("LLM_API_KEY")
if not os.getenv("PERPLEXITY_API_KEY"):
missing_optional_vars.append("PERPLEXITY_API_KEY")
if missing_required_vars:
error_text = Text()
error_text.append("", style="bold red")
error_text.append("MISSING REQUIRED ENVIRONMENT VARIABLES", style="bold red")
error_text.append("\n\n", style="white")
for var in missing_required_vars:
error_text.append(f"{var}", style="bold yellow")
error_text.append(" is not set\n", style="white")
if missing_optional_vars:
error_text.append(
"\nOptional (but recommended) environment variables:\n", style="dim white"
)
for var in missing_optional_vars:
error_text.append(f"{var}", style="dim yellow")
error_text.append(" is not set\n", style="dim white")
error_text.append("\nRequired environment variables:\n", style="white")
error_text.append("", style="white")
error_text.append("STRIX_LLM", style="bold cyan")
error_text.append(
" - Model name to use with litellm (e.g., 'anthropic/claude-sonnet-4-20250514')\n",
style="white",
)
error_text.append("", style="white")
error_text.append("LLM_API_KEY", style="bold cyan")
error_text.append(" - API key for the LLM provider\n", style="white")
if missing_optional_vars:
error_text.append("\nOptional environment variables:\n", style="white")
error_text.append("", style="white")
error_text.append("PERPLEXITY_API_KEY", style="bold cyan")
error_text.append(
" - API key for Perplexity AI web search (enables real-time research)\n",
style="white",
)
error_text.append("\nExample setup:\n", style="white")
error_text.append(
"export STRIX_LLM='anthropic/claude-sonnet-4-20250514'\n", style="dim white"
)
error_text.append("export LLM_API_KEY='your-api-key-here'\n", style="dim white")
if missing_optional_vars:
error_text.append(
"export PERPLEXITY_API_KEY='your-perplexity-key-here'", style="dim white"
)
panel = Panel(
error_text,
title="[bold red]🛡️ STRIX CONFIGURATION ERROR",
title_align="center",
border_style="red",
padding=(1, 2),
)
console.print("\n")
console.print(panel)
console.print()
sys.exit(1)
def _validate_llm_response(response: Any) -> None:
if not response or not response.choices or not response.choices[0].message.content:
raise RuntimeError("Invalid response from LLM")
async def warm_up_llm() -> None:
console = Console()
try:
model_name = os.getenv("STRIX_LLM", "anthropic/claude-sonnet-4-20250514")
api_key = os.getenv("LLM_API_KEY")
if api_key:
litellm.api_key = api_key
test_messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Reply with just 'OK'."},
]
response = litellm.completion(
model=model_name,
messages=test_messages,
max_tokens=10,
)
_validate_llm_response(response)
except Exception as e: # noqa: BLE001
error_text = Text()
error_text.append("", style="bold red")
error_text.append("LLM CONNECTION FAILED", style="bold red")
error_text.append("\n\n", style="white")
error_text.append("Could not establish connection to the language model.\n", style="white")
error_text.append("Please check your configuration and try again.\n", style="white")
error_text.append(f"\nError: {e}", style="dim white")
panel = Panel(
error_text,
title="[bold red]🛡️ STRIX STARTUP ERROR",
title_align="center",
border_style="red",
padding=(1, 2),
)
console.print("\n")
console.print(panel)
console.print()
sys.exit(1)
def generate_run_name() -> str:
# fmt: off
adjectives = [
"stealthy", "sneaky", "crafty", "elite", "phantom", "shadow", "silent",
"rogue", "covert", "ninja", "ghost", "cyber", "digital", "binary",
"encrypted", "obfuscated", "masked", "cloaked", "invisible", "anonymous"
]
nouns = [
"exploit", "payload", "backdoor", "rootkit", "keylogger", "botnet", "trojan",
"worm", "virus", "packet", "buffer", "shell", "daemon", "spider", "crawler",
"scanner", "sniffer", "honeypot", "firewall", "breach"
]
# fmt: on
adj = secrets.choice(adjectives)
noun = secrets.choice(nouns)
number = secrets.randbelow(900) + 100
return f"{adj}-{noun}-{number}"
def infer_target_type(target: str) -> tuple[str, dict[str, str]]:
if not target or not isinstance(target, str):
raise ValueError("Target must be a non-empty string")
target = target.strip()
parsed = urlparse(target)
if parsed.scheme in ("http", "https"):
if any(
host in parsed.netloc.lower() for host in ["github.com", "gitlab.com", "bitbucket.org"]
):
return "repository", {"target_repo": target}
return "web_application", {"target_url": target}
path = Path(target)
try:
if path.exists():
if path.is_dir():
return "local_code", {"target_path": str(path.absolute())}
raise ValueError(f"Path exists but is not a directory: {target}")
except (OSError, RuntimeError) as e:
raise ValueError(f"Invalid path: {target} - {e!s}") from e
if target.startswith("git@") or target.endswith(".git"):
return "repository", {"target_repo": target}
if "." in target and "/" not in target and not target.startswith("."):
parts = target.split(".")
if len(parts) >= 2 and all(p and p.strip() for p in parts):
return "web_application", {"target_url": f"https://{target}"}
raise ValueError(
f"Invalid target: {target}\n"
"Target must be one of:\n"
"- A valid URL (http:// or https://)\n"
"- A Git repository URL (https://github.com/... or git@github.com:...)\n"
"- A local directory path\n"
"- A domain name (e.g., example.com)"
)
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Strix Multi-Agent Cybersecurity Scanner",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Web application scan
strix --target https://example.com
# GitHub repository analysis
strix --target https://github.com/user/repo
strix --target git@github.com:user/repo.git
# Local code analysis
strix --target ./my-project
# Domain scan
strix --target example.com
# Custom instructions
strix --target example.com --instruction "Focus on authentication vulnerabilities"
""",
)
parser.add_argument(
"--target",
type=str,
required=True,
help="Target to scan (URL, repository, local directory path, or domain name)",
)
parser.add_argument(
"--instruction",
type=str,
help="Custom instructions for the scan. This can be "
"specific vulnerability types to focus on (e.g., 'Focus on IDOR and XSS'), "
"testing approaches (e.g., 'Perform thorough authentication testing'), "
"test credentials (e.g., 'Use the following credentials to access the app: "
"admin:password123'), "
"or areas of interest (e.g., 'Check login API endpoint for security issues')",
)
parser.add_argument(
"--run-name",
type=str,
help="Custom name for this scan run",
)
args = parser.parse_args()
try:
args.target_type, args.target_dict = infer_target_type(args.target)
except ValueError as e:
parser.error(str(e))
return args
def _build_stats_text(tracer: Any) -> Text:
stats_text = Text()
if not tracer:
return stats_text
vuln_count = len(tracer.vulnerability_reports)
tool_count = tracer.get_real_tool_count()
agent_count = len(tracer.agents)
if vuln_count > 0:
stats_text.append("🔍 Vulnerabilities Found: ", style="bold red")
stats_text.append(str(vuln_count), style="bold yellow")
stats_text.append("", style="dim white")
stats_text.append("🤖 Agents Used: ", style="bold cyan")
stats_text.append(str(agent_count), style="bold white")
stats_text.append("", style="dim white")
stats_text.append("🛠️ Tools Called: ", style="bold cyan")
stats_text.append(str(tool_count), style="bold white")
return stats_text
def _build_llm_stats_text(tracer: Any) -> Text:
llm_stats_text = Text()
if not tracer:
return llm_stats_text
llm_stats = tracer.get_total_llm_stats()
total_stats = llm_stats["total"]
if total_stats["requests"] > 0:
llm_stats_text.append("📥 Input Tokens: ", style="bold cyan")
llm_stats_text.append(format_token_count(total_stats["input_tokens"]), style="bold white")
if total_stats["cached_tokens"] > 0:
llm_stats_text.append("", style="dim white")
llm_stats_text.append("⚡ Cached: ", style="bold green")
llm_stats_text.append(
format_token_count(total_stats["cached_tokens"]), style="bold green"
)
llm_stats_text.append("", style="dim white")
llm_stats_text.append("📤 Output Tokens: ", style="bold cyan")
llm_stats_text.append(format_token_count(total_stats["output_tokens"]), style="bold white")
if total_stats["cost"] > 0:
llm_stats_text.append("", style="dim white")
llm_stats_text.append("💰 Total Cost: $", style="bold cyan")
llm_stats_text.append(f"{total_stats['cost']:.4f}", style="bold yellow")
return llm_stats_text
def display_completion_message(args: argparse.Namespace, results_path: Path) -> None:
console = Console()
tracer = get_global_tracer()
target_value = next(iter(args.target_dict.values())) if args.target_dict else args.target
completion_text = Text()
completion_text.append("🦉 ", style="bold white")
completion_text.append("AGENT FINISHED", style="bold green")
completion_text.append("", style="dim white")
completion_text.append("Security assessment completed", style="white")
stats_text = _build_stats_text(tracer)
llm_stats_text = _build_llm_stats_text(tracer)
target_text = Text()
target_text.append("🎯 Target: ", style="bold cyan")
target_text.append(str(target_value), style="bold white")
results_text = Text()
results_text.append("📊 Results Saved To: ", style="bold cyan")
results_text.append(str(results_path), style="bold yellow")
if stats_text.plain:
if llm_stats_text.plain:
panel_content = Text.assemble(
completion_text,
"\n\n",
target_text,
"\n",
stats_text,
"\n",
llm_stats_text,
"\n",
results_text,
)
else:
panel_content = Text.assemble(
completion_text, "\n\n", target_text, "\n", stats_text, "\n", results_text
)
elif llm_stats_text.plain:
panel_content = Text.assemble(
completion_text, "\n\n", target_text, "\n", llm_stats_text, "\n", results_text
)
else:
panel_content = Text.assemble(completion_text, "\n\n", target_text, "\n", results_text)
panel = Panel(
panel_content,
title="[bold green]🛡️ STRIX CYBERSECURITY AGENT",
title_align="center",
border_style="green",
padding=(1, 2),
)
console.print("\n")
console.print(panel)
console.print()
def _check_docker_connection() -> Any:
try:
return docker.from_env()
except DockerException:
console = Console()
error_text = Text()
error_text.append("", style="bold red")
error_text.append("DOCKER NOT AVAILABLE", style="bold red")
error_text.append("\n\n", style="white")
error_text.append("Cannot connect to Docker daemon.\n", style="white")
error_text.append("Please ensure Docker is installed and running.\n\n", style="white")
error_text.append("Try running: ", style="dim white")
error_text.append("sudo systemctl start docker", style="dim cyan")
panel = Panel(
error_text,
title="[bold red]🛡️ STRIX STARTUP ERROR",
title_align="center",
border_style="red",
padding=(1, 2),
)
console.print("\n", panel, "\n")
sys.exit(1)
def _image_exists(client: Any) -> bool:
try:
client.images.get(STRIX_IMAGE)
except docker.errors.ImageNotFound:
return False
else:
return True
def _update_layer_status(layers_info: dict[str, str], layer_id: str, layer_status: str) -> None:
if "Pull complete" in layer_status or "Already exists" in layer_status:
layers_info[layer_id] = ""
elif "Downloading" in layer_status:
layers_info[layer_id] = ""
elif "Extracting" in layer_status:
layers_info[layer_id] = "📦"
elif "Waiting" in layer_status:
layers_info[layer_id] = ""
else:
layers_info[layer_id] = ""
def _process_pull_line(
line: dict[str, Any], layers_info: dict[str, str], status: Any, last_update: str
) -> str:
if "id" in line and "status" in line:
layer_id = line["id"]
_update_layer_status(layers_info, layer_id, line["status"])
completed = sum(1 for v in layers_info.values() if v == "")
total = len(layers_info)
if total > 0:
update_msg = f"[bold cyan]Progress: {completed}/{total} layers complete"
if update_msg != last_update:
status.update(update_msg)
return update_msg
elif "status" in line and "id" not in line:
global_status = line["status"]
if "Pulling from" in global_status:
status.update("[bold cyan]Fetching image manifest...")
elif "Digest:" in global_status:
status.update("[bold cyan]Verifying image...")
elif "Status:" in global_status:
status.update("[bold cyan]Finalizing...")
return last_update
def pull_docker_image() -> None:
console = Console()
client = _check_docker_connection()
if _image_exists(client):
return
console.print()
console.print(f"[bold cyan]🐳 Pulling Docker image:[/bold cyan] {STRIX_IMAGE}")
console.print(
"[dim yellow]This only happens on first run and may take a few minutes...[/dim yellow]"
)
console.print()
with console.status("[bold cyan]Downloading image layers...", spinner="dots") as status:
try:
layers_info: dict[str, str] = {}
last_update = ""
for line in client.api.pull(STRIX_IMAGE, stream=True, decode=True):
last_update = _process_pull_line(line, layers_info, status, last_update)
except DockerException as e:
console.print()
error_text = Text()
error_text.append("", style="bold red")
error_text.append("FAILED TO PULL IMAGE", style="bold red")
error_text.append("\n\n", style="white")
error_text.append(f"Could not download: {STRIX_IMAGE}\n", style="white")
error_text.append(str(e), style="dim red")
panel = Panel(
error_text,
title="[bold red]🛡️ DOCKER PULL ERROR",
title_align="center",
border_style="red",
padding=(1, 2),
)
console.print(panel, "\n")
sys.exit(1)
success_text = Text()
success_text.append("", style="bold green")
success_text.append("Successfully pulled Docker image", style="green")
console.print(success_text)
console.print()
def main() -> None:
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
pull_docker_image()
validate_environment()
asyncio.run(warm_up_llm())
args = parse_arguments()
if not args.run_name:
args.run_name = generate_run_name()
asyncio.run(run_strix_cli(args))
results_path = Path("agent_runs") / args.run_name
display_completion_message(args, results_path)
if __name__ == "__main__":
main()
+39
View File
@@ -0,0 +1,39 @@
from . import (
agents_graph_renderer,
browser_renderer,
file_edit_renderer,
finish_renderer,
notes_renderer,
proxy_renderer,
python_renderer,
reporting_renderer,
scan_info_renderer,
terminal_renderer,
thinking_renderer,
user_message_renderer,
web_search_renderer,
)
from .base_renderer import BaseToolRenderer
from .registry import ToolTUIRegistry, get_tool_renderer, register_tool_renderer, render_tool_widget
__all__ = [
"BaseToolRenderer",
"ToolTUIRegistry",
"agents_graph_renderer",
"browser_renderer",
"file_edit_renderer",
"finish_renderer",
"get_tool_renderer",
"notes_renderer",
"proxy_renderer",
"python_renderer",
"register_tool_renderer",
"render_tool_widget",
"reporting_renderer",
"scan_info_renderer",
"terminal_renderer",
"thinking_renderer",
"user_message_renderer",
"web_search_renderer",
]
@@ -0,0 +1,129 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class ViewAgentGraphRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "view_agent_graph"
css_classes: ClassVar[list[str]] = ["tool-call", "agents-graph-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static: # noqa: ARG003
content_text = "🕸️ [bold #fbbf24]Viewing agents graph[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class CreateAgentRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "create_agent"
css_classes: ClassVar[list[str]] = ["tool-call", "agents-graph-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
task = args.get("task", "")
name = args.get("name", "Agent")
header = f"🤖 [bold #fbbf24]Creating {name}[/]"
if task:
task_display = task[:400] + "..." if len(task) > 400 else task
content_text = f"{header}\n [dim]{cls.escape_markup(task_display)}[/]"
else:
content_text = f"{header}\n [dim]Spawning agent...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class SendMessageToAgentRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "send_message_to_agent"
css_classes: ClassVar[list[str]] = ["tool-call", "agents-graph-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
message = args.get("message", "")
header = "💬 [bold #fbbf24]Sending message[/]"
if message:
message_display = message[:400] + "..." if len(message) > 400 else message
content_text = f"{header}\n [dim]{cls.escape_markup(message_display)}[/]"
else:
content_text = f"{header}\n [dim]Sending...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class AgentFinishRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "agent_finish"
css_classes: ClassVar[list[str]] = ["tool-call", "agents-graph-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
result_summary = args.get("result_summary", "")
findings = args.get("findings", [])
success = args.get("success", True)
header = (
"🏁 [bold #fbbf24]Agent completed[/]" if success else "🏁 [bold #fbbf24]Agent failed[/]"
)
if result_summary:
summary_display = (
result_summary[:400] + "..." if len(result_summary) > 400 else result_summary
)
content_parts = [f"{header}\n [bold]{cls.escape_markup(summary_display)}[/]"]
if findings and isinstance(findings, list):
finding_lines = [f"{finding}" for finding in findings[:3]]
if len(findings) > 3:
finding_lines.append(f"• ... +{len(findings) - 3} more findings")
content_parts.append(
f" [dim]{chr(10).join([cls.escape_markup(line) for line in finding_lines])}[/]"
)
content_text = "\n".join(content_parts)
else:
content_text = f"{header}\n [dim]Completing task...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class WaitForMessageRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "wait_for_message"
css_classes: ClassVar[list[str]] = ["tool-call", "agents-graph-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
reason = args.get("reason", "Waiting for messages from other agents or user input")
header = "⏸️ [bold #fbbf24]Waiting for messages[/]"
if reason:
reason_display = reason[:400] + "..." if len(reason) > 400 else reason
content_text = f"{header}\n [dim]{cls.escape_markup(reason_display)}[/]"
else:
content_text = f"{header}\n [dim]Agent paused until message received...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@@ -0,0 +1,61 @@
from abc import ABC, abstractmethod
from typing import Any, ClassVar
from textual.widgets import Static
class BaseToolRenderer(ABC):
tool_name: ClassVar[str] = ""
css_classes: ClassVar[list[str]] = ["tool-call"]
@classmethod
@abstractmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
pass
@classmethod
def escape_markup(cls, text: str) -> str:
return text.replace("[", "\\[").replace("]", "\\]")
@classmethod
def format_args(cls, args: dict[str, Any], max_length: int = 500) -> str:
if not args:
return ""
args_parts = []
for k, v in args.items():
str_v = str(v)
if len(str_v) > max_length:
str_v = str_v[: max_length - 3] + "..."
args_parts.append(f" [dim]{k}:[/] {cls.escape_markup(str_v)}")
return "\n".join(args_parts)
@classmethod
def format_result(cls, result: Any, max_length: int = 1000) -> str:
if result is None:
return ""
str_result = str(result).strip()
if not str_result:
return ""
if len(str_result) > max_length:
str_result = str_result[: max_length - 3] + "..."
return cls.escape_markup(str_result)
@classmethod
def get_status_icon(cls, status: str) -> str:
status_icons = {
"running": "[#f59e0b]●[/#f59e0b] In progress...",
"completed": "[#22c55e]✓[/#22c55e] Done",
"failed": "[#dc2626]✗[/#dc2626] Failed",
"error": "[#dc2626]✗[/#dc2626] Error",
}
return status_icons.get(status, "[dim]○[/dim] Unknown")
@classmethod
def get_css_classes(cls, status: str) -> str:
base_classes = cls.css_classes.copy()
base_classes.append(f"status-{status}")
return " ".join(base_classes)
@@ -0,0 +1,107 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class BrowserRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "browser_action"
css_classes: ClassVar[list[str]] = ["tool-call", "browser-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
status = tool_data.get("status", "unknown")
action = args.get("action", "unknown")
content = cls._build_sleek_content(action, args)
css_classes = cls.get_css_classes(status)
return Static(content, classes=css_classes)
@classmethod
def _build_sleek_content(cls, action: str, args: dict[str, Any]) -> str:
browser_icon = "🌐"
url = args.get("url")
text = args.get("text")
js_code = args.get("js_code")
if action in [
"launch",
"goto",
"new_tab",
"type",
"execute_js",
"click",
"double_click",
"hover",
]:
if action == "launch":
display_url = cls._format_url(url) if url else None
message = (
f"launching {display_url} on browser" if display_url else "launching browser"
)
elif action == "goto":
display_url = cls._format_url(url) if url else None
message = f"navigating to {display_url}" if display_url else "navigating"
elif action == "new_tab":
display_url = cls._format_url(url) if url else None
message = f"opening tab {display_url}" if display_url else "opening tab"
elif action == "type":
display_text = cls._format_text(text) if text else None
message = f"typing {display_text}" if display_text else "typing"
elif action == "execute_js":
display_js = cls._format_js(js_code) if js_code else None
message = (
f"executing javascript\n{display_js}" if display_js else "executing javascript"
)
else:
action_words = {
"click": "clicking",
"double_click": "double clicking",
"hover": "hovering",
}
message = action_words[action]
return f"{browser_icon} [#06b6d4]{message}[/]"
simple_actions = {
"back": "going back in browser history",
"forward": "going forward in browser history",
"refresh": "refreshing browser tab",
"close_tab": "closing browser tab",
"switch_tab": "switching browser tab",
"list_tabs": "listing browser tabs",
"view_source": "viewing page source",
"screenshot": "taking screenshot of browser tab",
"wait": "waiting...",
"close": "closing browser",
}
if action in simple_actions:
return f"{browser_icon} [#06b6d4]{simple_actions[action]}[/]"
return f"{browser_icon} [#06b6d4]{action}[/]"
@classmethod
def _format_url(cls, url: str) -> str:
if len(url) > 300:
url = url[:297] + "..."
return cls.escape_markup(url)
@classmethod
def _format_text(cls, text: str) -> str:
if len(text) > 200:
text = text[:197] + "..."
return cls.escape_markup(text)
@classmethod
def _format_js(cls, js_code: str) -> str:
if len(js_code) > 200:
js_code = js_code[:197] + "..."
return f"[white]{cls.escape_markup(js_code)}[/white]"
@@ -0,0 +1,95 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class StrReplaceEditorRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "str_replace_editor"
css_classes: ClassVar[list[str]] = ["tool-call", "file-edit-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
result = tool_data.get("result")
command = args.get("command", "")
path = args.get("path", "")
if command == "view":
header = "📖 [bold #10b981]Reading file[/]"
elif command == "str_replace":
header = "✏️ [bold #10b981]Editing file[/]"
elif command == "create":
header = "📝 [bold #10b981]Creating file[/]"
else:
header = "📄 [bold #10b981]File operation[/]"
if (result and isinstance(result, dict) and "content" in result) or path:
path_display = path[-60:] if len(path) > 60 else path
content_text = f"{header} [dim]{cls.escape_markup(path_display)}[/]"
else:
content_text = f"{header} [dim]Processing...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class ListFilesRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "list_files"
css_classes: ClassVar[list[str]] = ["tool-call", "file-edit-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
path = args.get("path", "")
header = "📂 [bold #10b981]Listing files[/]"
if path:
path_display = path[-60:] if len(path) > 60 else path
content_text = f"{header} [dim]{cls.escape_markup(path_display)}[/]"
else:
content_text = f"{header} [dim]Current directory[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class SearchFilesRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "search_files"
css_classes: ClassVar[list[str]] = ["tool-call", "file-edit-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
path = args.get("path", "")
regex = args.get("regex", "")
header = "🔍 [bold purple]Searching files[/]"
if path and regex:
path_display = path[-30:] if len(path) > 30 else path
regex_display = regex[:30] if len(regex) > 30 else regex
content_text = (
f"{header} [dim]{cls.escape_markup(path_display)} for "
f"'{cls.escape_markup(regex_display)}'[/]"
)
elif path:
path_display = path[-60:] if len(path) > 60 else path
content_text = f"{header} [dim]{cls.escape_markup(path_display)}[/]"
elif regex:
regex_display = regex[:60] if len(regex) > 60 else regex
content_text = f"{header} [dim]'{cls.escape_markup(regex_display)}'[/]"
else:
content_text = f"{header} [dim]Searching...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@@ -0,0 +1,32 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class FinishScanRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "finish_scan"
css_classes: ClassVar[list[str]] = ["tool-call", "finish-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
content = args.get("content", "")
success = args.get("success", True)
header = (
"🏁 [bold #dc2626]Finishing Scan[/]" if success else "🏁 [bold #dc2626]Scan Failed[/]"
)
if content:
content_display = content[:600] + "..." if len(content) > 600 else content
content_text = f"{header}\n [bold]{cls.escape_markup(content_display)}[/]"
else:
content_text = f"{header}\n [dim]Generating final report...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
+108
View File
@@ -0,0 +1,108 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class CreateNoteRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "create_note"
css_classes: ClassVar[list[str]] = ["tool-call", "notes-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
title = args.get("title", "")
content = args.get("content", "")
header = "📝 [bold #fbbf24]Note[/]"
if title:
title_display = title[:100] + "..." if len(title) > 100 else title
note_parts = [f"{header}\n [bold]{cls.escape_markup(title_display)}[/]"]
if content:
content_display = content[:200] + "..." if len(content) > 200 else content
note_parts.append(f" [dim]{cls.escape_markup(content_display)}[/]")
content_text = "\n".join(note_parts)
else:
content_text = f"{header}\n [dim]Creating note...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class DeleteNoteRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "delete_note"
css_classes: ClassVar[list[str]] = ["tool-call", "notes-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static: # noqa: ARG003
header = "🗑️ [bold #fbbf24]Delete Note[/]"
content_text = f"{header}\n [dim]Deleting...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class UpdateNoteRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "update_note"
css_classes: ClassVar[list[str]] = ["tool-call", "notes-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
title = args.get("title", "")
content = args.get("content", "")
header = "✏️ [bold #fbbf24]Update Note[/]"
if title or content:
note_parts = [header]
if title:
title_display = title[:100] + "..." if len(title) > 100 else title
note_parts.append(f" [bold]{cls.escape_markup(title_display)}[/]")
if content:
content_display = content[:200] + "..." if len(content) > 200 else content
note_parts.append(f" [dim]{cls.escape_markup(content_display)}[/]")
content_text = "\n".join(note_parts)
else:
content_text = f"{header}\n [dim]Updating...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class ListNotesRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "list_notes"
css_classes: ClassVar[list[str]] = ["tool-call", "notes-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
result = tool_data.get("result")
header = "📋 [bold #fbbf24]Listing notes[/]"
if result and isinstance(result, dict) and "notes" in result:
notes = result["notes"]
if isinstance(notes, list):
count = len(notes)
content_text = f"{header}\n [dim]{count} notes found[/]"
else:
content_text = f"{header}\n [dim]No notes found[/]"
else:
content_text = f"{header}\n [dim]Listing notes...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
+255
View File
@@ -0,0 +1,255 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class ListRequestsRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "list_requests"
css_classes: ClassVar[list[str]] = ["tool-call", "proxy-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
result = tool_data.get("result")
httpql_filter = args.get("httpql_filter")
header = "📋 [bold #06b6d4]Listing requests[/]"
if result and isinstance(result, dict) and "requests" in result:
requests = result["requests"]
if isinstance(requests, list) and requests:
request_lines = []
for req in requests[:3]:
if isinstance(req, dict):
method = req.get("method", "?")
path = req.get("path", "?")
response = req.get("response") or {}
status = response.get("statusCode", "?")
line = f"{method} {path}{status}"
request_lines.append(line)
if len(requests) > 3:
request_lines.append(f"... +{len(requests) - 3} more")
escaped_lines = [cls.escape_markup(line) for line in request_lines]
content_text = f"{header}\n [dim]{chr(10).join(escaped_lines)}[/]"
else:
content_text = f"{header}\n [dim]No requests found[/]"
elif httpql_filter:
filter_display = (
httpql_filter[:300] + "..." if len(httpql_filter) > 300 else httpql_filter
)
content_text = f"{header}\n [dim]{cls.escape_markup(filter_display)}[/]"
else:
content_text = f"{header}\n [dim]All requests[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class ViewRequestRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "view_request"
css_classes: ClassVar[list[str]] = ["tool-call", "proxy-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
result = tool_data.get("result")
part = args.get("part", "request")
header = f"👀 [bold #06b6d4]Viewing {part}[/]"
if result and isinstance(result, dict):
if "content" in result:
content = result["content"]
content_preview = content[:500] + "..." if len(content) > 500 else content
content_text = f"{header}\n [dim]{cls.escape_markup(content_preview)}[/]"
elif "matches" in result:
matches = result["matches"]
if isinstance(matches, list) and matches:
match_lines = [
match["match"]
for match in matches[:3]
if isinstance(match, dict) and "match" in match
]
if len(matches) > 3:
match_lines.append(f"... +{len(matches) - 3} more matches")
escaped_lines = [cls.escape_markup(line) for line in match_lines]
content_text = f"{header}\n [dim]{chr(10).join(escaped_lines)}[/]"
else:
content_text = f"{header}\n [dim]No matches found[/]"
else:
content_text = f"{header}\n [dim]Viewing content...[/]"
else:
content_text = f"{header}\n [dim]Loading...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class SendRequestRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "send_request"
css_classes: ClassVar[list[str]] = ["tool-call", "proxy-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
result = tool_data.get("result")
method = args.get("method", "GET")
url = args.get("url", "")
header = f"📤 [bold #06b6d4]Sending {method}[/]"
if result and isinstance(result, dict):
status_code = result.get("status_code")
response_body = result.get("body", "")
if status_code:
response_preview = f"Status: {status_code}"
if response_body:
body_preview = (
response_body[:300] + "..." if len(response_body) > 300 else response_body
)
response_preview += f"\n{body_preview}"
content_text = f"{header}\n [dim]{cls.escape_markup(response_preview)}[/]"
else:
content_text = f"{header}\n [dim]Response received[/]"
elif url:
url_display = url[:400] + "..." if len(url) > 400 else url
content_text = f"{header}\n [dim]{cls.escape_markup(url_display)}[/]"
else:
content_text = f"{header}\n [dim]Sending...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class RepeatRequestRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "repeat_request"
css_classes: ClassVar[list[str]] = ["tool-call", "proxy-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
result = tool_data.get("result")
modifications = args.get("modifications", {})
header = "🔄 [bold #06b6d4]Repeating request[/]"
if result and isinstance(result, dict):
status_code = result.get("status_code")
response_body = result.get("body", "")
if status_code:
response_preview = f"Status: {status_code}"
if response_body:
body_preview = (
response_body[:300] + "..." if len(response_body) > 300 else response_body
)
response_preview += f"\n{body_preview}"
content_text = f"{header}\n [dim]{cls.escape_markup(response_preview)}[/]"
else:
content_text = f"{header}\n [dim]Response received[/]"
elif modifications:
mod_text = str(modifications)
mod_display = mod_text[:400] + "..." if len(mod_text) > 400 else mod_text
content_text = f"{header}\n [dim]{cls.escape_markup(mod_display)}[/]"
else:
content_text = f"{header}\n [dim]No modifications[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class ScopeRulesRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "scope_rules"
css_classes: ClassVar[list[str]] = ["tool-call", "proxy-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static: # noqa: ARG003
header = "⚙️ [bold #06b6d4]Updating proxy scope[/]"
content_text = f"{header}\n [dim]Configuring...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class ListSitemapRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "list_sitemap"
css_classes: ClassVar[list[str]] = ["tool-call", "proxy-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
result = tool_data.get("result")
header = "🗺️ [bold #06b6d4]Listing sitemap[/]"
if result and isinstance(result, dict) and "entries" in result:
entries = result["entries"]
if isinstance(entries, list) and entries:
entry_lines = []
for entry in entries[:4]:
if isinstance(entry, dict):
label = entry.get("label", "?")
kind = entry.get("kind", "?")
line = f"{kind}: {label}"
entry_lines.append(line)
if len(entries) > 4:
entry_lines.append(f"... +{len(entries) - 4} more")
escaped_lines = [cls.escape_markup(line) for line in entry_lines]
content_text = f"{header}\n [dim]{chr(10).join(escaped_lines)}[/]"
else:
content_text = f"{header}\n [dim]No entries found[/]"
else:
content_text = f"{header}\n [dim]Loading...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@register_tool_renderer
class ViewSitemapEntryRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "view_sitemap_entry"
css_classes: ClassVar[list[str]] = ["tool-call", "proxy-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
result = tool_data.get("result")
header = "📍 [bold #06b6d4]Viewing sitemap entry[/]"
if result and isinstance(result, dict):
if "entry" in result:
entry = result["entry"]
if isinstance(entry, dict):
label = entry.get("label", "")
kind = entry.get("kind", "")
if label and kind:
entry_info = f"{kind}: {label}"
content_text = f"{header}\n [dim]{cls.escape_markup(entry_info)}[/]"
else:
content_text = f"{header}\n [dim]Entry details loaded[/]"
else:
content_text = f"{header}\n [dim]Entry details loaded[/]"
else:
content_text = f"{header}\n [dim]Loading entry...[/]"
else:
content_text = f"{header}\n [dim]Loading...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@@ -0,0 +1,34 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class PythonRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "python_action"
css_classes: ClassVar[list[str]] = ["tool-call", "python-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
action = args.get("action", "")
code = args.get("code", "")
header = "</> [bold #3b82f6]Python[/]"
if code and action in ["new_session", "execute"]:
code_display = code[:250] + "..." if len(code) > 250 else code
content_text = f"{header}\n [italic white]{cls.escape_markup(code_display)}[/]"
elif action == "close":
content_text = f"{header}\n [dim]Closing session...[/]"
elif action == "list_sessions":
content_text = f"{header}\n [dim]Listing sessions...[/]"
else:
content_text = f"{header}\n [dim]Running...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
+72
View File
@@ -0,0 +1,72 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
class ToolTUIRegistry:
_renderers: ClassVar[dict[str, type[BaseToolRenderer]]] = {}
@classmethod
def register(cls, renderer_class: type[BaseToolRenderer]) -> None:
if not renderer_class.tool_name:
raise ValueError(f"Renderer {renderer_class.__name__} must define tool_name")
cls._renderers[renderer_class.tool_name] = renderer_class
@classmethod
def get_renderer(cls, tool_name: str) -> type[BaseToolRenderer] | None:
return cls._renderers.get(tool_name)
@classmethod
def list_tools(cls) -> list[str]:
return list(cls._renderers.keys())
@classmethod
def has_renderer(cls, tool_name: str) -> bool:
return tool_name in cls._renderers
def register_tool_renderer(renderer_class: type[BaseToolRenderer]) -> type[BaseToolRenderer]:
ToolTUIRegistry.register(renderer_class)
return renderer_class
def get_tool_renderer(tool_name: str) -> type[BaseToolRenderer] | None:
return ToolTUIRegistry.get_renderer(tool_name)
def render_tool_widget(tool_data: dict[str, Any]) -> Static:
tool_name = tool_data.get("tool_name", "")
renderer = get_tool_renderer(tool_name)
if renderer:
return renderer.render(tool_data)
return _render_default_tool_widget(tool_data)
def _render_default_tool_widget(tool_data: dict[str, Any]) -> Static:
tool_name = BaseToolRenderer.escape_markup(tool_data.get("tool_name", "Unknown Tool"))
args = tool_data.get("args", {})
status = tool_data.get("status", "unknown")
result = tool_data.get("result")
status_text = BaseToolRenderer.get_status_icon(status)
header = f"→ Using tool [bold blue]{tool_name}[/]"
content_parts = [header]
args_str = BaseToolRenderer.format_args(args)
if args_str:
content_parts.append(args_str)
if status in ["completed", "failed", "error"] and result is not None:
result_str = BaseToolRenderer.format_result(result)
if result_str:
content_parts.append(f"[bold]Result:[/] {result_str}")
else:
content_parts.append(status_text)
css_classes = BaseToolRenderer.get_css_classes(status)
return Static("\n".join(content_parts), classes=css_classes)
@@ -0,0 +1,53 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class CreateVulnerabilityReportRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "create_vulnerability_report"
css_classes: ClassVar[list[str]] = ["tool-call", "reporting-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
title = args.get("title", "")
severity = args.get("severity", "")
content = args.get("content", "")
header = "🐞 [bold #ea580c]Vulnerability Report[/]"
if title:
content_parts = [f"{header}\n [bold]{cls.escape_markup(title)}[/]"]
if severity:
severity_color = cls._get_severity_color(severity.lower())
content_parts.append(
f" [dim]Severity: [{severity_color}]{severity.upper()}[/{severity_color}][/]"
)
if content:
content_preview = content[:100] + "..." if len(content) > 100 else content
content_parts.append(f" [dim]{cls.escape_markup(content_preview)}[/]")
content_text = "\n".join(content_parts)
else:
content_text = f"{header}\n [dim]Creating report...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
@classmethod
def _get_severity_color(cls, severity: str) -> str:
severity_colors = {
"critical": "#dc2626",
"high": "#ea580c",
"medium": "#d97706",
"low": "#65a30d",
"info": "#0284c7",
}
return severity_colors.get(severity, "#6b7280")
@@ -0,0 +1,58 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class ScanStartInfoRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "scan_start_info"
css_classes: ClassVar[list[str]] = ["tool-call", "scan-info-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
status = tool_data.get("status", "unknown")
target = args.get("target", {})
target_display = cls._build_target_display(target)
content = f"🚀 Starting scan on {target_display}"
css_classes = cls.get_css_classes(status)
return Static(content, classes=css_classes)
@classmethod
def _build_target_display(cls, target: dict[str, Any]) -> str:
if target_url := target.get("target_url"):
return f"[bold #22c55e]{target_url}[/bold #22c55e]"
if target_repo := target.get("target_repo"):
return f"[bold #22c55e]{target_repo}[/bold #22c55e]"
if target_path := target.get("target_path"):
return f"[bold #22c55e]{target_path}[/bold #22c55e]"
return "[dim]unknown target[/dim]"
@register_tool_renderer
class SubagentStartInfoRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "subagent_start_info"
css_classes: ClassVar[list[str]] = ["tool-call", "subagent-info-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
status = tool_data.get("status", "unknown")
name = args.get("name", "Unknown Agent")
task = args.get("task", "")
content = f"🤖 Spawned subagent [bold #22c55e]{name}[/bold #22c55e]"
if task:
display_task = task[:80] + "..." if len(task) > 80 else task
content += f"\n Task: [dim]{display_task}[/dim]"
css_classes = cls.get_css_classes(status)
return Static(content, classes=css_classes)
@@ -0,0 +1,99 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class TerminalRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "terminal_action"
css_classes: ClassVar[list[str]] = ["tool-call", "terminal-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
status = tool_data.get("status", "unknown")
result = tool_data.get("result", {})
action = args.get("action", "unknown")
inputs = args.get("inputs", [])
terminal_id = args.get("terminal_id", "default")
content = cls._build_sleek_content(action, inputs, terminal_id, result)
css_classes = cls.get_css_classes(status)
return Static(content, classes=css_classes)
@classmethod
def _build_sleek_content(
cls,
action: str,
inputs: list[str],
terminal_id: str, # noqa: ARG003
result: dict[str, Any], # noqa: ARG003
) -> str:
terminal_icon = ">_"
if action in {"create", "new_terminal"}:
command = cls._format_command(inputs) if inputs else "bash"
return f"{terminal_icon} [#22c55e]${command}[/]"
if action == "send_input":
command = cls._format_command(inputs)
return f"{terminal_icon} [#22c55e]${command}[/]"
if action == "wait":
return f"{terminal_icon} [dim]waiting...[/]"
if action == "close":
return f"{terminal_icon} [dim]close[/]"
if action == "get_snapshot":
return f"{terminal_icon} [dim]snapshot[/]"
return f"{terminal_icon} [dim]{action}[/]"
@classmethod
def _format_command(cls, inputs: list[str]) -> str:
if not inputs:
return ""
command_parts = []
for input_item in inputs:
if input_item == "Enter":
break
if input_item.startswith("literal:"):
command_parts.append(input_item[8:])
elif input_item in [
"Space",
"Tab",
"Backspace",
"Up",
"Down",
"Left",
"Right",
"Home",
"End",
"PageUp",
"PageDown",
"Insert",
"Delete",
"Escape",
] or input_item.startswith(("^", "C-", "S-", "A-", "F")):
if input_item == "Space":
command_parts.append(" ")
elif input_item == "Tab":
command_parts.append("\t")
continue
else:
command_parts.append(input_item)
command = "".join(command_parts).strip()
if len(command) > 200:
command = command[:197] + "..."
return cls.escape_markup(command) if command else "bash"
@@ -0,0 +1,29 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class ThinkRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "think"
css_classes: ClassVar[list[str]] = ["tool-call", "thinking-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
thought = args.get("thought", "")
header = "🧠 [bold #a855f7]Thinking[/]"
if thought:
thought_display = thought[:200] + "..." if len(thought) > 200 else thought
content = f"{header}\n [italic dim]{cls.escape_markup(thought_display)}[/]"
else:
content = f"{header}\n [italic dim]Thinking...[/]"
css_classes = cls.get_css_classes("completed")
return Static(content, classes=css_classes)
@@ -0,0 +1,43 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class UserMessageRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "user_message"
css_classes: ClassVar[list[str]] = ["chat-message", "user-message"]
@classmethod
def render(cls, message_data: dict[str, Any]) -> Static:
content = message_data.get("content", "")
if not content:
return Static("", classes=cls.css_classes)
if len(content) > 300:
content = content[:297] + "..."
lines = content.split("\n")
bordered_lines = [f"[#3b82f6]▍[/#3b82f6] {line}" for line in lines]
bordered_content = "\n".join(bordered_lines)
formatted_content = f"[#3b82f6]▍[/#3b82f6] [bold]You:[/]\n{bordered_content}"
css_classes = " ".join(cls.css_classes)
return Static(formatted_content, classes=css_classes)
@classmethod
def render_simple(cls, content: str) -> str:
if not content:
return ""
if len(content) > 300:
content = content[:297] + "..."
lines = content.split("\n")
bordered_lines = [f"[#3b82f6]▍[/#3b82f6] {line}" for line in lines]
bordered_content = "\n".join(bordered_lines)
return f"[#3b82f6]▍[/#3b82f6] [bold]You:[/]\n{bordered_content}"
@@ -0,0 +1,28 @@
from typing import Any, ClassVar
from textual.widgets import Static
from .base_renderer import BaseToolRenderer
from .registry import register_tool_renderer
@register_tool_renderer
class WebSearchRenderer(BaseToolRenderer):
tool_name: ClassVar[str] = "web_search"
css_classes: ClassVar[list[str]] = ["tool-call", "web-search-tool"]
@classmethod
def render(cls, tool_data: dict[str, Any]) -> Static:
args = tool_data.get("args", {})
query = args.get("query", "")
header = "🌐 [bold #60a5fa]Searching the web...[/]"
if query:
query_display = query[:100] + "..." if len(query) > 100 else query
content_text = f"{header}\n [dim]{cls.escape_markup(query_display)}[/]"
else:
content_text = f"{header}"
css_classes = cls.get_css_classes("completed")
return Static(content_text, classes=css_classes)
+308
View File
@@ -0,0 +1,308 @@
import logging
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Optional
from uuid import uuid4
logger = logging.getLogger(__name__)
_global_tracer: Optional["Tracer"] = None
def get_global_tracer() -> Optional["Tracer"]:
return _global_tracer
def set_global_tracer(tracer: "Tracer") -> None:
global _global_tracer # noqa: PLW0603
_global_tracer = tracer
class Tracer:
def __init__(self, run_name: str | None = None):
self.run_name = run_name
self.run_id = run_name or f"run-{uuid4().hex[:8]}"
self.start_time = datetime.now(UTC).isoformat()
self.end_time: str | None = None
self.agents: dict[str, dict[str, Any]] = {}
self.tool_executions: dict[int, dict[str, Any]] = {}
self.chat_messages: list[dict[str, Any]] = []
self.vulnerability_reports: list[dict[str, Any]] = []
self.final_scan_result: str | None = None
self.scan_results: dict[str, Any] | None = None
self.scan_config: dict[str, Any] | None = None
self.run_metadata: dict[str, Any] = {
"run_id": self.run_id,
"run_name": self.run_name,
"start_time": self.start_time,
"end_time": None,
"target": None,
"scan_type": None,
"status": "running",
}
self._run_dir: Path | None = None
self._next_execution_id = 1
self._next_message_id = 1
def set_run_name(self, run_name: str) -> None:
self.run_name = run_name
self.run_id = run_name
def get_run_dir(self) -> Path:
if self._run_dir is None:
workspace_root = Path(__file__).parent.parent.parent
runs_dir = workspace_root / "agent_runs"
runs_dir.mkdir(exist_ok=True)
run_dir_name = self.run_name if self.run_name else self.run_id
self._run_dir = runs_dir / run_dir_name
self._run_dir.mkdir(exist_ok=True)
return self._run_dir
def add_vulnerability_report(
self,
title: str,
content: str,
severity: str,
) -> str:
report_id = f"vuln-{len(self.vulnerability_reports) + 1:04d}"
report = {
"id": report_id,
"title": title.strip(),
"content": content.strip(),
"severity": severity.lower().strip(),
"timestamp": datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S UTC"),
}
self.vulnerability_reports.append(report)
logger.info(f"Added vulnerability report: {report_id} - {title}")
return report_id
def set_final_scan_result(
self,
content: str,
success: bool = True,
) -> None:
self.final_scan_result = content.strip()
self.scan_results = {
"scan_completed": True,
"content": content,
"success": success,
}
logger.info(f"Set final scan result: success={success}")
def log_agent_creation(
self, agent_id: str, name: str, task: str, parent_id: str | None = None
) -> None:
agent_data: dict[str, Any] = {
"id": agent_id,
"name": name,
"task": task,
"status": "running",
"parent_id": parent_id,
"created_at": datetime.now(UTC).isoformat(),
"updated_at": datetime.now(UTC).isoformat(),
"tool_executions": [],
}
self.agents[agent_id] = agent_data
def log_chat_message(
self,
content: str,
role: str,
agent_id: str | None = None,
metadata: dict[str, Any] | None = None,
) -> int:
message_id = self._next_message_id
self._next_message_id += 1
message_data = {
"message_id": message_id,
"content": content,
"role": role,
"agent_id": agent_id,
"timestamp": datetime.now(UTC).isoformat(),
"metadata": metadata or {},
}
self.chat_messages.append(message_data)
return message_id
def log_tool_execution_start(self, agent_id: str, tool_name: str, args: dict[str, Any]) -> int:
execution_id = self._next_execution_id
self._next_execution_id += 1
now = datetime.now(UTC).isoformat()
execution_data = {
"execution_id": execution_id,
"agent_id": agent_id,
"tool_name": tool_name,
"args": args,
"status": "running",
"result": None,
"timestamp": now,
"started_at": now,
"completed_at": None,
}
self.tool_executions[execution_id] = execution_data
if agent_id in self.agents:
self.agents[agent_id]["tool_executions"].append(execution_id)
return execution_id
def update_tool_execution(
self, execution_id: int, status: str, result: Any | None = None
) -> None:
if execution_id in self.tool_executions:
self.tool_executions[execution_id]["status"] = status
self.tool_executions[execution_id]["result"] = result
self.tool_executions[execution_id]["completed_at"] = datetime.now(UTC).isoformat()
def update_agent_status(self, agent_id: str, status: str) -> None:
if agent_id in self.agents:
self.agents[agent_id]["status"] = status
self.agents[agent_id]["updated_at"] = datetime.now(UTC).isoformat()
def set_scan_config(self, config: dict[str, Any]) -> None:
self.scan_config = config
self.run_metadata.update(
{
"target": config.get("target", {}),
"scan_type": config.get("scan_type", "general"),
"user_instructions": config.get("user_instructions", ""),
"max_iterations": config.get("max_iterations", 200),
}
)
def save_run_data(self) -> None:
try:
run_dir = self.get_run_dir()
self.end_time = datetime.now(UTC).isoformat()
if self.final_scan_result:
scan_report_file = run_dir / "scan_report.md"
with scan_report_file.open("w", encoding="utf-8") as f:
f.write("# Security Scan Report\n\n")
f.write(
f"**Generated:** {datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S UTC')}\n\n"
)
f.write(f"{self.final_scan_result}\n")
logger.info(f"Saved final scan report to: {scan_report_file}")
if self.vulnerability_reports:
vuln_dir = run_dir / "vulnerabilities"
vuln_dir.mkdir(exist_ok=True)
severity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4}
sorted_reports = sorted(
self.vulnerability_reports,
key=lambda x: (severity_order.get(x["severity"], 5), x["timestamp"]),
)
for report in sorted_reports:
vuln_file = vuln_dir / f"{report['id']}.md"
with vuln_file.open("w", encoding="utf-8") as f:
f.write(f"# {report['title']}\n\n")
f.write(f"**ID:** {report['id']}\n")
f.write(f"**Severity:** {report['severity'].upper()}\n")
f.write(f"**Found:** {report['timestamp']}\n\n")
f.write("## Description\n\n")
f.write(f"{report['content']}\n")
vuln_csv_file = run_dir / "vulnerabilities.csv"
with vuln_csv_file.open("w", encoding="utf-8", newline="") as f:
import csv
fieldnames = ["id", "title", "severity", "timestamp", "file"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for report in sorted_reports:
writer.writerow(
{
"id": report["id"],
"title": report["title"],
"severity": report["severity"].upper(),
"timestamp": report["timestamp"],
"file": f"vulnerabilities/{report['id']}.md",
}
)
logger.info(
f"Saved {len(self.vulnerability_reports)} vulnerability reports to: {vuln_dir}"
)
logger.info(f"Saved vulnerability index to: {vuln_csv_file}")
logger.info(f"📊 Essential scan data saved to: {run_dir}")
except (OSError, RuntimeError):
logger.exception("Failed to save scan data")
def _calculate_duration(self) -> float:
try:
start = datetime.fromisoformat(self.start_time.replace("Z", "+00:00"))
if self.end_time:
end = datetime.fromisoformat(self.end_time.replace("Z", "+00:00"))
return (end - start).total_seconds()
except (ValueError, TypeError):
pass
return 0.0
def get_agent_tools(self, agent_id: str) -> list[dict[str, Any]]:
return [
exec_data
for exec_data in self.tool_executions.values()
if exec_data.get("agent_id") == agent_id
]
def get_real_tool_count(self) -> int:
return sum(
1
for exec_data in self.tool_executions.values()
if exec_data.get("tool_name") not in ["scan_start_info", "subagent_start_info"]
)
def get_total_llm_stats(self) -> dict[str, Any]:
from strix.tools.agents_graph.agents_graph_actions import _agent_instances
total_stats = {
"input_tokens": 0,
"output_tokens": 0,
"cached_tokens": 0,
"cache_creation_tokens": 0,
"cost": 0.0,
"requests": 0,
"failed_requests": 0,
}
for agent_instance in _agent_instances.values():
if hasattr(agent_instance, "llm") and hasattr(agent_instance.llm, "_total_stats"):
agent_stats = agent_instance.llm._total_stats
total_stats["input_tokens"] += agent_stats.input_tokens
total_stats["output_tokens"] += agent_stats.output_tokens
total_stats["cached_tokens"] += agent_stats.cached_tokens
total_stats["cache_creation_tokens"] += agent_stats.cache_creation_tokens
total_stats["cost"] += agent_stats.cost
total_stats["requests"] += agent_stats.requests
total_stats["failed_requests"] += agent_stats.failed_requests
total_stats["cost"] = round(total_stats["cost"], 4)
return {
"total": total_stats,
"total_tokens": total_stats["input_tokens"] + total_stats["output_tokens"],
}
def cleanup(self) -> None:
self.save_run_data()