Skip to content

The agent that turns websites into APIs!

Fix strict mypy errors and enforce type checking in CI (#125)

kalil0321743796c7253b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8318a3e..a124f5b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -34,15 +34,10 @@ jobs:
- run: uv sync --all-extras --locked
- run: uv run ruff check src tests
- # mypy reports ~170 pre-existing errors across src/. Until those are fixed the
- # job is informational only: it runs on every PR so regressions are visible
- # in the logs, but it never blocks a merge. Remove `continue-on-error` once
- # `uv run mypy src` is clean.
typecheck:
if: github.event_name != 'workflow_dispatch' || !inputs.live_windows
- name: mypy (informational)
+ name: mypy
runs-on: ubuntu-latest
- continue-on-error: true
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
diff --git a/src/reverse_api/agent_browser.py b/src/reverse_api/agent_browser.py
index 4ec4d26..31537d6 100644
--- a/src/reverse_api/agent_browser.py
+++ b/src/reverse_api/agent_browser.py
@@ -16,6 +16,8 @@ import subprocess
from dataclasses import dataclass
from typing import Any
+from rich.console import Console
+
from .utils import get_config_path
_AGENT_BROWSER_TOOLS = frozenset(
@@ -54,7 +56,7 @@ def reset_agent_browser_setup_cache() -> None:
_SHELL_INVOKER = None
-def print_agent_browser_setup_notices(console, setup: AgentBrowserSetup) -> None:
+def print_agent_browser_setup_notices(console: Console, setup: AgentBrowserSetup) -> None:
"""Emit install/fallback chatter before streaming."""
for note in setup.notices:
diff --git a/src/reverse_api/auto_engineer.py b/src/reverse_api/auto_engineer.py
index 2b17855..0f55e5f 100644
--- a/src/reverse_api/auto_engineer.py
+++ b/src/reverse_api/auto_engineer.py
@@ -5,9 +5,15 @@ Providers **auto** and **chrome-mcp** attach a browser MCP server to the SDK. Pr
when missing, validated with ``--help``) instead of attaching browser MCP here.
"""
+from __future__ import annotations
+
import asyncio
import logging
-from typing import Any
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Protocol
+
+if TYPE_CHECKING:
+ from copilot.types import PostToolUseHookInput, PostToolUseHookOutput, PreToolUseHookInput, PreToolUseHookOutput
import httpx2 as httpx
from claude_agent_sdk import (
@@ -16,6 +22,7 @@ from claude_agent_sdk import (
PermissionResultAllow,
ToolPermissionContext,
)
+from claude_agent_sdk.types import McpStdioServerConfig
from .agent_browser import (
agent_browser_prompt_fields,
@@ -45,6 +52,20 @@ def _agent_browser_prompt_context(engineer: Any) -> tuple[str, bool]:
return run_id, headless
+class AutoPromptEngineer(Protocol):
+ agent_provider: str
+ mcp_run_id: str
+ headless: bool
+ prompt: str
+ scripts_dir: Path
+ har_path: Path
+
+ def _get_language_name(self) -> str: ...
+ def _get_codegen_instructions(self) -> str: ...
+ def _get_client_filename(self) -> str: ...
+ def _get_auto_output_files(self, language_name: str, client_filename: str) -> str: ...
+
+
class ClaudeAutoEngineer(ClaudeEngineer):
"""Auto mode using Claude SDK: LLM-led browsing plus reverse-engineering codegen."""
@@ -55,8 +76,8 @@ class ClaudeAutoEngineer(ClaudeEngineer):
model: str,
output_dir: str | None = None,
agent_provider: str = "auto",
- **kwargs,
- ):
+ **kwargs: Any,
+ ) -> None:
"""Initialize Claude-backed agent engineer (HAR path derives from ``run_id``)."""
# `headless` is auto-engineer specific: for MCP providers it configures the MCP
# server's browser launch; for `agent-browser` it only adjusts prompt wording.
@@ -76,7 +97,7 @@ class ClaudeAutoEngineer(ClaudeEngineer):
self.agent_provider = agent_provider
self.headless = headless
- def _build_auto_prompts(self) -> tuple[str, str]:
+ def _build_auto_prompts(self: AutoPromptEngineer) -> tuple[str, str]:
"""Build (system_prompt, user_message) for auto mode.
The system prompt contains the agent role, codegen instructions, and output
@@ -149,7 +170,7 @@ class ClaudeAutoEngineer(ClaudeEngineer):
# Auto-approve all other tools
return PermissionResultAllow(updated_input=input_data)
- def _get_mcp_config(self) -> tuple[str, dict]:
+ def _get_mcp_config(self) -> tuple[str, McpStdioServerConfig]:
"""Return ``(server_name, mcp_config)`` for Playwright or Chrome MCP providers.
Not applicable to ``agent-browser`` (calling this raises). Auto-connect Chrome
@@ -308,11 +329,13 @@ class ClaudeAutoEngineer(ClaudeEngineer):
self.ui.console.print("\n[dim]Make sure Claude Code CLI is installed: npm install -g @anthropic-ai/claude-code[/dim]")
return None
+ return None
+
class OpenCodeAutoEngineer(OpenCodeEngineer):
"""Agent mode via OpenCode: registers a browser MCP server when the provider uses MCP."""
- def __init__(self, run_id: str, prompt: str, output_dir: str | None = None, agent_provider: str = "auto", **kwargs):
+ def __init__(self, run_id: str, prompt: str, output_dir: str | None = None, agent_provider: str = "auto", **kwargs: Any) -> None:
"""Initialize OpenCode-backed agent engineer."""
headless = kwargs.pop("headless", False)
har_dir = get_har_dir(run_id, output_dir)
@@ -327,7 +350,7 @@ class OpenCodeAutoEngineer(OpenCodeEngineer):
)
self.mcp_run_id = run_id
self.agent_provider = agent_provider
- self.mcp_name = None
+ self.mcp_name: str | None = None
self.headless = headless
def _get_active_prompts(self) -> tuple[str, str]:
@@ -564,7 +587,7 @@ class CopilotAutoEngineer:
output_dir: str | None = None,
agent_provider: str = "auto",
**kwargs: Any,
- ):
+ ) -> None:
from .copilot_engineer import CopilotEngineer
headless = kwargs.pop("headless", False)
@@ -691,14 +714,14 @@ class CopilotAutoEngineer:
},
}
- async def on_pre_tool_use(input: dict, _invocation: dict) -> dict:
+ async def on_pre_tool_use(input: PreToolUseHookInput, _invocation: dict[str, str]) -> PreToolUseHookOutput:
tool_name = input.get("toolName", "unknown")
tool_args = input.get("toolArgs") or {}
eng.ui.tool_start(tool_name, tool_args)
eng.message_store.save_tool_start(tool_name, tool_args)
return {"permissionDecision": "allow", "modifiedArgs": tool_args}
- async def on_post_tool_use(input: dict, invocation: dict) -> dict:
+ async def on_post_tool_use(input: PostToolUseHookInput, invocation: dict[str, str]) -> PostToolUseHookOutput:
tool_name = input.get("toolName", "unknown")
is_error = invocation.get("resultType") == "error" if isinstance(invocation, dict) else False
output = invocation.get("result") if isinstance(invocation, dict) else None
diff --git a/src/reverse_api/base_engineer.py b/src/reverse_api/base_engineer.py
index fdc8c87..932aaf8 100644
--- a/src/reverse_api/base_engineer.py
+++ b/src/reverse_api/base_engineer.py
@@ -12,6 +12,7 @@ from typing import Any
import questionary
from .messages import MessageStore
+from .opencode_ui import OpenCodeUI
from .session import SessionManager
from .sync import FileSyncWatcher, get_available_directory
from .tui import THEME_PRIMARY, THEME_SECONDARY, ClaudeUI
@@ -87,7 +88,7 @@ class BaseEngineer(ABC):
output_language: str = "python",
output_mode: str = "client",
interactive: bool = True,
- ):
+ ) -> None:
self.run_id = run_id
self.har_path = har_path
self.prompt = prompt
@@ -101,7 +102,7 @@ class BaseEngineer(ABC):
else:
self.scripts_dir = get_scripts_dir(run_id, output_dir)
- self.ui = ClaudeUI(verbose=verbose)
+ self.ui: ClaudeUI | OpenCodeUI = ClaudeUI(verbose=verbose)
self.usage_metadata: dict[str, Any] = {}
self.message_store = MessageStore(run_id, output_dir)
self.enable_sync = enable_sync
@@ -147,7 +148,7 @@ class BaseEngineer(ABC):
if line.startswith(" at ") or "| " in line[:20]:
return
- def start_sync(self):
+ def start_sync(self) -> None:
"""Start real-time file sync if enabled."""
if not self.enable_sync:
return
@@ -167,10 +168,10 @@ class BaseEngineer(ABC):
self.local_scripts_dir = local_dir
# Create sync watcher
- def on_sync(message):
+ def on_sync(message: str) -> None:
self.ui.sync_flash(message)
- def on_error(message):
+ def on_error(message: str) -> None:
self.ui.sync_error(message)
self.sync_watcher = FileSyncWatcher(
@@ -183,7 +184,7 @@ class BaseEngineer(ABC):
self.sync_watcher.start()
self.ui.sync_started(str(local_dir))
- def stop_sync(self):
+ def stop_sync(self) -> None:
"""Stop real-time file sync."""
if self.sync_watcher:
try:
@@ -193,7 +194,7 @@ class BaseEngineer(ABC):
finally:
self.sync_watcher = None
- def flush_sync(self):
+ def flush_sync(self) -> None:
"""Flush pending sync events and ensure all files are synced locally."""
if self.sync_watcher:
self.sync_watcher.flush()
@@ -387,8 +388,10 @@ class BaseEngineer(ABC):
def _get_opt_field(opt: Any, field: str) -> str:
"""Get a field from an option, supporting both dict and object access."""
if isinstance(opt, dict):
- return opt.get(field, "")
- return getattr(opt, field, "")
+ value = opt.get(field, "")
+ else:
+ value = getattr(opt, field, "")
+ return "" if value is None else str(value)
def _get_output_extension(self) -> str:
"""Return file extension based on output language."""
@@ -506,7 +509,7 @@ class BaseEngineer(ABC):
return f"api_client{self._get_output_extension()}"
@staticmethod
- def _quote_path(path) -> str:
+ def _quote_path(path: str | Path) -> str:
"""Shell-quote a path for the platform's default shell.
shlex.quote is POSIX-only: cmd.exe/PowerShell pass its single quotes
diff --git a/src/reverse_api/browser.py b/src/reverse_api/browser.py
index e094e8b..7b16182 100644
--- a/src/reverse_api/browser.py
+++ b/src/reverse_api/browser.py
@@ -5,9 +5,11 @@ import json
import random
import signal
import sys
+from collections.abc import Callable
from pathlib import Path
+from types import FrameType
-from playwright.sync_api import Browser, BrowserContext, Page, sync_playwright
+from playwright.sync_api import Browser, BrowserContext, Page, Playwright, sync_playwright
from playwright_stealth import Stealth
from rich.console import Console
from rich.status import Status
@@ -187,7 +189,7 @@ class ManualBrowser:
prompt: str,
output_dir: str | None = None,
use_real_chrome: bool = True, # New option to use real Chrome
- ):
+ ) -> None:
self.run_id = run_id
self.prompt = prompt
self.output_dir = output_dir
@@ -197,7 +199,7 @@ class ManualBrowser:
self.har_path = self.har_dir / "recording.har"
self.metadata_path = self.har_dir / "metadata.json"
- self._playwright = None
+ self._playwright: Playwright | None = None
self._browser: Browser | None = None
self._context: BrowserContext | None = None
self._start_time: str | None = None
@@ -216,7 +218,7 @@ class ManualBrowser:
with open(self.metadata_path, "w") as f:
json.dump(metadata, f, indent=2)
- def _handle_signal(self, signum, frame) -> None:
+ def _handle_signal(self, signum: int, frame: FrameType | None) -> None:
"""Handle interrupt signals gracefully."""
console.print("\n\n [dim]terminating capture...[/dim]")
self.close()
@@ -244,11 +246,14 @@ class ManualBrowser:
prompt) fail with "asyncio.run() cannot be called from a running event
loop". Safe to call with partially-initialized state.
"""
- for teardown in (
- lambda: self._context and self._context.close(),
- lambda: self._browser and not self._using_persistent and self._browser.close(),
- lambda: self._playwright and self._playwright.stop(),
- ):
+ teardowns: list[Callable[[], None]] = []
+ if self._context is not None:
+ teardowns.append(self._context.close)
+ if self._browser is not None and not self._using_persistent:
+ teardowns.append(self._browser.close)
+ if self._playwright is not None:
+ teardowns.append(self._playwright.stop)
+ for teardown in teardowns:
try:
teardown()
except Exception:
@@ -257,6 +262,11 @@ class ManualBrowser:
self._browser = None
self._playwright = None
+ def _require_playwright(self) -> Playwright:
+ if self._playwright is None:
+ raise RuntimeError("Playwright has not been started")
+ return self._playwright
+
def _start_with_real_chrome(self, start_url: str | None = None) -> Path:
"""Start using the real Chrome browser with user's profile."""
import shutil
@@ -277,7 +287,7 @@ class ManualBrowser:
try:
# Use launch_persistent_context with channel="chrome" to use real Chrome binary
- self._context = self._playwright.chromium.launch_persistent_context(
+ self._context = self._require_playwright().chromium.launch_persistent_context(
user_data_dir=str(temp_profile_dir),
channel="chrome", # Use real Chrome binary
headless=False,
@@ -357,7 +367,7 @@ class ManualBrowser:
"--use-mock-keychain",
]
- self._browser = self._playwright.chromium.launch(
+ self._browser = self._require_playwright().chromium.launch(
headless=False,
args=chrome_args,
ignore_default_args=["--enable-automation", "--no-sandbox"],
diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.py
index 195cfb3..9e5a8e5 100644
--- a/src/reverse_api/cli.py
+++ b/src/reverse_api/cli.py
@@ -1,19 +1,24 @@
+from __future__ import annotations
+
import asyncio
import json
import os
import random
import sys
+from collections.abc import Callable, Iterable, Iterator
from contextlib import contextmanager
from pathlib import Path
+from typing import IO, Any, Protocol, TextIO, TypedDict
import click
import questionary
import setproctitle
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
-from prompt_toolkit.completion import Completer, Completion
+from prompt_toolkit.completion import CompleteEvent, Completer, Completion
+from prompt_toolkit.document import Document
from prompt_toolkit.formatted_text import HTML
-from prompt_toolkit.key_binding import KeyBindings
+from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent
from prompt_toolkit.styles import Style as PtStyle
from questionary import Choice
from rich.console import Console
@@ -48,6 +53,16 @@ from .utils import (
resolve_run,
)
+
+class CliEventEmitter(Protocol):
+ def __call__(self, event: str, **fields: Any) -> None: ...
+
+
+class PromptModeState(TypedDict):
+ mode: str
+ mode_index: int
+
+
setproctitle.setproctitle("reverse-api-engineer")
setproctitle.setthreadtitle("reverse-api-engineer")
@@ -112,12 +127,12 @@ def default_model_for_configured_sdk(sdk: str | None = None) -> str:
"""Return the configured default model id for the given SDK (or current config SDK)."""
s = (sdk or config_manager.get("sdk", "claude") or "claude").lower()
if s == "opencode":
- return config_manager.get("opencode_model", DEFAULT_OPENCODE_MODEL)
+ return str(config_manager.get("opencode_model") or DEFAULT_OPENCODE_MODEL)
if s == "copilot":
- return config_manager.get("copilot_model", "gpt-5")
+ return str(config_manager.get("copilot_model") or "gpt-5")
if s == "cursor":
- return config_manager.get("cursor_model", "composer-2.5")
- return config_manager.get("claude_code_model", "claude-sonnet-4-6")
+ return str(config_manager.get("cursor_model") or "composer-2.5")
+ return str(config_manager.get("claude_code_model") or "claude-sonnet-4-6")
async def _load_opencode_catalog_for_settings() -> dict:
@@ -139,7 +154,7 @@ async def _load_opencode_catalog_for_settings() -> dict:
return await get_opencode_model_catalog(client)
-def _select_opencode_pair_for_settings(mode_color=THEME_PRIMARY) -> tuple[str, str] | None:
+def _select_opencode_pair_for_settings(mode_color: str = THEME_PRIMARY) -> tuple[str, str] | None:
"""Select a valid tool-capable provider/model pair from the live OpenCode catalog."""
from .opencode_runtime import opencode_model_is_free, opencode_model_is_selectable
@@ -158,7 +173,8 @@ def _select_opencode_pair_for_settings(mode_color=THEME_PRIMARY) -> tuple[str, s
return None
providers = [provider for provider in catalog.get("providers", []) if isinstance(provider, dict)]
- defaults = catalog.get("default") if isinstance(catalog.get("default"), dict) else {}
+ raw_defaults = catalog.get("default")
+ defaults = raw_defaults if isinstance(raw_defaults, dict) else {}
selectable = []
for provider in providers:
models = provider.get("models")
@@ -338,7 +354,7 @@ def _classify_error(error: str | BaseException | None, *, default: str = "unknow
@contextmanager
-def _quiet_consoles_for_json():
+def _quiet_consoles_for_json() -> Iterator[TextIO]:
"""Reserve stdout for the final JSON payload; route Rich output to stderr.
Yields the original stdout file object so the caller can write JSON to it
@@ -347,7 +363,7 @@ def _quiet_consoles_for_json():
rather than the resolved file object.
"""
real_stdout = sys.stdout
- redirected_consoles: list[tuple[Console, object]] = []
+ redirected_consoles: list[tuple[Console, IO[str] | None]] = []
sys.stdout = sys.stderr
for mod_name, mod in list(sys.modules.items()):
if not mod_name.startswith("reverse_api") or mod is None:
@@ -364,7 +380,12 @@ def _quiet_consoles_for_json():
c._file = original_inner
-def _write_json_stdout(real_stdout, payload: dict, *, json_stream: bool) -> None:
+def _write_json_line(stream: TextIO, line: str) -> None:
+ stream.write(line + "\n")
+ stream.flush()
+
+
+def _write_json_stdout(real_stdout: TextIO, payload: dict, *, json_stream: bool) -> None:
"""Write final CLI JSON payload (single doc or NDJSON terminal event)."""
out = {"event": "result", **payload} if json_stream else payload
real_stdout.write(json.dumps(out) + "\n")
@@ -716,7 +737,7 @@ def _build_run_payload(
}
-def _write_json_event(real_stdout, payload: dict) -> None:
+def _write_json_event(real_stdout: TextIO, payload: dict) -> None:
real_stdout.write(json.dumps(payload) + "\n")
real_stdout.flush()
@@ -780,7 +801,7 @@ def prompt_interactive_options( # noqa: C901 — long questionary flow; split w
class EnhancedCompleter(Completer):
"""Autocomplete for slash commands and run IDs."""
- def get_completions(self, document, complete_event):
+ def get_completions(self, document: Document, complete_event: CompleteEvent) -> Iterable[Completion]:
text = document.text_before_cursor
# Slash command completion
@@ -811,7 +832,7 @@ def prompt_interactive_options( # noqa: C901 — long questionary flow; split w
display_meta=self._get_run_meta(run_id),
)
- def _get_run_ids(self):
+ def _get_run_ids(self) -> list[str]:
"""Get all run IDs from history (newest first)."""
try:
history = session_manager.get_history(limit=50)
@@ -819,7 +840,7 @@ def prompt_interactive_options( # noqa: C901 — long questionary flow; split w
except Exception:
return []
- def _get_run_meta(self, run_id):
+ def _get_run_meta(self, run_id: str) -> str:
"""Get metadata for a run ID (timestamp + prompt snippet)."""
try:
run = session_manager.get_run(run_id)
@@ -834,13 +855,13 @@ def prompt_interactive_options( # noqa: C901 — long questionary flow; split w
command_completer = EnhancedCompleter()
# Track mode state (mutable container for closure)
- mode_state = {"mode": current_mode, "mode_index": MODES.index(current_mode)}
+ mode_state: PromptModeState = {"mode": current_mode, "mode_index": MODES.index(current_mode)}
# Create key bindings for mode cycling and autocomplete
kb = KeyBindings()
@kb.add("s-tab") # Shift+Tab
- def cycle_mode(event):
+ def cycle_mode(event: KeyPressEvent) -> None:
"""Cycle to next mode."""
mode_state["mode_index"] = (mode_state["mode_index"] + 1) % len(MODES)
mode_state["mode"] = MODES[mode_state["mode_index"]]
@@ -848,7 +869,7 @@ def prompt_interactive_options( # noqa: C901 — long questionary flow; split w
event.app.invalidate()
@kb.add("right") # Right arrow
- def accept_completion(event):
+ def accept_completion(event: KeyPressEvent) -> None:
"""Accept the current autocomplete suggestion with right arrow."""
buff = event.app.current_buffer
if buff.complete_state:
@@ -864,7 +885,7 @@ def prompt_interactive_options( # noqa: C901 — long questionary flow; split w
buff.cursor_right()
@kb.add("c-r") # Ctrl+R: random task suggestion (agent mode)
- def random_suggestion(event):
+ def random_suggestion(event: KeyPressEvent) -> None:
"""Fill prompt with a random task suggestion for agent mode."""
if mode_state["mode"] == "agent":
suggestion = random.choice(AGENT_TASK_SUGGESTIONS)
@@ -872,7 +893,7 @@ def prompt_interactive_options( # noqa: C901 — long questionary flow; split w
buff.text = suggestion
buff.cursor_position = len(suggestion)
- def get_prompt():
+ def get_prompt() -> HTML:
"""Generate prompt with current mode indicator."""
mode = mode_state["mode"]
mode_color = MODE_COLORS.get(mode, THEME_PRIMARY)
@@ -887,7 +908,7 @@ def prompt_interactive_options( # noqa: C901 — long questionary flow; split w
}
)
- session = PromptSession(
+ session: PromptSession[str] = PromptSession(
message=get_prompt, # Dynamic prompt function
completer=command_completer,
auto_suggest=AutoSuggestFromHistory(),
@@ -998,7 +1019,7 @@ CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
is_flag=True,
help="Print the agent/engineer JSON schema_version this binary emits and exit.",
)
-def main(ctx: click.Context, show_schema_version: bool):
+def main(ctx: click.Context, show_schema_version: bool) -> None:
"""reverse-api-engineer: reverse engineer apis.
Run without a subcommand to start the interactive REPL; use agent, manual,
@@ -1030,7 +1051,7 @@ def main(ctx: click.Context, show_schema_version: bool):
repl_loop()
-def repl_loop():
+def repl_loop() -> None:
"""Main interactive loop for the CLI."""
from concurrent.futures import ThreadPoolExecutor
@@ -1156,13 +1177,13 @@ def repl_loop():
console.print(f" [dim]{ERROR_CTA}[/dim]")
-def handle_settings(mode_color=THEME_PRIMARY):
+def handle_settings(mode_color: str = THEME_PRIMARY) -> None:
"""Keep the settings menu open until the user explicitly goes back."""
while _handle_settings_action(mode_color):
pass
-def _handle_settings_action(mode_color=THEME_PRIMARY) -> bool: # noqa: C901 — one branch per settings menu entry; split when next touched
+def _handle_settings_action(mode_color: str = THEME_PRIMARY) -> bool: # noqa: C901 — one branch per settings menu entry; split when next touched
"""Display and manage settings with improved layout and descriptions."""
from rich.table import Table
@@ -1463,7 +1484,7 @@ def _handle_settings_action(mode_color=THEME_PRIMARY) -> bool: # noqa: C901 —
return True
-def handle_history(mode_color=THEME_PRIMARY):
+def handle_history(mode_color: str = THEME_PRIMARY) -> None:
"""Display history of runs."""
history = session_manager.get_history(limit=15)
if not history:
@@ -1496,8 +1517,9 @@ def handle_history(mode_color=THEME_PRIMARY):
if not run_id or run_id == "back":
return
- run = session_manager.get_run(run_id)
- if run:
+ selected_run = session_manager.get_run(run_id)
+ if selected_run:
+ run = selected_run
from rich.table import Table
# Create a formatted display of the run details
@@ -1532,7 +1554,7 @@ def handle_history(mode_color=THEME_PRIMARY):
console.print(" [dim]> not found[/dim]")
-def handle_help(mode_color=THEME_PRIMARY):
+def handle_help(mode_color: str = THEME_PRIMARY) -> None:
"""Show enhanced help with command details and examples."""
from rich.table import Table
@@ -1588,7 +1610,7 @@ def handle_help(mode_color=THEME_PRIMARY):
console.print()
-def handle_messages(run_id: str, mode_color=THEME_PRIMARY):
+def handle_messages(run_id: str, mode_color: str = THEME_PRIMARY) -> None:
"""Display messages from a previous run."""
from rich.table import Table
@@ -1726,7 +1748,17 @@ Exit codes:
"Implies --json. Exits 0 if all checks pass, 1 if any error."
),
)
-def agent(prompt, url, model, output_dir, no_interactive, as_json, json_stream, headless, dry_run):
+def agent(
+ prompt: str | None,
+ url: str | None,
+ model: str | None,
+ output_dir: str | None,
+ no_interactive: bool,
+ as_json: bool,
+ json_stream: bool,
+ headless: bool,
+ dry_run: bool,
+) -> None:
"""Run autonomous agent browser session.
Agent mode runs an integrated capture + reverse-engineering pipeline.
@@ -1779,10 +1811,9 @@ def agent(prompt, url, model, output_dir, no_interactive, as_json, json_stream,
from .json_stream import make_json_stream_sink
- payload: dict
with _quiet_consoles_for_json() as real_stdout:
sink = (
- make_json_stream_sink(lambda line: (real_stdout.write(line + "\n"), real_stdout.flush()))
+ make_json_stream_sink(lambda line: _write_json_line(real_stdout, line))
if json_stream
else None
)
@@ -1827,7 +1858,7 @@ Examples:
default=None,
)
@click.option("--output-dir", "-o", default=None, help="Custom output directory for run metadata and messages.")
-def collector(prompt, model, output_dir):
+def collector(prompt: str | None, model: str | None, output_dir: str | None) -> None:
"""Run AI-powered data collection."""
if prompt is None:
if not sys.stdin.isatty():
@@ -1848,7 +1879,13 @@ def collector(prompt, model, output_dir):
sys.exit(1)
-def run_manual_capture(prompt=None, url=None, reverse_engineer=True, model=None, output_dir=None):
+def run_manual_capture(
+ prompt: str | None = None,
+ url: str | None = None,
+ reverse_engineer: bool = True,
+ model: str | None = None,
+ output_dir: str | None = None,
+) -> None:
"""Shared logic for manual capture."""
output_dir = output_dir or config_manager.get("output_dir")
@@ -1922,14 +1959,14 @@ def run_manual_capture(prompt=None, url=None, reverse_engineer=True, model=None,
def run_agent_capture(
- prompt=None,
- url=None,
- model=None,
- output_dir=None,
- interactive=True,
- headless=False,
- json_event_sink=None,
-):
+ prompt: str | None = None,
+ url: str | None = None,
+ model: str | None = None,
+ output_dir: str | None = None,
+ interactive: bool = True,
+ headless: bool = False,
+ json_event_sink: Callable[[dict[str, Any]], None] | None = None,
+) -> dict[str, Any] | None:
"""Shared logic for agent capture mode."""
output_dir = output_dir or config_manager.get("output_dir")
@@ -1941,7 +1978,7 @@ def run_agent_capture(
model=model,
)
if "command" in options:
- return
+ return None
prompt = options["prompt"]
url = options["url"]
model = options["model"]
@@ -1959,9 +1996,8 @@ def run_agent_capture(
)
-def run_collector(prompt=None, model=None, output_dir=None):
+def run_collector(prompt: str | None = None, model: str | None = None, output_dir: str | None = None) -> dict[str, Any] | None:
"""Run AI-powered data collection with Collector class."""
- import asyncio
from .collector import Collector
@@ -2014,15 +2050,15 @@ def run_collector(prompt=None, model=None, output_dir=None):
def run_auto_capture(
- prompt=None,
- url=None,
- model=None,
- output_dir=None,
- agent_provider="auto",
- interactive=True,
- headless=False,
- json_event_sink=None,
-):
+ prompt: str | None = None,
+ url: str | None = None,
+ model: str | None = None,
+ output_dir: str | None = None,
+ agent_provider: str = "auto",
+ interactive: bool = True,
+ headless: bool = False,
+ json_event_sink: Callable[[dict[str, Any]], None] | None = None,
+) -> dict[str, Any] | None:
"""Auto mode: LLM-driven browser automation + real-time reverse engineering."""
output_dir = output_dir or config_manager.get("output_dir")
@@ -2034,7 +2070,7 @@ def run_auto_capture(
model=model,
)
if "command" in options:
- return
+ return None
prompt = options["prompt"]
url = options.get("url")
model = options["model"]
@@ -2101,6 +2137,10 @@ def run_auto_capture(
try:
output_language = config_manager.get("output_language", "python")
+ from .auto_engineer import ClaudeAutoEngineer, CopilotAutoEngineer, OpenCodeAutoEngineer
+ from .cursor_engineer import CursorAutoEngineer
+
+ engineer: ClaudeAutoEngineer | CopilotAutoEngineer | OpenCodeAutoEngineer | CursorAutoEngineer
if sdk == "opencode":
from .auto_engineer import OpenCodeAutoEngineer
@@ -2297,7 +2337,16 @@ Exit codes:
is_flag=True,
help="Emit NDJSON progress events on stdout during the run, then a final {\"event\":\"result\",...} line. Implies --no-interactive.",
)
-def engineer(run_id, prompt, fresh, model, output_dir, no_interactive, as_json, json_stream):
+def engineer(
+ run_id: str,
+ prompt: str | None,
+ fresh: bool,
+ model: str | None,
+ output_dir: str | None,
+ no_interactive: bool,
+ as_json: bool,
+ json_stream: bool,
+) -> None:
"""Run reverse engineering on a previous run."""
# `run_id` is declared optional at the click level so that wrappers using
# --json get a JSON misuse payload instead of Click's plain-text "missing
@@ -2348,10 +2397,9 @@ def engineer(run_id, prompt, fresh, model, output_dir, no_interactive, as_json,
from .json_stream import make_json_stream_sink
- payload: dict
with _quiet_consoles_for_json() as real_stdout:
sink = (
- make_json_stream_sink(lambda line: (real_stdout.write(line + "\n"), real_stdout.flush()))
+ make_json_stream_sink(lambda line: _write_json_line(real_stdout, line))
if json_stream
else None
)
@@ -2382,17 +2430,17 @@ def engineer(run_id, prompt, fresh, model, output_dir, no_interactive, as_json,
def run_engineer(
- run_id,
- har_path=None,
- prompt=None,
- model=None,
- output_dir=None,
- additional_instructions=None,
- is_fresh=False,
- output_mode="client",
- interactive=True,
- json_event_sink=None,
-):
+ run_id: str,
+ har_path: Path | None = None,
+ prompt: str | None = None,
+ model: str | None = None,
+ output_dir: str | None = None,
+ additional_instructions: str | None = None,
+ is_fresh: bool = False,
+ output_mode: str = "client",
+ interactive: bool = True,
+ json_event_sink: Callable[[dict[str, Any]], None] | None = None,
+) -> dict[str, Any] | None:
"""Shared logic for reverse engineering."""
if not har_path or not prompt:
# Load from history if possible
@@ -2601,7 +2649,7 @@ JSON output (--json) is always a flat array (possibly empty []).
@click.option("--mode", "-m", type=str, default=None, help="Filter by mode (auto/manual/agent/engineer/collector).")
@click.option("--model", type=str, default=None, help="Filter by model name.")
@click.option("--search", "-s", type=str, default=None, help="Case-insensitive substring match on prompt.")
-def list_runs(as_json, full, limit, mode, model, search):
+def list_runs(as_json: bool, full: bool, limit: int, mode: str | None, model: str | None, search: str | None) -> None:
"""List generated scripts and runs with optional filters."""
from rich.table import Table
@@ -2690,7 +2738,7 @@ Exit codes (--json):
)
@click.argument("run_id", required=False)
@click.option("--json", "as_json", is_flag=True, help="Output as JSON object.")
-def show_run(run_id, as_json):
+def show_run(run_id: str, as_json: bool) -> None:
"""Show detailed info for a specific run."""
from rich.table import Table
from rich.text import Text
@@ -2778,7 +2826,7 @@ def show_run(run_id, as_json):
t.append("✓" if exists else "✗", style="green" if exists else "red")
return t
- rows: list[tuple[str, Text | str]] = [
+ rows: list[tuple[str, Text | str | None]] = [
("prompt", details["prompt"]),
("timestamp", details["timestamp"]),
("model", details["model"]),
@@ -2832,7 +2880,7 @@ def _extract_missing_module(stderr: str) -> str | None:
return missing
-def _run_non_python_script(script, script_args) -> None:
+def _run_non_python_script(script: Path, script_args: tuple[str, ...]) -> None:
"""Run a non-Python generated client with its language's toolchain and exit."""
import shutil
import subprocess
@@ -2860,7 +2908,7 @@ def _run_script_machine_payload(
file_name: str | None,
list_scripts: bool,
auto_install: bool,
- emit_event,
+ emit_event: CliEventEmitter,
) -> dict:
"""Run or list generated scripts without prompts and with JSON-safe stdout."""
import subprocess
@@ -2952,6 +3000,7 @@ def _run_script_machine_payload(
result = subprocess.run(cmd, cwd=str(script.parent), capture_output=True, text=True)
if result.returncode != 0:
break
+ assert result is not None, "build_script_commands returned no execution steps"
return _build_run_payload(
identifier=identifier,
run_id=run_id,
@@ -2970,22 +3019,21 @@ def _run_script_machine_payload(
venv_python = venv_dir / venv_bin / ("python.exe" if sys.platform == "win32" else "python")
venv_pip = venv_dir / venv_bin / ("pip.exe" if sys.platform == "win32" else "pip")
- subprocess_kwargs = {"capture_output": True, "text": True}
if not venv_dir.exists():
emit_event("venv_setup_started", run_id=run_id, path=str(venv_dir))
- subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], check=True, **subprocess_kwargs)
- subprocess.run([str(venv_pip), "install", "-q", "requests"], check=True, **subprocess_kwargs)
+ subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], check=True, capture_output=True, text=True)
+ subprocess.run([str(venv_pip), "install", "-q", "requests"], check=True, capture_output=True, text=True)
emit_event("venv_setup_completed", run_id=run_id, path=str(venv_dir))
requirements = script.parent / "requirements.txt"
if requirements.exists():
emit_event("requirements_install_started", run_id=run_id, path=str(requirements))
- subprocess.run([str(venv_pip), "install", "-q", "-r", str(requirements)], check=True, **subprocess_kwargs)
+ subprocess.run([str(venv_pip), "install", "-q", "-r", str(requirements)], check=True, capture_output=True, text=True)
emit_event("requirements_install_completed", run_id=run_id, path=str(requirements))
cmd = [str(venv_python), str(script), *script_args]
emit_event("process_started", run_id=run_id, script_path=str(script))
- result = subprocess.run(cmd, **subprocess_kwargs)
+ result = subprocess.run(cmd, capture_output=True, text=True)
stderr = result.stderr or ""
if result.returncode != 0 and "ModuleNotFoundError: No module named" in stderr:
@@ -2994,10 +3042,10 @@ def _run_script_machine_payload(
emit_event("dependency_missing", run_id=run_id, package=missing)
if auto_install:
emit_event("dependency_install_started", run_id=run_id, package=missing)
- subprocess.run([str(venv_pip), "install", "-q", missing], check=True, **subprocess_kwargs)
+ subprocess.run([str(venv_pip), "install", "-q", missing], check=True, capture_output=True, text=True)
emit_event("dependency_install_completed", run_id=run_id, package=missing)
emit_event("process_retried", run_id=run_id, script_path=str(script))
- result = subprocess.run(cmd, **subprocess_kwargs)
+ result = subprocess.run(cmd, capture_output=True, text=True)
else:
return _build_run_payload(
identifier=identifier,
@@ -3104,7 +3152,17 @@ Exit codes:
help='Emit NDJSON progress events on stdout, then a final {"event":"result",...} line. Implies --no-interactive.',
)
@click.pass_context
-def run_script(ctx, identifier, script_args, file_name, list_scripts, no_interactive, auto_install, as_json, json_stream):
+def run_script(
+ ctx: click.Context,
+ identifier: str,
+ script_args: tuple[str, ...],
+ file_name: str | None,
+ list_scripts: bool,
+ no_interactive: bool,
+ auto_install: bool,
+ as_json: bool,
+ json_stream: bool,
+) -> None:
"""Run a generated script from a previous run.
IDENTIFIER is a run ID or search term to match against prompts.
@@ -3131,7 +3189,7 @@ def run_script(ctx, identifier, script_args, file_name, list_scripts, no_interac
if machine_output:
with _quiet_consoles_for_json() as real_stdout:
- def emit_event(event: str, **fields) -> None:
+ def emit_event(event: str, **fields: Any) -> None:
if json_stream:
_write_json_event(real_stdout, {"event": event, **fields})
@@ -3259,8 +3317,8 @@ def run_script(ctx, identifier, script_args, file_name, list_scripts, no_interac
if install:
subprocess.run([str(venv_pip), "install", "-q", missing], check=True)
console.print(f"Installed [green]{missing}[/green]. Retrying...")
- result = subprocess.run(cmd)
- raise SystemExit(result.returncode)
+ retry_result = subprocess.run(cmd)
+ raise SystemExit(retry_result.returncode)
raise SystemExit(result.returncode)
diff --git a/src/reverse_api/collector.py b/src/reverse_api/collector.py
index dba22e8..d6e605b 100644
--- a/src/reverse_api/collector.py
+++ b/src/reverse_api/collector.py
@@ -39,7 +39,7 @@ class Collector:
prompt: str,
model: str,
output_dir: str | None = None,
- ):
+ ) -> None:
"""Initialize collector.
Args:
diff --git a/src/reverse_api/collector_ui.py b/src/reverse_api/collector_ui.py
index eb97c5d..7969e7c 100644
--- a/src/reverse_api/collector_ui.py
+++ b/src/reverse_api/collector_ui.py
@@ -1,5 +1,7 @@
"""Terminal UI for collector mode with streaming progress updates."""
+from typing import Any
+
from rich.console import Console
from .theme import MODE_COLORS
@@ -11,12 +13,12 @@ COLLECTOR_COLOR = MODE_COLORS["collector"]
class CollectorUI:
"""Terminal UI with real-time collection progress."""
- def __init__(self, verbose: bool = True):
+ def __init__(self, verbose: bool = True) -> None:
self.console = Console()
self.verbose = verbose
self._items_collected = 0
- def header(self, run_id: str, prompt: str, model: str | None = None, **kwargs) -> None:
+ def header(self, run_id: str, prompt: str, model: str | None = None, **kwargs: Any) -> None:
"""Display the collector session header."""
task = prompt[:80] + ("..." if len(prompt) > 80 else "")
print_session_header(
diff --git a/src/reverse_api/config.py b/src/reverse_api/config.py
index 0c11b40..18061ef 100644
--- a/src/reverse_api/config.py
+++ b/src/reverse_api/config.py
@@ -37,12 +37,12 @@ DEFAULT_CONFIG = {
class ConfigManager:
"""Handles user settings and persistence."""
- def __init__(self, config_path: Path):
+ def __init__(self, config_path: Path) -> None:
self.config_path = config_path
self.config = DEFAULT_CONFIG.copy()
self.load()
- def load(self):
+ def load(self) -> None:
"""Load configuration from disk."""
if self.config_path.exists():
try:
@@ -65,7 +65,7 @@ class ConfigManager:
# Fallback to defaults if file is corrupted
pass
- def save(self):
+ def save(self) -> None:
"""Save configuration to disk."""
self.config_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.config_path, "w") as f:
@@ -75,12 +75,12 @@ class ConfigManager:
"""Get a configuration value."""
return self.config.get(key, default)
- def set(self, key: str, value: Any):
+ def set(self, key: str, value: Any) -> None:
"""Set a configuration value and save."""
self.config[key] = value
self.save()
- def update(self, settings: dict[str, Any]):
+ def update(self, settings: dict[str, Any]) -> None:
"""Update multiple settings and save."""
self.config.update(settings)
self.save()
diff --git a/src/reverse_api/copilot_engineer.py b/src/reverse_api/copilot_engineer.py
index 6eb7756..2b38edb 100644
--- a/src/reverse_api/copilot_engineer.py
+++ b/src/reverse_api/copilot_engineer.py
@@ -12,6 +12,11 @@ _SESSION_TIMEOUT = 600
class CopilotEngineer(BaseEngineer):
"""Uses GitHub Copilot SDK to analyze HAR files and generate API scripts."""
+ # Populated by CopilotAutoEngineer before building the shared agent prompt.
+ agent_provider: str
+ mcp_run_id: str
+ headless: bool
+
def __init__(
self,
run_id: str,
@@ -19,7 +24,7 @@ class CopilotEngineer(BaseEngineer):
prompt: str,
copilot_model: str | None = None,
**kwargs: Any,
- ):
+ ) -> None:
super().__init__(run_id=run_id, har_path=har_path, prompt=prompt, **kwargs)
self.copilot_model = copilot_model or "gpt-5"
@@ -50,7 +55,7 @@ class CopilotEngineer(BaseEngineer):
# Capture self for use in the tool handler
engineer = self
- @define_tool(description="Ask the user a clarifying question. Use when you need user input to proceed.") # type: ignore[misc]
+ @define_tool(description="Ask the user a clarifying question. Use when you need user input to proceed.")
async def ask_user_question(params: AskUserParams) -> str:
# Convert pydantic models to dicts for the shared method
question_dicts = [q.model_dump() for q in params.questions]
diff --git a/src/reverse_api/cursor_engineer.py b/src/reverse_api/cursor_engineer.py
index 8843236..5ec22be 100644
--- a/src/reverse_api/cursor_engineer.py
+++ b/src/reverse_api/cursor_engineer.py
@@ -97,7 +97,7 @@ def _ensure_cursor_bridge_deps() -> str | None:
class CursorStreamUI(ClaudeUI):
"""Routes `.thinking()` into the Cursor buffer so nothing prints token-sized `..` lines."""
- def __init__(self, engineer: CursorEngineer, **kwargs: Any):
+ def __init__(self, engineer: CursorEngineer, **kwargs: Any) -> None:
super().__init__(**kwargs)
self._eng = engineer
@@ -110,6 +110,8 @@ class CursorStreamUI(ClaudeUI):
class CursorEngineer(BaseEngineer):
"""Reverse engineering using Cursor's TypeScript agent SDK (Node subprocess)."""
+ ui: ClaudeUI
+
def __init__(
self,
run_id: str,
@@ -120,7 +122,7 @@ class CursorEngineer(BaseEngineer):
cursor_web_search: bool = True,
cursor_setting_sources: list[str] | None = None,
**kwargs: Any,
- ):
+ ) -> None:
cm = cursor_model or model or "composer-2.5"
super().__init__(run_id=run_id, har_path=har_path, prompt=prompt, model=cm, **kwargs)
self.cursor_model = cm
@@ -393,10 +395,6 @@ class CursorEngineer(BaseEngineer):
except asyncio.CancelledError:
pass
- if ret is None:
- err_t = stderr_acc.decode("utf-8", errors="replace").strip()
- ret = {"error": err_t or "cursor bridge produced no result"}
-
if ret.get("ok"):
code = proc.returncode
if code not in (None, 0):
@@ -486,7 +484,7 @@ class CursorAutoEngineer(CursorEngineer):
output_dir: str | None = None,
agent_provider: str = "auto",
**kwargs: Any,
- ):
+ ) -> None:
headless = kwargs.pop("headless", False)
from .utils import get_har_dir
diff --git a/src/reverse_api/engineer.py b/src/reverse_api/engineer.py
index 60c9c02..aff6724 100644
--- a/src/reverse_api/engineer.py
+++ b/src/reverse_api/engineer.py
@@ -12,6 +12,7 @@ from claude_agent_sdk import (
McpSdkServerConfig,
PermissionResultAllow,
ResultMessage,
+ SdkMcpTool,
TextBlock,
ToolPermissionContext,
ToolResultBlock,
@@ -59,7 +60,7 @@ class ClaudeEngineer(BaseEngineer):
# Auto-approve all other tools
return PermissionResultAllow(updated_input=input_data)
- def _build_verification_tool(self):
+ def _build_verification_tool(self) -> SdkMcpTool[dict[str, Any]]:
"""The report_client_verified SdkMcpTool itself (handler + schema),
separate from _build_verification_mcp_server's server-wrapping step
purely so tests can call `.handler(args)` directly — create_sdk_mcp_
@@ -187,13 +188,23 @@ class ClaudeEngineer(BaseEngineer):
if getattr(block, "content", None) is not None:
output = block.content
elif getattr(block, "result", None) is not None:
- output = block.result
+ output = getattr(block, "result", None)
elif getattr(block, "output", None) is not None:
- output = block.output
+ output = getattr(block, "output", None)
tool_name = last_tool_name or "Tool"
- self.ui.tool_result(tool_name, is_error, output)
- self.message_store.save_tool_result(tool_name, is_error, str(output) if output else None)
+ output_text: str | None
+ if isinstance(output, list):
+ output_text = "\n".join(
+ str(item["text"])
+ if isinstance(item, dict) and item.get("type") == "text" and isinstance(item.get("text"), str)
+ else str(item)
+ for item in output
+ )
+ else:
+ output_text = str(output) if output is not None else None
+ self.ui.tool_result(tool_name, is_error, output_text)
+ self.message_store.save_tool_result(tool_name, is_error, output_text)
# The real-time "client_executed" --json-stream event
# (once inferred here from Bash tool-call text) now
# comes from the report_client_verified tool itself —
@@ -323,6 +334,8 @@ class ClaudeEngineer(BaseEngineer):
self.ui.console.print("\n[dim]Make sure Claude Code CLI is installed: npm install -g @anthropic-ai/claude-code[/dim]")
return None
+ return None
+
# Keep old class name for backwards compatibility
APIReverseEngineer = ClaudeEngineer
@@ -365,6 +378,7 @@ def run_reverse_engineering(
output_language: Target language - "python", "javascript", "typescript", "go", "java", "csharp", "php", "ruby", or "c"
output_mode: Output mode - "client" for API client code, "docs" for OpenAPI specification
"""
+ engineer: BaseEngineer
if sdk == "opencode":
from .opencode_engineer import OpenCodeEngineer
diff --git a/src/reverse_api/messages.py b/src/reverse_api/messages.py
index 564a160..763fc91 100644
--- a/src/reverse_api/messages.py
+++ b/src/reverse_api/messages.py
@@ -10,7 +10,7 @@ from .utils import get_messages_path
class MessageStore:
"""Handles saving and loading messages for engineer runs."""
- def __init__(self, run_id: str, output_dir: str | None = None):
+ def __init__(self, run_id: str, output_dir: str | None = None) -> None:
self.run_id = run_id
self.messages_path = get_messages_path(run_id, output_dir)
self.messages_path.parent.mkdir(parents=True, exist_ok=True)
@@ -19,7 +19,7 @@ class MessageStore:
"""Get current timestamp in ISO format."""
return datetime.now().isoformat()
- def append(self, msg_type: str, content: Any, **kwargs) -> None:
+ def append(self, msg_type: str, content: Any, **kwargs: Any) -> None:
"""Append a message to the JSONL file."""
message = {
"timestamp": self._get_timestamp(),
diff --git a/src/reverse_api/opencode_engineer.py b/src/reverse_api/opencode_engineer.py
index de280b1..31920a7 100644
--- a/src/reverse_api/opencode_engineer.py
+++ b/src/reverse_api/opencode_engineer.py
@@ -34,7 +34,7 @@ from .opencode_ui import OpenCodeUI
DEBUG = os.environ.get("OPENCODE_DEBUG", "0") == "1"
-def debug_log(msg: str):
+def debug_log(msg: str) -> None:
"""Print debug message if DEBUG mode is enabled."""
if DEBUG:
ts = datetime.now().strftime("%H:%M:%S.%f")[:-3]
@@ -122,7 +122,7 @@ class OpenCodeEngineer(BaseEngineer):
"haiku": "claude-haiku-4-5",
}
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
# Pop OpenCode-specific kwargs before passing to parent class
self.opencode_provider = kwargs.pop("opencode_provider", DEFAULT_OPENCODE_PROVIDER)
self.opencode_model = kwargs.pop("opencode_model", DEFAULT_OPENCODE_MODEL)
@@ -320,7 +320,7 @@ class OpenCodeEngineer(BaseEngineer):
self.message_store.save_error(error_msg)
return None
- async def _stream_events(self, client: httpx.AsyncClient): # noqa: C901 — SSE event dispatch loop; split when next touched
+ async def _stream_events(self, client: httpx.AsyncClient) -> None: # noqa: C901 — SSE event dispatch loop; split when next touched
"""Stream events from OpenCode and update UI."""
seen_parts: set = set() # Track part IDs to avoid duplicates
import time
@@ -599,7 +599,7 @@ class OpenCodeEngineer(BaseEngineer):
return False
return True
- async def _check_session_error(self, client: httpx.AsyncClient):
+ async def _check_session_error(self, client: httpx.AsyncClient) -> None:
"""Check session for errors when we get suspiciously fast idle."""
try:
# Get the session details to check for errors
@@ -651,7 +651,7 @@ class OpenCodeEngineer(BaseEngineer):
except Exception as e:
debug_log(f"Error checking session: {e}")
- async def _handle_part_update(self, properties: dict, seen_parts: set):
+ async def _handle_part_update(self, properties: dict, seen_parts: set) -> None:
"""Handle message.part.updated events."""
part = properties.get("part", {})
delta = properties.get("delta") # Incremental text update
diff --git a/src/reverse_api/opencode_runtime.py b/src/reverse_api/opencode_runtime.py
index c7eb6f3..6f6333a 100644
--- a/src/reverse_api/opencode_runtime.py
+++ b/src/reverse_api/opencode_runtime.py
@@ -16,7 +16,7 @@ import threading
import time
from collections.abc import Mapping
from dataclasses import dataclass
-from typing import Any
+from typing import Any, TypeGuard
from urllib.parse import urlparse
import httpx2 as httpx
@@ -53,7 +53,7 @@ def _parse_version(value: object) -> tuple[int, int, int] | None:
match = re.match(r"^(\d+)\.(\d+)\.(\d+)", str(value or "").strip())
if match is None:
return None
- return tuple(int(part) for part in match.groups())
+ return int(match[1]), int(match[2]), int(match[3])
def _format_version(version: tuple[int, int, int]) -> str:
@@ -85,7 +85,7 @@ def _active(model: dict[str, Any]) -> bool:
return str(model.get("status") or "active").casefold() == "active"
-def opencode_model_is_selectable(model: object) -> bool:
+def opencode_model_is_selectable(model: object) -> TypeGuard[dict[str, Any]]:
"""Return whether a catalog model is active and supports the tools RAE needs."""
return isinstance(model, dict) and _active(model) and _tool_capable(model)
@@ -164,7 +164,8 @@ async def validate_opencode_model(client: httpx.AsyncClient, provider_id: str, m
payload = await get_opencode_model_catalog(client)
providers = [provider for provider in payload["providers"] if isinstance(provider, dict)]
- defaults = payload.get("default") if isinstance(payload.get("default"), dict) else {}
+ raw_defaults = payload.get("default")
+ defaults = raw_defaults if isinstance(raw_defaults, dict) else {}
provider = next((item for item in providers if item.get("id") == provider_id), None)
free_models = _model_references(providers, defaults, free_only=True)
free_hint = f" Free options currently available: {', '.join(free_models)}." if free_models else ""
diff --git a/src/reverse_api/opencode_ui.py b/src/reverse_api/opencode_ui.py
index e0b7cab..479644c 100644
--- a/src/reverse_api/opencode_ui.py
+++ b/src/reverse_api/opencode_ui.py
@@ -14,7 +14,7 @@ from .tui import ERROR_CTA, print_session_header
class OpenCodeUI:
"""Terminal UI for OpenCode with live streaming support."""
- def __init__(self, console: Console | None = None, verbose: bool = True):
+ def __init__(self, console: Console | None = None, verbose: bool = True) -> None:
self.console = console or Console()
self.verbose = verbose
self._live: Live | None = None
@@ -226,7 +226,7 @@ class OpenCodeUI:
display_text += "..."
self.console.print(f" .. {display_text}", style=THEME_DIM)
- def success(self, script_path: str, local_path: str = None) -> None:
+ def success(self, script_path: str, local_path: str | None = None) -> None:
"""Display success message."""
self.console.print()
self.console.print(" [dim]decoding complete[/dim]")
diff --git a/src/reverse_api/pricing.py b/src/reverse_api/pricing.py
index f3038a8..547f068 100644
--- a/src/reverse_api/pricing.py
+++ b/src/reverse_api/pricing.py
@@ -1,6 +1,6 @@
"""Pricing models for different models."""
-MODEL_PRICING = {
+MODEL_PRICING: dict[str, dict[str, float]] = {
"claude-sonnet-4-6": {
"input": 3.00,
"output": 15.00,
@@ -214,7 +214,7 @@ def get_model_pricing(model_id: str) -> dict[str, float] | None:
Pricing dictionary with keys: input, output, cache_creation, cache_read, reasoning
Returns None if model not found
"""
- if model_id in MODEL_PRICING:
+ if model_id is not None and model_id in MODEL_PRICING:
return MODEL_PRICING[model_id]
elif litellm_pricing := _get_pricing_from_litellm(model_id):
return litellm_pricing
@@ -247,7 +247,7 @@ def calculate_cost(
Returns:
Total cost in USD
"""
- if model_id in MODEL_PRICING:
+ if model_id is not None and model_id in MODEL_PRICING:
pricing = MODEL_PRICING[model_id]
elif model_id and (litellm_pricing := _get_pricing_from_litellm(model_id)):
pricing = litellm_pricing
diff --git a/src/reverse_api/session.py b/src/reverse_api/session.py
index 20a3c70..ba07dae 100644
--- a/src/reverse_api/session.py
+++ b/src/reverse_api/session.py
@@ -8,12 +8,12 @@ from typing import Any
class SessionManager:
"""Handles history tracking and persistence of runs."""
- def __init__(self, history_path: Path):
+ def __init__(self, history_path: Path) -> None:
self.history_path = history_path
self.history: list[dict[str, Any]] = []
self.load()
- def load(self):
+ def load(self) -> None:
"""Load history from disk."""
if self.history_path.exists():
try:
@@ -23,13 +23,13 @@ class SessionManager:
# Fallback to empty history if file is corrupted
self.history = []
- def save(self):
+ def save(self) -> None:
"""Save history to disk."""
self.history_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.history_path, "w") as f:
json.dump(self.history, f, indent=4)
- def add_run(self, run_id: str, prompt: str, **kwargs):
+ def add_run(self, run_id: str, prompt: str, **kwargs: Any) -> None:
"""Add a new run to history."""
run_data = {
"run_id": run_id,
@@ -48,7 +48,7 @@ class SessionManager:
self.history.insert(0, run_data) # Most recent first
self.save()
- def update_run(self, run_id: str, **kwargs):
+ def update_run(self, run_id: str, **kwargs: Any) -> None:
"""Update an existing run with more data (e.g., usage after engineer)."""
for run in self.history:
if run["run_id"] == run_id:
diff --git a/src/reverse_api/sync.py b/src/reverse_api/sync.py
index 5dcf677..3cd6967 100644
--- a/src/reverse_api/sync.py
+++ b/src/reverse_api/sync.py
@@ -1,11 +1,13 @@
"""Real-time file synchronization with watchdog."""
+import os
import shutil
import time
from collections.abc import Callable
from datetime import datetime
from pathlib import Path
from threading import Event, Thread
+from typing import TypedDict
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
@@ -30,6 +32,11 @@ def get_available_directory(base_path: Path, base_name: str) -> Path:
return base_path / folder_name
+class PendingSyncEvent(TypedDict):
+ time: float
+ is_delete: bool
+
+
class SyncHandler(FileSystemEventHandler):
"""Handle file system events for syncing."""
@@ -40,14 +47,14 @@ class SyncHandler(FileSystemEventHandler):
on_sync: Callable[[str], None] | None = None,
on_error: Callable[[str], None] | None = None,
debounce_ms: int = 500,
- ):
+ ) -> None:
self.source_dir = source_dir
self.dest_dir = dest_dir
self.on_sync = on_sync
self.on_error = on_error
self.debounce_ms = debounce_ms / 1000.0 # Convert to seconds
- self.pending_events = {}
- self.last_sync_time = 0
+ self.pending_events: dict[str, PendingSyncEvent] = {}
+ self.last_sync_time = 0.0
self.file_count = 0
def _is_ignored_file(self, file_path: str) -> bool:
@@ -63,29 +70,29 @@ class SyncHandler(FileSystemEventHandler):
"""Backward-compatible helper for temporary/ignored sync paths."""
return self._is_ignored_file(file_path)
- def on_created(self, event: FileSystemEvent):
+ def on_created(self, event: FileSystemEvent) -> None:
"""Handle file creation."""
- if not event.is_directory and not self._is_ignored_file(event.src_path):
- self._queue_sync(event.src_path)
+ if not event.is_directory and not self._is_ignored_file(os.fsdecode(event.src_path)):
+ self._queue_sync(os.fsdecode(event.src_path))
- def on_modified(self, event: FileSystemEvent):
+ def on_modified(self, event: FileSystemEvent) -> None:
"""Handle file modification."""
- if not event.is_directory and not self._is_ignored_file(event.src_path):
- self._queue_sync(event.src_path)
+ if not event.is_directory and not self._is_ignored_file(os.fsdecode(event.src_path)):
+ self._queue_sync(os.fsdecode(event.src_path))
- def on_deleted(self, event: FileSystemEvent):
+ def on_deleted(self, event: FileSystemEvent) -> None:
"""Handle file deletion."""
- if not event.is_directory and not self._is_ignored_file(event.src_path):
- self._queue_sync(event.src_path, is_delete=True)
+ if not event.is_directory and not self._is_ignored_file(os.fsdecode(event.src_path)):
+ self._queue_sync(os.fsdecode(event.src_path), is_delete=True)
- def _queue_sync(self, file_path: str, is_delete: bool = False):
+ def _queue_sync(self, file_path: str, is_delete: bool = False) -> None:
"""Queue a file for syncing with debouncing."""
self.pending_events[file_path] = {
"time": time.time(),
"is_delete": is_delete,
}
- def process_pending(self):
+ def process_pending(self) -> None:
"""Process pending sync events (debounced)."""
current_time = time.time()
to_sync = []
@@ -104,7 +111,7 @@ class SyncHandler(FileSystemEventHandler):
if self.on_error:
self.on_error(f"Error syncing {Path(file_path).name}: {str(e)}")
- def _sync_file(self, source_path: str, is_delete: bool = False):
+ def _sync_file(self, source_path: str, is_delete: bool = False) -> None:
"""Sync a single file from source to destination."""
source = Path(source_path)
relative = source.relative_to(self.source_dir)
@@ -149,7 +156,7 @@ class FileSyncWatcher:
on_sync: Callable[[str], None] | None = None,
on_error: Callable[[str], None] | None = None,
debounce_ms: int = 500,
- ):
+ ) -> None:
self.source_dir = source_dir
self.dest_dir = dest_dir
self.debounce_ms = debounce_ms
@@ -171,7 +178,7 @@ class FileSyncWatcher:
self.stop_event = Event()
self.process_thread: Thread | None = None
- def start(self):
+ def start(self) -> None:
"""Start watching and syncing."""
# Ensure destination exists
self.dest_dir.mkdir(parents=True, exist_ok=True)
@@ -183,7 +190,7 @@ class FileSyncWatcher:
self.process_thread = Thread(target=self._process_loop, daemon=True)
self.process_thread.start()
- def stop(self):
+ def stop(self) -> None:
"""Stop watching and syncing."""
self.stop_event.set()
@@ -201,18 +208,18 @@ class FileSyncWatcher:
# Perform final sync of all existing files to ensure nothing is missed
self._final_sync()
- def flush(self):
+ def flush(self) -> None:
"""Flush pending events and perform a full sync without stopping the watcher."""
self.handler.process_pending()
self._final_sync()
- def _process_loop(self):
+ def _process_loop(self) -> None:
"""Background loop to process pending sync events."""
while not self.stop_event.is_set():
self.handler.process_pending()
time.sleep(0.1) # Check every 100ms
- def _final_sync(self):
+ def _final_sync(self) -> None:
"""Perform a final sync of all existing files in source directory."""
if not self.source_dir.exists():
return
@@ -277,7 +284,7 @@ def _should_skip_path(relative_path: Path) -> bool:
return False
-def sync_directory_once(source_dir: Path, dest_dir: Path):
+def sync_directory_once(source_dir: Path, dest_dir: Path) -> Path:
"""
Perform a one-time sync of a directory.
diff --git a/src/reverse_api/tui.py b/src/reverse_api/tui.py
index e947892..47094f3 100644
--- a/src/reverse_api/tui.py
+++ b/src/reverse_api/tui.py
@@ -61,7 +61,7 @@ TOOL_COLORS = {
class ClaudeUI:
"""Interactive terminal UI for Claude SDK operations."""
- def __init__(self, verbose: bool = True):
+ def __init__(self, verbose: bool = True) -> None:
self.console = Console()
self.verbose = verbose
self._tool_count = 0
@@ -385,7 +385,7 @@ def print_session_header(
console.print()
-def display_banner(console: Console, sdk: str | None = None, model: str | None = None):
+def display_banner(console: Console, sdk: str | None = None, model: str | None = None) -> None:
"""Display minimalist startup banner with * rae branding."""
# Redirected Windows streams may use a legacy encoding such as cp1252.
divider = "--" if console.options.ascii_only else "━━"
@@ -404,7 +404,7 @@ def display_banner(console: Console, sdk: str | None = None, model: str | None =
console.print()
-def display_footer(console: Console):
+def display_footer(console: Console) -> None:
"""Display minimalist footer."""
from datetime import datetime
diff --git a/src/reverse_api/utils.py b/src/reverse_api/utils.py
index b53eb64..813b479 100644
--- a/src/reverse_api/utils.py
+++ b/src/reverse_api/utils.py
@@ -1,5 +1,7 @@
"""Utility functions for run ID generation and path management."""
+from __future__ import annotations
+
import asyncio
import os
import platform
@@ -7,6 +9,10 @@ import re
import uuid
from datetime import datetime
from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+if TYPE_CHECKING:
+ from .session import SessionManager
import httpx2 as httpx
@@ -103,7 +109,7 @@ def check_for_updates() -> str | None:
return None
-def generate_folder_name(prompt: str, sdk: str = None, session_id: str = None) -> str:
+def generate_folder_name(prompt: str, sdk: str | None = None, session_id: str | None = None) -> str:
"""Generate a clean folder name from a prompt.
Uses Claude Agent SDK (for Claude SDK) or OpenCode API (for OpenCode SDK)
@@ -196,7 +202,7 @@ 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 = None) -> str:
"""Async helper to generate folder name using OpenCode API with event streaming.
Args:
@@ -247,7 +253,7 @@ async def _generate_folder_name_opencode_async(prompt: str, session_id: str = No
try:
event_complete = asyncio.Event()
- async def stream_events():
+ async def stream_events() -> None:
"""Stream events and wait for session.idle."""
try:
async with client.stream("GET", "/event", timeout=None) as response:
@@ -644,7 +650,7 @@ def get_visible_save_path(domain: str, base_dir: Path | str, suffix: int = 0) ->
return path
-def resolve_run(identifier: str, session_manager, *, interactive: bool = True) -> dict:
+def resolve_run(identifier: str, session_manager: SessionManager, *, interactive: bool = True) -> dict:
"""Resolve a run by exact ID or fuzzy prompt/folder name match.
Args:
@@ -709,7 +715,7 @@ def resolve_run(identifier: str, session_manager, *, interactive: bool = True) -
if selected is None:
raise click.Abort()
- return selected
+ return cast(dict[str, Any], selected)
def discover_scripts(run_id: str, output_dir: str | None = None, run_metadata: dict | None = None) -> list[Path]:
@@ -866,7 +872,7 @@ def extract_domain_from_har(har_path: Path) -> str | None:
return None
# Get domain from first entry's URL
- first_url = entries[0].get("request", {}).get("url", "")
+ first_url: str = entries[0].get("request", {}).get("url", "")
if first_url:
from urllib.parse import urlparse
diff --git a/tests/test_base_engineer.py b/tests/test_base_engineer.py
index 4e134c4..47b5283 100644
--- a/tests/test_base_engineer.py
+++ b/tests/test_base_engineer.py
@@ -4,6 +4,7 @@ import os
import shlex
import sys
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock, patch
@@ -30,6 +31,11 @@ class ConcreteEngineer(BaseEngineer):
return {"test": True}
[email protected]("option", [{"description": None}, SimpleNamespace(description=None)])
+def test_null_option_description_is_omitted(option):
+ assert BaseEngineer._get_opt_field(option, "description") == ""
+
+
class TestBaseEngineerInit:
"""Test BaseEngineer initialization."""
diff --git a/tests/test_cli_settings.py b/tests/test_cli_settings.py
index ea6d415..dd1fcfb 100644
--- a/tests/test_cli_settings.py
+++ b/tests/test_cli_settings.py
@@ -3,10 +3,23 @@
from unittest.mock import AsyncMock, MagicMock, patch
import httpx2 as httpx
+import pytest
from reverse_api import cli
[email protected]("sdk,key,default", [
+ ("claude", "claude_code_model", "claude-sonnet-4-6"),
+ ("opencode", "opencode_model", cli.DEFAULT_OPENCODE_MODEL),
+ ("copilot", "copilot_model", "gpt-5"),
+ ("cursor", "cursor_model", "composer-2.5"),
+])
[email protected]("saved", [None, "", "custom-model"])
+def test_default_model_handles_empty_settings(sdk, key, default, saved):
+ with patch.object(cli.config_manager, "get", side_effect=lambda name: {key: saved}.get(name)):
+ assert cli.default_model_for_configured_sdk(sdk) == (saved or default)
+
+
def test_settings_stays_open_until_back():
"""Changing settings should return to settings, not the REPL."""
with patch.object(cli, "_handle_settings_action", side_effect=[True, True, False]) as action:
diff --git a/tests/test_engineer.py b/tests/test_engineer.py
index 6670180..5ba1a19 100644
--- a/tests/test_engineer.py
+++ b/tests/test_engineer.py
@@ -574,12 +574,23 @@ class TestClaudeEngineerAnalyzeAndGenerate:
assert result is None
@pytest.mark.asyncio
- async def test_assistant_message_with_tools(self, tmp_path):
+ @pytest.mark.parametrize("tool_content,expected", [
+ ("file content", "file content"),
+ ([{"type": "text", "text": "file content"}], "file content"),
+ ([{"type": "text", "text": "first"}, {"type": "text", "text": "second"}], "first\nsecond"),
+ ([{"type": "text", "text": None}], "{'type': 'text', 'text': None}"),
+ ([{"type": "text"}], "{'type': 'text'}"),
+ ("", ""),
+ ([], ""),
+ (0, "0"),
+ (None, None),
+ ])
+ async def test_assistant_message_with_tools(self, tmp_path, tool_content, expected):
"""AssistantMessage with tool blocks processes correctly."""
eng = self._make_engineer(tmp_path)
mock_tool_use = self._make_tool_use_block("Read", {"file_path": "/test.py"})
- mock_tool_result = self._make_tool_result_block(is_error=False, content="file content")
+ mock_tool_result = self._make_tool_result_block(is_error=False, content=tool_content)
mock_text = self._make_text_block("Analyzing the file...")
mock_assistant = self._make_assistant_message(
@@ -609,9 +620,13 @@ class TestClaudeEngineerAnalyzeAndGenerate:
mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)
mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)
- with patch.object(eng, "_prompt_follow_up", new_callable=AsyncMock, return_value=None):
+ with patch.object(eng, "_prompt_follow_up", new_callable=AsyncMock, return_value=None), patch.object(
+ eng.ui, "tool_result"
+ ) as render_result:
result = await eng.analyze_and_generate()
assert result is not None
+ render_result.assert_called_once_with("Read", False, expected)
+ eng.message_store.save_tool_result.assert_called_once_with("Read", False, expected)
@pytest.mark.asyncio
async def test_exception_handling(self, tmp_path):
diff --git a/tests/test_sync.py b/tests/test_sync.py
index 35e6984..dbdd610 100644
--- a/tests/test_sync.py
+++ b/tests/test_sync.py
@@ -1,8 +1,11 @@
"""Tests for sync.py - File synchronization."""
+import os
import time
from unittest.mock import MagicMock, patch
+from watchdog.events import FileCreatedEvent, FileDeletedEvent, FileModifiedEvent
+
from reverse_api.sync import (
FileSyncWatcher,
SyncHandler,
@@ -120,6 +123,31 @@ class TestSyncHandler:
handler.on_deleted(event)
assert handler.pending_events[str(tmp_path / "file.py")]["is_delete"] is True
+ def test_byte_paths_sync_and_delete_files(self, tmp_path):
+ """Watchdog can supply bytes; preserve non-ASCII paths through all events."""
+ source = tmp_path / "source"
+ dest = tmp_path / "dest"
+ source.mkdir()
+ dest.mkdir()
+ src_file = source / "café.py"
+ src_file.write_text("initial")
+ path_bytes = os.fsencode(src_file)
+ handler = SyncHandler(source, dest, debounce_ms=0)
+
+ handler.on_created(FileCreatedEvent(path_bytes))
+ handler.process_pending()
+ assert (dest / src_file.name).read_text() == "initial"
+
+ src_file.write_text("updated")
+ handler.on_modified(FileModifiedEvent(path_bytes))
+ handler.process_pending()
+ assert (dest / src_file.name).read_text() == "updated"
+
+ src_file.unlink()
+ handler.on_deleted(FileDeletedEvent(path_bytes))
+ handler.process_pending()
+ assert not (dest / src_file.name).exists()
+
def test_process_pending_syncs_files(self, tmp_path):
"""process_pending syncs ready files."""
source = tmp_path / "source"