The agent that turns websites into APIs!
fix(cli): suppress follow-up prompt in --json / --no-interactive mode
Kalil Bouziguesea9ea77e3025
diff --git a/src/reverse_api/base_engineer.py b/src/reverse_api/base_engineer.pyindex dba7d56..0f83ae1 100644--- a/src/reverse_api/base_engineer.py+++ b/src/reverse_api/base_engineer.py@@ -42,6 +42,7 @@ class BaseEngineer(ABC):is_fresh: bool = False,output_language: str = "python",output_mode: str = "client",+ interactive: bool = True,):self.run_id = run_idself.har_path = har_path@@ -67,6 +68,10 @@ class BaseEngineer(ABC):self.sync_watcher: FileSyncWatcher | None = Noneself.local_scripts_dir: Path | None = Noneself._stderr_error_shown = False+ # When False, _prompt_follow_up() returns None immediately so the+ # conversation loop in subclasses ends after the first generation.+ # Set this from --json / --no-interactive entry points.+ self.interactive = interactivedef _handle_cli_stderr(self, line: str) -> None:"""Filter CLI subprocess stderr. Shows full output in DEBUG mode, otherwise shows a single clean error."""@@ -279,9 +284,16 @@ class BaseEngineer(ABC):async def _prompt_follow_up(self) -> str | None:"""Prompt user for a follow-up message. Returns None to finish.- Uses plain input() via executor instead of questionary to avoid- terminal state issues after the SDK subprocess exits.+ In non-interactive mode (e.g. --json / --no-interactive) returns None+ immediately so the conversation loop terminates after the first+ generation. Otherwise uses plain input() via executor instead of+ questionary to avoid terminal state issues after the SDK subprocess+ exits."""+ if not self.interactive:+ # Still flush sync so any partial output reaches disk before we exit.+ self.flush_sync()+ return None# Ensure all files are synced locally before waiting for user inputself.flush_sync()self.ui.console.print()diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.pyindex fca2eef..ee2e093 100644--- a/src/reverse_api/cli.py+++ b/src/reverse_api/cli.py@@ -1111,8 +1111,14 @@ def agent(prompt, url, model, output_dir, no_interactive, as_json):click.echo("error: --prompt is required when --no-interactive is set", err=True)sys.exit(2)+ # Either flag must suppress the post-generation follow-up prompt that would+ # otherwise block on stdin (`input(" > ")`) inside ClaudeAutoEngineer.+ interactive = not (as_json or no_interactive)+if not as_json:- run_agent_capture(prompt=prompt, url=url, model=model, output_dir=output_dir)+ run_agent_capture(+ prompt=prompt, url=url, model=model, output_dir=output_dir, interactive=interactive+ )returnpayload: dict@@ -1123,6 +1129,7 @@ def agent(prompt, url, model, output_dir, no_interactive, as_json):url=url,model=model,output_dir=output_dir,+ interactive=interactive,)payload = _build_agent_payload(result, prompt=prompt, url=url, output_dir=output_dir)except KeyboardInterrupt:@@ -1198,7 +1205,7 @@ def run_manual_capture(prompt=None, url=None, reverse_engineer=True, model=None,console.print(f" [dim]>[/dim] [dim]use 'reverse-api-engineer engineer {run_id}' to engineer later[/dim]\n")-def run_agent_capture(prompt=None, url=None, model=None, output_dir=None):+def run_agent_capture(prompt=None, url=None, model=None, output_dir=None, interactive=True):"""Shared logic for agent capture mode."""output_dir = output_dir or config_manager.get("output_dir")@@ -1222,6 +1229,7 @@ def run_agent_capture(prompt=None, url=None, model=None, output_dir=None):model=model,output_dir=output_dir,agent_provider=agent_provider,+ interactive=interactive,)@@ -1274,7 +1282,9 @@ def run_collector(prompt=None, model=None, output_dir=None):traceback.print_exc()-def run_auto_capture(prompt=None, url=None, model=None, output_dir=None, agent_provider="auto"):+def run_auto_capture(+ prompt=None, url=None, model=None, output_dir=None, agent_provider="auto", interactive=True+):"""Auto mode: LLM-driven browser automation + real-time reverse engineering."""output_dir = output_dir or config_manager.get("output_dir")@@ -1338,6 +1348,7 @@ def run_auto_capture(prompt=None, url=None, model=None, output_dir=None, agent_penable_sync=config_manager.get("real_time_sync", False),sdk=sdk,output_language=output_language,+ interactive=interactive,)elif sdk == "copilot":from .auto_engineer import CopilotAutoEngineer@@ -1351,6 +1362,7 @@ def run_auto_capture(prompt=None, url=None, model=None, output_dir=None, agent_penable_sync=config_manager.get("real_time_sync", False),sdk=sdk,output_language=output_language,+ interactive=interactive,)else:from .auto_engineer import ClaudeAutoEngineer@@ -1364,6 +1376,7 @@ def run_auto_capture(prompt=None, url=None, model=None, output_dir=None, agent_penable_sync=config_manager.get("real_time_sync", False),sdk=sdk,output_language=output_language,+ interactive=interactive,)# Start sync before analysis@@ -1478,6 +1491,9 @@ def engineer(run_id, prompt, fresh, model, output_dir, no_interactive, as_json):# without --fresh, --prompt is additive so the captured run's context is preserved.main_prompt = prompt if fresh else Noneadditional = prompt if (prompt and not fresh) else None+ # Either flag must suppress the post-generation follow-up prompt that+ # would otherwise block on stdin (`input(" > ")`) inside ClaudeEngineer.+ interactive = not (as_json or no_interactive)if not as_json:run_engineer(@@ -1487,6 +1503,7 @@ def engineer(run_id, prompt, fresh, model, output_dir, no_interactive, as_json):model=model,output_dir=output_dir,is_fresh=fresh,+ interactive=interactive,)return@@ -1500,6 +1517,7 @@ def engineer(run_id, prompt, fresh, model, output_dir, no_interactive, as_json):model=model,output_dir=output_dir,is_fresh=fresh,+ interactive=interactive,)payload = _build_engineer_payload(result, run_id=run_id, prompt=prompt, fresh=fresh)except KeyboardInterrupt:@@ -1525,6 +1543,7 @@ def run_engineer(additional_instructions=None,is_fresh=False,output_mode="client",+ interactive=True,):"""Shared logic for reverse engineering."""if not har_path or not prompt:@@ -1566,6 +1585,7 @@ def run_engineer(is_fresh=is_fresh,output_language=output_language,output_mode=output_mode,+ interactive=interactive,)elif sdk == "copilot":result = run_reverse_engineering(@@ -1581,6 +1601,7 @@ def run_engineer(is_fresh=is_fresh,output_language=output_language,output_mode=output_mode,+ interactive=interactive,)else:result = run_reverse_engineering(@@ -1595,6 +1616,7 @@ def run_engineer(is_fresh=is_fresh,output_language=output_language,output_mode=output_mode,+ interactive=interactive,)if result:diff --git a/src/reverse_api/engineer.py b/src/reverse_api/engineer.pyindex b958f4f..2a11792 100644--- a/src/reverse_api/engineer.py+++ b/src/reverse_api/engineer.py@@ -214,6 +214,7 @@ def run_reverse_engineering(is_fresh: bool = False,output_language: str = "python",output_mode: str = "client",+ interactive: bool = True,) -> dict[str, Any] | None:"""Run reverse engineering with the specified SDK.@@ -245,6 +246,7 @@ def run_reverse_engineering(is_fresh=is_fresh,output_language=output_language,output_mode=output_mode,+ interactive=interactive,)elif sdk == "copilot":from .copilot_engineer import CopilotEngineer@@ -263,6 +265,7 @@ def run_reverse_engineering(output_language=output_language,output_mode=output_mode,copilot_model=copilot_model,+ interactive=interactive,)else:engineer = ClaudeEngineer(@@ -278,6 +281,7 @@ def run_reverse_engineering(is_fresh=is_fresh,output_language=output_language,output_mode=output_mode,+ interactive=interactive,)# Start sync before analysisdiff --git a/tests/test_cli_followups.py b/tests/test_cli_followups.pyindex 08d96da..6939cfb 100644--- a/tests/test_cli_followups.py+++ b/tests/test_cli_followups.py@@ -200,3 +200,120 @@ class TestRootHelpMentionsScripted:assert result.exit_code == 0assert "--json" in result.outputassert "--no-interactive" in result.output+++# ---------------------------------------------------------------------------+# Follow-up suppression in non-interactive mode+# ---------------------------------------------------------------------------+++class TestFollowUpPromptSuppressed:+ """Regression for chatgpt-codex-connector PR #65 review (P2):++ `BaseEngineer._prompt_follow_up()` blocks on `input(" > ")` after the+ first generation. In --json / --no-interactive mode the conversation loop+ must terminate immediately so stdin is never read; otherwise scripted+ invocations like `engineer <run_id> --json | jq` hang before emitting the+ payload.+ """++ def test_prompt_follow_up_returns_none_when_not_interactive(self, tmp_path):+ """The base engineer's follow-up prompt short-circuits when+ interactive=False, without ever touching stdin."""+ import asyncio+ from unittest.mock import MagicMock, patch++ from reverse_api.base_engineer import BaseEngineer++ class _Eng(BaseEngineer):+ def _build_prompts(self):+ return ("", "")++ async def analyze_and_generate(self):+ return None++ har_path = tmp_path / "test.har"+ har_path.touch()++ with patch("reverse_api.base_engineer.get_scripts_dir", return_value=tmp_path):+ with patch("reverse_api.base_engineer.MessageStore"):+ with patch("reverse_api.base_engineer.SessionManager") as mock_sm:+ mock_sm.return_value.get_run.return_value = None+ eng = _Eng(+ run_id="test123",+ har_path=har_path,+ prompt="x",+ interactive=False,+ )++ # Patch input() at the builtin level — the test fails loudly if it's+ # ever reached, proving the short-circuit happens before stdin access.+ def _explode(*_args, **_kwargs):+ raise AssertionError("input() must not be called when interactive=False")++ with patch("builtins.input", side_effect=_explode):+ result = asyncio.run(eng._prompt_follow_up())++ assert result is None++ def test_engineer_default_interactive_true(self, tmp_path):+ """Sanity: the default value of interactive on BaseEngineer is True+ so existing REPL UX is unchanged."""+ from reverse_api.base_engineer import BaseEngineer++ class _Eng(BaseEngineer):+ def _build_prompts(self):+ return ("", "")++ async def analyze_and_generate(self):+ return None++ har_path = tmp_path / "test.har"+ har_path.touch()++ with patch("reverse_api.base_engineer.get_scripts_dir", return_value=tmp_path):+ with patch("reverse_api.base_engineer.MessageStore"):+ with patch("reverse_api.base_engineer.SessionManager") as mock_sm:+ mock_sm.return_value.get_run.return_value = None+ eng = _Eng(run_id="test123", har_path=har_path, prompt="x")+ assert eng.interactive is True++ def test_engineer_command_threads_interactive_through_run_engineer(self):+ """`engineer --json` must pass interactive=False to run_engineer so+ BaseEngineer drops the follow-up loop in the SDK."""+ runner = CliRunner()+ with patch("reverse_api.cli.run_engineer", return_value={"script_path": "/x.py"}) as mock_run:+ result = runner.invoke(engineer, ["abc123", "--json"])+ assert result.exit_code == 0, result.output+ assert mock_run.call_args.kwargs["interactive"] is False++ def test_engineer_command_no_interactive_threads_through(self):+ """`engineer --no-interactive` (without --json) also disables follow-up."""+ runner = CliRunner()+ with patch("reverse_api.cli.run_engineer", return_value={"script_path": "/x.py"}) as mock_run:+ result = runner.invoke(engineer, ["abc123", "--no-interactive"])+ assert result.exit_code == 0, result.output+ assert mock_run.call_args.kwargs["interactive"] is False++ def test_engineer_default_threads_interactive_true(self):+ """Without flags, run_engineer is called with interactive=True+ (preserves the current REPL UX)."""+ runner = CliRunner()+ with patch("reverse_api.cli.run_engineer", return_value={"script_path": "/x.py"}) as mock_run:+ result = runner.invoke(engineer, ["abc123"])+ assert result.exit_code == 0, result.output+ assert mock_run.call_args.kwargs["interactive"] is True++ def test_agent_command_threads_interactive_through_run_agent_capture(self):+ """`agent --json` must propagate interactive=False so+ ClaudeAutoEngineer drops the follow-up loop too (same code path)."""+ from reverse_api.cli import agent as agent_cmd++ runner = CliRunner()+ with patch(+ "reverse_api.cli.run_agent_capture",+ return_value={"run_id": "abc", "mode": "auto", "script_path": None, "usage": {}},+ ) as mock_run:+ result = runner.invoke(agent_cmd, ["--json", "-p", "x"])+ assert result.exit_code == 0, result.output+ assert mock_run.call_args.kwargs["interactive"] is False