k0ntrol-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. k0ntrol/__init__.py +1 -0
  2. k0ntrol/agents.py +998 -0
  3. k0ntrol/cli.py +190 -0
  4. k0ntrol/config.py +330 -0
  5. k0ntrol/credentials.py +78 -0
  6. k0ntrol/defaults/config.yaml +23 -0
  7. k0ntrol/events.py +838 -0
  8. k0ntrol/frontends/__init__.py +1 -0
  9. k0ntrol/frontends/ask.py +218 -0
  10. k0ntrol/frontends/badges.py +228 -0
  11. k0ntrol/frontends/banner.py +128 -0
  12. k0ntrol/frontends/diffview.py +174 -0
  13. k0ntrol/frontends/editor.py +701 -0
  14. k0ntrol/frontends/klog.html +740 -0
  15. k0ntrol/frontends/klog.py +403 -0
  16. k0ntrol/frontends/logo.py +12 -0
  17. k0ntrol/frontends/mentions.py +29 -0
  18. k0ntrol/frontends/prompt.py +340 -0
  19. k0ntrol/frontends/render.py +485 -0
  20. k0ntrol/frontends/session.py +717 -0
  21. k0ntrol/frontends/setup.py +442 -0
  22. k0ntrol/frontends/terminal.py +396 -0
  23. k0ntrol/frontends/theme.py +24 -0
  24. k0ntrol/helpers.py +108 -0
  25. k0ntrol/init_flow.py +362 -0
  26. k0ntrol/langfuse.py +173 -0
  27. k0ntrol/memory/__init__.py +0 -0
  28. k0ntrol/memory/index.py +235 -0
  29. k0ntrol/memory/layout.py +66 -0
  30. k0ntrol/memory/python_extract.py +189 -0
  31. k0ntrol/memory/reflect.py +366 -0
  32. k0ntrol/memory/refresh.py +21 -0
  33. k0ntrol/memory/scan.py +538 -0
  34. k0ntrol/memory/session.py +145 -0
  35. k0ntrol/otel.py +429 -0
  36. k0ntrol/pricing.py +29 -0
  37. k0ntrol/prompts/chatty.md +17 -0
  38. k0ntrol/prompts/implementer.md +14 -0
  39. k0ntrol/prompts/planner.md +42 -0
  40. k0ntrol/prompts/researcher.md +20 -0
  41. k0ntrol/prompts/reviewer.md +34 -0
  42. k0ntrol/providers.py +718 -0
  43. k0ntrol/search.py +133 -0
  44. k0ntrol/tools/__init__.py +0 -0
  45. k0ntrol/tools/bulk_read.py +93 -0
  46. k0ntrol/tools/errors.py +50 -0
  47. k0ntrol/tools/fetch_url.py +212 -0
  48. k0ntrol/tools/net.py +317 -0
  49. k0ntrol/tools/path_guard.py +45 -0
  50. k0ntrol/tools/read.py +174 -0
  51. k0ntrol/tools/run_tests.py +66 -0
  52. k0ntrol/tools/runner.py +177 -0
  53. k0ntrol/tools/search_memory.py +32 -0
  54. k0ntrol/tools/slice_guard.py +166 -0
  55. k0ntrol/tools/slice_journal.py +481 -0
  56. k0ntrol/tools/tracker.py +115 -0
  57. k0ntrol/tools/web_search.py +199 -0
  58. k0ntrol/tools/write.py +123 -0
  59. k0ntrol/tracker/__init__.py +31 -0
  60. k0ntrol/tracker/github.py +371 -0
  61. k0ntrol/tracker/local_files.py +241 -0
  62. k0ntrol/tracker/protocol.py +210 -0
  63. k0ntrol/workflow/__init__.py +29 -0
  64. k0ntrol/workflow/change.py +605 -0
  65. k0ntrol/workflow/ci_gate.py +96 -0
  66. k0ntrol/workflow/context.py +137 -0
  67. k0ntrol/workflow/implement.py +1150 -0
  68. k0ntrol/workflow/nodes.py +331 -0
  69. k0ntrol/workflow/plan.py +675 -0
  70. k0ntrol/workflow/qa.py +98 -0
  71. k0ntrol/workflow/research.py +533 -0
  72. k0ntrol/workflow/routers.py +273 -0
  73. k0ntrol/workflow/run.py +1165 -0
  74. k0ntrol/workflow/state.py +146 -0
  75. k0ntrol/workflow/triage.py +269 -0
  76. k0ntrol_cli-0.1.0.dist-info/METADATA +154 -0
  77. k0ntrol_cli-0.1.0.dist-info/RECORD +80 -0
  78. k0ntrol_cli-0.1.0.dist-info/WHEEL +4 -0
  79. k0ntrol_cli-0.1.0.dist-info/entry_points.txt +2 -0
  80. k0ntrol_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,701 @@
1
+ """A tiny line editor: a closed rounded box whose border shows the mode.
2
+
3
+ ``input()`` and readline cannot draw a right border, nor recolour while the
4
+ user types, so this module reads keys itself and redraws the whole box after
5
+ every key. Everything that decides something is pure and tests without a
6
+ terminal: :func:`apply_key` (one key in, new state out), :func:`render_box`
7
+ (state in, lines out) and :func:`paint_frame` (lines in, escape codes out).
8
+ Only the byte read at the bottom of the file touches the terminal.
9
+
10
+ ```
11
+ ╭─ chat ─────────────────────────────────────────────────╮
12
+ │ ❯ what does slugify do? │
13
+ ╰────────────────────────────────────────────────────────╯
14
+ bedrock · 25s · ↑ 3.9k ↓ 473 · ≈ $0.0012 · shift+tab mode · ? shortcuts
15
+ ```
16
+ """
17
+
18
+ import os
19
+ import re
20
+ import select
21
+ import shutil
22
+ import sys
23
+ from collections.abc import Callable, Iterator, Mapping
24
+ from contextlib import AbstractContextManager, contextmanager, nullcontext
25
+ from dataclasses import dataclass, field, replace
26
+ from pathlib import Path
27
+ from typing import TextIO
28
+
29
+ from rich.cells import cell_len
30
+
31
+ from k0ntrol.frontends.theme import ACCENT, BRAND, DIM, OK, POINTER
32
+
33
+ try:
34
+ import termios
35
+ import tty as tty_mode
36
+ except ImportError: # pragma: no cover - Windows
37
+ termios = None # type: ignore[assignment]
38
+ tty_mode = None # type: ignore[assignment]
39
+
40
+ HISTORY_LIMIT = 1000
41
+ MIN_WIDTH = 20
42
+ FRAME_PADDING = 6 # "│ ❯ " on the left, " │" on the right
43
+ ESC = "\x1b"
44
+ PASTE_START = "\x1b[200~"
45
+ PASTE_END = "\x1b[201~"
46
+ HIDE_CURSOR = "\x1b[?25l"
47
+ SHOW_CURSOR = "\x1b[?25h"
48
+ CLEAR_ROW = "\x1b[2K"
49
+ CLEAR_BELOW = "\x1b[J"
50
+ PASTE_ON = "\x1b[?2004h"
51
+ PASTE_OFF = "\x1b[?2004l"
52
+ _ESCAPE_TIMEOUT = 0.05
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Mode:
57
+ name: str
58
+ color: str
59
+ hint: str = ""
60
+
61
+
62
+ DEFAULT_MODES = (
63
+ Mode("chat", BRAND, "ask about this repo"),
64
+ Mode("plan", ACCENT, "new work: Q&A, then a spec and its tickets"),
65
+ Mode("implement", OK, "build #<ticket> or a task, test-first"),
66
+ )
67
+ _PREFIX_MODES = {
68
+ "/plan": "plan",
69
+ "/implement": "implement",
70
+ "/ask": "chat",
71
+ }
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class EditorState:
76
+ buffer: str = ""
77
+ cursor: int = 0
78
+ history_index: int | None = None # None: editing the draft, not browsing
79
+ draft: str = "" # what was typed before the first Up
80
+ mode_index: int = 0
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class Submitted:
85
+ text: str
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Cancelled:
90
+ eof: bool # True for Ctrl-D (EOFError), False for Ctrl-C (KeyboardInterrupt)
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class Env:
95
+ """What a key press needs besides the state: history, commands, modes."""
96
+
97
+ history: tuple[str, ...] = ()
98
+ commands: Mapping[str, str] = field(default_factory=dict)
99
+ mode_count: int = 1
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class Geometry:
104
+ """Where the last frame left the cursor: its size and the caret's row."""
105
+
106
+ rows: int
107
+ caret_row: int
108
+
109
+
110
+ Outcome = EditorState | Submitted | Cancelled
111
+ Handler = Callable[[EditorState, Env], Outcome]
112
+
113
+
114
+ # --- modes -----------------------------------------------------------------
115
+
116
+
117
+ def prefix_mode_name(buffer: str) -> str | None:
118
+ """The mode a typed prefix forces (``/plan``, ``/implement``, ``/ask``)."""
119
+ words = buffer.split(maxsplit=1)
120
+ if not words:
121
+ return None
122
+ return _PREFIX_MODES.get(words[0])
123
+
124
+
125
+ def effective_mode(buffer: str, mode_index: int, modes: list[Mode]) -> Mode:
126
+ """The mode Enter would use: a typed prefix wins over the selected mode."""
127
+ selected = modes[mode_index % len(modes)]
128
+ forced = prefix_mode_name(buffer)
129
+ return next((mode for mode in modes if mode.name == forced), selected)
130
+
131
+
132
+ # --- history ---------------------------------------------------------------
133
+
134
+
135
+ def add_entry(entries: list[str], text: str) -> list[str]:
136
+ """Append ``text`` unless it is blank or repeats the last entry."""
137
+ if not text.strip() or (entries and entries[-1] == text):
138
+ return entries
139
+ return (entries + [text])[-HISTORY_LIMIT:]
140
+
141
+
142
+ def load_history(path: Path) -> list[str]:
143
+ try:
144
+ lines = path.read_text(encoding="utf-8").splitlines()
145
+ except OSError:
146
+ return []
147
+ entries: list[str] = []
148
+ for line in lines:
149
+ entries = add_entry(entries, line)
150
+ return entries
151
+
152
+
153
+ def save_history(path: Path, entries: list[str]) -> None:
154
+ try:
155
+ path.parent.mkdir(parents=True, exist_ok=True)
156
+ path.write_text("\n".join(entries[-HISTORY_LIMIT:]) + "\n", encoding="utf-8")
157
+ except OSError:
158
+ pass
159
+
160
+
161
+ # --- keys ------------------------------------------------------------------
162
+
163
+ _CONTROLS = {
164
+ "\x01": "ctrl_a",
165
+ "\x03": "ctrl_c",
166
+ "\x04": "ctrl_d",
167
+ "\x05": "ctrl_e",
168
+ "\x15": "ctrl_u",
169
+ "\x17": "ctrl_w",
170
+ "\t": "tab",
171
+ "\r": "enter",
172
+ "\n": "enter",
173
+ "\x7f": "backspace",
174
+ "\x08": "backspace",
175
+ }
176
+ _ESCAPES = {
177
+ "[A": "up",
178
+ "OA": "up",
179
+ "[B": "down",
180
+ "OB": "down",
181
+ "[C": "right",
182
+ "OC": "right",
183
+ "[D": "left",
184
+ "OD": "left",
185
+ "[H": "home",
186
+ "OH": "home",
187
+ "[1~": "home",
188
+ "[7~": "home",
189
+ "[F": "end",
190
+ "OF": "end",
191
+ "[4~": "end",
192
+ "[8~": "end",
193
+ "[3~": "delete",
194
+ "[Z": "shift_tab",
195
+ }
196
+ _NEWLINES = re.compile(r"[\r\n\t]+")
197
+
198
+
199
+ def sanitize_text(text: str) -> str:
200
+ """Text safe to insert: newlines and tabs become one space, controls go."""
201
+ flat = _NEWLINES.sub(" ", text)
202
+ return "".join(char for char in flat if char.isprintable())
203
+
204
+
205
+ def normalize_key(key: str) -> str:
206
+ """A key name, the text to insert, or "" for a key to ignore.
207
+
208
+ Accepts key names, raw control characters and raw escape sequences, so the
209
+ reader and the tests can feed either.
210
+ """
211
+ if key in KEY_NAMES:
212
+ return key
213
+ if key.startswith(ESC):
214
+ return _ESCAPES.get(key[1:], "")
215
+ if key in _CONTROLS:
216
+ return _CONTROLS[key]
217
+ return sanitize_text(key)
218
+
219
+
220
+ # --- editing ---------------------------------------------------------------
221
+
222
+
223
+ def _edit(state: EditorState, buffer: str, cursor: int) -> EditorState:
224
+ return replace(state, buffer=buffer, cursor=cursor)
225
+
226
+
227
+ def _move(state: EditorState, cursor: int) -> EditorState:
228
+ return replace(state, cursor=max(0, min(len(state.buffer), cursor)))
229
+
230
+
231
+ def insert_text(state: EditorState, text: str) -> EditorState:
232
+ head, tail = state.buffer[: state.cursor], state.buffer[state.cursor :]
233
+ return _edit(state, head + text + tail, state.cursor + len(text))
234
+
235
+
236
+ def _word_start(buffer: str, cursor: int) -> int:
237
+ start = cursor
238
+ while start > 0 and buffer[start - 1] == " ":
239
+ start -= 1
240
+ while start > 0 and buffer[start - 1] != " ":
241
+ start -= 1
242
+ return start
243
+
244
+
245
+ def _left(state: EditorState, env: Env) -> Outcome:
246
+ return _move(state, state.cursor - 1)
247
+
248
+
249
+ def _right(state: EditorState, env: Env) -> Outcome:
250
+ return _move(state, state.cursor + 1)
251
+
252
+
253
+ def _home(state: EditorState, env: Env) -> Outcome:
254
+ return _move(state, 0)
255
+
256
+
257
+ def _end(state: EditorState, env: Env) -> Outcome:
258
+ return _move(state, len(state.buffer))
259
+
260
+
261
+ def _backspace(state: EditorState, env: Env) -> Outcome:
262
+ if state.cursor == 0:
263
+ return state
264
+ buffer = state.buffer[: state.cursor - 1] + state.buffer[state.cursor :]
265
+ return _edit(state, buffer, state.cursor - 1)
266
+
267
+
268
+ def _delete(state: EditorState, env: Env) -> Outcome:
269
+ buffer = state.buffer[: state.cursor] + state.buffer[state.cursor + 1 :]
270
+ return _edit(state, buffer, state.cursor)
271
+
272
+
273
+ def _kill_to_start(state: EditorState, env: Env) -> Outcome:
274
+ return _edit(state, state.buffer[state.cursor :], 0)
275
+
276
+
277
+ def _kill_word(state: EditorState, env: Env) -> Outcome:
278
+ start = _word_start(state.buffer, state.cursor)
279
+ return _edit(state, state.buffer[:start] + state.buffer[state.cursor :], start)
280
+
281
+
282
+ def _ctrl_c(state: EditorState, env: Env) -> Outcome:
283
+ return Cancelled(eof=False)
284
+
285
+
286
+ def _ctrl_d(state: EditorState, env: Env) -> Outcome:
287
+ return _delete(state, env) if state.buffer else Cancelled(eof=True)
288
+
289
+
290
+ def _enter(state: EditorState, env: Env) -> Outcome:
291
+ return Submitted(state.buffer)
292
+
293
+
294
+ def _next_mode(state: EditorState, env: Env) -> Outcome:
295
+ return replace(state, mode_index=(state.mode_index + 1) % max(1, env.mode_count))
296
+
297
+
298
+ def _tab(state: EditorState, env: Env) -> Outcome:
299
+ text = state.buffer
300
+ if not text.startswith("/") or " " in text:
301
+ return state
302
+ matches = sorted(name for name in env.commands if name.startswith(text))
303
+ if not matches:
304
+ return state
305
+ done = os.path.commonprefix(matches)
306
+ return _edit(state, done, len(done))
307
+
308
+
309
+ def _show_history(state: EditorState, env: Env, index: int, draft: str) -> EditorState:
310
+ entry = env.history[index]
311
+ return replace(state, buffer=entry, cursor=len(entry), history_index=index, draft=draft)
312
+
313
+
314
+ def _up(state: EditorState, env: Env) -> Outcome:
315
+ if not env.history:
316
+ return state
317
+ if state.history_index is None:
318
+ return _show_history(state, env, len(env.history) - 1, state.buffer)
319
+ return _show_history(state, env, max(0, state.history_index - 1), state.draft)
320
+
321
+
322
+ def _down(state: EditorState, env: Env) -> Outcome:
323
+ index = state.history_index
324
+ if index is None:
325
+ return state
326
+ if index + 1 < len(env.history):
327
+ return _show_history(state, env, index + 1, state.draft)
328
+ return replace(
329
+ state, buffer=state.draft, cursor=len(state.draft), history_index=None, draft=""
330
+ )
331
+
332
+
333
+ _HANDLERS: dict[str, Handler] = {
334
+ "left": _left,
335
+ "right": _right,
336
+ "home": _home,
337
+ "end": _end,
338
+ "ctrl_a": _home,
339
+ "ctrl_e": _end,
340
+ "backspace": _backspace,
341
+ "delete": _delete,
342
+ "ctrl_u": _kill_to_start,
343
+ "ctrl_w": _kill_word,
344
+ "ctrl_c": _ctrl_c,
345
+ "ctrl_d": _ctrl_d,
346
+ "enter": _enter,
347
+ "shift_tab": _next_mode,
348
+ "tab": _tab,
349
+ "up": _up,
350
+ "down": _down,
351
+ }
352
+ KEY_NAMES = frozenset(_HANDLERS)
353
+
354
+
355
+ def apply_key(state: EditorState, key: str, env: Env | None = None) -> Outcome:
356
+ """One key press: the next state, or Submitted / Cancelled when it ends."""
357
+ name = normalize_key(key)
358
+ if not name:
359
+ return state
360
+ handler = _HANDLERS.get(name)
361
+ if handler is None:
362
+ return insert_text(state, name)
363
+ return handler(state, env or Env())
364
+
365
+
366
+ # --- layout and rendering --------------------------------------------------
367
+
368
+
369
+ def text_width(width: int) -> int:
370
+ """Columns available for text inside a box ``width`` columns wide."""
371
+ return max(width, MIN_WIDTH) - FRAME_PADDING
372
+
373
+
374
+ def wrap_segments(text: str, columns: int) -> list[tuple[int, int]]:
375
+ """Split ``text`` into (start, end) index ranges that fit ``columns`` cells."""
376
+ segments: list[tuple[int, int]] = []
377
+ start = used = 0
378
+ for index, char in enumerate(text):
379
+ size = cell_len(char)
380
+ if used + size > columns:
381
+ segments.append((start, index))
382
+ start, used = index, 0
383
+ used += size
384
+ segments.append((start, len(text)))
385
+ return segments
386
+
387
+
388
+ def layout(state: EditorState, width: int) -> list[tuple[int, int]]:
389
+ """The rows of the input, with an empty one when the caret needs it."""
390
+ columns = text_width(width)
391
+ segments = wrap_segments(state.buffer, columns)
392
+ start, end = segments[-1]
393
+ if state.cursor == len(state.buffer) and cell_len(state.buffer[start:end]) >= columns:
394
+ segments.append((end, end))
395
+ return segments
396
+
397
+
398
+ def caret_position(state: EditorState, width: int) -> tuple[int, int]:
399
+ """The caret as (row from the box's top border, 0-based column)."""
400
+ segments = layout(state, width)
401
+ row = max(i for i, (start, _) in enumerate(segments) if start <= state.cursor)
402
+ column = cell_len(state.buffer[segments[row][0] : state.cursor])
403
+ return row + 1, column + 4
404
+
405
+
406
+ def paint(text: str, color: str, enabled: bool) -> str:
407
+ """Wrap ``text`` in a 24-bit foreground colour (``#RRGGBB``)."""
408
+ if not enabled or not text:
409
+ return text
410
+ red, green, blue = (int(color[i : i + 2], 16) for i in (1, 3, 5))
411
+ return f"\x1b[38;2;{red};{green};{blue}m{text}\x1b[0m"
412
+
413
+
414
+ def crop(text: str, columns: int) -> str:
415
+ """``text`` cut to ``columns`` characters, ending in ``…`` when cut."""
416
+ if len(text) <= columns:
417
+ return text
418
+ return text[: max(0, columns - 1)] + "…"
419
+
420
+
421
+ def _top_border(mode: Mode, width: int, color: bool) -> str:
422
+ label = f" {mode.name} "
423
+ fill = "─" * max(0, width - 3 - len(label))
424
+ return paint(f"╭─{label}{fill}╮", mode.color, color)
425
+
426
+
427
+ def _bottom_border(mode: Mode, width: int, color: bool) -> str:
428
+ return paint("╰" + "─" * (width - 2) + "╯", mode.color, color)
429
+
430
+
431
+ def _row(index: int, text: str, shown: str, mode: Mode, width: int, color: bool) -> str:
432
+ edge = paint("│", mode.color, color)
433
+ lead = paint(POINTER, mode.color, color) if index == 0 else " "
434
+ pad = " " * (text_width(width) - cell_len(text))
435
+ return f"{edge} {lead} {shown}{pad} {edge}"
436
+
437
+
438
+ def _content_rows(state: EditorState, mode: Mode, width: int, color: bool) -> list[str]:
439
+ if not state.buffer:
440
+ hint = crop(mode.hint, text_width(width))
441
+ return [_row(0, hint, paint(hint, DIM, color), mode, width, color)]
442
+ rows = layout(state, width)
443
+ return [
444
+ _row(i, state.buffer[a:b], state.buffer[a:b], mode, width, color)
445
+ for i, (a, b) in enumerate(rows)
446
+ ]
447
+
448
+
449
+ def render_box(
450
+ state: EditorState,
451
+ *,
452
+ width: int,
453
+ status: str,
454
+ modes: list[Mode],
455
+ color: bool = True,
456
+ ) -> list[str]:
457
+ """The frame: top border, input rows, bottom border, dim status line."""
458
+ width = max(width, MIN_WIDTH)
459
+ mode = effective_mode(state.buffer, state.mode_index, modes)
460
+ return [
461
+ _top_border(mode, width, color),
462
+ *_content_rows(state, mode, width, color),
463
+ _bottom_border(mode, width, color),
464
+ paint(" " + crop(status, width - 2), DIM, color),
465
+ ]
466
+
467
+
468
+ def _up_rows(count: int) -> str:
469
+ return f"\x1b[{count}A" if count > 0 else ""
470
+
471
+
472
+ def paint_frame(
473
+ lines: list[str], caret: tuple[int, int], previous: Geometry | None
474
+ ) -> str:
475
+ """Escape codes that replace the previous frame with ``lines``.
476
+
477
+ Moves up to the old frame's top, clears every row either frame uses,
478
+ writes the new rows and parks the cursor at ``caret``.
479
+ """
480
+ rows = max(len(lines), previous.rows if previous else 0)
481
+ padded = lines + [""] * (rows - len(lines))
482
+ top = _up_rows(previous.caret_row) + "\r" if previous else ""
483
+ body = "\n".join(CLEAR_ROW + line for line in padded)
484
+ park = _up_rows(rows - 1 - caret[0]) + f"\x1b[{caret[1] + 1}G"
485
+ return HIDE_CURSOR + top + body + park + SHOW_CURSOR
486
+
487
+
488
+ def erase_frame(previous: Geometry | None) -> str:
489
+ """Escape codes that wipe the frame, leaving the cursor at its top."""
490
+ if previous is None:
491
+ return ""
492
+ return _up_rows(previous.caret_row) + "\r" + CLEAR_BELOW
493
+
494
+
495
+ # --- the editor ------------------------------------------------------------
496
+
497
+
498
+ class LineEditor:
499
+ def __init__(
500
+ self,
501
+ out: TextIO,
502
+ *,
503
+ read_key: Callable[[], str],
504
+ commands: dict[str, str],
505
+ modes: list[Mode] | None = None,
506
+ history_path: Path | None = None,
507
+ width: Callable[[], int] | None = None,
508
+ color: bool = True,
509
+ history: list[str] | None = None,
510
+ ) -> None:
511
+ self._out = out
512
+ self._read_key = read_key
513
+ self._commands = commands
514
+ self._modes = modes or list(DEFAULT_MODES)
515
+ self._history_path = history_path
516
+ self._width = width or _terminal_width
517
+ self._color = color
518
+ self._mode_index = 0
519
+ self._geometry: Geometry | None = None
520
+ self._history = self._initial_history(history or [])
521
+
522
+ @property
523
+ def mode(self) -> str:
524
+ """The mode selected with Shift+Tab (a typed prefix may override it)."""
525
+ return self._modes[self._mode_index].name
526
+
527
+ @property
528
+ def history(self) -> list[str]:
529
+ return list(self._history)
530
+
531
+ def read(self, *, status: Callable[[], str]) -> tuple[str, str]:
532
+ """Block for one line: ``(mode_name, text)``. Ctrl-C / Ctrl-D raise."""
533
+ self._geometry = None
534
+ try:
535
+ with self._terminal_session():
536
+ text, mode = self._loop(status)
537
+ except (KeyboardInterrupt, EOFError):
538
+ self._erase()
539
+ raise
540
+ self._erase()
541
+ self._write(paint(f"{POINTER} {text}", DIM, self._color) + "\n")
542
+ self._remember(text)
543
+ return mode, text
544
+
545
+ def _loop(self, status: Callable[[], str]) -> tuple[str, str]:
546
+ state = EditorState(mode_index=self._mode_index)
547
+ env = Env(tuple(self._history), self._commands, len(self._modes))
548
+ while True:
549
+ self._draw(state, status())
550
+ outcome = apply_key(state, self._read_key(), env)
551
+ if not isinstance(outcome, EditorState):
552
+ return self._finish(outcome, state)
553
+ state = outcome
554
+ self._mode_index = state.mode_index
555
+
556
+ def _finish(self, outcome: Submitted | Cancelled, state: EditorState) -> tuple[str, str]:
557
+ if isinstance(outcome, Cancelled):
558
+ raise EOFError if outcome.eof else KeyboardInterrupt
559
+ mode = effective_mode(outcome.text, state.mode_index, self._modes)
560
+ return outcome.text, mode.name
561
+
562
+ def _terminal_session(self) -> AbstractContextManager[object]:
563
+ opener = getattr(self._read_key, "session", None)
564
+ return opener() if opener is not None else nullcontext()
565
+
566
+ def _draw(self, state: EditorState, status: str) -> None:
567
+ width = self._width()
568
+ lines = render_box(
569
+ state, width=width, status=status, modes=self._modes, color=self._color
570
+ )
571
+ caret = caret_position(state, width)
572
+ self._write(paint_frame(lines, caret, self._geometry))
573
+ self._geometry = Geometry(rows=len(lines), caret_row=caret[0])
574
+
575
+ def _erase(self) -> None:
576
+ self._write(erase_frame(self._geometry) + SHOW_CURSOR)
577
+ self._geometry = None
578
+
579
+ def _write(self, text: str) -> None:
580
+ self._out.write(text)
581
+ self._out.flush()
582
+
583
+ def _initial_history(self, seed: list[str]) -> list[str]:
584
+ entries: list[str] = []
585
+ loaded = load_history(self._history_path) if self._history_path else []
586
+ for entry in [*seed, *loaded]:
587
+ entries = add_entry(entries, entry)
588
+ return entries
589
+
590
+ def _remember(self, text: str) -> None:
591
+ self._history = add_entry(self._history, text)
592
+ if self._history_path is not None:
593
+ save_history(self._history_path, self._history)
594
+
595
+
596
+ def _terminal_width() -> int:
597
+ return shutil.get_terminal_size().columns
598
+
599
+
600
+ # --- raw terminal input ----------------------------------------------------
601
+
602
+
603
+ def utf8_length(lead: int) -> int:
604
+ """How many bytes a UTF-8 character has, from its first byte."""
605
+ if lead >= 0xF0:
606
+ return 4
607
+ if lead >= 0xE0:
608
+ return 3
609
+ if lead >= 0xC0:
610
+ return 2
611
+ return 1
612
+
613
+
614
+ def escape_complete(sequence: str) -> bool:
615
+ """True when ``sequence`` (starting with ESC) has all its characters."""
616
+ if len(sequence) < 2:
617
+ return False
618
+ if sequence[1] == "[":
619
+ return len(sequence) > 2 and "@" <= sequence[-1] <= "~"
620
+ if sequence[1] == "O":
621
+ return len(sequence) >= 3
622
+ return True
623
+
624
+
625
+ def _read_paste(read_char: Callable[[], str]) -> str:
626
+ text = ""
627
+ while not text.endswith(PASTE_END):
628
+ text += read_char()
629
+ return sanitize_text(text[: -len(PASTE_END)])
630
+
631
+
632
+ def _read_escape(read_char: Callable[[], str], pending: Callable[[], bool]) -> str:
633
+ sequence = ESC
634
+ while pending() and not escape_complete(sequence):
635
+ sequence += read_char()
636
+ if sequence == PASTE_START:
637
+ return _read_paste(read_char)
638
+ return normalize_key(sequence)
639
+
640
+
641
+ def read_one(read_char: Callable[[], str], pending: Callable[[], bool]) -> str:
642
+ """One key from a character source: a key name or the text typed.
643
+
644
+ A newline with more input already waiting is part of a paste, so it
645
+ becomes a space instead of submitting.
646
+ """
647
+ first = read_char()
648
+ if first == ESC:
649
+ return _read_escape(read_char, pending)
650
+ if first in "\r\n" and pending():
651
+ return " "
652
+ return normalize_key(first)
653
+
654
+
655
+ def _read_char(fd: int) -> str: # pragma: no cover - raw terminal I/O
656
+ lead = os.read(fd, 1)
657
+ if not lead:
658
+ raise EOFError
659
+ rest = b"".join(os.read(fd, 1) for _ in range(utf8_length(lead[0]) - 1))
660
+ return (lead + rest).decode(errors="ignore")
661
+
662
+
663
+ def _pending(fd: int) -> bool: # pragma: no cover - raw terminal I/O
664
+ return bool(select.select([fd], [], [], _ESCAPE_TIMEOUT)[0])
665
+
666
+
667
+ class RawKeyReader:
668
+ """Reads key names from the terminal; cbreak holds for a whole ``session``."""
669
+
670
+ def __init__(self) -> None:
671
+ self._active = False
672
+
673
+ @contextmanager
674
+ def session(self) -> Iterator[None]: # pragma: no cover - raw terminal I/O
675
+ """Keep the terminal in cbreak (no echo) with bracketed paste on."""
676
+ if self._active:
677
+ yield
678
+ return
679
+ fd = sys.stdin.fileno()
680
+ saved = termios.tcgetattr(fd)
681
+ tty_mode.setcbreak(fd, termios.TCSANOW) # TCSAFLUSH would drop typed-ahead keys
682
+ sys.stdout.write(PASTE_ON)
683
+ sys.stdout.flush()
684
+ self._active = True
685
+ try:
686
+ yield
687
+ finally:
688
+ self._active = False
689
+ sys.stdout.write(PASTE_OFF)
690
+ sys.stdout.flush()
691
+ termios.tcsetattr(fd, termios.TCSADRAIN, saved)
692
+
693
+ def __call__(self) -> str: # pragma: no cover - raw terminal I/O
694
+ fd = sys.stdin.fileno()
695
+ with self.session():
696
+ return read_one(lambda: _read_char(fd), lambda: _pending(fd))
697
+
698
+
699
+ def raw_key_reader() -> Callable[[], str] | None:
700
+ """The key reader to pass to :class:`LineEditor`, or None without termios."""
701
+ return RawKeyReader() if termios is not None else None