Skip to content

The agent that turns websites into APIs!

feat(cli): TTY-detect at REPL entry + engineer --json/--no-interactive

Kalil Bouziguesd2c4e49b8692
diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.py
index 8cc0a14..fca2eef 100644
--- a/src/reverse_api/cli.py
+++ b/src/reverse_api/cli.py
@@ -119,6 +119,36 @@ def _build_agent_payload(
"error": final_error,
}
+
+def _build_engineer_payload(
+ result: dict | None,
+ *,
+ run_id: str,
+ prompt: str | None,
+ fresh: bool,
+ error: str | None = None,
+) -> dict:
+ """Normalize an engineer-mode result into a stable JSON shape.
+
+ Mirrors `_build_agent_payload`'s contract minus the agent-specific fields
+ (no `url`, no `mode`, no `har_path`). `prompt` is the value the user passed
+ to --prompt (which may have been used as either a full replacement or as
+ additional instructions depending on --fresh).
+ """
+ result = result if result is not None else {}
+ inner_error = result.get("error") if isinstance(result, dict) else None
+ final_error = error or inner_error or (None if result else "engineering produced no result")
+ return {
+ "schema_version": AGENT_JSON_SCHEMA_VERSION,
+ "status": "error" if final_error else "ok",
+ "run_id": run_id,
+ "prompt": prompt,
+ "fresh": fresh,
+ "script_path": result.get("script_path") if isinstance(result, dict) else None,
+ "usage": (result.get("usage") if isinstance(result, dict) else None) or {},
+ "error": final_error,
+ }
+
# Mode definitions
MODES = ["agent", "manual", "engineer", "collector"]
MODE_DESCRIPTIONS = {
@@ -391,8 +421,23 @@ def main(ctx: click.Context):
Run without a subcommand to start the interactive REPL; use agent, manual,
or engineer for CLI mode.
+
+ Most subcommands accept --json and --no-interactive for scripted use; see
+ `<cmd> --help` for per-command details.
"""
if ctx.invoked_subcommand is None:
+ # Refuse to drop into the prompt_toolkit REPL when stdin is not a TTY:
+ # without an interactive terminal the REPL would block on stdin
+ # forever (e.g. CI invocations, agent wrappers that forgot the
+ # subcommand). Print --help to stderr and exit 2 (misuse).
+ if not sys.stdin.isatty():
+ click.echo(ctx.get_help(), err=True)
+ click.echo(
+ "\nerror: no subcommand given and stdin is not a TTY; "
+ "the interactive REPL requires a terminal.",
+ err=True,
+ )
+ sys.exit(2)
repl_loop()
@@ -1366,7 +1411,34 @@ def run_auto_capture(prompt=None, url=None, model=None, output_dir=None, agent_p
+ epilog="""\b
+Examples:
+ reverse-api-engineer engineer abc123def456
+ reverse-api-engineer engineer abc123def456 -p "add pagination support"
+ reverse-api-engineer engineer abc123def456 --fresh -p "extract auth flow only"
+ reverse-api-engineer engineer abc123def456 --json | jq
+
+\b
+JSON output schema (--json):
+ {
+ "schema_version": 1,
+ "status": "ok" | "error",
+ "run_id": "<id>",
+ "prompt": "..." | null,
+ "fresh": false,
+ "script_path": "/abs/path/api_client.py" | null,
+ "usage": { "input_tokens": ..., "output_tokens": ..., "total_cost": ... },
+ "error": "<message>" | null
+ }
+
+\b
+Exit codes:
+ 0 success
+ 1 runtime error (engineering failed, run not found)
+ 2 misuse
+"""
+)
@click.argument("run_id")
@click.option(
"--prompt",
@@ -1389,20 +1461,59 @@ def run_auto_capture(prompt=None, url=None, model=None, output_dir=None, agent_p
default=None,
)
@click.option("--output-dir", "-o", default=None, help="Custom output directory.")
-def engineer(run_id, prompt, fresh, model, output_dir):
+ "--no-interactive",
+ is_flag=True,
+ help="Reserved for symmetry with `agent`/`run`; engineer mode is non-interactive by design.",
+)
+ "--json",
+ "as_json",
+ is_flag=True,
+ help="Emit a single JSON result on stdout (logs go to stderr). Implies --no-interactive.",
+)
+def engineer(run_id, prompt, fresh, model, output_dir, no_interactive, as_json):
"""Run reverse engineering on a previous run."""
# --fresh treats --prompt as a full replacement of the original goal;
# without --fresh, --prompt is additive so the captured run's context is preserved.
main_prompt = prompt if fresh else None
additional = prompt if (prompt and not fresh) else None
- run_engineer(
- run_id,
- prompt=main_prompt,
- additional_instructions=additional,
- model=model,
- output_dir=output_dir,
- is_fresh=fresh,
- )
+
+ if not as_json:
+ run_engineer(
+ run_id,
+ prompt=main_prompt,
+ additional_instructions=additional,
+ model=model,
+ output_dir=output_dir,
+ is_fresh=fresh,
+ )
+ return
+
+ payload: dict
+ with _quiet_consoles_for_json() as real_stdout:
+ try:
+ result = run_engineer(
+ run_id,
+ prompt=main_prompt,
+ additional_instructions=additional,
+ model=model,
+ output_dir=output_dir,
+ is_fresh=fresh,
+ )
+ payload = _build_engineer_payload(result, run_id=run_id, prompt=prompt, fresh=fresh)
+ except KeyboardInterrupt:
+ payload = _build_engineer_payload(
+ None, run_id=run_id, prompt=prompt, fresh=fresh, error="interrupted"
+ )
+ except Exception as e:
+ payload = _build_engineer_payload(
+ None, run_id=run_id, prompt=prompt, fresh=fresh, error=str(e)
+ )
+
+ real_stdout.write(json.dumps(payload) + "\n")
+ real_stdout.flush()
+ sys.exit(0 if payload["status"] == "ok" else 1)
def run_engineer(
diff --git a/tests/test_cli_followups.py b/tests/test_cli_followups.py
new file mode 100644
index 0000000..08d96da
--- /dev/null
+++ b/tests/test_cli_followups.py
@@ -0,0 +1,202 @@
+"""Tests for the issue #62 follow-up items.
+
+Covers:
+1. TTY-detect at REPL entry (no subcommand + non-TTY stdin → exit 2 + help)
+2. `engineer --json` / `--no-interactive` parity with `agent --json`
+"""
+
+import json
+import subprocess
+from unittest.mock import patch
+
+from click.testing import CliRunner
+
+from reverse_api.cli import (
+ AGENT_JSON_SCHEMA_VERSION,
+ _build_engineer_payload,
+ engineer,
+ main,
+)
+
+EXPECTED_ENGINEER_KEYS = {
+ "schema_version",
+ "status",
+ "run_id",
+ "prompt",
+ "fresh",
+ "script_path",
+ "usage",
+ "error",
+}
+
+
+# ---------------------------------------------------------------------------
+# Item #1: TTY-detect at REPL entry
+# ---------------------------------------------------------------------------
+
+
+class TestTtyDetectionAtReplEntry:
+ """Without a TTY and no subcommand, the REPL must NOT block on prompt_toolkit."""
+
+ def test_no_tty_no_subcommand_exits_2(self):
+ """End-to-end: invoke the installed binary with stdin redirected from /dev/null."""
+ result = subprocess.run(
+ ["uv", "run", "reverse-api-engineer"],
+ stdin=subprocess.DEVNULL,
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ assert result.returncode == 2
+ assert "stdin is not a TTY" in result.stderr
+ # Help is printed too so a wrapper can self-discover the subcommands
+ assert "agent" in result.stderr
+ assert "engineer" in result.stderr
+
+ def test_no_tty_with_subcommand_does_not_trip(self):
+ """Subcommands work fine without a TTY (this is the whole point of agent --json)."""
+ result = subprocess.run(
+ ["uv", "run", "reverse-api-engineer", "list", "--json"],
+ stdin=subprocess.DEVNULL,
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ # list --json on empty history should succeed with []
+ assert result.returncode == 0
+ # Nothing about TTY in the output
+ assert "TTY" not in result.stderr
+
+
+# ---------------------------------------------------------------------------
+# Item #2: engineer --json
+# ---------------------------------------------------------------------------
+
+
+class TestBuildEngineerPayload:
+ """Stable shape for the `engineer --json` payload."""
+
+ def test_success_shape(self):
+ payload = _build_engineer_payload(
+ {"script_path": "/abs/api_client.py", "usage": {"total_cost": 0.001}},
+ run_id="abc123",
+ prompt="add pagination",
+ fresh=False,
+ )
+ assert payload["schema_version"] == AGENT_JSON_SCHEMA_VERSION
+ assert payload["status"] == "ok"
+ assert payload["run_id"] == "abc123"
+ assert payload["prompt"] == "add pagination"
+ assert payload["fresh"] is False
+ assert payload["script_path"] == "/abs/api_client.py"
+ assert payload["usage"]["total_cost"] == 0.001
+ assert payload["error"] is None
+ assert set(payload.keys()) == EXPECTED_ENGINEER_KEYS
+
+ def test_none_result_is_error(self):
+ payload = _build_engineer_payload(None, run_id="abc", prompt=None, fresh=False)
+ assert payload["status"] == "error"
+ assert payload["error"]
+ assert set(payload.keys()) == EXPECTED_ENGINEER_KEYS
+
+ def test_explicit_error_overrides(self):
+ payload = _build_engineer_payload(
+ {"script_path": "/x.py"}, run_id="abc", prompt=None, fresh=False, error="boom"
+ )
+ assert payload["status"] == "error"
+ assert payload["error"] == "boom"
+
+ def test_inner_error_propagates(self):
+ payload = _build_engineer_payload(
+ {"error": "engine crashed"}, run_id="abc", prompt=None, fresh=False
+ )
+ assert payload["status"] == "error"
+ assert payload["error"] == "engine crashed"
+
+
+class TestEngineerCommandJson:
+ """`engineer` click command --json wiring."""
+
+ def test_json_emits_payload_on_success(self):
+ runner = CliRunner()
+ fake_result = {"script_path": "/abs/api_client.py", "usage": {"total_cost": 0.0}}
+ with patch("reverse_api.cli.run_engineer", return_value=fake_result):
+ result = runner.invoke(engineer, ["abc123", "--json"])
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.stdout.strip().splitlines()[-1])
+ assert payload["status"] == "ok"
+ assert payload["run_id"] == "abc123"
+ assert payload["script_path"] == "/abs/api_client.py"
+ assert set(payload.keys()) == EXPECTED_ENGINEER_KEYS
+
+ def test_json_emits_error_on_not_found(self):
+ runner = CliRunner()
+ # run_engineer returns None when the run can't be located
+ with patch("reverse_api.cli.run_engineer", return_value=None):
+ result = runner.invoke(engineer, ["doesnotexist", "--json"])
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout.strip().splitlines()[-1])
+ assert payload["status"] == "error"
+ assert payload["run_id"] == "doesnotexist"
+ assert payload["error"]
+ assert set(payload.keys()) == EXPECTED_ENGINEER_KEYS
+
+ def test_json_emits_error_on_keyboard_interrupt(self):
+ runner = CliRunner()
+ with patch("reverse_api.cli.run_engineer", side_effect=KeyboardInterrupt):
+ result = runner.invoke(engineer, ["abc123", "--json"])
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout.strip().splitlines()[-1])
+ assert payload["status"] == "error"
+ assert payload["error"] == "interrupted"
+
+ def test_json_emits_error_on_exception(self):
+ runner = CliRunner()
+ with patch("reverse_api.cli.run_engineer", side_effect=RuntimeError("boom")):
+ result = runner.invoke(engineer, ["abc123", "--json"])
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout.strip().splitlines()[-1])
+ assert payload["status"] == "error"
+ assert payload["error"] == "boom"
+
+ def test_prompt_without_fresh_threaded_as_additional(self):
+ """--prompt without --fresh must reach run_engineer as additional_instructions
+ even on the JSON path (regression for the cubic-dev-ai catch on PR #63)."""
+ runner = CliRunner()
+ with patch("reverse_api.cli.run_engineer", return_value={"script_path": "/x.py"}) as mock_run:
+ result = runner.invoke(engineer, ["abc123", "--json", "-p", "add pagination"])
+ assert result.exit_code == 0, result.output
+ kwargs = mock_run.call_args.kwargs
+ assert kwargs["prompt"] is None
+ assert kwargs["additional_instructions"] == "add pagination"
+ assert kwargs["is_fresh"] is False
+
+ def test_fresh_with_prompt_threaded_as_main(self):
+ runner = CliRunner()
+ with patch("reverse_api.cli.run_engineer", return_value={"script_path": "/x.py"}) as mock_run:
+ result = runner.invoke(
+ engineer, ["abc123", "--json", "--fresh", "-p", "extract auth"]
+ )
+ assert result.exit_code == 0, result.output
+ kwargs = mock_run.call_args.kwargs
+ assert kwargs["prompt"] == "extract auth"
+ assert kwargs["additional_instructions"] is None
+ assert kwargs["is_fresh"] is True
+
+ def test_no_interactive_flag_accepted(self):
+ """--no-interactive is reserved for symmetry; should not crash."""
+ runner = CliRunner()
+ with patch("reverse_api.cli.run_engineer", return_value={"script_path": "/x.py"}):
+ result = runner.invoke(engineer, ["abc123", "--no-interactive"])
+ assert result.exit_code == 0, result.output
+
+
+class TestRootHelpMentionsScripted:
+ """Item #6 partial: root --help should advertise scripted features."""
+
+ def test_root_help_mentions_json_and_no_interactive(self):
+ runner = CliRunner()
+ result = runner.invoke(main, ["--help"])
+ assert result.exit_code == 0
+ assert "--json" in result.output
+ assert "--no-interactive" in result.output