Skip to content

Commit 151a6bf

Browse files
committed
Merge remote-tracking branch 'origin/main' into kalil0321/engineer-mode
# Conflicts: # CHANGELOG.md
2 parents e81a276 + 606e889 commit 151a6bf

8 files changed

Lines changed: 617 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99

1010
### Added
1111
- **`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.
12+
- **Copy text from the session**: the session takes the mouse for the wheel and for clicking files and links, so the terminal could not select its text. Dragging over the conversation now selects it and copies it to the clipboard when you let go, with `pbcopy`, `wl-copy`, `xclip` or `xsel`, or through the terminal (OSC 52) otherwise and over SSH. A click without a drag still opens a link.
1213
- **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.
1314

1415
### Removed
1516
- **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.
1617

1718
### Fixed
19+
- **Option+Delete in the session's input bar**: it deleted a single character, and on an empty bar it stopped the run, because the terminal sends it as Esc then Delete and the session acted on Esc at once. Esc now waits 50 ms for what follows, so Option+Delete deletes the word before the cursor and Option+arrows sent as Esc b / Esc f jump by word, while a lone Esc still stops the run or closes a menu.
1820
- **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.
1921
- 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.
2022
- `/history` opened while a run wraps up waits for it, instead of listing that run's cost from before.

‎src/reverse_api/repl/app.py‎

Lines changed: 122 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import time
1919
import warnings
2020
from collections.abc import Callable
21-
from concurrent.futures import Future
21+
from concurrent.futures import Future, ThreadPoolExecutor
2222
from datetime import datetime
2323
from pathlib import Path
2424
from typing import IO, Any, cast
@@ -35,20 +35,33 @@
3535
from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent, merge_key_bindings
3636
from prompt_toolkit.key_binding.defaults import load_key_bindings
3737
from prompt_toolkit.layout import ConditionalContainer, HSplit, Layout, VSplit, Window
38-
from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
3938
from prompt_toolkit.layout.processors import AfterInput, ConditionalProcessor
4039
from prompt_toolkit.lexers import Lexer
40+
from prompt_toolkit.mouse_events import MouseButton, MouseEvent, MouseEventType
4141
from prompt_toolkit.output import create_output
4242
from prompt_toolkit.styles import Style
4343
from rich.console import Console, RenderableType
4444
from rich.text import Text
4545

4646
from ..messages import MessageStore
4747
from ..utils import recorded_cost, usage_tokens
48-
from . import settings
48+
from . import clipboard, settings
4949
from .bridge import Bridge, LedgerUI, activate, first_line, short_name
5050
from .style import DIM, INK, SKY, THEME, height, width
51-
from .transcript import Raw, Transcript, TranscriptControl, TranscriptWriter
51+
from .transcript import (
52+
LINE_END,
53+
InputBelow,
54+
Line,
55+
Raw,
56+
Selection,
57+
TextBelow,
58+
Transcript,
59+
TranscriptControl,
60+
TranscriptWriter,
61+
highlight,
62+
selected_text,
63+
text_of,
64+
)
5265
from .view import EFFORTS, LedgerView, Picker, SessionState, model_label, run_summary
5366

5467
MODES = {
@@ -88,11 +101,15 @@
88101
("ctrl+o", "everything from this session, unfolded"),
89102
("pageup pagedown", "scroll, as does the mouse wheel · end jumps to the latest"),
90103
("click", "open a file or a URL"),
104+
("drag", "select text, copied when you let go"),
105+
("option+delete", "delete a word, with Option as Meta · or ctrl+w"),
106+
("ctrl+u", "delete to the start of the bar"),
91107
("ctrl+c", "stop the run · clear the bar · quit"),
92108
("ctrl+d", "quit"),
93109
)
94110
ALIASES = {"/quit": "/exit", "/commands": "/help"}
95111
HISTORY_RUNS = 20
112+
ESC_WAIT = 0.05 # seconds a lone Esc waits for a key that would make it Option+something
96113
# Commands that open a picker are echoed once a choice shows something, not when the picker opens.
97114
PICKER_COMMANDS = {"/model", "/effort", "/mode", "/engineer", "/history", "/resume", "/settings"}
98115
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")
@@ -221,6 +238,16 @@ def __init__(self) -> None:
221238
self.worker: threading.Thread | None = None
222239
self.update_checked = False
223240
self.buf.on_text_changed += self._reset_palette
241+
# The selection, by (line, column) in the lines last drawn: the header and the conversation.
242+
self.selection: Selection | None = None
243+
self.view_lines: list[Line] = []
244+
self.view_start = self.view_end = 0 # the first of them on screen, and the one past the last
245+
self.view_width = 0
246+
# Off the app's loop, so a slow clipboard command never holds up the screen, and one copy at a time, so an
247+
# older selection cannot land on the clipboard after a newer one.
248+
self.copier = ThreadPoolExecutor(max_workers=1, thread_name_prefix="rae-copy")
249+
self.copies_asked = 0
250+
self.buf.on_text_changed += self._drop_selection
224251
# Stray prints read as notices: dim and indented like the rest of the ledger.
225252
self.capture = TranscriptWriter(self._captured, plain_style=f"fg:{DIM}", indent=" ")
226253

@@ -236,6 +263,9 @@ def _reset_palette(self, _buf: Buffer) -> None:
236263
if self.st.picker is not None and self.st.picker.search:
237264
self.st.picker.index = 0
238265

266+
def _drop_selection(self, _buf: Buffer) -> None:
267+
self.selection = None
268+
239269
def _captured(self, raw: Raw) -> None:
240270
self.view.out(raw)
241271
self.invalidate()
@@ -456,6 +486,7 @@ def run_command(self, text: str) -> None:
456486
self.end_run()
457487
view.flush_live()
458488
self.transcript.clear()
489+
self.selection = None
459490
st.scroll, st.folded, st.cost, st.tokens, st.step = 0, False, 0.0, 0, 0
460491
st.last_client, st.client_name, st.host, st.run_id = None, "", "", None
461492
self.bridge.cost_base = 0.0
@@ -1000,11 +1031,84 @@ def transcript_view(self, window: Window) -> FormattedText:
10001031
rows = window.render_info.window_height if window.render_info else height() - 5
10011032
st.scroll = max(0, min(st.scroll, len(lines) - rows))
10021033
end = len(lines) - st.scroll
1034+
if self.view_width != width():
1035+
self.selection = None # the conversation wraps anew, so its lines no longer match
1036+
self.view_lines, self.view_start, self.view_end, self.view_width = lines, max(0, end - rows), end, width()
10031037
out: list[Any] = []
1004-
for i, line in enumerate(lines[max(0, end - rows) : end]):
1005-
out += ([("", "\n")] if i else []) + line
1038+
for i, line in enumerate(lines[self.view_start : end]):
1039+
picked = self.selection.chars(self.view_start + i) if self.selection else None
1040+
# A line with no character gives the pointer no position: the window would report the first line.
1041+
shown = (highlight(line, *picked) if picked else line) if text_of(line) else [("", " ")]
1042+
out += ([("", "\n")] if i else []) + shown
10061043
return FormattedText(out)
10071044

1045+
def drag(self, event: MouseEvent) -> bool:
1046+
"""A drag over the conversation selects text, copied on release; a click without one still opens a link."""
1047+
at = (self.view_start + event.position.y, event.position.x)
1048+
kind, sel = event.event_type, self.selection
1049+
if kind == MouseEventType.MOUSE_DOWN:
1050+
self.selection = Selection(at, at) if event.button == MouseButton.LEFT else None
1051+
return False
1052+
if sel is None or not sel.dragging:
1053+
return False
1054+
if kind == MouseEventType.MOUSE_MOVE and event.button == MouseButton.LEFT:
1055+
sel.head = at
1056+
return True
1057+
# A release here, or a move with no button held, after a release the session did not see.
1058+
if kind == MouseEventType.MOUSE_UP:
1059+
sel.head = at
1060+
return self.end_drag()
1061+
1062+
def drag_below(self, event: MouseEvent) -> bool:
1063+
"""Mouse events under the conversation: a drag there reaches the end of its last line on screen."""
1064+
sel = self.selection
1065+
if sel is None or not sel.dragging or event.event_type not in (MouseEventType.MOUSE_MOVE, MouseEventType.MOUSE_UP):
1066+
return False
1067+
sel.head = (self.view_end - 1, LINE_END)
1068+
if event.event_type == MouseEventType.MOUSE_MOVE and event.button == MouseButton.LEFT:
1069+
return True
1070+
self.end_drag()
1071+
return True
1072+
1073+
def end_drag(self) -> bool:
1074+
"""Copies what the drag went over; a press and release on one spot was a click."""
1075+
if self.selection is None:
1076+
return False
1077+
self.selection.dragging = False
1078+
if self.selection.anchor == self.selection.head:
1079+
self.selection = None
1080+
return False
1081+
self.copy_selection()
1082+
return True
1083+
1084+
def copy_selection(self) -> None:
1085+
if self.selection is None:
1086+
return
1087+
text = selected_text(self.view_lines, self.selection)
1088+
if not text.strip():
1089+
return
1090+
rows = text.count("\n") + 1
1091+
done = f"copied {rows} lines" if rows > 1 else f"copied {len(text)} characters"
1092+
self.copies_asked += 1
1093+
ticket = self.copies_asked
1094+
1095+
def copy() -> None:
1096+
if ticket != self.copies_asked:
1097+
return # a newer selection came while this one waited its turn
1098+
clipboard.copy(text, lambda data: self.call_soon(lambda: self.write_raw(data)))
1099+
self.call_soon(lambda: self.flash(done))
1100+
1101+
self.copier.submit(copy)
1102+
1103+
def flash(self, message: str) -> None:
1104+
self.st.flash = (message, time.time() + 2)
1105+
self.invalidate()
1106+
1107+
def write_raw(self, data: str) -> None:
1108+
if self.app is not None:
1109+
self.app.output.write_raw(data)
1110+
self.app.output.flush()
1111+
10081112
def build(self) -> Application:
10091113
st, view, buf = self.st, self.view, self.buf
10101114
palette_open = Condition(self.palette_active)
@@ -1028,11 +1132,11 @@ def picker_view() -> FormattedText:
10281132
return view.menu(rows, title=p.title, empty="nothing matches what you typed")
10291133

10301134
transcript_window: Window = Window(wrap_lines=False)
1031-
transcript_window.content = TranscriptControl(lambda: self.transcript_view(transcript_window), self.scroll)
1135+
transcript_window.content = TranscriptControl(lambda: self.transcript_view(transcript_window), self.scroll, self.drag)
10321136
kb = self.bindings(palette_open, picker_open)
10331137

10341138
def text_window(fn: Callable[[], Any]) -> Window:
1035-
return Window(FormattedTextControl(fn), dont_extend_height=True)
1139+
return Window(TextBelow(fn, self.drag_below), dont_extend_height=True)
10361140

10371141
picker_hinted = Condition(lambda: bool(st.picker and st.picker.hint))
10381142
placeholder = ConditionalProcessor(
@@ -1055,9 +1159,11 @@ def text_window(fn: Callable[[], Any]) -> Window:
10551159
text_window(lambda: FormattedText(view.seam())),
10561160
VSplit(
10571161
[
1058-
Window(FormattedTextControl(lambda: FormattedText(view.marker())), dont_extend_width=True, dont_extend_height=True),
1162+
Window(TextBelow(lambda: FormattedText(view.marker()), self.drag_below), dont_extend_width=True, dont_extend_height=True),
10591163
Window(
1060-
BufferControl(buffer=buf, lexer=InputLexer(st), input_processors=[placeholder, follow_hint, picker_hint]),
1164+
InputBelow(
1165+
self.drag_below, buffer=buf, lexer=InputLexer(st), input_processors=[placeholder, follow_hint, picker_hint]
1166+
),
10611167
dont_extend_height=True,
10621168
wrap_lines=True,
10631169
),
@@ -1071,7 +1177,7 @@ def text_window(fn: Callable[[], Any]) -> Window:
10711177
),
10721178
focused_element=buf,
10731179
)
1074-
return Application(
1180+
app: Application[None] = Application(
10751181
layout=layout,
10761182
key_bindings=merge_key_bindings([load_key_bindings(), kb]),
10771183
style=Style.from_dict({"": INK}),
@@ -1080,6 +1186,10 @@ def text_window(fn: Callable[[], Any]) -> Window:
10801186
refresh_interval=0.05,
10811187
output=create_output(stdout=sys.__stdout__),
10821188
)
1189+
# Option+Delete and Option+arrows arrive as Esc and a key, so Esc waits for what follows instead of firing at
1190+
# once. A terminal writes such a pair in one go, so a short wait keeps a lone Esc as quick.
1191+
app.ttimeoutlen = app.timeoutlen = ESC_WAIT
1192+
return app
10831193

10841194
def scroll(self, delta: int) -> None:
10851195
self.st.scroll = max(0, self.st.scroll + delta)
@@ -1160,7 +1270,7 @@ def _(event: KeyPressEvent) -> None:
11601270
def _(event: KeyPressEvent) -> None:
11611271
self.show_output()
11621272

1163-
@kb.add("escape", eager=True)
1273+
@kb.add("escape")
11641274
def _(event: KeyPressEvent) -> None:
11651275
if st.picker is not None:
11661276
p, st.picker = st.picker, None

‎src/reverse_api/repl/clipboard.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""The system clipboard, for text selected in the full-screen session."""
2+
3+
from __future__ import annotations
4+
5+
import base64
6+
import os
7+
import shutil
8+
import subprocess
9+
import sys
10+
from collections.abc import Callable
11+
12+
LINUX_COMMANDS = (["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"])
13+
14+
15+
def copy_command() -> list[str] | None:
16+
"""The platform's copy command, when this machine has one."""
17+
if sys.platform == "darwin":
18+
candidates: tuple[list[str], ...] = (["pbcopy"],)
19+
elif sys.platform.startswith("linux"):
20+
candidates = ((["wl-copy"],) if os.environ.get("WAYLAND_DISPLAY") else ()) + LINUX_COMMANDS
21+
else:
22+
candidates = ()
23+
return next((cmd for cmd in candidates if shutil.which(cmd[0])), None)
24+
25+
26+
def copy(text: str, write_raw: Callable[[str], None]) -> None:
27+
"""Puts text on the clipboard with the platform's command, else asks the terminal to with OSC 52.
28+
29+
Over SSH the platform's clipboard is the remote machine's, so the terminal, on the user's own, does it.
30+
"""
31+
remote = bool(os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_TTY"))
32+
command = None if remote else copy_command()
33+
if command is not None:
34+
# pbcopy reads its input in the locale's encoding.
35+
env = {**os.environ, "LC_CTYPE": "UTF-8"} if command[0] == "pbcopy" else None
36+
try:
37+
# xclip stays in the background to serve the clipboard, holding open any output pipe it was given.
38+
out = subprocess.DEVNULL
39+
subprocess.run(command, input=text.encode(), env=env, check=True, stdout=out, stderr=out, timeout=2)
40+
return
41+
except (OSError, subprocess.SubprocessError):
42+
pass
43+
write_raw(f"\x1b]52;c;{base64.b64encode(text.encode()).decode()}\x07")

0 commit comments

Comments
 (0)