codetheory 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.
- codetheory-0.1.0.dist-info/METADATA +58 -0
- codetheory-0.1.0.dist-info/RECORD +15 -0
- codetheory-0.1.0.dist-info/WHEEL +5 -0
- codetheory-0.1.0.dist-info/entry_points.txt +2 -0
- codetheory-0.1.0.dist-info/licenses/LICENSE +21 -0
- codetheory-0.1.0.dist-info/top_level.txt +1 -0
- local_agent/__init__.py +4 -0
- local_agent/cli.py +698 -0
- local_agent/config.py +263 -0
- local_agent/loop.py +460 -0
- local_agent/orchestrator.py +221 -0
- local_agent/providers.py +593 -0
- local_agent/sessions.py +85 -0
- local_agent/tools.py +820 -0
- local_agent/ui.py +448 -0
local_agent/ui.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
"""Terminal UI helpers: Spinner, countdown, diffs, autocomplete, and tool cards."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import difflib
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import sys
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
import readline
|
|
17
|
+
except ImportError:
|
|
18
|
+
readline = None
|
|
19
|
+
|
|
20
|
+
from .config import C, PROVIDERS, redact_secrets
|
|
21
|
+
|
|
22
|
+
COMMAND_DOCS: list[tuple[str, str]] = [
|
|
23
|
+
("/setup", "Configure all providers (keys, URLs, env vars) + web search"),
|
|
24
|
+
("/providers", "List all providers and API key status"),
|
|
25
|
+
("/provider", "Switch provider by name or number [1-15]"),
|
|
26
|
+
("/key", "Set or replace an API key for a provider"),
|
|
27
|
+
("/models", "List and pick a model for the active provider"),
|
|
28
|
+
("/model", "Set model name directly"),
|
|
29
|
+
("/settings", "Customize context window, theme, max turns, shell, GPU"),
|
|
30
|
+
("/history", "Browse, resume, view, or clear per-session chat history"),
|
|
31
|
+
("/sessions", "Alias for /history"),
|
|
32
|
+
("/agents", "Inspect active/completed parallel agents and manager messages"),
|
|
33
|
+
("/shell", "Drop into an interactive shell ('/shell sandbox' uses bwrap) & return on exit"),
|
|
34
|
+
("/search", "Configure web search backend (DuckDuckGo/Brave/Tavily/SearXNG)"),
|
|
35
|
+
("/auto", "Toggle auto-approve for non-delete tools"),
|
|
36
|
+
("/think", "Toggle reasoning/thinking mode"),
|
|
37
|
+
("/gpu", "Set Ollama GPU layers for qwen3.5 (<n|auto>)"),
|
|
38
|
+
("/clear", "Clear current chat and start a new session"),
|
|
39
|
+
("/help", "Show all commands"),
|
|
40
|
+
("/exit", "Exit the agent"),
|
|
41
|
+
]
|
|
42
|
+
COMMANDS = [cmd for cmd, _ in COMMAND_DOCS]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Spinner:
|
|
46
|
+
"""Thread-safe terminal spinner with an elapsed timer."""
|
|
47
|
+
FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
|
|
48
|
+
current: "Spinner | None" = None
|
|
49
|
+
|
|
50
|
+
def __init__(self, label: str = "Thinking") -> None:
|
|
51
|
+
self.label = label
|
|
52
|
+
self._stop_event = threading.Event()
|
|
53
|
+
self._thread: threading.Thread | None = None
|
|
54
|
+
self._lock = threading.Lock()
|
|
55
|
+
self._t0 = 0.0
|
|
56
|
+
self._tty = sys.stdout.isatty()
|
|
57
|
+
|
|
58
|
+
def __enter__(self) -> "Spinner":
|
|
59
|
+
self.start()
|
|
60
|
+
return self
|
|
61
|
+
|
|
62
|
+
def __exit__(self, *_exc: object) -> None:
|
|
63
|
+
self.stop()
|
|
64
|
+
|
|
65
|
+
def start(self) -> None:
|
|
66
|
+
with self._lock:
|
|
67
|
+
if self._thread is not None or not self._tty:
|
|
68
|
+
return
|
|
69
|
+
self._stop_event.clear()
|
|
70
|
+
self._t0 = time.perf_counter()
|
|
71
|
+
self._thread = threading.Thread(target=self._run, daemon=True)
|
|
72
|
+
self._thread.start()
|
|
73
|
+
Spinner.current = self
|
|
74
|
+
|
|
75
|
+
def _run(self) -> None:
|
|
76
|
+
i = 0
|
|
77
|
+
while True:
|
|
78
|
+
elapsed = time.perf_counter() - self._t0
|
|
79
|
+
frame = self.FRAMES[i % len(self.FRAMES)]
|
|
80
|
+
sys.stdout.write(f"\r\033[K{C.CYAN}{frame}{C.RESET} {C.DIM}{self.label}... ({elapsed:.1f}s){C.RESET}")
|
|
81
|
+
sys.stdout.flush()
|
|
82
|
+
i += 1
|
|
83
|
+
if self._stop_event.wait(0.1):
|
|
84
|
+
break
|
|
85
|
+
|
|
86
|
+
def stop(self) -> None:
|
|
87
|
+
with self._lock:
|
|
88
|
+
thread, self._thread = self._thread, None
|
|
89
|
+
if Spinner.current is self:
|
|
90
|
+
Spinner.current = None
|
|
91
|
+
if thread is None:
|
|
92
|
+
return
|
|
93
|
+
self._stop_event.set()
|
|
94
|
+
thread.join(timeout=1.0)
|
|
95
|
+
sys.stdout.write("\r\033[K")
|
|
96
|
+
sys.stdout.flush()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def countdown(seconds: float, reason: str) -> None:
|
|
100
|
+
if Spinner.current is not None:
|
|
101
|
+
Spinner.current.stop()
|
|
102
|
+
end = time.time() + seconds
|
|
103
|
+
while True:
|
|
104
|
+
left = end - time.time()
|
|
105
|
+
if left <= 0:
|
|
106
|
+
break
|
|
107
|
+
s = math.ceil(left)
|
|
108
|
+
shown = f"{s // 3600:d}:{(s % 3600) // 60:02d}:{s % 60:02d}" if s >= 3600 else f"{s // 60:02d}:{s % 60:02d}"
|
|
109
|
+
print(f"\r [wait] {reason}: resuming in {shown} ", end="", flush=True)
|
|
110
|
+
time.sleep(min(1, left))
|
|
111
|
+
print("\r" + " " * 90 + "\r", end="", flush=True)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def print_diff_preview(old_text: str, new_text: str, label: str, indent: str = "") -> None:
|
|
115
|
+
"""Display a colored unified diff preview (up to 30 lines)."""
|
|
116
|
+
diff = list(difflib.unified_diff(
|
|
117
|
+
old_text.splitlines(), new_text.splitlines(),
|
|
118
|
+
fromfile=f"a/{label}", tofile=f"b/{label}", lineterm="", n=2,
|
|
119
|
+
))
|
|
120
|
+
if not diff:
|
|
121
|
+
return
|
|
122
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {C.CYAN}Diff Preview:{C.RESET}")
|
|
123
|
+
for line in diff[:30]:
|
|
124
|
+
if line.startswith(("+++", "---", "@@")):
|
|
125
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {C.DIM}{line[:115]}{C.RESET}")
|
|
126
|
+
elif line.startswith("+"):
|
|
127
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {C.GREEN}{line[:115]}{C.RESET}")
|
|
128
|
+
elif line.startswith("-"):
|
|
129
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {C.RED}{line[:115]}{C.RESET}")
|
|
130
|
+
else:
|
|
131
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {C.DIM}{line[:115]}{C.RESET}")
|
|
132
|
+
if len(diff) > 30:
|
|
133
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {C.GRAY}... ({len(diff) - 30} more diff lines){C.RESET}")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def print_tool_result(result: str, elapsed: float, indent: str = "") -> None:
|
|
137
|
+
is_err = result.startswith(("Error", "Action denied")) or ("Exit code: " in result and not result.startswith("Exit code: 0"))
|
|
138
|
+
icon, color = ("❌", C.RED) if is_err else ("✅", C.GREEN)
|
|
139
|
+
lines = result.splitlines()
|
|
140
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {icon} {color}Result{C.RESET} {C.DIM}({elapsed:.2f}s){C.RESET}")
|
|
141
|
+
for ln in lines[:8]:
|
|
142
|
+
trimmed = ln[:115] + ("..." if len(ln) > 115 else "")
|
|
143
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {C.DIM}{trimmed}{C.RESET}")
|
|
144
|
+
if len(lines) > 8:
|
|
145
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {C.GRAY}... ({len(lines) - 8} more lines){C.RESET}")
|
|
146
|
+
print(f"{indent}{C.YELLOW}└───────────────────────────────────────────────────────────{C.RESET}")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def format_tool_header(fn_name: str, args: dict[str, Any], indent: str = "") -> None:
|
|
150
|
+
print(f"\n{indent}{C.YELLOW}┌─ 🔧 Tool: {C.BOLD}{fn_name}{C.RESET}")
|
|
151
|
+
args_str = redact_secrets(json.dumps(args, ensure_ascii=False))
|
|
152
|
+
if len(args_str) > 130:
|
|
153
|
+
args_str = args_str[:130] + "..."
|
|
154
|
+
print(f"{indent}{C.YELLOW}│{C.RESET} {C.DIM}Args:{C.RESET} {args_str}")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def setup_autocomplete() -> None:
|
|
158
|
+
"""Register non-repeating prefix Tab autocomplete on POSIX terminals."""
|
|
159
|
+
if readline is None:
|
|
160
|
+
return
|
|
161
|
+
try:
|
|
162
|
+
readline.set_auto_history(True)
|
|
163
|
+
except AttributeError:
|
|
164
|
+
pass # nosec B110: older Python/libedit builds omit set_auto_history
|
|
165
|
+
|
|
166
|
+
def completer(text: str, state: int) -> str | None:
|
|
167
|
+
buf = readline.get_line_buffer()
|
|
168
|
+
parts = buf.lstrip().split()
|
|
169
|
+
if len(parts) <= 1 and buf.lstrip().startswith("/"):
|
|
170
|
+
opts = sorted(set(c for c in COMMANDS if c.startswith(text)))
|
|
171
|
+
elif len(parts) == 2 and parts[0] in ("/provider", "/setup", "/key"):
|
|
172
|
+
sub = list(PROVIDERS) + (["search"] if parts[0] == "/setup" else [])
|
|
173
|
+
opts = sorted(set(s for s in sub if s.startswith(text)))
|
|
174
|
+
elif len(parts) == 2 and parts[0] in ("/history", "/sessions"):
|
|
175
|
+
sub = ["list", "show", "new", "clear"]
|
|
176
|
+
opts = sorted(set(s for s in sub if s.startswith(text)))
|
|
177
|
+
else:
|
|
178
|
+
opts = []
|
|
179
|
+
return opts[state] if state < len(opts) else None
|
|
180
|
+
|
|
181
|
+
readline.set_completer_delims(" \t\n")
|
|
182
|
+
readline.set_completer(completer)
|
|
183
|
+
if "libedit" in (getattr(readline, "__doc__", "") or "").lower():
|
|
184
|
+
readline.parse_and_bind("bind ^I rl_complete")
|
|
185
|
+
else:
|
|
186
|
+
readline.parse_and_bind("tab: complete")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def suggest_slash_command(typed: str) -> str | None:
|
|
190
|
+
cmd = typed.split()[0].lower()
|
|
191
|
+
prefix_matches = sorted(set(c for c in COMMANDS if c.startswith(cmd)))
|
|
192
|
+
if len(prefix_matches) == 1 and " " not in typed:
|
|
193
|
+
return prefix_matches[0]
|
|
194
|
+
if prefix_matches:
|
|
195
|
+
print(f"{C.YELLOW}Suggestions:{C.RESET} {', '.join(prefix_matches)}")
|
|
196
|
+
return None
|
|
197
|
+
fuzzy = difflib.get_close_matches(cmd, COMMANDS, n=3, cutoff=0.5)
|
|
198
|
+
if fuzzy:
|
|
199
|
+
print(f"{C.RED}Unknown command '{cmd}'. Did you mean:{C.RESET} {', '.join(fuzzy)}")
|
|
200
|
+
else:
|
|
201
|
+
print(f"{C.RED}Unknown command '{cmd}'. Type /help.{C.RESET}")
|
|
202
|
+
return None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _matching_commands(buf: str) -> list[tuple[str, str]]:
|
|
206
|
+
if not buf.startswith("/") or " " in buf:
|
|
207
|
+
return []
|
|
208
|
+
low = buf.lower()
|
|
209
|
+
return [(cmd, desc) for cmd, desc in COMMAND_DOCS if cmd.startswith(low)]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _read_key_posix() -> str:
|
|
213
|
+
import termios
|
|
214
|
+
import tty
|
|
215
|
+
fd = sys.stdin.fileno()
|
|
216
|
+
old = termios.tcgetattr(fd)
|
|
217
|
+
try:
|
|
218
|
+
tty.setraw(fd)
|
|
219
|
+
ch = sys.stdin.read(1)
|
|
220
|
+
if ch == "\x1b":
|
|
221
|
+
nxt = sys.stdin.read(1)
|
|
222
|
+
if nxt == "[":
|
|
223
|
+
code = sys.stdin.read(1)
|
|
224
|
+
if code == "A":
|
|
225
|
+
return "UP"
|
|
226
|
+
if code == "B":
|
|
227
|
+
return "DOWN"
|
|
228
|
+
if code == "C":
|
|
229
|
+
return "RIGHT"
|
|
230
|
+
if code == "D":
|
|
231
|
+
return "LEFT"
|
|
232
|
+
return "ESC"
|
|
233
|
+
return ch
|
|
234
|
+
finally:
|
|
235
|
+
termios.tcsetattr(fd, termios.TCSADRAIN, old)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _read_key_win() -> str:
|
|
239
|
+
import msvcrt
|
|
240
|
+
ch = msvcrt.getwch()
|
|
241
|
+
if ch in ("\x00", "\xe0"):
|
|
242
|
+
code = msvcrt.getwch()
|
|
243
|
+
if code == "H":
|
|
244
|
+
return "UP"
|
|
245
|
+
if code == "P":
|
|
246
|
+
return "DOWN"
|
|
247
|
+
if code == "M":
|
|
248
|
+
return "RIGHT"
|
|
249
|
+
if code == "K":
|
|
250
|
+
return "LEFT"
|
|
251
|
+
return ""
|
|
252
|
+
return ch
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def prompt_with_slash_menu(prompt_str: str, history: list[str]) -> str:
|
|
256
|
+
"""Interactive prompt that shows a live slash-command menu as soon as '/' is typed."""
|
|
257
|
+
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
|
258
|
+
return input(prompt_str)
|
|
259
|
+
|
|
260
|
+
read_key = _read_key_win if os.name == "nt" else _read_key_posix
|
|
261
|
+
leading_nl = "\n" if prompt_str.startswith("\n") else ""
|
|
262
|
+
clean_prompt = prompt_str.lstrip("\n")
|
|
263
|
+
if leading_nl:
|
|
264
|
+
sys.stdout.write(leading_nl)
|
|
265
|
+
buf = ""
|
|
266
|
+
menu_idx = 0
|
|
267
|
+
hist_idx = len(history)
|
|
268
|
+
menu_lines = 0
|
|
269
|
+
|
|
270
|
+
def render() -> None:
|
|
271
|
+
nonlocal menu_lines
|
|
272
|
+
if menu_lines > 0:
|
|
273
|
+
sys.stdout.write("\r\033[K")
|
|
274
|
+
sys.stdout.write("\033[J")
|
|
275
|
+
sys.stdout.write(f"\r\033[K{clean_prompt}{buf}")
|
|
276
|
+
matches = _matching_commands(buf)
|
|
277
|
+
if matches:
|
|
278
|
+
cols = max(40, shutil.get_terminal_size((80, 24)).columns)
|
|
279
|
+
shown = matches[:10]
|
|
280
|
+
sel = min(menu_idx, len(shown) - 1)
|
|
281
|
+
lines_out = []
|
|
282
|
+
for idx, (cmd, desc) in enumerate(shown):
|
|
283
|
+
max_desc = max(10, cols - 20)
|
|
284
|
+
d = desc[:max_desc - 1] + "…" if len(desc) > max_desc else desc
|
|
285
|
+
if idx == sel:
|
|
286
|
+
lines_out.append(f" {C.CYAN}{C.BOLD}▶ {cmd:<12}{C.RESET} {C.DIM}{d}{C.RESET}")
|
|
287
|
+
else:
|
|
288
|
+
lines_out.append(f" {C.GREEN}{cmd:<12}{C.RESET} {C.GRAY}{d}{C.RESET}")
|
|
289
|
+
if len(matches) > 10:
|
|
290
|
+
lines_out.append(f" {C.GRAY}... ({len(matches) - 10} more; keep typing){C.RESET}")
|
|
291
|
+
block = "\n" + "\n".join(lines_out)
|
|
292
|
+
menu_lines = len(lines_out)
|
|
293
|
+
sys.stdout.write(block)
|
|
294
|
+
sys.stdout.write(f"\033[{menu_lines}A\r")
|
|
295
|
+
visible_prompt = len(re_strip_ansi(clean_prompt)) + len(buf)
|
|
296
|
+
if visible_prompt > 0:
|
|
297
|
+
sys.stdout.write(f"\033[{visible_prompt}C")
|
|
298
|
+
else:
|
|
299
|
+
menu_lines = 0
|
|
300
|
+
sys.stdout.flush()
|
|
301
|
+
|
|
302
|
+
def clear_menu() -> None:
|
|
303
|
+
nonlocal menu_lines
|
|
304
|
+
if menu_lines > 0:
|
|
305
|
+
sys.stdout.write("\n\033[J\033[A")
|
|
306
|
+
menu_lines = 0
|
|
307
|
+
|
|
308
|
+
sys.stdout.write(clean_prompt)
|
|
309
|
+
sys.stdout.flush()
|
|
310
|
+
|
|
311
|
+
while True:
|
|
312
|
+
key = read_key()
|
|
313
|
+
if key in ("\r", "\n"):
|
|
314
|
+
matches = _matching_commands(buf)
|
|
315
|
+
if matches and buf == "/":
|
|
316
|
+
buf = matches[min(menu_idx, len(matches) - 1)][0]
|
|
317
|
+
elif matches and buf not in [m[0] for m in matches]:
|
|
318
|
+
buf = matches[min(menu_idx, len(matches) - 1)][0]
|
|
319
|
+
clear_menu()
|
|
320
|
+
sys.stdout.write(f"\r\033[K{clean_prompt}{buf}\n")
|
|
321
|
+
sys.stdout.flush()
|
|
322
|
+
return buf
|
|
323
|
+
if key == "\x03": # Ctrl+C
|
|
324
|
+
clear_menu()
|
|
325
|
+
sys.stdout.write("\n")
|
|
326
|
+
sys.stdout.flush()
|
|
327
|
+
raise KeyboardInterrupt
|
|
328
|
+
if key == "\x04" and not buf: # Ctrl+D on empty line
|
|
329
|
+
clear_menu()
|
|
330
|
+
sys.stdout.write("\n")
|
|
331
|
+
sys.stdout.flush()
|
|
332
|
+
raise EOFError
|
|
333
|
+
if key in ("\x7f", "\x08"): # Backspace
|
|
334
|
+
if buf:
|
|
335
|
+
buf = buf[:-1]
|
|
336
|
+
menu_idx = 0
|
|
337
|
+
render()
|
|
338
|
+
continue
|
|
339
|
+
if key == "\t": # Tab completes highlighted command
|
|
340
|
+
matches = _matching_commands(buf)
|
|
341
|
+
if matches:
|
|
342
|
+
buf = matches[min(menu_idx, len(matches) - 1)][0]
|
|
343
|
+
if len(matches) == 1:
|
|
344
|
+
buf += " "
|
|
345
|
+
menu_idx = 0
|
|
346
|
+
render()
|
|
347
|
+
continue
|
|
348
|
+
if key == "UP":
|
|
349
|
+
matches = _matching_commands(buf)
|
|
350
|
+
if matches:
|
|
351
|
+
menu_idx = (menu_idx - 1) % min(len(matches), 10)
|
|
352
|
+
render()
|
|
353
|
+
elif history and hist_idx > 0:
|
|
354
|
+
hist_idx -= 1
|
|
355
|
+
buf = history[hist_idx]
|
|
356
|
+
render()
|
|
357
|
+
continue
|
|
358
|
+
if key == "DOWN":
|
|
359
|
+
matches = _matching_commands(buf)
|
|
360
|
+
if matches:
|
|
361
|
+
menu_idx = (menu_idx + 1) % min(len(matches), 10)
|
|
362
|
+
render()
|
|
363
|
+
elif hist_idx < len(history) - 1:
|
|
364
|
+
hist_idx += 1
|
|
365
|
+
buf = history[hist_idx]
|
|
366
|
+
render()
|
|
367
|
+
elif hist_idx == len(history) - 1:
|
|
368
|
+
hist_idx = len(history)
|
|
369
|
+
buf = ""
|
|
370
|
+
render()
|
|
371
|
+
continue
|
|
372
|
+
if key in ("ESC", "LEFT", "RIGHT", ""):
|
|
373
|
+
continue
|
|
374
|
+
if key.isprintable():
|
|
375
|
+
buf += key
|
|
376
|
+
menu_idx = 0
|
|
377
|
+
render()
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def re_strip_ansi(text: str) -> str:
|
|
381
|
+
return re.sub(r"\x1b\[[0-9;]*m", "", text)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def enter_alt_screen() -> None:
|
|
385
|
+
"""Switch terminal into an alternate full-screen buffer (like Cline/vim)."""
|
|
386
|
+
if sys.stdout.isatty():
|
|
387
|
+
sys.stdout.write("\033[?1049h\033[H\033[2J")
|
|
388
|
+
sys.stdout.flush()
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def exit_alt_screen() -> None:
|
|
392
|
+
"""Restore original terminal buffer on exit."""
|
|
393
|
+
if sys.stdout.isatty():
|
|
394
|
+
sys.stdout.write("\033[?1049l")
|
|
395
|
+
sys.stdout.flush()
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def render_markdown_line(line: str, in_code_block: bool = False) -> tuple[str, bool]:
|
|
399
|
+
"""Format one Markdown line into clean ANSI terminal output."""
|
|
400
|
+
stripped = line.lstrip()
|
|
401
|
+
if stripped.startswith("```"):
|
|
402
|
+
lang = stripped[3:].strip()
|
|
403
|
+
if not in_code_block:
|
|
404
|
+
hdr = f"{C.GRAY}─── {lang or 'code'} ───{C.RESET}"
|
|
405
|
+
return hdr, True
|
|
406
|
+
return f"{C.GRAY}───────────{C.RESET}", False
|
|
407
|
+
|
|
408
|
+
if in_code_block:
|
|
409
|
+
return f"{C.CYAN} {line}{C.RESET}", True
|
|
410
|
+
|
|
411
|
+
# Headings
|
|
412
|
+
hm = re.match(r"^(#{1,6})\s+(.+)$", stripped)
|
|
413
|
+
if hm:
|
|
414
|
+
return f"\n{C.CYAN}{C.BOLD}{hm.group(2)}{C.RESET}", False
|
|
415
|
+
|
|
416
|
+
# Bullet items (- or *)
|
|
417
|
+
bm = re.match(r"^(\s*)[-*]\s+(.+)$", line)
|
|
418
|
+
if bm:
|
|
419
|
+
line = f"{bm.group(1)} {C.CYAN}•{C.RESET} {bm.group(2)}"
|
|
420
|
+
|
|
421
|
+
# Inline formatting: **bold**, *italic*, `code`
|
|
422
|
+
line = re.sub(r"`([^`]+)`", lambda m: f"{C.CYAN}{m.group(1)}{C.RESET}", line)
|
|
423
|
+
line = re.sub(r"\*\*([^*]+)\*\*", lambda m: f"{C.BOLD}{m.group(1)}{C.RESET}", line)
|
|
424
|
+
line = re.sub(r"(?<!\*)\*([^*]+)\*(?!\*)", lambda m: f"{C.ITALIC}{m.group(1)}{C.RESET}", line)
|
|
425
|
+
return line, False
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
class MarkdownStreamRenderer:
|
|
429
|
+
"""Line-buffered streaming Markdown-to-ANSI renderer for clean CLI output."""
|
|
430
|
+
|
|
431
|
+
def __init__(self) -> None:
|
|
432
|
+
self._buf = ""
|
|
433
|
+
self._in_code = False
|
|
434
|
+
|
|
435
|
+
def feed(self, token: str) -> None:
|
|
436
|
+
self._buf += token
|
|
437
|
+
while "\n" in self._buf:
|
|
438
|
+
line, self._buf = self._buf.split("\n", 1)
|
|
439
|
+
rendered, self._in_code = render_markdown_line(line, self._in_code)
|
|
440
|
+
sys.stdout.write(rendered + "\n")
|
|
441
|
+
sys.stdout.flush()
|
|
442
|
+
|
|
443
|
+
def flush(self) -> None:
|
|
444
|
+
if self._buf:
|
|
445
|
+
rendered, self._in_code = render_markdown_line(self._buf, self._in_code)
|
|
446
|
+
sys.stdout.write(rendered)
|
|
447
|
+
self._buf = ""
|
|
448
|
+
sys.stdout.flush()
|