From e81a276a766aeb32410d2f71861426271a1a4eb0 Mon Sep 17 00:00:00 2001 From: kalil0321 Date: Sat, 14 Nov 2026 21:28:31 +0100 Subject: [PATCH] feat(engineer): name the run engineer mode works on, /engineer to pick it, keep each run's cost --- CHANGELOG.md | 6 ++ README.md | 3 +- src/reverse_api/cli.py | 45 ++++++-- src/reverse_api/repl/app.py | 82 +++++++++++--- src/reverse_api/repl/bridge.py | 12 ++- src/reverse_api/repl/view.py | 32 ++++-- tests/test_repl.py | 138 ++++++++++++++++++++++-- tests/test_resume.py | 25 +++++ website/content/docs/cli/commands.mdx | 1 + website/content/docs/modes/engineer.mdx | 11 +- 10 files changed, 314 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d5a89c3..05ebb502 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,10 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - **`hermes` backend**: `"sdk": "hermes"` engineers a saved capture through the local [`hermes` CLI](https://hermes-agent.nousresearch.com/docs) (`hermes chat --oneshot --format stream-json`), so a run needs no API key in rae — the model, the provider and the authentication are the user's own Hermes configuration. `hermes chat` reads the prompt on stdin, so nothing the model reads is shell-parsed; `hermes_max_turns` overrides the turn cap from the user's Hermes config; runs start with `--ignore-rules` so an `AGENTS.md`/`CLAUDE.md` cannot steer them, and estimate cost from the CLI's token counts, leaving it at 0 for a model with no known price. The backend covers `engineer` only: with `"sdk": "hermes"` the `agent` command stops before browser setup, so capture with another SDK (claude, opencode, copilot or cursor) and engineer that run with hermes; `agent --dry-run` reports the same error. The CLI is found on `PATH` or through `RAE_HERMES_BIN`, and `agent --dry-run` reports it as a check. +- **Engineer mode names the run it works on**: the line above the input shows its id and prompt, by default your latest run with a HAR, and an engineer run's first line names the run it changes. `/engineer [run_id]` picks another one among the runs that have a HAR. A choice holds until another run is engineered or a new agent run captures one. ### Removed - **Collector mode**: the `collector` command, the session's collector mode, the `collector_model` setting and the `collector` install extra. rae stays on turning a site's traffic into an API client. Existing configs and histories still load: an old `collector_model` is ignored, past collector runs stay in `/history`, and `./collected/` folders are left as they are. +### Fixed +- **A re-engineered run keeps its cost**: its tokens and cost in `/history`, `list` and `show` add up every re-engineer instead of keeping only the last, so a run's cost still counts its capture. +- The client card shows what its own run cost, not the session's spend so far; the chip under the input still shows the session's. +- `/history` opened while a run wraps up waits for it, instead of listing that run's cost from before. + ## [0.15.0] - 2026-11-08 ### Changed diff --git a/README.md b/README.md index d2061723..6d07b2fd 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ Cycle modes with **Shift+Tab**: |------|--------------| | `manual` | You drive the browser; AI generates the client from captured traffic. | | `agent` | An AI agent drives capture autonomously (Playwright or Chrome MCP, or Vercel agent-browser CLI). | -| `engineer` | Re-run generation on a previous capture (`engineer `). Needs a HAR, so it works on `auto`, `agent-browser` and manual runs, not chrome-mcp runs. | +| `engineer` | Re-run generation on a previous capture (`engineer `). In the session it works on your latest run with a HAR, named above the input; `/engineer` picks another. Needs a HAR, so it works on `auto`, `agent-browser` and manual runs, not chrome-mcp runs. | Agent mode providers: - **chrome-mcp** (default for new configs; an existing `config.json` keeps its provider): drives your real Chrome so you keep existing sessions/cookies. Needs Node.js 20.19+; headed runs also need Chrome 146+ open with auto-connect enabled at `chrome://inspect/#remote-debugging`, and someone at the machine to accept Chrome's connection prompt when the run starts. For headed runs, rae checks before launching that Chrome's remote debugging port is reachable (not the Chrome or Node version) and stops with setup steps if it isn't; `agent --dry-run` shows the same check. Headless runs skip it. `--headless` starts a separate headless Chrome without your sessions. No HAR file is saved, so `engineer ` cannot regenerate these runs; run `agent` again instead. @@ -132,6 +132,7 @@ Settings live in `~/.reverse-api/config.json` and can be edited via `/settings` `reverse-api-engineer` opens a full-screen session; `agent` and `engineer` open it too when run in a terminal, and stay plain with `--json` or `--no-interactive`. Type `/` for the commands: - `/model`, `/effort`, `/mode`: switch the model, how hard it thinks, and the mode (also Shift+Tab, ctrl+e). +- `/engineer [run_id]`: the run engineer mode works on, by default the latest with a HAR. - `/settings`: SDK, agent provider, models, output and sync, changed in place in the session. - `/history`: past runs with their details, to resume or re-engineer. - `/resume [run_id]`: show a past run's conversation as it was and continue it where it stopped, on any SDK. Works for agent and engineer runs from this version on, which save their SDK session. diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.py index ec2b486e..701e0fac 100644 --- a/src/reverse_api/cli.py +++ b/src/reverse_api/cli.py @@ -714,16 +714,18 @@ def open_session( model: str | None = None, prompt: str | None = None, run: Callable[[], Any] | None = None, - runner: Callable[[str, str | None], Any] | None = None, + runner: Callable[..., Any] | None = None, + target: str | None = None, ) -> None: """The interactive CLI: the full-screen session, in ``mode``. A subcommand hands over ``run``, its ``prompt`` with every option bound, and ``runner(prompt, model)``, which starts later prompts in that mode with the options that still apply, such as --headless. + In engineer mode, ``target`` is the run it works on, and the runner also takes it. """ from .repl.app import run_session - run_session(mode=mode, model=model, first=(prompt, run) if prompt and run else None, runner=runner) + run_session(mode=mode, model=model, first=(prompt, run) if prompt and run else None, runner=runner, target=target) @main.command( @@ -1443,7 +1445,8 @@ def engineer( lambda: run_engineer( run_id, prompt=main_prompt, additional_instructions=additional, model=model, output_dir=output_dir, is_fresh=fresh ), - lambda p, m: engineer_from_prompt(p, m or model, output_dir), + lambda p, m, target=None: engineer_from_prompt(p, m or model, output_dir, target), + target=run_id, ) return if not machine_output: @@ -1497,15 +1500,33 @@ def engineer( sys.exit(0 if payload["status"] == "ok" else 1) -def engineer_from_prompt(text: str, model: str | None = None, output_dir: str | None = None) -> dict[str, Any] | None: - """A prompt in engineer mode: a known run id re-engineers that run; anything else is an instruction for the latest run.""" +NO_CAPTURE = "no run has a HAR to engineer yet · manual mode records one, as does agent mode with agent_provider auto" + + +def has_capture(run: dict[str, Any]) -> bool: + """Whether engineer can work on a run: its HAR is still on disk.""" + try: + har_dir = Path((run.get("paths") or {}).get("har_dir") or get_har_dir(str(run["run_id"]), None)) + except (KeyError, TypeError, ValueError): + return False + return (har_dir / "recording.har").exists() + + +def latest_capture() -> dict[str, Any] | None: + return next((r for r in session_manager.get_history(limit=len(session_manager.history)) if has_capture(r)), None) + + +def engineer_from_prompt( + text: str, model: str | None = None, output_dir: str | None = None, run_id: str | None = None +) -> dict[str, Any] | None: + """A prompt in engineer mode: a known run id re-engineers that run; anything else is an instruction for + ``run_id``, else for the latest run with a HAR.""" if session_manager.get_run(text): return run_engineer(text, model=model, output_dir=output_dir) - # Histories can still hold collector runs, which captured no traffic; run_engineer explains any other run that has none. - latest = next((r for r in session_manager.get_history(limit=50) if r.get("mode") != "collector"), None) - if latest is None: - raise RuntimeError("no captured runs yet · start one in agent or manual mode") - return run_engineer(latest["run_id"], model=model, output_dir=output_dir, additional_instructions=text) + target = run_id or (latest_capture() or {}).get("run_id") + if target is None: + raise RuntimeError(NO_CAPTURE) + return run_engineer(target, model=model, output_dir=output_dir, additional_instructions=text) def run_engineer( @@ -1556,6 +1577,8 @@ def run_engineer( enable_sync = config_manager.get("real_time_sync", True) output_language = config_manager.get("output_language", "python") resume_session, cost_before = _resume_point(resume) if resume else (None, 0.0) + # The run keeps what it spent before, its capture included: a re-engineer adds to it. + spent_before = dict((resume or session_manager.get_run(run_id) or {}).get("usage") or {}) # OpenCode and Copilot take their model from settings, except when reopening a session made with another. resume_model = (resume or {}).get("sdk_session", {}).get("model") session_model = { @@ -1734,7 +1757,7 @@ def run_engineer( run_id=run_id, sdk=sdk, output_mode=output_mode, - usage=_run_totals(resume.get("usage") or {}, usage) if resume else usage, + usage=_run_totals(spent_before, usage), paths={"script_path": result.get("script_path")}, ) _keep_session_cost(run_id, cost_before, usage) diff --git a/src/reverse_api/repl/app.py b/src/reverse_api/repl/app.py index a7590ba7..99b318f7 100644 --- a/src/reverse_api/repl/app.py +++ b/src/reverse_api/repl/app.py @@ -68,6 +68,7 @@ "/model": "choose the model", "/effort": "how hard the agent thinks", "/mode": "choose the mode", + "/engineer": "choose the run engineer mode works on", "/settings": "all settings", "/history": "past runs: their details, resume or re-engineer", "/resume": "a past run's conversation, to continue it", @@ -93,7 +94,7 @@ ALIASES = {"/quit": "/exit", "/commands": "/help"} HISTORY_RUNS = 20 # Commands that open a picker are echoed once a choice shows something, not when the picker opens. -PICKER_COMMANDS = {"/model", "/effort", "/mode", "/history", "/resume", "/settings"} +PICKER_COMMANDS = {"/model", "/effort", "/mode", "/engineer", "/history", "/resume", "/settings"} URL_IN_PROMPT = re.compile(r"https?://([^/\s]+)|\b((?:[\w-]+\.)+(?:com|io|co|ch|de|fr|uk|org|net|dev|ai|app|so|sh|eu|jobs))\b") @@ -214,8 +215,9 @@ def __init__(self) -> None: self.real_out, self.real_err = sys.stdout, sys.stderr self.after_run: Callable[[], None] | None = None # what starts once the open run has wrapped up self.first: tuple[str, Callable[[], Any]] | None = None # a run a subcommand handed over - # Per mode, how a subcommand's options (--headless, --output-dir...) start each prompt: runner(prompt, model). - self.runners: dict[str, Callable[[str, str | None], Any]] = {} + # Per mode, how a subcommand's options (--headless, --output-dir...) start each prompt: runner(prompt, model), + # and in engineer mode runner(prompt, model, target run). + self.runners: dict[str, Callable[..., Any]] = {} self.worker: threading.Thread | None = None self.update_checked = False self.buf.on_text_changed += self._reset_palette @@ -354,8 +356,42 @@ def set_effort(self, value: str | None) -> None: def set_mode(self, value: str | None) -> None: if value and value != self.st.mode: old, self.st.mode = self.st.mode, value + self.find_target() self.view.event("mode", old, value) + def find_target(self) -> None: + """Unless a run was chosen, engineer mode works on the latest one with a HAR.""" + st = self.st + if st.mode == "engineer" and not st.engineer_chosen: + run = self.cli.latest_capture() + st.engineer_target = (run["run_id"], str(run.get("prompt") or "")) if run else None + + def placeholder(self) -> str: + """The empty bar's hint: in engineer mode, what to type about the run it works on.""" + if self.st.mode != "engineer": + return "describe the API you want, e.g. all open jobs on jobs.ashbyhq.com/openai" + if self.st.engineer_target is None: + return "no HAR yet · manual mode records one, as does agent with agent_provider auto" + return "what should change, e.g. add pagination · /engineer picks another run" + + def choose_target(self, run_id: str | None) -> None: + """/engineer: the run engineer mode works on, until another one is engineered or captured.""" + if not run_id: + return + st, view = self.st, self.view + run = self.cli.session_manager.get_run(run_id) + view.command("/engineer", run_id) + if run is None: + view.notice(f"no run {run_id}") + elif not self.cli.has_capture(run): + view.notice(f"run {run_id} has no HAR, so engineer cannot work on it · /engineer lists the runs that have one") + else: + st.engineer_target, st.engineer_chosen = (run_id, str(run.get("prompt") or "")), True + self.set_mode("engineer") + view.run_details(run) + view.notice("type what should change in its client" + (" · from the next run, /new ends this one" if st.run_open else "")) + self.invalidate() + def cycle_effort(self) -> None: if not self.st.has_effort: return @@ -399,6 +435,12 @@ def run_command(self, text: str) -> None: self.open_picker("how hard the agent thinks", [(e, e, EFFORT_NOTES[e]) for e in EFFORTS], st.effort_label, self.set_effort) elif cmd == "/mode": self.open_picker("choose a mode", [(m, m, d) for m, d in MODES.items()], st.mode, self.set_mode) + elif cmd == "/engineer": + if arg: + self.choose_target(arg) + else: + current = st.engineer_target[0] if st.engineer_target else None + self.pick_run(cmd, "engineer which run", self.choose_target, keep=self.cli.has_capture, empty=self.cli.NO_CAPTURE, current=current) elif cmd == "/output": self.show_output() elif cmd == "/open": @@ -611,7 +653,12 @@ def pick_run( then: Callable[[str], None], keep: Callable[[dict[str, Any]], bool] | None = None, empty: str = "no runs yet", + current: str | None = None, ) -> None: + if self.st.running and self.bridge.stopping: + # A run wrapping up records its cost last: the list waits for it rather than show the cost before. + self.after_run = lambda: self.pick_run(cmd, title, then, keep, empty, current) + return runs = self.cli.session_manager.get_history(limit=len(self.cli.session_manager.history)) runs = [r for r in runs if keep is None or keep(r)][:HISTORY_RUNS] if not runs: @@ -619,7 +666,7 @@ def pick_run( self.view.notice(empty) return items = [(r["run_id"], r["run_id"], run_summary(r)) for r in runs] - self.open_picker(title, items, None, lambda value: then(value) if value else None) + self.open_picker(title, items, current, lambda value: then(value) if value else None) def show_run(self, run_id: str) -> None: run = self.cli.session_manager.get_run(run_id) @@ -690,14 +737,14 @@ def replay(self, run_id: str, run: dict[str, Any]) -> bool: if not messages: return False st, b, ui = self.st, self.bridge, LedgerUI(self.bridge) - saved = (st.step, st.tokens, st.cost, st.started, st.run_model, st.run_sdk, st.run_effort, st.kind, st.verb, st.host, st.client_name) + saved = (st.step, st.tokens, st.run_cost, st.started, st.run_model, st.run_sdk, st.run_effort, st.kind, st.verb, st.host, st.client_name) # A conversation that waits for a follow-up keeps its own client card and folder. bridge_saved = (b.verified, b.workspace, b.pending_card, b.plan, b.plan_calls, b.plan_made, b.plan_changed, b.plan_shown) b.verified, b.pending_card = False, None b.reset_plan() # The client card reads the run's own numbers, not this session's; each result sets them as they were then. usage, session = run.get("usage") or {}, run.get("sdk_session") or {} - st.step, st.tokens, st.cost = 0, usage_tokens(usage), recorded_cost(usage) or 0.0 + st.step, st.tokens, st.run_cost = 0, usage_tokens(usage), recorded_cost(usage) or 0.0 st.run_model, st.run_sdk, st.run_effort = session.get("model") or run.get("model"), run.get("sdk"), session.get("effort") script = (run.get("paths") or {}).get("script_path") b.workspace = (Path(script).parent, None) if script else None @@ -733,13 +780,13 @@ def replay(self, run_id: str, run: dict[str, Any]) -> bool: self.view.error(str(content)) elif kind == "result" and isinstance(content, dict) and content.get("script_path"): if isinstance(content.get("usage"), dict): - st.tokens, st.cost = usage_tokens(content["usage"]), recorded_cost(content["usage"]) or st.cost + st.tokens, st.run_cost = usage_tokens(content["usage"]), recorded_cost(content["usage"]) or st.run_cost st.run_model = content.get("model") or session.get("model") or run.get("model") ui.success(str(content["script_path"])) b.flush_card() # drawn now, with the numbers of its own moment b.flush_card() finally: - st.step, st.tokens, st.cost, st.started, st.run_model, st.run_sdk, st.run_effort, st.kind, st.verb, st.host, st.client_name = saved + st.step, st.tokens, st.run_cost, st.started, st.run_model, st.run_sdk, st.run_effort, st.kind, st.verb, st.host, st.client_name = saved b.verified, b.workspace, b.pending_card, b.plan, b.plan_calls, b.plan_made, b.plan_changed, b.plan_shown = bridge_saved return True @@ -780,12 +827,13 @@ def start(self, prompt: str, mode: str | None = None, echo: bool = True) -> None model = self.st.model if self.st.sdk == "claude" else None run: Callable[[], Any] runner = self.runners.get(mode) + target = self.st.engineer_target[0] if self.st.engineer_target else None if runner is not None: - run = lambda: runner(prompt, model) # noqa: E731 + run = (lambda: runner(prompt, model, target)) if mode == "engineer" else (lambda: runner(prompt, model)) elif mode == "manual": run = lambda: cli.run_manual_capture(prompt=prompt, url=None, reverse_engineer=True, model=model) # noqa: E731 elif mode == "engineer": - run = lambda: cli.engineer_from_prompt(prompt, model) # noqa: E731 + run = lambda: cli.engineer_from_prompt(prompt, model, run_id=target) # noqa: E731 else: run = lambda: cli.run_agent_capture(prompt=prompt, model=model) # noqa: E731 self.launch(prompt, run, mode, echo) @@ -794,7 +842,8 @@ def launch(self, prompt: str, run: Callable[[], Any], mode: str | None = None, e """Start a run in the session; its engine's UI calls stream into the conversation.""" st = self.st mode = mode or st.mode - st.host, st.client_name = host_in(prompt), "" + # The new run's id comes with its header; until then the status row names none. + st.host, st.client_name, st.run_id = host_in(prompt), "", None if echo: self.view.user(prompt) # Manual capture first waits for the user to browse; the engine takes over the verb when it starts. @@ -987,7 +1036,7 @@ def text_window(fn: Callable[[], Any]) -> Window: picker_hinted = Condition(lambda: bool(st.picker and st.picker.hint)) placeholder = ConditionalProcessor( - AfterInput("describe the API you want, e.g. all open jobs on jobs.ashbyhq.com/openai", style=f"fg:{DIM} italic"), + AfterInput(self.placeholder, style=f"fg:{DIM} italic"), filter=Condition(lambda: not buf.text and not st.waiting and st.question is None) & ~picker_hinted, ) picker_hint = ConditionalProcessor( @@ -1101,6 +1150,7 @@ def _(event: KeyPressEvent) -> None: def _(event: KeyPressEvent) -> None: modes = list(MODES) st.mode = modes[(modes.index(st.mode) + 1) % len(modes)] + self.find_target() @kb.add("c-e") def _(event: KeyPressEvent) -> None: @@ -1176,12 +1226,14 @@ def run_session( mode: str = "agent", model: str | None = None, first: tuple[str, Callable[[], Any]] | None = None, - runner: Callable[[str, str | None], Any] | None = None, + runner: Callable[..., Any] | None = None, + target: str | None = None, ) -> None: """Entry point for the interactive CLI: the full-screen session. A subcommand hands over its options: ``first`` is its prompt and run, with every option bound, and ``runner(prompt, model)`` starts the prompts typed later in ``mode`` with the options that still apply. + ``target`` is the run engineer mode works on. """ session = Session() session.st.mode = mode @@ -1190,6 +1242,10 @@ def run_session( session.first = first if runner is not None: session.runners[mode] = runner + run = session.cli.session_manager.get_run(target) if target else None + if run is not None: + session.st.engineer_target, session.st.engineer_chosen = (str(target), str(run.get("prompt") or "")), True + session.find_target() try: asyncio.run(session.run()) except KeyboardInterrupt: diff --git a/src/reverse_api/repl/bridge.py b/src/reverse_api/repl/bridge.py index 763bdcb7..84f87830 100644 --- a/src/reverse_api/repl/bridge.py +++ b/src/reverse_api/repl/bridge.py @@ -376,16 +376,21 @@ def _changed(self) -> None: def header(self, run_id: str, prompt: str, model: str | None = None, sdk: str | None = None, mode: str | None = None) -> None: self.b.bind_task() st = self.st - st.run_id, st.step, st.tokens = run_id, 0, 0 + st.run_id, st.step, st.tokens, st.run_cost = run_id, 0, 0, 0.0 st.running, st.waiting, st.verb, st.kind = True, False, "starting", "other" self.b.cost_base = st.cost + if mode == "engineer": + # The run being engineered stays the target of engineer mode; a new agent capture hands it to the latest. + st.engineer_target, st.engineer_chosen = (run_id, prompt), True + elif mode == "agent": + st.engineer_chosen = False self.b.verified, self.b.workspace = False, None self.b.reset_plan() # The run's own model and SDK; the selection in st.model stays for the next run. st.run_model, st.run_sdk = model or st.model, sdk or st.sdk claude = st.run_sdk == "claude" and not predates_effort(st.run_model) st.run_effort = (st.effort or default_effort(st.run_model)) if claude else None - self.view.run_line(run_id, mode) + self.view.run_line(run_id, mode, prompt) self._changed() def start_analysis(self) -> None: @@ -512,7 +517,8 @@ def usage(self, usage: dict[str, Any]) -> None: st.tokens = usage_tokens(usage) cost = usage.get("estimated_cost_usd") if isinstance(cost, (int, float)): - st.cost = self.b.cost_base + float(cost) + st.run_cost = float(cost) + st.cost = self.b.cost_base + st.run_cost self.b.flush_card() def error(self, message: str) -> None: diff --git a/src/reverse_api/repl/view.py b/src/reverse_api/repl/view.py index da3d3c20..aecef2c8 100644 --- a/src/reverse_api/repl/view.py +++ b/src/reverse_api/repl/view.py @@ -220,8 +220,9 @@ class SessionState: verb: str = "thinking" kind: str = "other" started: float = 0.0 - tokens: int = 0 - cost: float = 0.0 + tokens: int = 0 # the open run's + cost: float = 0.0 # the session's spend + run_cost: float = 0.0 # the open run's, next to its tokens on the client card step: int = 0 host: str = "" client_name: str = "" @@ -237,6 +238,9 @@ class SessionState: run_model: str | None = None run_sdk: str | None = None run_effort: str | None = None + # The run engineer mode works on, (run id, prompt): the one chosen, else the latest with a HAR. + engineer_target: tuple[str, str] | None = None + engineer_chosen: bool = False @property def accent(self) -> str: @@ -478,8 +482,11 @@ def command(self, cmd: str, arg: str = "") -> None: self.gap() self.out(f" [{DIM}]›[/] [{self.st.accent}]{escape(cmd)}[/]" + (f" [{INK_SOFT}]{escape(arg)}[/]" if arg else "")) - def run_line(self, run_id: str, mode: str | None) -> None: - self.out(f" [{DIM}]run {escape(run_id)} · {escape(mode or self.st.mode)}[/]") + def run_line(self, run_id: str, mode: str | None, prompt: str = "") -> None: + mode = mode or self.st.mode + # In engineer mode the user typed only what should change: the line names the run it changes. + about = f" · {first_words(prompt, max(10, width() - len(run_id) - 24))}" if prompt and mode == self.st.mode == "engineer" else "" + self.out(f" [{DIM}]run {escape(run_id)} · {escape(mode)}{escape(about)}[/]") self.out("") def note(self, text: str) -> None: @@ -594,7 +601,7 @@ def card(self, path: Path, lines_written: int, language: str) -> None: main = [ (f"[{st.accent}]*[/] [bold {INK}]{link(path.name, path)}[/] [italic {PINK}]ready[/]", f"* {path.name} ready"), (f" [{INK_SOFT}]{lang} · {lines_written} lines[/]", f" {lang} · {lines_written} lines"), - (f" [{DIM}]{k(st.tokens)} tokens · {money(st.cost)}[/]", f" {k(st.tokens)} tokens · {money(st.cost)}"), + (f" [{DIM}]{k(st.tokens)} tokens · {money(st.run_cost)}[/]", f" {k(st.tokens)} tokens · {money(st.run_cost)}"), ] model, effort, sdk = st.live_model_label, st.run_effort, st.run_sdk or st.sdk stub = [ @@ -709,11 +716,24 @@ def spinner(self) -> list[tuple[str, str]]: return out + [("", "\n")] # a blank row between the tape and the input def seam(self) -> list[tuple[str, str]]: - """The line above the input, a fieldset legend: the mode on the left, the model on the right.""" + """The line above the input, a fieldset legend: the mode on the left, the model on the right. + + In engineer mode the run it works on follows the mode, unless another run is open. + """ st = self.st left = [(f"fg:{HAIRLINE}", " ┄┄ "), (f"fg:{st.accent} italic", st.mode), ("", " ")] right = [("", " "), (f"fg:{INK_SOFT}", st.live_model_label), (f"fg:{HAIRLINE}", " ┄┄")] used = sum(len(t) for _, t in left) + sum(len(t) for _, t in right) + target = st.engineer_target + other_run_open = st.run_open and st.run_id is not None and st.run_id != (target[0] if target else None) + if st.mode == "engineer" and not other_run_open: + if target is None: + about = [(f"fg:{DIM}", "· no run with a HAR yet ")] + else: + room = width() - used - len(target[0]) - 8 + prompt = first_words(target[1], room) if room >= 12 else "" + about = [(f"fg:{DIM}", f"· {target[0]} "), (f"fg:{INK_SOFT}", f"{prompt} " if prompt else "")] + left, used = left + about, used + sum(len(t) for _, t in about) return left + [(f"fg:{HAIRLINE}", "┄" * max(1, width() - used - 1))] + right def seam_under(self) -> list[tuple[str, str]]: diff --git a/tests/test_repl.py b/tests/test_repl.py index 5d852c72..e706a8cb 100644 --- a/tests/test_repl.py +++ b/tests/test_repl.py @@ -274,6 +274,21 @@ def test_no_card_until_the_agent_verified_the_client(self, session, tmp_path): ui.usage({"input_tokens": 10, "output_tokens": 5, "estimated_cost_usd": 0.01}) assert "ready" not in plain(t), "a client path that does not exist gets no card" + def test_each_card_shows_its_own_run_cost_and_the_chip_the_session_spend(self, session, tmp_path): + st, t, view, b = session + ui = LedgerUI(b) + for run_id, cost in (("run1", 0.5), ("run2", 0.25)): + ui.header(run_id, "prompt", model="claude-sonnet-5-5") + client = tmp_path / f"{run_id}.py" + client.write_text("a\n", encoding="utf-8") + ui.tool_start("mcp__verification__report_client_verified", {"summary": "ok"}) + ui.tool_result("mcp__verification__report_client_verified", output="Recorded") + ui.success(str(client)) + ui.usage({"input_tokens": 1200, "output_tokens": 0, "estimated_cost_usd": cost}) + text = plain(t) + assert "1.2k tokens · $0.50" in text and "1.2k tokens · $0.25" in text and "$0.75" not in text + assert "$0.75" in "".join(frag[1] for frag in view.status()) + def test_verified_shows_where_the_files_are(self, session): _st, t, _view, b = session ui = LedgerUI(b) @@ -1734,6 +1749,106 @@ def test_an_update_shows_as_a_notice(self, app_session): assert "update available: 0.14.0 → 0.15.0" in plain(session.transcript) +class TestEngineerTarget: + @pytest.fixture + def runs(self, app_session, tmp_path): + """A history whose newest run, from chrome-mcp, saved no HAR; the two before it did.""" + session, history = app_session + + def run(run_id: str, prompt: str, har: bool) -> dict[str, Any]: + if har: + (tmp_path / run_id).mkdir() + (tmp_path / run_id / "recording.har").write_text("{}", encoding="utf-8") + return {"run_id": run_id, "prompt": prompt, "timestamp": "2026-11-14T10:00:00", "paths": {"har_dir": str(tmp_path / run_id)}} + + history.history = [ + run("chrome1", "jobs at stripe", har=False), + run("jobs1", "all open jobs on jobs.ashbyhq.com/openai", har=True), + run("nba1", "last night's NBA scores", har=True), + ] + history.get_history.side_effect = lambda limit=10: history.history[:limit] + history.get_run.side_effect = lambda run_id: next((r for r in history.history if r["run_id"] == run_id), None) + return session + + @staticmethod + def seam(session) -> str: + return "".join(text for _, text in session.view.seam()) + + def test_engineer_mode_works_on_the_latest_run_with_a_har_and_shows_it(self, runs): + runs.set_mode("engineer") + assert runs.st.engineer_target == ("jobs1", "all open jobs on jobs.ashbyhq.com/openai") + assert "engineer · jobs1 all open jobs on jobs.ashbyhq.com/openai" in self.seam(runs) + assert runs.placeholder().startswith("what should change") + runs.set_mode("agent") + assert "jobs1" not in self.seam(runs) and runs.placeholder().startswith("describe the API") + + def test_engineer_lists_the_runs_with_a_har_and_the_choice_holds_until_a_new_capture(self, runs): + runs.run_command("/engineer") + assert runs.st.picker is not None and [v for v, _, _ in runs.st.picker.items] == ["jobs1", "nba1"] + pick(runs.st, "nba1") + assert runs.st.mode == "engineer" and runs.st.engineer_target == ("nba1", "last night's NBA scores") + assert "last night's NBA scores" in plain(runs.transcript) + runs.set_mode("agent") + runs.set_mode("engineer") + assert runs.st.engineer_target[0] == "nba1" + LedgerUI(runs.bridge).header("new1", "jobs", mode="agent") + runs.set_mode("agent") + runs.set_mode("engineer") + assert runs.st.engineer_target[0] == "jobs1" + + def test_the_run_list_waits_for_a_run_wrapping_up_to_record_its_cost(self, runs): + runs.st.running, runs.bridge.stopping = True, True + runs.run_command("/history") + assert runs.st.picker is None and runs.after_run is not None + runs.st.running, runs.bridge.stopping = False, False + runs.after_run() + assert runs.st.picker is not None and runs.st.picker.title == "past runs" + + def test_a_run_without_a_har_cannot_be_chosen(self, runs): + runs.run_command("/engineer chrome1") + assert runs.st.mode == "agent" and not runs.st.engineer_chosen + assert "run chrome1 has no HAR" in plain(runs.transcript) + + def test_a_prompt_goes_to_the_run_engineer_mode_works_on(self, runs): + runs.run_command("/engineer nba1") + with patch.object(runs, "work") as work: + runs.start("add pagination") + with patch.object(runs.cli, "engineer_from_prompt") as engineer: + work.call_args.args[0]() + assert engineer.call_args == call("add pagination", runs.st.model, run_id="nba1") + + def test_an_engineer_run_names_the_run_it_changes(self, runs): + runs.set_mode("engineer") + runs.st.run_id = "nba1" # the previous run + with patch.object(runs, "work"): + runs.start("add pagination") + assert runs.st.run_id is None and "jobs1" in self.seam(runs), "the new run's id comes with its header" + LedgerUI(runs.bridge).header("jobs1", "all open jobs on jobs.ashbyhq.com/openai", model="claude-sonnet-5-5", mode="engineer") + assert "run jobs1 · engineer · all open jobs on jobs.ashbyhq.com/openai" in plain(runs.transcript) + assert "jobs1" in self.seam(runs) + # Another run open in engineer mode, such as a resumed agent run, is not the target. + LedgerUI(runs.bridge).header("chrome1", "jobs at stripe", mode="agent") + assert "jobs1" not in self.seam(runs) + + def test_the_engineer_subcommand_starts_on_its_run(self, runs, monkeypatch): + from reverse_api.repl import app as app_mod + + monkeypatch.setattr(app_mod, "Session", lambda: runs) + monkeypatch.setattr(runs, "run", AsyncMock()) + monkeypatch.setattr(runs, "wait_for_run", lambda: None) + monkeypatch.setattr(runs, "print_transcript", lambda: None) + app_mod.run_session(mode="engineer", target="nba1") + assert runs.st.engineer_target == ("nba1", "last night's NBA scores") + + def test_without_any_har_engineer_mode_says_how_to_get_one(self, app_session): + session, _history = app_session + session.set_mode("engineer") + assert session.st.engineer_target is None + assert "no run with a HAR yet" in self.seam(session) and session.placeholder().startswith("no HAR yet") + session.run_command("/engineer") + assert session.st.picker is None and "no run has a HAR to engineer yet" in plain(session.transcript) + + class TestSubcommands: def test_agent_in_a_terminal_opens_the_session_with_every_option(self, monkeypatch): from click.testing import CliRunner @@ -1765,23 +1880,34 @@ def test_engineer_keeps_its_output_dir_for_later_prompts(self, monkeypatch): with patch.object(cli, "open_session") as session, patch.object(cli, "engineer_from_prompt") as later: CliRunner().invoke(cli.main, ["engineer", "abc123", "-o", "/out"]) runner = session.call_args.args[4] - runner("add pagination", None) - later.assert_called_once_with("add pagination", None, "/out") + runner("add pagination", None, "abc123") + assert session.call_args.kwargs["target"] == "abc123" + later.assert_called_once_with("add pagination", None, "/out", "abc123") - def test_an_engineer_prompt_is_a_run_id_or_an_instruction_for_the_latest_capture(self, monkeypatch): + def test_an_engineer_prompt_is_a_run_id_or_an_instruction_for_its_target(self, monkeypatch, tmp_path): from reverse_api import cli + def run(run_id: str, har: bool) -> dict[str, Any]: + if har: + (tmp_path / run_id).mkdir() + (tmp_path / run_id / "recording.har").write_text("{}", encoding="utf-8") + return {"run_id": run_id, "paths": {"har_dir": str(tmp_path / run_id)}} + + # The newest run is a chrome-mcp one, which saved no HAR. history = MagicMock() + history.history = [run("chrome1", har=False), run("capture1", har=True), run("capture0", har=True)] + history.get_history.side_effect = lambda limit=10: history.history[:limit] history.get_run.side_effect = lambda text: {"run_id": text} if text == "abc123" else None - history.get_history.return_value = [{"run_id": "collect1", "mode": "collector"}, {"run_id": "capture1", "mode": "agent"}] monkeypatch.setattr(cli, "session_manager", history) with patch.object(cli, "run_engineer") as engineer: cli.engineer_from_prompt("abc123", "m", "/out") cli.engineer_from_prompt("add pagination", "m", "/out") + cli.engineer_from_prompt("add pagination", "m", "/out", run_id="capture0") assert engineer.call_args_list[0] == call("abc123", model="m", output_dir="/out") assert engineer.call_args_list[1] == call("capture1", model="m", output_dir="/out", additional_instructions="add pagination") - history.get_history.return_value = history.get_history.return_value[:1] - with pytest.raises(RuntimeError, match="no captured runs yet"): + assert engineer.call_args_list[2] == call("capture0", model="m", output_dir="/out", additional_instructions="add pagination") + history.history = history.history[:1] + with pytest.raises(RuntimeError, match="no run has a HAR"): cli.engineer_from_prompt("add pagination") def test_without_a_terminal_a_prompt_is_required(self, monkeypatch): diff --git a/tests/test_resume.py b/tests/test_resume.py index 2c735816..d3365561 100644 --- a/tests/test_resume.py +++ b/tests/test_resume.py @@ -443,6 +443,31 @@ def test_a_run_stopped_after_a_turn_keeps_that_turn(self, history): assert history.update_run.call_args.kwargs["paths"] == {"script_path": "/tmp/scripts/r1/api_client.py"} +class TestReengineeredRunCost: + @pytest.fixture + def history(self, monkeypatch, tmp_path): + from reverse_api.session import SessionManager + + config = MagicMock() + config.get.side_effect = lambda key, default=None: {"sdk": "claude", "real_time_sync": True}.get(key, default) + monkeypatch.setattr(cli, "config_manager", config) + (tmp_path / "recording.har").write_text("{}") + sm = SessionManager(tmp_path / "history.json") + sm.add_run("r1", "jobs", mode="auto", paths={"har_dir": str(tmp_path)}, usage={"estimated_cost_usd": 0.5, "input_tokens": 1000}) + monkeypatch.setattr(cli, "session_manager", sm) + return sm + + def test_a_reengineer_adds_to_what_the_run_spent(self, history, tmp_path): + result = {"script_path": str(tmp_path / "api_client.py"), "usage": {"estimated_cost_usd": 0.25, "input_tokens": 400}} + with patch.object(cli, "run_reverse_engineering", return_value=result): + cli.run_engineer("r1", additional_instructions="add pagination") + cli.run_engineer("r1", additional_instructions="add retries") + from reverse_api.session import SessionManager + + usage = SessionManager(tmp_path / "history.json").get_run("r1")["usage"] + assert usage == {"estimated_cost_usd": pytest.approx(1.0), "input_tokens": 1800} + + def test_haiku_4_5_never_gets_an_effort(): from reverse_api import utils diff --git a/website/content/docs/cli/commands.mdx b/website/content/docs/cli/commands.mdx index db6ce835..98591b8c 100644 --- a/website/content/docs/cli/commands.mdx +++ b/website/content/docs/cli/commands.mdx @@ -13,6 +13,7 @@ menu; `Tab` completes and `Enter` runs the highlighted command. | `/model` | Choose the model. | | `/effort` | How hard the agent thinks, for Claude models (`low` to `max`). | | `/mode` | Switch between agent, manual and engineer. | +| `/engineer [run_id]` | The run engineer mode works on, by default the latest with a HAR. | | `/settings` | SDK, agent provider, models, output and sync, changed in place. | | `/history` | Past runs with their cost; open one to resume or re-engineer it. | | `/resume [run_id]` | Show a past run's conversation as it was and continue it, on any SDK. | diff --git a/website/content/docs/modes/engineer.mdx b/website/content/docs/modes/engineer.mdx index a8e22fbb..bd5cfbed 100644 --- a/website/content/docs/modes/engineer.mdx +++ b/website/content/docs/modes/engineer.mdx @@ -26,9 +26,18 @@ Interactive: ```bash reverse-api-engineer -# switch to engineer mode with Shift+Tab, then enter +# switch to engineer mode with Shift+Tab ``` +Engineer mode works on your latest run with a HAR. The line above the input +names it, with its id and prompt. Type what should change, such as +`add pagination`, and rae regenerates that run's client with it. `/engineer` +lists the runs that have a HAR to pick another one, and a run id typed on its +own regenerates that run as it was. + +The run's cost in `/history` includes every re-engineer of it, and the client +card shows what the last one cost. + Direct: ```bash