rigcode 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.
- rigcode/__init__.py +4 -0
- rigcode/__main__.py +4 -0
- rigcode/agent/__init__.py +0 -0
- rigcode/agent/loop.py +627 -0
- rigcode/agent/mentions.py +70 -0
- rigcode/agent/prompts.py +195 -0
- rigcode/agent/runtime.py +535 -0
- rigcode/agent/session.py +165 -0
- rigcode/agent/state.py +161 -0
- rigcode/cli.py +283 -0
- rigcode/config.py +284 -0
- rigcode/doctor.py +158 -0
- rigcode/extensions.py +275 -0
- rigcode/hooks.py +142 -0
- rigcode/llm/__init__.py +0 -0
- rigcode/llm/client.py +259 -0
- rigcode/llm/probe.py +229 -0
- rigcode/llm/stream.py +240 -0
- rigcode/llm/textmode.py +161 -0
- rigcode/llm/types.py +92 -0
- rigcode/llm/wire.py +76 -0
- rigcode/mcp.py +329 -0
- rigcode/permissions.py +221 -0
- rigcode/prompts/agents/coder.md +13 -0
- rigcode/prompts/agents/debugger.md +14 -0
- rigcode/prompts/agents/explore.md +22 -0
- rigcode/prompts/agents/plan.md +21 -0
- rigcode/prompts/agents/researcher.md +14 -0
- rigcode/prompts/agents/reviewer.md +18 -0
- rigcode/prompts/agents/verifier.md +15 -0
- rigcode/prompts/commit.md +5 -0
- rigcode/prompts/compact.md +24 -0
- rigcode/prompts/init.md +10 -0
- rigcode/prompts/system.md +27 -0
- rigcode/tools/__init__.py +0 -0
- rigcode/tools/base.py +245 -0
- rigcode/tools/bashsafety.py +262 -0
- rigcode/tools/editmatch.py +367 -0
- rigcode/tools/files.py +534 -0
- rigcode/tools/interact.py +69 -0
- rigcode/tools/search.py +309 -0
- rigcode/tools/shell.py +424 -0
- rigcode/tools/skill.py +37 -0
- rigcode/tools/task.py +54 -0
- rigcode/tools/todo.py +62 -0
- rigcode/tools/web.py +346 -0
- rigcode/ui/__init__.py +0 -0
- rigcode/ui/base.py +69 -0
- rigcode/ui/commands.py +581 -0
- rigcode/ui/plain.py +321 -0
- rigcode/ui/render.py +207 -0
- rigcode/ui/terminal.py +1154 -0
- rigcode/utils/__init__.py +0 -0
- rigcode/utils/files.py +176 -0
- rigcode/utils/frontmatter.py +38 -0
- rigcode/utils/globmatch.py +91 -0
- rigcode/utils/jsonrepair.py +110 -0
- rigcode/utils/paths.py +83 -0
- rigcode/utils/text.py +105 -0
- rigcode-0.1.0.dist-info/METADATA +203 -0
- rigcode-0.1.0.dist-info/RECORD +64 -0
- rigcode-0.1.0.dist-info/WHEEL +4 -0
- rigcode-0.1.0.dist-info/entry_points.txt +2 -0
- rigcode-0.1.0.dist-info/licenses/LICENSE +21 -0
rigcode/ui/plain.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""Line-oriented front end for `rigcode -p` (headless) and for terminals where the
|
|
2
|
+
interactive prompt can't run (pipes, dumb terminals).
|
|
3
|
+
|
|
4
|
+
Headless output formats:
|
|
5
|
+
text only the final answer on stdout (progress on stderr with --verbose)
|
|
6
|
+
json one JSON object with the answer, usage and session id at the end
|
|
7
|
+
stream-json one JSON event per line as things happen
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
import signal
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
|
|
18
|
+
from rigcode.agent.mentions import expand_mentions
|
|
19
|
+
from rigcode.permissions import Decision
|
|
20
|
+
from rigcode.tools.base import ToolContext
|
|
21
|
+
from rigcode.tools.shell import build_invocation
|
|
22
|
+
from rigcode.ui.base import BaseUI
|
|
23
|
+
from rigcode.ui.commands import build_registry
|
|
24
|
+
from rigcode.ui.render import Renderer
|
|
25
|
+
from rigcode.utils.text import fmt_duration, fmt_tokens, one_line
|
|
26
|
+
|
|
27
|
+
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
|
|
28
|
+
_STYLE_ANSI = {"class:error": "\x1b[31m", "class:warn": "\x1b[33m", "class:dim": "\x1b[2m", "class:faint": "\x1b[2m",
|
|
29
|
+
"class:ok": "\x1b[32m", "bold": "\x1b[1m"}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PlainUI(BaseUI):
|
|
33
|
+
def __init__(self, settings, *, interactive: bool, output_format: str = "text", verbose: bool = False,
|
|
34
|
+
color: bool | None = None):
|
|
35
|
+
self.interactive = interactive
|
|
36
|
+
self.fmt = output_format
|
|
37
|
+
self.verbose = verbose or interactive
|
|
38
|
+
self.thinking_mode = str(settings.get("ui.thinking", "collapsed"))
|
|
39
|
+
self.r = Renderer()
|
|
40
|
+
self.rt = None
|
|
41
|
+
self.commands = build_registry()
|
|
42
|
+
self.running: dict = {}
|
|
43
|
+
self.busy = False
|
|
44
|
+
self.exit_requested = False
|
|
45
|
+
self._mid_line = False
|
|
46
|
+
self._thinking_since: float | None = None
|
|
47
|
+
self._pending: list[str] = []
|
|
48
|
+
for s in (sys.stdout, sys.stderr):
|
|
49
|
+
try:
|
|
50
|
+
s.reconfigure(encoding="utf-8", errors="replace")
|
|
51
|
+
except (AttributeError, ValueError):
|
|
52
|
+
pass
|
|
53
|
+
self.stream = sys.stdout if interactive else sys.stderr
|
|
54
|
+
self.color = color if color is not None else bool(getattr(self.stream, "isatty", lambda: False)())
|
|
55
|
+
|
|
56
|
+
# ---------------------------------------------------------------- output
|
|
57
|
+
def _write(self, text: str, style: str = "") -> None:
|
|
58
|
+
if self.fmt == "stream-json" or not self.verbose:
|
|
59
|
+
return
|
|
60
|
+
if self._mid_line and not text.startswith("\n"):
|
|
61
|
+
text = "\n" + text
|
|
62
|
+
self._mid_line = False
|
|
63
|
+
if self.color and style in _STYLE_ANSI:
|
|
64
|
+
text = _STYLE_ANSI[style] + text + "\x1b[0m"
|
|
65
|
+
self.stream.write(text)
|
|
66
|
+
self.stream.flush()
|
|
67
|
+
|
|
68
|
+
def _event(self, kind: str, **data) -> None:
|
|
69
|
+
if self.fmt == "stream-json":
|
|
70
|
+
sys.stdout.write(json.dumps({"type": kind, **data}, ensure_ascii=False, default=str) + "\n")
|
|
71
|
+
sys.stdout.flush()
|
|
72
|
+
|
|
73
|
+
def out_line(self, text: str, style: str = "") -> None:
|
|
74
|
+
if self.fmt == "stream-json":
|
|
75
|
+
self._event("notice", text=text)
|
|
76
|
+
else:
|
|
77
|
+
self._write(text + "\n", style)
|
|
78
|
+
|
|
79
|
+
def out(self, fragments) -> None:
|
|
80
|
+
self._write("".join(t for _, t in fragments))
|
|
81
|
+
|
|
82
|
+
def out_ansi(self, text: str) -> None:
|
|
83
|
+
self._write((text if self.color else _ANSI_RE.sub("", text)).rstrip("\n") + "\n")
|
|
84
|
+
|
|
85
|
+
def out_markdown(self, text: str, bullet: str | None = None, style: str | None = None) -> None:
|
|
86
|
+
if text.strip():
|
|
87
|
+
self._write("\n" + (bullet or "") + text.strip() + "\n")
|
|
88
|
+
|
|
89
|
+
def print_tool(self, label: str, res, output_lines: int | None = None) -> None:
|
|
90
|
+
self._write(f"\n{'✗' if res.is_error else '●'} {label}\n", "class:error" if res.is_error else "bold")
|
|
91
|
+
self._write(f" ⎿ {one_line(res.summary or res.content, 160)}\n",
|
|
92
|
+
"class:error" if res.is_error else "class:dim")
|
|
93
|
+
disp = res.display or {}
|
|
94
|
+
if disp.get("type") == "output" and output_lines:
|
|
95
|
+
lines = [l for l in disp.get("text", "").split("\n") if l.strip()][-output_lines:]
|
|
96
|
+
self._write("".join(f" {l}\n" for l in lines), "class:dim")
|
|
97
|
+
|
|
98
|
+
def begin_activity(self, key: str, label: str) -> None:
|
|
99
|
+
self._write(f"\n● {label} …\n", "class:dim")
|
|
100
|
+
|
|
101
|
+
def end_activity(self, key: str) -> None:
|
|
102
|
+
pass
|
|
103
|
+
|
|
104
|
+
def request_exit(self) -> None:
|
|
105
|
+
self.exit_requested = True
|
|
106
|
+
|
|
107
|
+
def submit_message(self, text: str) -> None:
|
|
108
|
+
self._pending.append(text)
|
|
109
|
+
|
|
110
|
+
# ---------------------------------------------------------------- engine events
|
|
111
|
+
def on_notice(self, level: str, text: str) -> None:
|
|
112
|
+
if self.fmt == "stream-json":
|
|
113
|
+
if level != "info": # the init event carries the discovered server and model
|
|
114
|
+
self._event("notice", level=level, text=text)
|
|
115
|
+
return
|
|
116
|
+
if level == "error" and not self.verbose:
|
|
117
|
+
sys.stderr.write(f"error: {text}\n")
|
|
118
|
+
return
|
|
119
|
+
style = {"warn": "class:warn", "error": "class:error"}.get(level, "class:dim")
|
|
120
|
+
prefix = {"warn": "⚠ ", "error": "✗ "}.get(level, " ⎿ ")
|
|
121
|
+
self._write(prefix + text + "\n", style)
|
|
122
|
+
|
|
123
|
+
def on_model_start(self, agent, info: dict) -> None:
|
|
124
|
+
self._thinking_since = None
|
|
125
|
+
|
|
126
|
+
def on_delta(self, agent, d) -> None:
|
|
127
|
+
if not agent.is_main:
|
|
128
|
+
return
|
|
129
|
+
if self.fmt == "stream-json":
|
|
130
|
+
if d.kind == "content":
|
|
131
|
+
self._event("text_delta", text=d.text)
|
|
132
|
+
return
|
|
133
|
+
if d.kind == "reasoning":
|
|
134
|
+
if self._thinking_since is None:
|
|
135
|
+
self._thinking_since = time.monotonic()
|
|
136
|
+
if self.thinking_mode != "hidden":
|
|
137
|
+
self._write("✻ thinking…\n", "class:dim")
|
|
138
|
+
if self.thinking_mode == "full" and self.verbose:
|
|
139
|
+
self.stream.write(d.text)
|
|
140
|
+
self.stream.flush()
|
|
141
|
+
self._mid_line = not d.text.endswith("\n")
|
|
142
|
+
elif d.kind == "content":
|
|
143
|
+
if self.interactive:
|
|
144
|
+
self.stream.write(d.text)
|
|
145
|
+
self.stream.flush()
|
|
146
|
+
self._mid_line = not d.text.endswith("\n")
|
|
147
|
+
elif d.kind == "reset":
|
|
148
|
+
self._write(f"⚠ {d.text}\n", "class:warn")
|
|
149
|
+
|
|
150
|
+
def on_model_end(self, agent, turn) -> None:
|
|
151
|
+
if self._mid_line:
|
|
152
|
+
self.stream.write("\n")
|
|
153
|
+
self.stream.flush()
|
|
154
|
+
self._mid_line = False
|
|
155
|
+
if turn is not None and self.fmt == "stream-json":
|
|
156
|
+
self._event("assistant", agent=agent.name, message=turn.to_message(),
|
|
157
|
+
usage={"prompt_tokens": turn.usage.prompt_tokens, "cached_tokens": turn.usage.cached_tokens,
|
|
158
|
+
"completion_tokens": turn.usage.completion_tokens})
|
|
159
|
+
|
|
160
|
+
def on_tool_start(self, agent, prepared, args: dict) -> None:
|
|
161
|
+
self._event("tool_use", agent=agent.name, id=prepared.call.id, name=prepared.call.name, input=args)
|
|
162
|
+
|
|
163
|
+
def on_tool_end(self, agent, prepared, result) -> None:
|
|
164
|
+
if self.fmt == "stream-json":
|
|
165
|
+
self._event("tool_result", agent=agent.name, id=prepared.call.id, is_error=result.is_error,
|
|
166
|
+
summary=result.summary, content=result.content[:20000])
|
|
167
|
+
elif agent.is_main:
|
|
168
|
+
self.print_tool(prepared.label, result)
|
|
169
|
+
else:
|
|
170
|
+
self._write(f" ⎿ [{agent.name}] {one_line(prepared.label, 90)}\n", "class:dim")
|
|
171
|
+
|
|
172
|
+
def on_compact_start(self, agent, before: int, reason: str) -> None:
|
|
173
|
+
self._write(f"✻ compacting {fmt_tokens(before)} tokens of conversation…\n", "class:dim")
|
|
174
|
+
|
|
175
|
+
def on_compact_end(self, agent, before: int, after: int, summary: str | None) -> None:
|
|
176
|
+
if summary:
|
|
177
|
+
self._write(f" ⎿ compacted: {fmt_tokens(before)} → {fmt_tokens(after)} tokens\n", "class:dim")
|
|
178
|
+
|
|
179
|
+
def on_subagent_start(self, agent, description: str) -> None:
|
|
180
|
+
self._write(f" ⎿ {agent.name} subagent: {description}\n", "class:dim")
|
|
181
|
+
|
|
182
|
+
def on_warmup(self, state: str, data: dict | None = None) -> None:
|
|
183
|
+
if state == "failed":
|
|
184
|
+
self._write(f" ⎿ cache warm-up failed: {(data or {}).get('error')}\n", "class:dim")
|
|
185
|
+
|
|
186
|
+
# ---------------------------------------------------------------- questions
|
|
187
|
+
async def _input(self, prompt: str) -> str | None:
|
|
188
|
+
if not self.interactive:
|
|
189
|
+
return None
|
|
190
|
+
try:
|
|
191
|
+
return await asyncio.to_thread(input, prompt)
|
|
192
|
+
except (EOFError, KeyboardInterrupt):
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
async def choose(self, title: str, options: list[str]) -> int | None:
|
|
196
|
+
if not self.interactive:
|
|
197
|
+
return None
|
|
198
|
+
self._write(title + "\n" + "".join(f" {i}. {o}\n" for i, o in enumerate(options, 1)))
|
|
199
|
+
ans = (await self._input("choice> ") or "").strip()
|
|
200
|
+
if not ans.isdigit():
|
|
201
|
+
return None
|
|
202
|
+
idx = int(ans) - 1
|
|
203
|
+
return idx if 0 <= idx < len(options) else None
|
|
204
|
+
|
|
205
|
+
async def ask_text(self, title: str, label: str = "") -> str | None:
|
|
206
|
+
self._write(title + "\n")
|
|
207
|
+
return await self._input("> ")
|
|
208
|
+
|
|
209
|
+
async def request_permission(self, req, agent):
|
|
210
|
+
if not self.interactive:
|
|
211
|
+
return None
|
|
212
|
+
self._write(f"\n● Permission needed: {req.label}\n", "bold")
|
|
213
|
+
if req.reason:
|
|
214
|
+
self._write(f" {req.reason}\n", "class:dim")
|
|
215
|
+
if req.danger:
|
|
216
|
+
self._write(f" ⚠ {req.danger}\n", "class:warn")
|
|
217
|
+
pv = req.preview or {}
|
|
218
|
+
if pv.get("type") == "diff":
|
|
219
|
+
self._write("".join(f" {l}\n" for l in pv.get("diff", "").split("\n")[:40]), "class:dim")
|
|
220
|
+
always = req.rule_suggestion or ("all edits this session" if req.kind == "edit" else None)
|
|
221
|
+
prompt = "Allow? [y]es" + (f" / [a]lways ({always})" if always else "") + " / [n]o, or type instructions: "
|
|
222
|
+
a = ((await self._input(prompt)) or "").strip()
|
|
223
|
+
if a.lower() in ("y", "yes", ""):
|
|
224
|
+
return Decision(allow=True)
|
|
225
|
+
if a.lower() in ("a", "always") and always:
|
|
226
|
+
if req.kind == "edit":
|
|
227
|
+
return Decision(allow=True, session_mode="acceptEdits")
|
|
228
|
+
return Decision(allow=True, remember_rule=req.rule_suggestion)
|
|
229
|
+
if a.lower() in ("n", "no"):
|
|
230
|
+
return Decision(allow=False, stop=True)
|
|
231
|
+
return Decision(allow=False, feedback=a)
|
|
232
|
+
|
|
233
|
+
async def ask_user(self, question: str, options: list[str]) -> str | None:
|
|
234
|
+
if not self.interactive:
|
|
235
|
+
return None
|
|
236
|
+
self._write(f"\n? {question}\n" + "".join(f" {i}. {o}\n" for i, o in enumerate(options, 1)), "bold")
|
|
237
|
+
ans = ((await self._input("answer> ")) or "").strip()
|
|
238
|
+
if ans.isdigit() and options and 1 <= int(ans) <= len(options):
|
|
239
|
+
return options[int(ans) - 1]
|
|
240
|
+
return ans or "(no answer)"
|
|
241
|
+
|
|
242
|
+
async def review_plan(self, plan: str):
|
|
243
|
+
if not self.interactive:
|
|
244
|
+
return None
|
|
245
|
+
self._write("\n● Plan\n" + plan.strip() + "\n", "bold")
|
|
246
|
+
ans = ((await self._input("Proceed? [y]es with auto-accepted edits / [m]anual approval / or type feedback: "))
|
|
247
|
+
or "").strip()
|
|
248
|
+
if ans.lower() in ("y", "yes"):
|
|
249
|
+
return (True, "acceptEdits", None)
|
|
250
|
+
if ans.lower() in ("m", "manual"):
|
|
251
|
+
return (True, "default", None)
|
|
252
|
+
return (False, None, ans or None)
|
|
253
|
+
|
|
254
|
+
# ---------------------------------------------------------------- running
|
|
255
|
+
async def run_turn(self, text: str):
|
|
256
|
+
rt = self.rt
|
|
257
|
+
expanded, notes = expand_mentions(text, rt)
|
|
258
|
+
for n in notes:
|
|
259
|
+
self._write(f" ⎿ {n}\n", "class:dim")
|
|
260
|
+
loop = asyncio.get_running_loop()
|
|
261
|
+
task = loop.create_task(rt.submit(expanded))
|
|
262
|
+
old = None
|
|
263
|
+
try:
|
|
264
|
+
old = signal.signal(signal.SIGINT, lambda *_: loop.call_soon_threadsafe(task.cancel))
|
|
265
|
+
except (ValueError, OSError):
|
|
266
|
+
pass
|
|
267
|
+
self.busy = True
|
|
268
|
+
try:
|
|
269
|
+
stats = await task
|
|
270
|
+
finally:
|
|
271
|
+
self.busy = False
|
|
272
|
+
if old is not None:
|
|
273
|
+
signal.signal(signal.SIGINT, old)
|
|
274
|
+
if self.interactive:
|
|
275
|
+
self._write(f" {fmt_duration(stats.elapsed)} · {stats.tool_calls} tool calls · {stats.stopped_reason}\n",
|
|
276
|
+
"class:faint")
|
|
277
|
+
return stats
|
|
278
|
+
|
|
279
|
+
async def run(self, rt, initial: str | None = None) -> None:
|
|
280
|
+
"""A simple line-based REPL (used when the interactive prompt is unavailable)."""
|
|
281
|
+
self.rt = rt
|
|
282
|
+
self._write(f"rigcode - {rt.client.model} @ {rt.client.base_url}. Type /help, or /exit to quit.\n", "bold")
|
|
283
|
+
if initial:
|
|
284
|
+
await self.handle(initial)
|
|
285
|
+
while not self.exit_requested:
|
|
286
|
+
line = await self._input("\n> ")
|
|
287
|
+
if line is None:
|
|
288
|
+
break
|
|
289
|
+
await self.handle(line)
|
|
290
|
+
while self._pending and not self.exit_requested:
|
|
291
|
+
await self.handle(self._pending.pop(0))
|
|
292
|
+
|
|
293
|
+
async def handle(self, line: str) -> None:
|
|
294
|
+
text = line.strip()
|
|
295
|
+
if not text:
|
|
296
|
+
return
|
|
297
|
+
rt = self.rt
|
|
298
|
+
if text.startswith("/") and not text.startswith("//"):
|
|
299
|
+
name, _, args = text[1:].partition(" ")
|
|
300
|
+
cmd = self.commands.find(name)
|
|
301
|
+
if cmd is not None:
|
|
302
|
+
await cmd.run(self, rt, args.strip())
|
|
303
|
+
return
|
|
304
|
+
custom = rt.commands.get(name)
|
|
305
|
+
if custom is not None:
|
|
306
|
+
prompt = custom.render(args.strip(), rt.cwd,
|
|
307
|
+
lambda c: build_invocation(rt.shell, c, rt.cwd, track_cwd=False))
|
|
308
|
+
await self.run_turn(prompt)
|
|
309
|
+
return
|
|
310
|
+
if "/" not in name and "." not in name:
|
|
311
|
+
self._write(f"Unknown command /{name}\n", "class:warn")
|
|
312
|
+
return
|
|
313
|
+
if text.startswith("!"):
|
|
314
|
+
tool = rt.tools.get("Bash")
|
|
315
|
+
if tool is not None:
|
|
316
|
+
command = text[1:].strip()
|
|
317
|
+
res = await tool.run({"command": command, "timeout": 600}, ToolContext(rt, rt.main_agent, "user-shell"))
|
|
318
|
+
self._write(res.content + "\n")
|
|
319
|
+
rt.main_agent.add_reminder(f"The user ran this shell command themselves:\n$ {command}\n{res.content[:6000]}")
|
|
320
|
+
return
|
|
321
|
+
await self.run_turn(line)
|
rigcode/ui/render.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Rendering helpers: rich renderables -> ANSI strings, streamed-markdown block
|
|
2
|
+
splitting, diffs and todo lists."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
|
|
9
|
+
from rich.console import Console
|
|
10
|
+
from rich.markdown import Heading, Markdown
|
|
11
|
+
from rich.text import Text
|
|
12
|
+
from rich.theme import Theme
|
|
13
|
+
|
|
14
|
+
THEME = Theme({
|
|
15
|
+
"markdown.code": "bold color(117)",
|
|
16
|
+
"markdown.h1": "bold underline",
|
|
17
|
+
"markdown.h2": "bold",
|
|
18
|
+
"markdown.h3": "bold",
|
|
19
|
+
"markdown.h4": "bold italic",
|
|
20
|
+
"markdown.link": "underline color(117)",
|
|
21
|
+
"markdown.link_url": "underline color(117)",
|
|
22
|
+
"markdown.block_quote": "italic color(245)",
|
|
23
|
+
"markdown.item.bullet": "color(117)",
|
|
24
|
+
"markdown.item.number": "color(117)",
|
|
25
|
+
"markdown.hr": "color(240)",
|
|
26
|
+
"markdown.table.border": "color(240)",
|
|
27
|
+
"diff.add": "color(114) on color(22)",
|
|
28
|
+
"diff.del": "color(217) on color(52)",
|
|
29
|
+
"diff.ctx": "color(250)",
|
|
30
|
+
"diff.lineno": "color(242)",
|
|
31
|
+
"diff.hunk": "color(242)",
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
_FENCE_RE = re.compile(r"^\s{0,3}(`{3,}|~{3,})(.*)$")
|
|
35
|
+
_TRAILING_RE = re.compile(r"[ ]+((?:\x1b\[[0-9;]*m)*)$", re.M)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def term_width(default: int = 100) -> int:
|
|
39
|
+
return max(40, shutil.get_terminal_size((default, 30)).columns)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _LeftHeading(Heading):
|
|
43
|
+
"""Headings left-aligned and unboxed (rich centers them and boxes h1)."""
|
|
44
|
+
|
|
45
|
+
def __rich_console__(self, console, options):
|
|
46
|
+
text = self.text.copy()
|
|
47
|
+
text.justify = "left"
|
|
48
|
+
if self.tag in ("h1", "h2"):
|
|
49
|
+
yield Text("")
|
|
50
|
+
yield text
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class KMarkdown(Markdown):
|
|
54
|
+
elements = {**Markdown.elements, "heading_open": _LeftHeading}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Renderer:
|
|
58
|
+
def __init__(self, code_theme: str = "ansi_dark"):
|
|
59
|
+
self.code_theme = code_theme
|
|
60
|
+
self.console = Console(file=io.StringIO(), force_terminal=True, color_system="256", theme=THEME,
|
|
61
|
+
legacy_windows=False, highlight=False, emoji=False, width=term_width() - 1)
|
|
62
|
+
|
|
63
|
+
def ansi(self, *renderables, width: int | None = None) -> str:
|
|
64
|
+
self.console.width = (width or term_width()) - 1
|
|
65
|
+
with self.console.capture() as cap:
|
|
66
|
+
for r in renderables:
|
|
67
|
+
self.console.print(r)
|
|
68
|
+
return _TRAILING_RE.sub(r"\1", cap.get())
|
|
69
|
+
|
|
70
|
+
def markdown(self, text: str, width: int | None = None, style: str | None = None) -> str:
|
|
71
|
+
md = KMarkdown(text, code_theme=self.code_theme, hyperlinks=False, justify="default", style=style or "none")
|
|
72
|
+
return self.ansi(md, width=width)
|
|
73
|
+
|
|
74
|
+
def diff(self, diff_text: str, max_lines: int = 40, indent: int = 5) -> Text:
|
|
75
|
+
return render_diff(diff_text, max_lines=max_lines, indent=indent)
|
|
76
|
+
|
|
77
|
+
def new_file(self, content: str, max_lines: int = 12, indent: int = 5) -> Text:
|
|
78
|
+
out = Text()
|
|
79
|
+
lines = content.split("\n")
|
|
80
|
+
if lines and lines[-1] == "":
|
|
81
|
+
lines.pop()
|
|
82
|
+
width = len(str(min(len(lines), max_lines)))
|
|
83
|
+
for i, line in enumerate(lines[:max_lines], 1):
|
|
84
|
+
out.append(" " * indent)
|
|
85
|
+
out.append(f"{i:>{width}} ", style="diff.lineno")
|
|
86
|
+
out.append(line.expandtabs(4) + "\n", style="diff.ctx")
|
|
87
|
+
if len(lines) > max_lines:
|
|
88
|
+
out.append(" " * indent + f"… {len(lines) - max_lines} more lines\n", style="diff.lineno")
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
_HUNK_RE = re.compile(r"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _diff_rows(diff_text: str) -> list[tuple[str, int, str]]:
|
|
96
|
+
"""Unified diff -> rows of (kind, line number, text); kind is + - space or @ (hunk break)."""
|
|
97
|
+
rows: list[tuple[str, int, str]] = []
|
|
98
|
+
old_no = new_no = 0
|
|
99
|
+
for line in diff_text.split("\n"):
|
|
100
|
+
if line.startswith(("--- ", "+++ ", "\\")):
|
|
101
|
+
continue
|
|
102
|
+
m = _HUNK_RE.match(line)
|
|
103
|
+
if m:
|
|
104
|
+
old_no, new_no = int(m.group(1)), int(m.group(2))
|
|
105
|
+
if rows:
|
|
106
|
+
rows.append(("@", 0, ""))
|
|
107
|
+
continue
|
|
108
|
+
text = line[1:].expandtabs(4)
|
|
109
|
+
if line.startswith("+"):
|
|
110
|
+
rows.append(("+", new_no, text))
|
|
111
|
+
new_no += 1
|
|
112
|
+
elif line.startswith("-"):
|
|
113
|
+
rows.append(("-", old_no, text))
|
|
114
|
+
old_no += 1
|
|
115
|
+
else:
|
|
116
|
+
rows.append((" ", new_no, text))
|
|
117
|
+
old_no += 1
|
|
118
|
+
new_no += 1
|
|
119
|
+
return rows
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def render_diff(diff_text: str, max_lines: int = 40, indent: int = 5) -> Text:
|
|
123
|
+
out = Text()
|
|
124
|
+
rows = _diff_rows(diff_text)
|
|
125
|
+
width = len(str(max((n for _, n, _ in rows), default=1)))
|
|
126
|
+
pad = " " * indent
|
|
127
|
+
shown = 0
|
|
128
|
+
for kind, no, text in rows:
|
|
129
|
+
if shown >= max_lines:
|
|
130
|
+
break
|
|
131
|
+
if kind == "@":
|
|
132
|
+
out.append(pad + " " * width + " ⋮\n", style="diff.hunk")
|
|
133
|
+
continue
|
|
134
|
+
out.append(pad)
|
|
135
|
+
out.append(f"{no:>{width}} ", style="diff.lineno")
|
|
136
|
+
style = {"+": "diff.add", "-": "diff.del"}.get(kind, "diff.ctx")
|
|
137
|
+
out.append(f"{kind} {text}\n", style=style)
|
|
138
|
+
shown += 1
|
|
139
|
+
total = sum(1 for k, _, _ in rows if k != "@")
|
|
140
|
+
if total > shown:
|
|
141
|
+
out.append(pad + f"… {total - shown} more diff lines\n", style="diff.lineno")
|
|
142
|
+
return out
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def render_todos(items: list[dict], indent: int = 5) -> Text:
|
|
146
|
+
out = Text()
|
|
147
|
+
for t in items:
|
|
148
|
+
status = t.get("status", "pending")
|
|
149
|
+
out.append(" " * indent)
|
|
150
|
+
if status == "completed":
|
|
151
|
+
out.append("☒ ", style="color(114)")
|
|
152
|
+
out.append(str(t.get("content", "")) + "\n", style="strike color(244)")
|
|
153
|
+
elif status == "in_progress":
|
|
154
|
+
out.append("☐ ", style="bold color(117)")
|
|
155
|
+
out.append(str(t.get("content", "")) + "\n", style="bold")
|
|
156
|
+
else:
|
|
157
|
+
out.append("☐ ", style="color(250)")
|
|
158
|
+
out.append(str(t.get("content", "")) + "\n")
|
|
159
|
+
return out
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class BlockSplitter:
|
|
163
|
+
"""Splits streamed markdown into complete blocks that are safe to render permanently.
|
|
164
|
+
|
|
165
|
+
A block ends at a blank line outside a fenced code block, or at the closing fence."""
|
|
166
|
+
|
|
167
|
+
def __init__(self) -> None:
|
|
168
|
+
self.buf = ""
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def pending(self) -> str:
|
|
172
|
+
return self.buf
|
|
173
|
+
|
|
174
|
+
def feed(self, text: str) -> list[str]:
|
|
175
|
+
self.buf += text
|
|
176
|
+
blocks = []
|
|
177
|
+
while True:
|
|
178
|
+
cut = self._find_cut()
|
|
179
|
+
if cut is None:
|
|
180
|
+
break
|
|
181
|
+
block, self.buf = self.buf[:cut], self.buf[cut:]
|
|
182
|
+
if block.strip():
|
|
183
|
+
blocks.append(block.strip("\n"))
|
|
184
|
+
return blocks
|
|
185
|
+
|
|
186
|
+
def flush(self) -> str:
|
|
187
|
+
rest, self.buf = self.buf, ""
|
|
188
|
+
return rest.strip("\n")
|
|
189
|
+
|
|
190
|
+
def _find_cut(self) -> int | None:
|
|
191
|
+
fence: str | None = None
|
|
192
|
+
offset = 0
|
|
193
|
+
lines = self.buf.split("\n")
|
|
194
|
+
for line in lines[:-1]: # complete lines only
|
|
195
|
+
end = offset + len(line) + 1
|
|
196
|
+
m = _FENCE_RE.match(line)
|
|
197
|
+
if fence:
|
|
198
|
+
if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not m.group(2).strip():
|
|
199
|
+
return end
|
|
200
|
+
elif m:
|
|
201
|
+
if self.buf[:offset].strip():
|
|
202
|
+
return offset # finish the text before the code block first
|
|
203
|
+
fence = m.group(1)
|
|
204
|
+
elif not line.strip() and self.buf[:offset].strip():
|
|
205
|
+
return end
|
|
206
|
+
offset = end
|
|
207
|
+
return None
|