The agent that turns websites into APIs!
fix: lint
kalil0321d739d408f9ee
diff --git a/src/reverse_api/__init__.py b/src/reverse_api/__init__.pyindex 17c6995..df2a509 100644--- a/src/reverse_api/__init__.py+++ b/src/reverse_api/__init__.py@@ -1,6 +1,6 @@"""Reverse API - Browser traffic capture for API reverse engineering."""-from importlib.metadata import version, PackageNotFoundError+from importlib.metadata import PackageNotFoundError, versiontry:__version__ = version("reverse-api-engineer")diff --git a/src/reverse_api/base_engineer.py b/src/reverse_api/base_engineer.pyindex 672fc34..ea550b7 100644--- a/src/reverse_api/base_engineer.py+++ b/src/reverse_api/base_engineer.py@@ -2,12 +2,12 @@from abc import ABC, abstractmethodfrom pathlib import Path-from typing import Optional, Dict, Any+from typing import Any-from .utils import get_scripts_dir, generate_folder_name-from .tui import ClaudeUIfrom .messages import MessageStorefrom .sync import FileSyncWatcher, get_available_directory+from .tui import ClaudeUI+from .utils import generate_folder_name, get_scripts_dirclass BaseEngineer(ABC):@@ -18,9 +18,9 @@ class BaseEngineer(ABC):run_id: str,har_path: Path,prompt: str,- model: Optional[str] = None,- additional_instructions: Optional[str] = None,- output_dir: Optional[str] = None,+ model: str | None = None,+ additional_instructions: str | None = None,+ output_dir: str | None = None,verbose: bool = True,enable_sync: bool = False,sdk: str = "claude",@@ -33,13 +33,13 @@ class BaseEngineer(ABC):self.additional_instructions = additional_instructionsself.scripts_dir = get_scripts_dir(run_id, output_dir)self.ui = ClaudeUI(verbose=verbose)- self.usage_metadata: Dict[str, Any] = {}+ self.usage_metadata: dict[str, Any] = {}self.message_store = MessageStore(run_id, output_dir)self.enable_sync = enable_syncself.sdk = sdkself.is_fresh = is_fresh- self.sync_watcher: Optional[FileSyncWatcher] = None- self.local_scripts_dir: Optional[Path] = None+ self.sync_watcher: FileSyncWatcher | None = None+ self.local_scripts_dir: Path | None = Nonedef start_sync(self):"""Start real-time file sync if enabled."""@@ -82,7 +82,7 @@ class BaseEngineer(ABC):finally:self.sync_watcher = None- def get_sync_status(self) -> Optional[dict]:+ def get_sync_status(self) -> dict | None:"""Get current sync status."""if self.sync_watcher:return self.sync_watcher.get_status()@@ -197,9 +197,7 @@ After testing, provide your final response with:Your final output should confirm that the files have been created and provide a brief summary of what was accomplished. Do not include the full code in your response - just confirm the files were saved and summarize the key findings."""if self.additional_instructions:- base_prompt += (- f"\n\nAdditional instructions:\n{self.additional_instructions}"- )+ base_prompt += f"\n\nAdditional instructions:\n{self.additional_instructions}"tag_context = f"""## Tag-Based Workflows@@ -224,6 +222,6 @@ conversation.return base_prompt + tag_context@abstractmethod- async def analyze_and_generate(self) -> Optional[Dict[str, Any]]:+ async def analyze_and_generate(self) -> dict[str, Any] | None:"""Run the reverse engineering analysis. Must be implemented by subclasses."""passdiff --git a/src/reverse_api/browser.py b/src/reverse_api/browser.pyindex ae57667..2094fc7 100644--- a/src/reverse_api/browser.py+++ b/src/reverse_api/browser.py@@ -1,25 +1,23 @@"""Browser management with Playwright for HAR recording."""+import asyncioimport io+import jsonimport loggingimport os--import asyncio-import jsonimport randomimport signalimport sysfrom contextlib import redirect_stderrfrom pathlib import Path-from typing import Optional-from playwright.sync_api import sync_playwright, Browser, BrowserContext, Page+from playwright.sync_api import Browser, BrowserContext, Page, sync_playwrightfrom playwright_stealth import Stealthfrom rich.console import Consolefrom rich.status import Status-from .utils import get_har_dir, get_timestampfrom . import __version__+from .utils import get_har_dir, get_timestampconsole = Console()@@ -212,9 +210,9 @@ class ManualBrowser:self.har_path = self.har_dir / "recording.har"self.metadata_path = self.har_dir / "metadata.json"self._playwright = None- self._browser: Optional[Browser] = None- self._context: Optional[BrowserContext] = None- self._start_time: Optional[str] = None+ self._browser: Browser | None = None+ self._context: BrowserContext | None = None+ self._start_time: str | None = Noneself._user_agent = random.choice(USER_AGENTS)self._using_persistent = False # Track if using persistent context@@ -232,7 +230,7 @@ class ManualBrowser:def _handle_signal(self, signum, frame) -> None:"""Handle interrupt signals gracefully."""- console.print(f"\n\n [dim]terminating capture...[/dim]")+ console.print("\n\n [dim]terminating capture...[/dim]")self.close()sys.exit(0)@@ -240,7 +238,7 @@ class ManualBrowser:"""Inject stealth scripts into page before any other scripts run."""page.add_init_script(STEALTH_JS)- def _start_with_real_chrome(self, start_url: Optional[str] = None) -> Path:+ def _start_with_real_chrome(self, start_url: str | None = None) -> Path:"""Start using the real Chrome browser with user's profile."""import shutilimport tempfile@@ -248,16 +246,16 @@ class ManualBrowser:chrome_profile = get_chrome_profile_dir()if not chrome_profile:console.print(- f" [yellow]chrome profile not found, falling back to stealth mode[/yellow]"+ " [yellow]chrome profile not found, falling back to stealth mode[/yellow]")return self._start_with_stealth_chromium(start_url)# Create a temporary profile directorytemp_profile_dir = Path(tempfile.mkdtemp(prefix="chrome_profile_"))- console.print(f" [dim]using real chrome (profile copy)[/dim]")- console.print(f" [yellow]⚠️ please browse in the FIRST tab only[/yellow]")- console.print(f" [yellow] (new tabs may not be recorded)[/yellow]")+ console.print(" [dim]using real chrome (profile copy)[/dim]")+ console.print(" [yellow]⚠️ please browse in the FIRST tab only[/yellow]")+ console.print(" [yellow] (new tabs may not be recorded)[/yellow]")console.print()try:@@ -307,7 +305,7 @@ class ManualBrowser:except Exception:pass- def _start_with_stealth_chromium(self, start_url: Optional[str] = None) -> Path:+ def _start_with_stealth_chromium(self, start_url: str | None = None) -> Path:"""Start using Playwright's Chromium with stealth patches."""# Comprehensive stealth Chrome argumentschrome_args = [@@ -393,7 +391,7 @@ class ManualBrowser:return self.close()- def start(self, start_url: Optional[str] = None) -> Path:+ def start(self, start_url: str | None = None) -> Path:"""Start the browser with HAR recording enabled. Returns HAR path when done."""self._start_time = get_timestamp()@@ -401,12 +399,12 @@ class ManualBrowser:signal.signal(signal.SIGINT, self._handle_signal)signal.signal(signal.SIGTERM, self._handle_signal)- console.print(f" [dim]capture starting...[/dim]")+ console.print(" [dim]capture starting...[/dim]")console.print(f" [dim]━[/dim] [white]{self.run_id}[/white]")console.print(f" [dim]goal[/dim] [white]{self.prompt}[/white]")console.print()- console.print(f" [dim]navigate and interact to record traffic[/dim]")- console.print(f" [dim]close browser or ctrl+c to finalize[/dim]")+ console.print(" [dim]navigate and interact to record traffic[/dim]")+ console.print(" [dim]close browser or ctrl+c to finalize[/dim]")console.print()self._playwright = sync_playwright().start()@@ -421,7 +419,7 @@ class ManualBrowser:"""Close the browser and save HAR file. Returns HAR path."""end_time = get_timestamp()- console.print(f" [dim]browser closed[/dim]")+ console.print(" [dim]browser closed[/dim]")if self._context:with Status(@@ -442,14 +440,12 @@ class ManualBrowser:har_size = self.har_path.stat().st_sizestatus.update(f" [dim]har saved: {har_size:,} bytes[/dim]")else:- console.print(- " [yellow]warning: har file was not created[/yellow]"- )+ console.print(" [yellow]warning: har file was not created[/yellow]")except Exception as e:console.print(f" [yellow]warning: error saving har: {e}[/yellow]")if self.har_path.exists():- console.print(f" [dim]har file exists despite error[/dim]")+ console.print(" [dim]har file exists despite error[/dim]")self._context = None# Only close browser if not using persistent context@@ -470,8 +466,8 @@ class ManualBrowser:# Save metadataself._save_metadata(end_time)- console.print(f" [dim]capture saved[/dim]")- console.print(f" [dim]metadata synced[/dim]")+ console.print(" [dim]capture saved[/dim]")+ console.print(" [dim]metadata synced[/dim]")return self.har_path@@ -539,9 +535,7 @@ def parse_agent_model()-def get_required_api_key(- provider: str, agent_provider: str = "browser-use"-) -> tuple[str, str]:+def get_required_api_key(provider: str, agent_provider: str = "browser-use") -> tuple[str, str]:"""Get the required API key environment variable name for a provider.Args:@@ -569,16 +563,12 @@ def get_required_api_key(if provider not in provider_map:supported = ", ".join(provider_map.keys())- raise ValueError(- f"Unsupported provider: {provider}. Supported providers: {supported}"- )+ raise ValueError(f"Unsupported provider: {provider}. Supported providers: {supported}")return provider_map[provider]-def validate_api_key(- provider: str, agent_provider: str = "browser-use"-) -> tuple[bool, str | None]:+def validate_api_key(provider: str, agent_provider: str = "browser-use") -> tuple[bool, str | None]:"""Validate that the required API key exists for the provider.Args:@@ -620,7 +610,7 @@ class AgentBrowser:browser_use_model: str = "bu-llm",stagehand_model: str = "openai/computer-use-preview-2025-03-11",agent_provider: str = "browser-use",- start_url: Optional[str] = None,+ start_url: str | None = None,):"""Initialize agent browser."""self.run_id = run_id@@ -637,16 +627,14 @@ class AgentBrowser:self.har_path = self.har_dir / "recording.har"self.metadata_path = self.har_dir / "metadata.json"- self._start_time: Optional[str] = None+ self._start_time: str | None = Noneself._cdp_port = 9222def _save_metadata(self, end_time: str, result: dict | None = None) -> None:"""Save run metadata to JSON file."""# Select the appropriate model based on agent_provideragent_model = (- self.stagehand_model- if self.agent_provider == "stagehand"- else self.browser_use_model+ self.stagehand_model if self.agent_provider == "stagehand" else self.browser_use_model)metadata = {@@ -679,12 +667,11 @@ class AgentBrowser:import os# Set before importing to ensure it takes effect- os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'WARNING'+ os.environ["BROWSER_USE_LOGGING_LEVEL"] = "WARNING"# Import browser-use after setting environment variabletry:- from browser_use import Agent, Browser- from browser_use import ChatBrowserUse+ from browser_use import Agent, Browser, ChatBrowserUse# Suppress all browser-use loggers after importdef suppress_browser_use_logs():@@ -763,7 +750,7 @@ class AgentBrowser:suppress_browser_use_logs()- console.print(f" [dim]starting browser with har...[/dim]")+ console.print(" [dim]starting browser with har...[/dim]")browser = Browser(record_har_path=str(self.har_path),record_har_mode="full",@@ -776,7 +763,7 @@ class AgentBrowser:suppress_browser_use_logs()- console.print(f" [dim]browser started[/dim]")+ console.print(" [dim]browser started[/dim]")task = self.prompt@@ -790,7 +777,9 @@ class AgentBrowser:final_message = Noneif agent_result and hasattr(agent_result, "final_result"):final_result_attr = agent_result.final_result- final_message = final_result_attr() if callable(final_result_attr) else final_result_attr+ final_message = (+ final_result_attr() if callable(final_result_attr) else final_result_attr+ )result["success"] = Trueresult["message"] = final_message or "Task completed"@@ -807,7 +796,7 @@ class AgentBrowser:har_size = self.har_path.stat().st_sizeconsole.print(f" [dim]har saved: {har_size} bytes[/dim]")else:- console.print(f" [dim]har not saved by browser-use[/dim]")+ console.print(" [dim]har not saved by browser-use[/dim]")except Exception as e:console.print(f" [dim]browser stop error: {e}[/dim]")@@ -831,9 +820,7 @@ class AgentBrowser:try:try:- provider, model_name = parse_agent_model(- self.stagehand_model, self.agent_provider- )+ provider, model_name = parse_agent_model(self.stagehand_model, self.agent_provider)except ValueError as e:result["error"] = str(e)console.print(f" [red]error:[/red] {e}")@@ -845,7 +832,7 @@ class AgentBrowser:console.print(f" [red]error:[/red] {error_msg}")return result- console.print(f" [dim]starting stagehand with har...[/dim]")+ console.print(" [dim]starting stagehand with har...[/dim]")env_var_name, _ = get_required_api_key(provider, self.agent_provider)api_key = os.getenv(env_var_name)@@ -884,9 +871,7 @@ class AgentBrowser:not_found="abort", # Abort requests not in HAR (but we have empty HAR))except Exception as e:- console.print(- f" [dim]warning: could not set up HAR recording: {e}[/dim]"- )+ console.print(f" [dim]warning: could not set up HAR recording: {e}[/dim]")agent_options = {"api_key": api_key,@@ -907,7 +892,7 @@ class AgentBrowser:options=agent_options,)- console.print(f" [dim]stagehand started[/dim]")+ console.print(" [dim]stagehand started[/dim]")# Navigate to start URL first if provided (best practice per Stagehand docs)if self.start_url:@@ -953,9 +938,7 @@ class AgentBrowser:final_message = agent_result.textelse:# Fallback: try to get message if it exists as attribute- final_message = getattr(- agent_result, "message", "Task completed"- )+ final_message = getattr(agent_result, "message", "Task completed")elif isinstance(agent_result, str):# String result (simple form)final_message = agent_result@@ -999,9 +982,9 @@ class AgentBrowser:if har_size > 100: # HAR file should have some contentconsole.print(f" [dim]har saved: {har_size} bytes[/dim]")else:- console.print(f" [dim]har file exists but appears empty[/dim]")+ console.print(" [dim]har file exists but appears empty[/dim]")else:- console.print(f" [dim]har not saved[/dim]")+ console.print(" [dim]har not saved[/dim]")return result@@ -1009,7 +992,7 @@ class AgentBrowser:"""Start agent execution with HAR recording. Returns HAR path when done."""self._start_time = get_timestamp()- console.print(f" [dim]agent mode starting...[/dim]")+ console.print(" [dim]agent mode starting...[/dim]")console.print(f" [dim]━[/dim] [white]{self.run_id}[/white]")console.print(f" [dim]task[/dim] [white]{self.prompt}[/white]")console.print()@@ -1020,7 +1003,7 @@ class AgentBrowser:result = asyncio.run(self._run_with_har_capture())if result.get("success"):- console.print(f" [green]agent task completed[/green]")+ console.print(" [green]agent task completed[/green]")msg = result.get("message", "").strip()if msg:if len(msg) > 500:@@ -1035,7 +1018,7 @@ class AgentBrowser:result = {"error": str(e)}self._save_metadata(get_timestamp(), result)- console.print(f" [dim]metadata synced[/dim]")+ console.print(" [dim]metadata synced[/dim]")return self.har_path@@ -1048,7 +1031,7 @@ def run_agent_browser(browser_use_model: str = "bu-llm",stagehand_model: str = "openai/computer-use-preview-2025-03-11",agent_provider: str = "browser-use",- start_url: Optional[str] = None,+ start_url: str | None = None,) -> Path:"""Run agent browser with HAR recording."""agent_browser = AgentBrowser(diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.pyindex 5cd4e84..d2615ea 100644--- a/src/reverse_api/cli.py+++ b/src/reverse_api/cli.py@@ -1,43 +1,41 @@+import refrom pathlib import Pathimport click-import reimport questionary+from prompt_toolkit import PromptSession+from prompt_toolkit.auto_suggest import AutoSuggestFromHistory+from prompt_toolkit.completion import Completer, Completion+from prompt_toolkit.formatted_text import HTML+from prompt_toolkit.key_binding import KeyBindings+from prompt_toolkit.styles import Style as PtStylefrom questionary import Choicefrom rich.console import Console+from . import __version__from .browser import ManualBrowser, run_agent_browser+from .config import ConfigManager+from .engineer import run_reverse_engineering+from .messages import MessageStore+from .session import SessionManager+from .tui import (+ MODE_COLORS,+ THEME_DIM,+ THEME_PRIMARY,+ THEME_SECONDARY,+ display_banner,+ display_footer,+ get_model_choices,+)from .utils import (- generate_run_id,generate_folder_name,+ generate_run_id,get_config_path,- get_history_path,get_har_dir,+ get_history_path,get_timestamp,parse_engineer_prompt,)-from .tui import (- get_model_choices,- display_banner,- display_footer,- THEME_PRIMARY,- THEME_SECONDARY,- THEME_DIM,- MODE_COLORS,-)-from .config import ConfigManager-from .session import SessionManager-from .engineer import run_reverse_engineering-from .messages import MessageStore-from . import __version__--from prompt_toolkit import PromptSession-from prompt_toolkit.key_binding import KeyBindings-from prompt_toolkit.styles import Style as PtStyle-from prompt_toolkit.formatted_text import HTML-from prompt_toolkit.completion import Completer, Completion-from prompt_toolkit.auto_suggest import AutoSuggestFromHistory-console = Console()config_manager = ConfigManager(get_config_path())@@ -147,7 +145,7 @@ def prompt_interactive_options(timestamp = run.get("timestamp", "")[:16] # YYYY-MM-DD HH:MMprompt = run.get("prompt", "")[:30]return f"[{timestamp}] {prompt}"- except:+ except Exception:passreturn ""@@ -238,8 +236,7 @@ def prompt_interactive_options(return {"mode": result_mode,"run_id": prompt,- "model": model- or config_manager.get("claude_code_model", "claude-sonnet-4-5"),+ "model": model or config_manager.get("claude_code_model", "claude-sonnet-4-5"),}# Agent mode: similar to manual but uses autonomous browser@@ -409,9 +406,7 @@ def repl_loop():else:# Input is neither a tag command nor a valid run IDconsole.print(f" [red]error:[/red] run '{user_text}' not found")- console.print(- " [dim]Use @id <run_id> or type a valid run ID[/dim]"- )+ console.print(" [dim]Use @id <run_id> or type a valid run ID[/dim]")continuerun_engineer(@@ -464,9 +459,7 @@ def repl_loop():else:# Input is neither a tag command nor a valid run IDconsole.print(f" [red]error:[/red] run '{user_text}' not found")- console.print(- " [dim]Use @id <run_id> or type a valid run ID[/dim]"- )+ console.print(" [dim]Use @id <run_id> or type a valid run ID[/dim]")continuerun_engineer(@@ -569,9 +562,7 @@ def handle_settings(mode_color=THEME_PRIMARY):config_table.add_row(key_display, display_val)# Display in a clean format- console.print(- f" [bold white]Settings[/bold white] [dim]Current Configuration[/dim]"- )+ console.print(" [bold white]Settings[/bold white] [dim]Current Configuration[/dim]")console.print(config_table)console.print()@@ -609,8 +600,7 @@ def handle_settings(mode_color=THEME_PRIMARY):if action == "claude_code_model":model_choices = [- Choice(title=c["name"].lower(), value=c["value"])- for c in get_model_choices()+ Choice(title=c["name"].lower(), value=c["value"]) for c in get_model_choices()]model_choices.append(Choice(title="back", value="back"))model = questionary.select(@@ -690,14 +680,10 @@ def handle_settings(mode_color=THEME_PRIMARY):if new_provider is not None:new_provider = new_provider.strip()if not new_provider:- console.print(- " [yellow]error:[/yellow] opencode provider cannot be empty\n"- )+ console.print(" [yellow]error:[/yellow] opencode provider cannot be empty\n")else:config_manager.set("opencode_provider", new_provider)- console.print(- f" [dim]updated[/dim] opencode provider: {new_provider}\n"- )+ console.print(f" [dim]updated[/dim] opencode provider: {new_provider}\n")elif action == "opencode_model":current = config_manager.get("opencode_model", "claude-sonnet-4-5")@@ -716,9 +702,7 @@ def handle_settings(mode_color=THEME_PRIMARY):if new_model is not None:new_model = new_model.strip()if not new_model:- console.print(- " [yellow]error:[/yellow] opencode model cannot be empty\n"- )+ console.print(" [yellow]error:[/yellow] opencode model cannot be empty\n")else:config_manager.set("opencode_model", new_model)console.print(f" [dim]updated[/dim] opencode model: {new_model}\n")@@ -744,17 +728,13 @@ def handle_settings(mode_color=THEME_PRIMARY):if new_model is not None:new_model = new_model.strip()if not new_model:- console.print(- " [yellow]error:[/yellow] browser-use model cannot be empty\n"- )+ console.print(" [yellow]error:[/yellow] browser-use model cannot be empty\n")else:# Validate format for browser-usetry:parse_agent_model(new_model, "browser-use")config_manager.set("browser_use_model", new_model)- console.print(- f" [dim]updated[/dim] browser-use model: {new_model}\n"- )+ console.print(f" [dim]updated[/dim] browser-use model: {new_model}\n")except ValueError as e:console.print(f" [yellow]error:[/yellow] {e}\n")console.print(@@ -767,9 +747,7 @@ def handle_settings(mode_color=THEME_PRIMARY):elif action == "stagehand_model":from .browser import parse_agent_model- current = config_manager.get(- "stagehand_model", "openai/computer-use-preview-2025-03-11"- )+ current = config_manager.get("stagehand_model", "openai/computer-use-preview-2025-03-11")instruction = "(Format: 'openai/model' or 'anthropic/model', e.g., 'openai/computer-use-preview-2025-03-11' or 'anthropic/claude-sonnet-4-5-20250929')"new_model = questionary.text(@@ -787,9 +765,7 @@ def handle_settings(mode_color=THEME_PRIMARY):if new_model is not None:new_model = new_model.strip()if not new_model:- console.print(- " [yellow]error:[/yellow] stagehand model cannot be empty\n"- )+ console.print(" [yellow]error:[/yellow] stagehand model cannot be empty\n")else:# Validate format for stagehandtry:@@ -904,19 +880,15 @@ def handle_history(mode_color=THEME_PRIMARY):input_tokens = usage.get("input_tokens", 0)output_tokens = usage.get("output_tokens", 0)if input_tokens or output_tokens:- details_table.add_row(- "Tokens", f"{input_tokens:,} in / {output_tokens:,} out"- )+ details_table.add_row("Tokens", f"{input_tokens:,} in / {output_tokens:,} out")console.print()- console.print(f" [bold white]Run Details[/bold white]")+ console.print(" [bold white]Run Details[/bold white]")console.print(details_table)console.print()if questionary.confirm(" > recode?", qmark="").ask():- model = run.get("model") or config_manager.get(- "claude_code_model", "claude-sonnet-4-5"- )+ model = run.get("model") or config_manager.get("claude_code_model", "claude-sonnet-4-5")run_engineer(run_id, model=model)else:console.print(" [dim]> not found[/dim]")@@ -925,7 +897,6 @@ def handle_history(mode_color=THEME_PRIMARY):def handle_help(mode_color=THEME_PRIMARY):"""Show enhanced help with command details and examples."""from rich.table import Table- from rich.text import Textconsole.print()@@ -955,11 +926,9 @@ def handle_help(mode_color=THEME_PRIMARY):commands_table.add_row("/help", "Show this help message\n[dim]Usage: /help[/dim]")commands_table.add_row("", "")- commands_table.add_row(- "/exit or /quit", "Exit the application\n[dim]Usage: /exit[/dim]"- )+ commands_table.add_row("/exit or /quit", "Exit the application\n[dim]Usage: /exit[/dim]")- console.print(f" [bold white]Available Commands[/bold white]")+ console.print(" [bold white]Available Commands[/bold white]")console.print(commands_table)# Modes table@@ -972,7 +941,7 @@ def handle_help(mode_color=THEME_PRIMARY):modes_table.add_row("engineer", "Reverse engineer only (enter run_id)")modes_table.add_row("agent", "Autonomous agent + capture")- console.print(f" [bold white]Modes[/bold white] [dim]Shift+Tab to cycle[/dim]")+ console.print(" [bold white]Modes[/bold white] [dim]Shift+Tab to cycle[/dim]")console.print(modes_table)console.print()@@ -995,7 +964,7 @@ def handle_messages(run_id: str, mode_color=THEME_PRIMARY):header_table.add_row(f"Total Messages: {len(messages)}")console.print()- console.print(f" [bold white]Message Log[/bold white]")+ console.print(" [bold white]Message Log[/bold white]")console.print(header_table)console.print()@@ -1057,9 +1026,7 @@ def manual(prompt, url, reverse_engineer, model, output_dir):run_manual_capture(prompt, url, reverse_engineer, model, output_dir)-def run_manual_capture(- prompt=None, url=None, reverse_engineer=True, model=None, output_dir=None-):+def run_manual_capture(prompt=None, url=None, reverse_engineer=True, model=None, output_dir=None):"""Shared logic for manual capture."""output_dir = output_dir or config_manager.get("output_dir")@@ -1079,6 +1046,7 @@ def run_manual_capture(run_id = generate_run_id()timestamp = get_timestamp()+ sdk = config_manager.get("sdk", "claude")# Record initial sessionsession_manager.add_run(@@ -1088,6 +1056,7 @@ def run_manual_capture(url=url,model=model,mode="manual", # Track mode in history+ sdk=sdk,paths={"har_dir": str(get_har_dir(run_id, output_dir))},)@@ -1103,16 +1072,16 @@ def run_manual_capture(output_dir=output_dir,)if result:+ sdk = config_manager.get("sdk", "claude")session_manager.update_run(run_id=run_id,+ sdk=sdk,usage=result.get("usage", {}),paths={"script_path": result.get("script_path")},)-def run_agent_capture(- prompt=None, url=None, reverse_engineer=False, model=None, output_dir=None-):+def run_agent_capture(prompt=None, url=None, reverse_engineer=False, model=None, output_dir=None):"""Shared logic for agent capture mode."""output_dir = output_dir or config_manager.get("output_dir")@@ -1132,6 +1101,7 @@ def run_agent_capture(run_id = generate_run_id()timestamp = get_timestamp()+ sdk = config_manager.get("sdk", "claude")# Get agent models and provider from configbrowser_use_model = config_manager.get("browser_use_model", "bu-llm")@@ -1148,6 +1118,7 @@ def run_agent_capture(url=url,model=model,mode="agent", # Track mode in history+ sdk=sdk,paths={"har_dir": str(get_har_dir(run_id, output_dir))},)@@ -1212,8 +1183,10 @@ def run_agent_capture(output_dir=output_dir,)if result:+ sdk = config_manager.get("sdk", "claude")session_manager.update_run(run_id=run_id,+ sdk=sdk,usage=result.get("usage", {}),paths={"script_path": result.get("script_path")},)@@ -1320,9 +1293,7 @@ def run_engineer(console.print(" [dim]>[/dim] [white]decoding complete[/white]")console.print(f" [dim]>[/dim] [white]{result['script_path']}[/white]")- console.print(- f" [dim]>[/dim] [white]copied to ./scripts/{local_dir.name}[/white]\n"- )+ console.print(f" [dim]>[/dim] [white]copied to ./scripts/{local_dir.name}[/white]\n")else:# With sync enabled, just show completionconsole.print(" [dim]>[/dim] [white]decoding complete[/white]")@@ -1330,6 +1301,7 @@ def run_engineer(session_manager.update_run(run_id=run_id,+ sdk=sdk,usage=result.get("usage", {}),paths={"script_path": result.get("script_path")},)diff --git a/src/reverse_api/config.py b/src/reverse_api/config.pyindex f690896..7b257f0 100644--- a/src/reverse_api/config.py+++ b/src/reverse_api/config.py@@ -2,7 +2,7 @@import jsonfrom pathlib import Path-from typing import Any, Dict+from typing import AnyDEFAULT_CONFIG = {"claude_code_model": "claude-sonnet-4-5",@@ -29,37 +29,26 @@ class ConfigManager:"""Load configuration from disk."""if self.config_path.exists():try:- with open(self.config_path, "r") as f:+ with open(self.config_path) as f:user_config = json.load(f)# Backward compatibility: migrate old config keys# Migrate "model" -> "claude_code_model"- if (- "model" in user_config- and "claude_code_model" not in user_config- ):+ if "model" in user_config and "claude_code_model" not in user_config:user_config["claude_code_model"] = user_config["model"]# Migrate "agent_model" -> "browser_use_model" and "stagehand_model"if "agent_model" in user_config:- agent_provider = user_config.get(- "agent_provider", "browser-use"- )+ agent_provider = user_config.get("agent_provider", "browser-use")if agent_provider == "stagehand":if "stagehand_model" not in user_config:- user_config["stagehand_model"] = user_config[- "agent_model"- ]+ user_config["stagehand_model"] = user_config["agent_model"]else:if "browser_use_model" not in user_config:- user_config["browser_use_model"] = user_config[- "agent_model"- ]+ user_config["browser_use_model"] = user_config["agent_model"]# Only keep valid keys- valid_config = {- k: v for k, v in user_config.items() if k in self.config- }+ valid_config = {k: v for k, v in user_config.items() if k in self.config}self.config.update(valid_config)except (json.JSONDecodeError, OSError):# Fallback to defaults if file is corrupted@@ -80,7 +69,7 @@ class ConfigManager:self.config[key] = valueself.save()- def update(self, settings: Dict[str, Any]):+ def update(self, settings: dict[str, Any]):"""Update multiple settings and save."""self.config.update(settings)self.save()diff --git a/src/reverse_api/engineer.py b/src/reverse_api/engineer.pyindex dd7945f..8faaa12 100644--- a/src/reverse_api/engineer.py+++ b/src/reverse_api/engineer.py@@ -3,31 +3,29 @@import asyncioimport loggingfrom pathlib import Path-from typing import Optional, Dict, Any+from typing import Anyfrom claude_agent_sdk import (- ClaudeSDKClient,- ClaudeAgentOptions,AssistantMessage,+ ClaudeAgentOptions,+ ClaudeSDKClient,+ ResultMessage,TextBlock,- ToolUseBlock,ToolResultBlock,- ResultMessage,+ ToolUseBlock,)from .base_engineer import BaseEngineer# Suppress claude_agent_sdk logslogging.getLogger("claude_agent_sdk").setLevel(logging.WARNING)-logging.getLogger("claude_agent_sdk._internal.transport.subprocess_cli").setLevel(- logging.WARNING-)+logging.getLogger("claude_agent_sdk._internal.transport.subprocess_cli").setLevel(logging.WARNING)class ClaudeEngineer(BaseEngineer):"""Uses Claude Agent SDK to analyze HAR files and generate Python API scripts."""- async def analyze_and_generate(self) -> Optional[Dict[str, Any]]:+ async def analyze_and_generate(self) -> dict[str, Any] | None:"""Run the reverse engineering analysis with Claude."""self.ui.header(self.run_id, self.prompt, self.model, self.sdk)self.ui.start_analysis()@@ -55,10 +53,8 @@ class ClaudeEngineer(BaseEngineer):# Process response and show progress with TUIasync for message in client.receive_response():# Check for usage metadata in message if applicable- if hasattr(message, "usage") and isinstance(- getattr(message, "usage"), dict- ):- self.usage_metadata.update(getattr(message, "usage"))+ if hasattr(message, "usage") and isinstance(message.usage, dict):+ self.usage_metadata.update(message.usage)if isinstance(message, AssistantMessage):last_tool_name = None@@ -66,9 +62,7 @@ class ClaudeEngineer(BaseEngineer):if isinstance(block, ToolUseBlock):last_tool_name = block.nameself.ui.tool_start(block.name, block.input)- self.message_store.save_tool_start(- block.name, block.input- )+ self.message_store.save_tool_start(block.name, block.input)elif isinstance(block, ToolResultBlock):is_error = block.is_error if block.is_error else False@@ -93,9 +87,7 @@ class ClaudeEngineer(BaseEngineer):elif isinstance(message, ResultMessage):if message.is_error:self.ui.error(message.result or "Unknown error")- self.message_store.save_error(- message.result or "Unknown error"- )+ self.message_store.save_error(message.result or "Unknown error")return Noneelse:script_path = str(self.scripts_dir / "api_client.py")@@ -108,12 +100,8 @@ class ClaudeEngineer(BaseEngineer):# Calculate estimated cost if we have usage dataif self.usage_metadata:- input_tokens = self.usage_metadata.get(- "input_tokens", 0- )- output_tokens = self.usage_metadata.get(- "output_tokens", 0- )+ input_tokens = self.usage_metadata.get("input_tokens", 0)+ output_tokens = self.usage_metadata.get("output_tokens", 0)cache_creation_tokens = self.usage_metadata.get("cache_creation_input_tokens", 0)@@ -134,7 +122,7 @@ class ClaudeEngineer(BaseEngineer):self.usage_metadata["estimated_cost_usd"] = cost# Display usage breakdown- self.ui.console.print(f" [dim]Usage:[/dim]")+ self.ui.console.print(" [dim]Usage:[/dim]")if input_tokens > 0:self.ui.console.print(f" [dim] input: {input_tokens:,} tokens[/dim]"@@ -151,11 +139,9 @@ class ClaudeEngineer(BaseEngineer):self.ui.console.print(f" [dim] output: {output_tokens:,} tokens[/dim]")- self.ui.console.print(- f" [dim] total cost: ${cost:.4f}[/dim]"- )+ self.ui.console.print(f" [dim] total cost: ${cost:.4f}[/dim]")- result: Dict[str, Any] = {+ result: dict[str, Any] = {"script_path": script_path,"usage": self.usage_metadata,}@@ -182,16 +168,16 @@ def run_reverse_engineering(run_id: str,har_path: Path,prompt: str,- model: Optional[str] = None,- additional_instructions: Optional[str] = None,- output_dir: Optional[str] = None,+ model: str | None = None,+ additional_instructions: str | None = None,+ output_dir: str | None = None,verbose: bool = True,sdk: str = "claude",- opencode_provider: Optional[str] = None,- opencode_model: Optional[str] = None,+ opencode_provider: str | None = None,+ opencode_model: str | None = None,enable_sync: bool = False,is_fresh: bool = False,-) -> Optional[Dict[str, Any]]:+) -> dict[str, Any] | None:"""Run reverse engineering with the specified SDK.Args:diff --git a/src/reverse_api/messages.py b/src/reverse_api/messages.pyindex 75c3c4c..23520c5 100644--- a/src/reverse_api/messages.py+++ b/src/reverse_api/messages.py@@ -2,8 +2,7 @@import jsonfrom datetime import datetime-from pathlib import Path-from typing import Any, Dict, List, Optional+from typing import Anyfrom .utils import get_messages_path@@ -11,7 +10,7 @@ from .utils import get_messages_pathclass MessageStore:"""Handles saving and loading messages for engineer runs."""- def __init__(self, run_id: str, output_dir: Optional[str] = None):+ def __init__(self, run_id: str, output_dir: str | None = None):self.run_id = run_idself.messages_path = get_messages_path(run_id, output_dir)self.messages_path.parent.mkdir(parents=True, exist_ok=True)@@ -40,7 +39,7 @@ class MessageStore:self.append("tool_start", {"name": tool_name, "input": tool_input})def save_tool_result(- self, tool_name: str, is_error: bool = False, output: Optional[str] = None+ self, tool_name: str, is_error: bool = False, output: str | None = None) -> None:"""Save a tool result event."""self.append(@@ -56,16 +55,16 @@ class MessageStore:"""Save an error event."""self.append("error", error)- def save_result(self, result: Dict[str, Any]) -> None:+ def save_result(self, result: dict[str, Any]) -> None:"""Save the final result."""self.append("result", result)- def load(self) -> List[Dict[str, Any]]:+ def load(self) -> list[dict[str, Any]]:"""Load all messages from the JSONL file."""if not self.messages_path.exists():return []messages = []- with open(self.messages_path, "r") as f:+ with open(self.messages_path) as f:for line in f:line = line.strip()if line:@@ -76,7 +75,7 @@ class MessageStore:return messages@classmethod- def exists(cls, run_id: str, output_dir: Optional[str] = None) -> bool:+ def exists(cls, run_id: str, output_dir: str | None = None) -> bool:"""Check if messages exist for a run."""from .utils import get_messages_pathdiff --git a/src/reverse_api/opencode_engineer.py b/src/reverse_api/opencode_engineer.pyindex b1bd074..5ffbfd3 100644--- a/src/reverse_api/opencode_engineer.py+++ b/src/reverse_api/opencode_engineer.py@@ -9,7 +9,7 @@ import jsonimport osfrom datetime import datetimefrom pathlib import Path-from typing import Optional, Dict, Any+from typing import Anyimport httpx@@ -49,11 +49,11 @@ class OpenCodeEngineer(BaseEngineer):# Override UI with OpenCode-specific versionself.opencode_ui = OpenCodeUI(verbose=kwargs.get("verbose", True))self.ui = self.opencode_ui # Ensure base class uses our specialized UI- self._last_error: Optional[str] = None- self._session_id: Optional[str] = None+ self._last_error: str | None = None+ self._session_id: str | None = Noneself._last_event_time = 0.0- async def analyze_and_generate(self) -> Optional[Dict[str, Any]]:+ async def analyze_and_generate(self) -> dict[str, Any] | None:"""Run the reverse engineering analysis with OpenCode."""self.opencode_ui.header(self.run_id, self.prompt, self.opencode_model, self.sdk)self.opencode_ui.start_analysis()@@ -62,9 +62,7 @@ class OpenCodeEngineer(BaseEngineer):self.message_store.save_prompt(self._build_analysis_prompt())try:- async with httpx.AsyncClient(- base_url=self.BASE_URL, timeout=600.0- ) as client:+ async with httpx.AsyncClient(base_url=self.BASE_URL, timeout=600.0) as client:# Health checktry:health_r = await client.get("/global/health")@@ -113,7 +111,7 @@ class OpenCodeEngineer(BaseEngineer):# Wait for events to completetry:await asyncio.wait_for(event_task, timeout=600.0)- except asyncio.TimeoutError:+ except TimeoutError:self._last_error = "Session timed out (10 min)"self.opencode_ui.error(self._last_error)@@ -131,12 +129,8 @@ class OpenCodeEngineer(BaseEngineer):# Fetch actual provider and model used from session messagestry:- async with httpx.AsyncClient(- base_url=self.BASE_URL, timeout=10.0- ) as client:- messages_r = await client.get(- f"/session/{self._session_id}/message"- )+ async with httpx.AsyncClient(base_url=self.BASE_URL, timeout=10.0) as client:+ messages_r = await client.get(f"/session/{self._session_id}/message")if messages_r.status_code == 200:messages = messages_r.json()# Find first assistant message with provider/model info@@ -154,13 +148,11 @@ class OpenCodeEngineer(BaseEngineer):# Show session summary before success messageself.opencode_ui.session_summary(self.usage_metadata)local_path = (- str(self.local_scripts_dir / "api_client.py")- if self.local_scripts_dir- else None+ str(self.local_scripts_dir / "api_client.py") if self.local_scripts_dir else None)self.opencode_ui.success(script_path, local_path)- result_data: Dict[str, Any] = {+ result_data: dict[str, Any] = {"script_path": script_path,"usage": self.usage_metadata,"session_id": self._session_id,@@ -170,9 +162,7 @@ class OpenCodeEngineer(BaseEngineer):except httpx.ConnectError:self.opencode_ui.error("Connection error")- self.opencode_ui.console.print(- "\n[dim]Make sure OpenCode is running: opencode[/dim]"- )+ self.opencode_ui.console.print("\n[dim]Make sure OpenCode is running: opencode[/dim]")self.message_store.save_error("Connection error")return None@@ -195,7 +185,7 @@ class OpenCodeEngineer(BaseEngineer):self.opencode_ui.start_streaming()try:- debug_log(f"Connecting to GET /event")+ debug_log("Connecting to GET /event")async with client.stream("GET", "/event", timeout=None) as response:debug_log(f"Event stream connected, status={response.status_code}")async for line in response.aiter_lines():@@ -246,9 +236,7 @@ class OpenCodeEngineer(BaseEngineer):event_sid = properties.get("sessionID")status = properties.get("status", {})status_type = status.get("type", "idle")- debug_log(- f"session.status: sessionID={event_sid}, status={status_type}"- )+ debug_log(f"session.status: sessionID={event_sid}, status={status_type}")if event_sid == self._session_id:if status_type == "retry":attempt = status.get("attempt", 1)@@ -282,13 +270,9 @@ class OpenCodeEngineer(BaseEngineer):try:perm_response = await client.post(f"/session/{self._session_id}/permissions/{permission_id}",- json={- "response": "always"- }, # "once", "always", or "reject"- )- debug_log(- f"Permission response: {perm_response.status_code}"+ json={"response": "always"}, # "once", "always", or "reject")+ debug_log(f"Permission response: {perm_response.status_code}")if perm_response.status_code == 200:self.opencode_ui.permission_approved(perm_type)except Exception as pe:@@ -323,9 +307,7 @@ class OpenCodeEngineer(BaseEngineer):elif event_type == "session.error":event_sid = properties.get("sessionID")if event_sid and event_sid != self._session_id:- debug_log(- f"session.error for other session {event_sid}, ignoring"- )+ debug_log(f"session.error for other session {event_sid}, ignoring")continueerror_obj = properties.get("error", {})@@ -343,7 +325,9 @@ class OpenCodeEngineer(BaseEngineer):elif error_name == "APIError":msg = error_data.get("message", "API error")status = error_data.get("statusCode", "")- self._last_error = f"API error{' (' + str(status) + ')' if status else ''}: {msg}"+ self._last_error = (+ f"API error{' (' + str(status) + ')' if status else ''}: {msg}"+ )elif error_name == "MessageAbortedError":self._last_error = "Aborted"else:@@ -352,9 +336,7 @@ class OpenCodeEngineer(BaseEngineer):if isinstance(error_data, dict)else str(error_data))- self._last_error = (- f"{error_name}: {msg}" if msg else error_name- )+ self._last_error = f"{error_name}: {msg}" if msg else error_nameelse:self._last_error = str(error_obj)@@ -397,9 +379,7 @@ class OpenCodeEngineer(BaseEngineer):state = part.get("state", {})status = state.get("status")- debug_log(- f"Handling tool part: id={part_id}, tool={tool_name}, status={status}"- )+ debug_log(f"Handling tool part: id={part_id}, tool={tool_name}, status={status}")if status == "running" and part_id not in seen_parts:seen_parts.add(part_id)@@ -468,13 +448,13 @@ def run_opencode_engineering(run_id: str,har_path: Path,prompt: str,- model: Optional[str] = None,- additional_instructions: Optional[str] = None,- output_dir: Optional[str] = None,+ model: str | None = None,+ additional_instructions: str | None = None,+ output_dir: str | None = None,verbose: bool = True,- opencode_provider: Optional[str] = None,- opencode_model: Optional[str] = None,-) -> Optional[Dict[str, Any]]:+ opencode_provider: str | None = None,+ opencode_model: str | None = None,+) -> dict[str, Any] | None:"""Synchronous wrapper for OpenCode reverse engineering."""engineer = OpenCodeEngineer(run_id=run_id,diff --git a/src/reverse_api/opencode_ui.py b/src/reverse_api/opencode_ui.pyindex 0500718..f170816 100644--- a/src/reverse_api/opencode_ui.py+++ b/src/reverse_api/opencode_ui.py@@ -1,6 +1,7 @@"""OpenCode-specific Terminal UI with live streaming updates."""-from typing import Optional, Dict, Any+from typing import Any+from rich.console import Consolefrom rich.live import Livefrom rich.text import Text@@ -15,12 +16,12 @@ THEME_SUCCESS = "#ff5f50"class OpenCodeUI:"""Terminal UI for OpenCode with live streaming support."""- def __init__(self, console: Optional[Console] = None, verbose: bool = True):+ def __init__(self, console: Console | None = None, verbose: bool = True):self.console = console or Console()self.verbose = verbose- self._live: Optional[Live] = None+ self._live: Live | None = Noneself._current_text = ""- self._current_tool: Optional[str] = None+ self._current_tool: str | None = Noneself._tool_status: str = ""self._session_status: str = "idle"self._tools_used: list[str] = []@@ -29,8 +30,8 @@ class OpenCodeUI:self,run_id: str,prompt: str,- model: Optional[str] = None,- sdk: Optional[str] = None,+ model: str | None = None,+ sdk: str | None = None,) -> None:"""Display the session header."""from . import __version__@@ -44,17 +45,15 @@ class OpenCodeUI:)else:self.console.print(f" [dim]model[/dim] [white]{model or '---'}[/white]")- self.console.print(- f" [{THEME_PRIMARY}]task[/{THEME_PRIMARY}] [white]{prompt}[/white]"- )+ self.console.print(f" [{THEME_PRIMARY}]task[/{THEME_PRIMARY}] [white]{prompt}[/white]")self.console.print()def start_analysis(self) -> None:"""Display analysis start message."""- self.console.print(f" [dim]decoding starting...[/dim]")+ self.console.print(" [dim]decoding starting...[/dim]")self.console.print()- def health_check(self, health: Dict[str, Any]) -> None:+ def health_check(self, health: dict[str, Any]) -> None:"""Display server health status."""version = health.get("version", "unknown")self.console.print(f" [dim]server: OpenCode v{version}[/dim]")@@ -89,13 +88,13 @@ class OpenCodeUI:# Show current tool if runningif self._current_tool and self._tool_status == "running":- display.append(f" ⟳ ", style=THEME_PRIMARY)+ display.append(" ⟳ ", style=THEME_PRIMARY)display.append(f"{self._current_tool}", style="white")display.append(" running...\n", style=THEME_DIM)return display- def update_text(self, text: str, delta: Optional[str] = None) -> None:+ def update_text(self, text: str, delta: str | None = None) -> None:"""Update the streaming text display."""if delta:self._current_text += delta@@ -105,7 +104,7 @@ class OpenCodeUI:if self._live:self._live.update(self._build_display())- def tool_start(self, tool_name: str, tool_input: Optional[Dict] = None) -> None:+ def tool_start(self, tool_name: str, tool_input: dict | None = None) -> None:"""Display when a tool starts execution."""self._current_tool = tool_nameself._tool_status = "running"@@ -119,7 +118,7 @@ class OpenCodeUI:self._live.update(self._build_display())def tool_result(- self, tool_name: str, is_error: bool = False, output: Optional[str] = None+ self, tool_name: str, is_error: bool = False, output: str | None = None) -> None:"""Display when a tool completes."""self._current_tool = None@@ -129,15 +128,13 @@ class OpenCodeUI:self._live.update(self._build_display())if is_error:- self.console.print(- f" [red]![/red] {tool_name.lower()} failed", style=THEME_DIM- )+ self.console.print(f" [red]![/red] {tool_name.lower()} failed", style=THEME_DIM)if output:# Show first 100 chars of errorerror_preview = str(output)[:100].replace("\n", " ")self.console.print(f" {error_preview}", style=THEME_DIM)- def step_finish(self, cost: float, tokens: Dict[str, Any]) -> None:+ def step_finish(self, cost: float, tokens: dict[str, Any]) -> None:"""Display step completion with usage stats."""input_tokens = tokens.get("input", 0)output_tokens = tokens.get("output", 0)@@ -165,7 +162,7 @@ class OpenCodeUI:elif token_parts:self.console.print(f" [dim]step: {token_summary}[/dim]")- def session_summary(self, usage_metadata: Dict[str, Any]) -> None:+ def session_summary(self, usage_metadata: dict[str, Any]) -> None:"""Display session usage summary."""input_tokens = usage_metadata.get("input_tokens", 0)output_tokens = usage_metadata.get("output_tokens", 0)@@ -183,13 +180,9 @@ class OpenCodeUI:if output_tokens > 0:self.console.print(f" [dim] output: {output_tokens:,} tokens[/dim]")if reasoning_tokens > 0:- self.console.print(- f" [dim] reasoning: {reasoning_tokens:,} tokens[/dim]"- )+ self.console.print(f" [dim] reasoning: {reasoning_tokens:,} tokens[/dim]")if cache_write > 0:- self.console.print(- f" [dim] cache write: {cache_write:,} tokens[/dim]"- )+ self.console.print(f" [dim] cache write: {cache_write:,} tokens[/dim]")if cache_read > 0:self.console.print(f" [dim] cache read: {cache_read:,} tokens[/dim]")@@ -215,7 +208,7 @@ class OpenCodeUI:def success(self, script_path: str, local_path: str = None) -> None:"""Display success message."""self.console.print()- self.console.print(f" [dim]decoding complete[/dim]")+ self.console.print(" [dim]decoding complete[/dim]")self.console.print(f" [dim]internal:[/dim] [white]{script_path}[/white]")if local_path:self.console.print(f" [dim]synced:[/dim] [white]{local_path}[/white]")@@ -228,9 +221,7 @@ class OpenCodeUI:def permission_requested(self, perm_type: str, title: str) -> None:"""Display when a permission is requested."""- self.console.print(- f" [yellow]?[/yellow] [dim]permission:[/dim] {title}", style=THEME_DIM- )+ self.console.print(f" [yellow]?[/yellow] [dim]permission:[/dim] {title}", style=THEME_DIM)def permission_approved(self, perm_type: str) -> None:"""Display when a permission is auto-approved."""@@ -259,15 +250,11 @@ class OpenCodeUI:# Show current task if there is one in progressif in_progress_todos:current_task = in_progress_todos[0]- task_content = current_task.get("activeForm") or current_task.get(- "content", ""- )+ task_content = current_task.get("activeForm") or current_task.get("content", "")# Truncate if too longif len(task_content) > 50:task_content = task_content[:47] + "..."- self.console.print(- f" [dim]tasks:[/dim] {status_str} [dim]→ {task_content}[/dim]"- )+ self.console.print(f" [dim]tasks:[/dim] {status_str} [dim]→ {task_content}[/dim]")else:self.console.print(f" [dim]tasks:[/dim] {status_str}")@@ -306,14 +293,12 @@ class OpenCodeUI:def session_compacted(self) -> None:"""Display context compaction notification."""- self.console.print(f" [dim]context compacted[/dim]")+ self.console.print(" [dim]context compacted[/dim]")def session_retry(self, attempt: int, message: str) -> None:"""Display retry status."""reason = message if message else "retrying..."- self.console.print(- f" [yellow]⟳[/yellow] [dim]attempt {attempt}:[/dim] {reason}"- )+ self.console.print(f" [yellow]⟳[/yellow] [dim]attempt {attempt}:[/dim] {reason}")def _summarize_input(self, tool_name: str, tool_input: dict) -> str:"""Create a brief summary of tool input."""diff --git a/src/reverse_api/pricing.py b/src/reverse_api/pricing.pyindex c8c30aa..06d0272 100644--- a/src/reverse_api/pricing.py+++ b/src/reverse_api/pricing.py@@ -166,16 +166,11 @@ def _get_pricing_from_litellm(model_id: str) -> dict[str, float] | None:# We need to multiply by 1,000,000 to get per-million costpricing = {"input": litellm_pricing.get("input_cost_per_token", 0) * 1_000_000,- "output": litellm_pricing.get("output_cost_per_token", 0)- * 1_000_000,- "cache_creation": litellm_pricing.get(- "cache_creation_input_token_cost", 0- )- * 1_000_000,- "cache_read": litellm_pricing.get("cache_read_input_token_cost", 0)- * 1_000_000,- "reasoning": litellm_pricing.get("output_cost_per_token", 0)+ "output": litellm_pricing.get("output_cost_per_token", 0) * 1_000_000,+ "cache_creation": litellm_pricing.get("cache_creation_input_token_cost", 0)* 1_000_000,+ "cache_read": litellm_pricing.get("cache_read_input_token_cost", 0) * 1_000_000,+ "reasoning": litellm_pricing.get("output_cost_per_token", 0) * 1_000_000,}if pricing["input"] > 0 or pricing["output"] > 0:diff --git a/src/reverse_api/session.py b/src/reverse_api/session.pyindex e1b175e..1945c26 100644--- a/src/reverse_api/session.py+++ b/src/reverse_api/session.py@@ -2,7 +2,7 @@import jsonfrom pathlib import Path-from typing import Any, Dict, List, Optional+from typing import Anyclass SessionManager:@@ -10,14 +10,14 @@ class SessionManager:def __init__(self, history_path: Path):self.history_path = history_path- self.history: List[Dict[str, Any]] = []+ self.history: list[dict[str, Any]] = []self.load()def load(self):"""Load history from disk."""if self.history_path.exists():try:- with open(self.history_path, "r") as f:+ with open(self.history_path) as f:self.history = json.load(f)except (json.JSONDecodeError, OSError):# Fallback to empty history if file is corrupted@@ -38,6 +38,7 @@ class SessionManager:"url": kwargs.get("url"),"model": kwargs.get("model"),"mode": kwargs.get("mode", "manual"), # Track which mode was used+ "sdk": kwargs.get("sdk"),"usage": kwargs.get("usage", {}),"paths": kwargs.get("paths", {}),}@@ -60,13 +61,13 @@ class SessionManager:breakself.save()- def get_run(self, run_id: str) -> Optional[Dict[str, Any]]:+ def get_run(self, run_id: str) -> dict[str, Any] | None:"""Get data for a specific run."""for run in self.history:if run["run_id"] == run_id:return runreturn None- def get_history(self, limit: int = 10) -> List[Dict[str, Any]]:+ def get_history(self, limit: int = 10) -> list[dict[str, Any]]:"""Get recent history."""return self.history[:limit]diff --git a/src/reverse_api/sync.py b/src/reverse_api/sync.pyindex 353b90f..fd352bc 100644--- a/src/reverse_api/sync.py+++ b/src/reverse_api/sync.py@@ -1,13 +1,14 @@"""Real-time file synchronization with watchdog."""-import timeimport shutil+import time+from collections.abc import Callablefrom datetime import datetimefrom pathlib import Path-from typing import Optional, Callable-from threading import Thread, Event+from threading import Event, Thread++from watchdog.events import FileSystemEvent, FileSystemEventHandlerfrom watchdog.observers import Observer-from watchdog.events import FileSystemEventHandler, FileSystemEventdef get_available_directory(base_path: Path, base_name: str) -> Path:@@ -20,9 +21,7 @@ def get_available_directory(base_path: Path, base_name: str) -> Path:target_dir = base_path / base_name# If directory doesn't exist or is empty, use it- if not target_dir.exists() or (- target_dir.is_dir() and not any(target_dir.iterdir())- ):+ if not target_dir.exists() or (target_dir.is_dir() and not any(target_dir.iterdir())):return target_dir# Otherwise, create a new directory with timestamp@@ -38,8 +37,8 @@ class SyncHandler(FileSystemEventHandler):self,source_dir: Path,dest_dir: Path,- on_sync: Optional[Callable[[str], None]] = None,- on_error: Optional[Callable[[str], None]] = None,+ on_sync: Callable[[str], None] | None = None,+ on_error: Callable[[str], None] | None = None,debounce_ms: int = 500,):self.source_dir = source_dir@@ -126,8 +125,8 @@ class FileSyncWatcher:self,source_dir: Path,dest_dir: Path,- on_sync: Optional[Callable[[str], None]] = None,- on_error: Optional[Callable[[str], None]] = None,+ on_sync: Callable[[str], None] | None = None,+ on_error: Callable[[str], None] | None = None,debounce_ms: int = 500,):self.source_dir = source_dir@@ -149,7 +148,7 @@ class FileSyncWatcher:# Thread controlself.stop_event = Event()- self.process_thread: Optional[Thread] = None+ self.process_thread: Thread | None = Nonedef start(self):"""Start watching and syncing."""@@ -187,9 +186,7 @@ class FileSyncWatcher:}seconds_since_sync = (- time.time() - self.handler.last_sync_time- if self.handler.last_sync_time > 0- else 0+ time.time() - self.handler.last_sync_time if self.handler.last_sync_time > 0 else 0)return {diff --git a/src/reverse_api/tui.py b/src/reverse_api/tui.pyindex 4ec95c7..4c2ea74 100644--- a/src/reverse_api/tui.py+++ b/src/reverse_api/tui.py@@ -1,6 +1,5 @@"""Rich Terminal UI for Claude SDK interactions."""-from typing import Optionalfrom rich.console import Consolefrom rich.text import Text@@ -56,7 +55,9 @@ class ClaudeUI:self._tool_count = 0self._tools_used: list[str] = []- def header(self, run_id: str, prompt: str, model: Optional[str] = None, sdk: Optional[str] = None) -> None:+ def header(+ self, run_id: str, prompt: str, model: str | None = None, sdk: str | None = None+ ) -> None:"""Display the session header."""from . import __version__@@ -64,17 +65,17 @@ class ClaudeUI:self.console.print(f" [white]reverse-api[/white] [dim]v{__version__}[/dim]")self.console.print(f" [dim]━[/dim] [white]{run_id}[/white]")if sdk:- self.console.print(f" [red]sdk[/red] [red]{sdk}[/red] [red]|[/red] [red]model[/red] [red]{model or '---'}[/red]")+ self.console.print(+ f" [red]sdk[/red] [red]{sdk}[/red] [red]|[/red] [red]model[/red] [red]{model or '---'}[/red]"+ )else:self.console.print(f" [dim]model[/dim] [white]{model or '---'}[/white]")- self.console.print(- f" [{THEME_PRIMARY}]task[/{THEME_PRIMARY}] [white]{prompt}[/white]"- )+ self.console.print(f" [{THEME_PRIMARY}]task[/{THEME_PRIMARY}] [white]{prompt}[/white]")self.console.print()def start_analysis(self) -> None:"""Display analysis start message."""- self.console.print(f" [dim]decoding starting...[/dim]")+ self.console.print(" [dim]decoding starting...[/dim]")self.console.print()def tool_start(self, tool_name: str, tool_input: dict) -> None:@@ -93,7 +94,7 @@ class ClaudeUI:)def tool_result(- self, tool_name: str, is_error: bool = False, output: Optional[str] = None+ self, tool_name: str, is_error: bool = False, output: str | None = None) -> None:"""Display when a tool completes."""if is_error:@@ -134,7 +135,7 @@ class ClaudeUI:def success(self, script_path: str, local_path: str = None) -> None:"""Display success message with generated script path."""self.console.print()- self.console.print(f" [dim]decoding complete[/dim]")+ self.console.print(" [dim]decoding complete[/dim]")self.console.print(f" [dim]internal:[/dim] [white]{script_path}[/white]")if local_path:self.console.print(f" [dim]synced:[/dim] [white]{local_path}[/white]")@@ -199,21 +200,24 @@ def get_model_choices() -> list[dict]:]-def display_banner(console: Console, sdk: Optional[str] = None, model: Optional[str] = None):+def display_banner(console: Console, sdk: str | None = None, model: str | None = None):"""Display ultra-minimalist banner."""console.print()- console.print(f" [bold white]reverse-api[/bold white]")+ console.print(" [bold white]reverse-api[/bold white]")console.print(f" [bold {THEME_PRIMARY}]━━[/bold {THEME_PRIMARY}]")if sdk and model:- console.print(f" [red]sdk[/red] [red]{sdk}[/red] [red]|[/red] [red]model[/red] [red]{model}[/red]")+ console.print(+ f" [red]sdk[/red] [red]{sdk}[/red] [red]|[/red] [red]model[/red] [red]{model}[/red]"+ )console.print()- console.print(f" [dim white]AI agents for API reverse engineering.[/dim white]")+ console.print(" [dim white]AI agents for API reverse engineering.[/dim white]")console.print()def display_footer(console: Console):"""Display minimalist footer."""from datetime import datetime+from . import __version__time_str = datetime.now().strftime("%H:%M")diff --git a/src/reverse_api/utils.py b/src/reverse_api/utils.pyindex 839ec5b..753590b 100644--- a/src/reverse_api/utils.py+++ b/src/reverse_api/utils.py@@ -43,10 +43,11 @@ def generate_folder_name(prompt: str, sdk: str = None, session_id: str = None) -async def _generate_folder_name_async(prompt: str) -> str:"""Async helper to generate folder name using Claude Agent SDK."""import logging+from claude_agent_sdk import (- ClaudeSDKClient,- ClaudeAgentOptions,AssistantMessage,+ ClaudeAgentOptions,+ ClaudeSDKClient,TextBlock,)@@ -85,17 +86,17 @@ async def _generate_folder_name_async(prompt: str) -> str:return name if name else _slugify(prompt)-async def _generate_folder_name_opencode_async(- prompt: str, session_id: str = None-) -> str:+async def _generate_folder_name_opencode_async(prompt: str, session_id: str = None) -> str:"""Async helper to generate folder name using OpenCode API with event streaming.Args:prompt: The task prompt to generate a folder name forsession_id: Optional existing session ID to reuse. If None, creates a new session."""- import httpximport json++ import httpx+from .config import ConfigManagerBASE_URL = "http://127.0.0.1:4096"@@ -113,8 +114,8 @@ async def _generate_folder_name_opencode_async(async with httpx.AsyncClient(base_url=BASE_URL, timeout=15.0) as client:try:await client.get("/global/health")- except Exception:- raise Exception("OpenCode server not responding")+ except Exception as e:+ raise Exception("OpenCode server not responding") from esession_created = Falseif session_id is None:@@ -172,7 +173,7 @@ async def _generate_folder_name_opencode_async(try:await asyncio.wait_for(event_complete.wait(), timeout=10.0)- except asyncio.TimeoutError:+ except TimeoutError:pass # Fall through to fetch messages anywayevent_task.cancel()@@ -216,6 +217,51 @@ def _slugify(text: str) -> str:return "_".join(words)[:50]+def parse_engineer_prompt(input_text: str) -> dict:+ """Parse engineer mode input for tags.++ Returns:+ dict: {+ "run_id": str | None,+ "fresh": bool,+ "prompt": str,+ "is_tag_command": bool+ }+ """+ if not input_text:+ return {+ "run_id": None,+ "fresh": False,+ "prompt": "",+ "is_tag_command": False,+ }++ # Regex for @id <run_id> [--fresh] <prompt>+ # Group 1: run_id+ # Group 2: fresh flag (optional)+ # Group 3: prompt (optional)+ pattern = r"@id\s+([a-zA-Z0-9-_]+)(?:\s+(--fresh))?(?:\s+(.*))?"+ match = re.match(pattern, input_text.strip())++ if match:+ run_id = match.group(1)+ fresh = bool(match.group(2))+ remaining_prompt = match.group(3) or ""+ return {+ "run_id": run_id,+ "fresh": fresh,+ "prompt": remaining_prompt,+ "is_tag_command": True,+ }++ return {+ "run_id": None,+ "fresh": False,+ "prompt": input_text.strip(),+ "is_tag_command": False,+ }++def generate_run_id() -> str:"""Generate a unique run ID using a short UUID format."""return uuid.uuid4().hex[:12]