liagent 0.9.0-zero → 0.9.0
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.
- package/README.md +7 -6
- package/agent.py +24 -1019
- package/bin/liagent.js +31 -6
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
# liagent
|
|
4
4
|
|
|
5
5
|
Terminal AI agent for Raspberry Pi cyberdecks. Runs on **every Pi** (Zero … 5, 32/64-bit) with Raspberry Pi OS, Kali or any Debian: one Python file,
|
|
6
|
-
|
|
6
|
+
two pure-Python dependencies (~12 MB with theirs). Also runs on Windows for testing.
|
|
7
7
|
|
|
8
|
-
>
|
|
9
|
-
>
|
|
8
|
+
> **Zero-dependency edition:** the same agent with its own terminal UI on the standard library, about 330 KB
|
|
9
|
+
> installed in total: `liagent-zero_all.deb` from the releases, `npx liagent@zero`, or the
|
|
10
|
+
> [`zero-deps`](https://github.com/Kuloka/liagent/tree/zero-deps) branch.
|
|
10
11
|
|
|
11
12
|
**Does:** shell commands (each one behind a yes / always / no menu) · files with diffs and `/undo` · system
|
|
12
13
|
status · opens apps, files and URLs · GPIO · Wi-Fi · voice in and out · remembers facts about your deck ·
|
|
@@ -18,11 +19,11 @@ OpenAI, DeepSeek, a custom URL, or Ollama offline.
|
|
|
18
19
|
## Install
|
|
19
20
|
- **Raspberry Pi:**
|
|
20
21
|
```bash
|
|
21
|
-
wget https://github.com/Kuloka/liagent/releases/latest/download/
|
|
22
|
-
sudo apt install ./
|
|
22
|
+
wget https://github.com/Kuloka/liagent/releases/latest/download/liagent_all.deb
|
|
23
|
+
sudo apt install ./liagent_all.deb && liagent --key && liagent
|
|
23
24
|
```
|
|
24
25
|
Details, Kali notes and troubleshooting: **[PI.md](PI.md)**
|
|
25
|
-
- **Anywhere with Node.js and Python 3.8+:** `npx liagent
|
|
26
|
+
- **Anywhere with Node.js and Python 3.8+:** `npx liagent` (the first run puts its two Python libraries in a private venv)
|
|
26
27
|
- **Windows:** `powershell -ExecutionPolicy Bypass -File install.ps1`, then in a new terminal `liagent --key`, `liagent`
|
|
27
28
|
|
|
28
29
|
## Commands
|
package/agent.py
CHANGED
|
@@ -42,9 +42,24 @@ from collections import deque
|
|
|
42
42
|
from datetime import datetime
|
|
43
43
|
from pathlib import Path
|
|
44
44
|
|
|
45
|
+
from prompt_toolkit import PromptSession
|
|
46
|
+
from prompt_toolkit.application import Application, run_in_terminal
|
|
47
|
+
from prompt_toolkit.completion import Completer, Completion
|
|
48
|
+
from prompt_toolkit.history import FileHistory
|
|
49
|
+
from prompt_toolkit.key_binding import KeyBindings
|
|
50
|
+
from prompt_toolkit.layout import Layout, Window
|
|
51
|
+
from prompt_toolkit.layout.controls import FormattedTextControl
|
|
52
|
+
from prompt_toolkit.styles import DynamicStyle, Style
|
|
53
|
+
from rich import box
|
|
54
|
+
from rich.console import Console
|
|
55
|
+
from rich.live import Live
|
|
56
|
+
from rich.markdown import Markdown
|
|
57
|
+
from rich.panel import Panel
|
|
58
|
+
from rich.table import Table
|
|
59
|
+
from rich.text import Text
|
|
45
60
|
|
|
46
61
|
NAME = "liagent"
|
|
47
|
-
VERSION = "0.9
|
|
62
|
+
VERSION = "0.9"
|
|
48
63
|
APP = "deck-agent" # config folder name — kept stable so the saved key survives renames
|
|
49
64
|
IS_WIN = sys.platform == "win32"
|
|
50
65
|
if IS_WIN:
|
|
@@ -89,1022 +104,6 @@ MAX_HISTORY = 40 # messages kept in context (Groq free tier has small
|
|
|
89
104
|
MAX_TOOL_OUTPUT = 6000 # chars of tool output sent back to the model
|
|
90
105
|
SHELL_TIMEOUT = 90 # seconds
|
|
91
106
|
|
|
92
|
-
# ───────────────────────────── terminal UI (no dependencies) ─────────────────────────────
|
|
93
|
-
# A small subset of the rich + prompt_toolkit APIs this file uses, on plain ANSI escapes: styled text and
|
|
94
|
-
# [markup], grids, panels, markdown, live redraw, raw keys, pickers and a line editor with history, slash
|
|
95
|
-
# completion and a bottom toolbar. Linux/macOS through termios, Windows through msvcrt + VT mode.
|
|
96
|
-
|
|
97
|
-
_OUT = threading.RLock()
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
def _enable_vt():
|
|
101
|
-
if not IS_WIN:
|
|
102
|
-
return
|
|
103
|
-
try:
|
|
104
|
-
import ctypes
|
|
105
|
-
k = ctypes.windll.kernel32
|
|
106
|
-
for h in (-11, -12):
|
|
107
|
-
handle, mode = k.GetStdHandle(h), ctypes.c_uint32()
|
|
108
|
-
if k.GetConsoleMode(handle, ctypes.byref(mode)):
|
|
109
|
-
k.SetConsoleMode(handle, mode.value | 4) # ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
|
110
|
-
except Exception:
|
|
111
|
-
pass
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
_enable_vt()
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
def _color_mode():
|
|
118
|
-
if os.environ.get("NO_COLOR") or not sys.stdout.isatty():
|
|
119
|
-
return 0
|
|
120
|
-
term, ct = os.environ.get("TERM", ""), os.environ.get("COLORTERM", "")
|
|
121
|
-
if ct in ("truecolor", "24bit") or IS_WIN or os.environ.get("WT_SESSION") or \
|
|
122
|
-
os.environ.get("TERM_PROGRAM") in ("vscode", "iTerm.app", "WezTerm", "ghostty"):
|
|
123
|
-
return 3
|
|
124
|
-
if "256" in term or "kitty" in term or "alacritty" in term or "foot" in term:
|
|
125
|
-
return 2
|
|
126
|
-
return 1 # TERM=linux and other basic consoles: 8 colors
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
COLOR_MODE = _color_mode()
|
|
130
|
-
_BASIC = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"]
|
|
131
|
-
_BASIC_RGB = [(0, 0, 0), (205, 49, 49), (13, 188, 121), (229, 229, 16), (36, 114, 200), (188, 63, 188),
|
|
132
|
-
(17, 168, 205), (229, 229, 229)]
|
|
133
|
-
_ATTRS = {"bold": "1", "dim": "2", "italic": "3", "underline": "4", "blink": "5", "reverse": "7", "strike": "9"}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
def _rgb(tok):
|
|
137
|
-
if tok.startswith("#") and len(tok) == 7:
|
|
138
|
-
return tuple(int(tok[i:i + 2], 16) for i in (1, 3, 5))
|
|
139
|
-
m = re.match(r"gr[ae]y(\d+)$", tok)
|
|
140
|
-
if m:
|
|
141
|
-
v = round(int(m.group(1)) * 2.55)
|
|
142
|
-
return v, v, v
|
|
143
|
-
return None
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
def _color(tok, bg):
|
|
147
|
-
base = 40 if bg else 30
|
|
148
|
-
name = tok.replace("bright_", "")
|
|
149
|
-
if name in _BASIC:
|
|
150
|
-
return str(base + _BASIC.index(name) + (60 if tok.startswith("bright_") else 0))
|
|
151
|
-
rgb = _rgb(tok)
|
|
152
|
-
if rgb is None or COLOR_MODE == 0:
|
|
153
|
-
return None
|
|
154
|
-
r, g, b = rgb
|
|
155
|
-
if COLOR_MODE == 3:
|
|
156
|
-
return f"{base + 8};2;{r};{g};{b}"
|
|
157
|
-
if COLOR_MODE == 2:
|
|
158
|
-
if abs(r - g) < 10 and abs(g - b) < 10:
|
|
159
|
-
idx = 16 if r < 8 else 231 if r > 248 else 232 + min(23, (r - 8) // 10)
|
|
160
|
-
else:
|
|
161
|
-
idx = 16 + 36 * round(r / 255 * 5) + 6 * round(g / 255 * 5) + round(b / 255 * 5)
|
|
162
|
-
return f"{base + 8};5;{idx}"
|
|
163
|
-
i = min(range(8), key=lambda k: sum((a - c) ** 2 for a, c in zip(rgb, _BASIC_RGB[k])))
|
|
164
|
-
return str(base + i + (60 if sum(rgb) > 500 and i else 0))
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
_SGR = {}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
def sgr(style):
|
|
171
|
-
"""'bold #ff6a1a on grey11' → an ANSI escape ('' when colors are off)."""
|
|
172
|
-
if not style or COLOR_MODE == 0:
|
|
173
|
-
return ""
|
|
174
|
-
if style in _SGR:
|
|
175
|
-
return _SGR[style]
|
|
176
|
-
codes, bg = [], False
|
|
177
|
-
for tok in style.split():
|
|
178
|
-
if tok == "on":
|
|
179
|
-
bg = True
|
|
180
|
-
elif tok in _ATTRS:
|
|
181
|
-
codes.append(_ATTRS[tok])
|
|
182
|
-
else:
|
|
183
|
-
c = _color(tok, bg)
|
|
184
|
-
if c:
|
|
185
|
-
codes.append(c)
|
|
186
|
-
bg = False
|
|
187
|
-
_SGR[style] = f"\x1b[{';'.join(codes)}m" if codes else ""
|
|
188
|
-
return _SGR[style]
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
def _is_style(tag):
|
|
192
|
-
toks = tag.split()
|
|
193
|
-
return bool(toks) and all(t in _ATTRS or t == "on" or _rgb(t) or t.replace("bright_", "") in _BASIC
|
|
194
|
-
for t in toks)
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
def cell_width(s):
|
|
198
|
-
w = 0
|
|
199
|
-
for ch in s:
|
|
200
|
-
o = ord(ch)
|
|
201
|
-
if o < 32 or 0x300 <= o < 0x370 or o in (0x200b, 0x200d, 0xfe0e, 0xfe0f):
|
|
202
|
-
continue
|
|
203
|
-
w += 2 if 0x1F300 <= o <= 0x1FAFF or unicodedata.east_asian_width(ch) in "WF" else 1
|
|
204
|
-
return w
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
class Text:
|
|
208
|
-
def __init__(self, text="", style="", no_wrap=False, overflow=None, end="\n", justify=None):
|
|
209
|
-
self.spans = [(str(text), style or "")] if text else []
|
|
210
|
-
self.style, self.no_wrap = style or "", no_wrap
|
|
211
|
-
|
|
212
|
-
@property
|
|
213
|
-
def plain(self):
|
|
214
|
-
return "".join(t for t, _ in self.spans)
|
|
215
|
-
|
|
216
|
-
def __str__(self):
|
|
217
|
-
return self.plain
|
|
218
|
-
|
|
219
|
-
def __len__(self):
|
|
220
|
-
return len(self.plain)
|
|
221
|
-
|
|
222
|
-
def append(self, text, style=None):
|
|
223
|
-
if isinstance(text, Text):
|
|
224
|
-
self.spans += text.spans
|
|
225
|
-
elif text:
|
|
226
|
-
self.spans.append((str(text), style or ""))
|
|
227
|
-
return self
|
|
228
|
-
|
|
229
|
-
def copy(self):
|
|
230
|
-
t = Text(style=self.style, no_wrap=self.no_wrap)
|
|
231
|
-
t.spans = list(self.spans)
|
|
232
|
-
return t
|
|
233
|
-
|
|
234
|
-
def __add__(self, other):
|
|
235
|
-
t = self.copy()
|
|
236
|
-
return t.append(other if isinstance(other, Text) else Text(str(other)))
|
|
237
|
-
|
|
238
|
-
def __radd__(self, other):
|
|
239
|
-
return Text(str(other)) + self
|
|
240
|
-
|
|
241
|
-
def join(self, items):
|
|
242
|
-
t = Text()
|
|
243
|
-
for i, x in enumerate(items):
|
|
244
|
-
if i:
|
|
245
|
-
t.append(self)
|
|
246
|
-
t.append(x if isinstance(x, Text) else Text(str(x)))
|
|
247
|
-
return t
|
|
248
|
-
|
|
249
|
-
@classmethod
|
|
250
|
-
def assemble(cls, *parts):
|
|
251
|
-
t = cls()
|
|
252
|
-
for p in parts:
|
|
253
|
-
if isinstance(p, tuple):
|
|
254
|
-
t.append(p[0], p[1] if len(p) > 1 else None)
|
|
255
|
-
else:
|
|
256
|
-
t.append(p)
|
|
257
|
-
return t
|
|
258
|
-
|
|
259
|
-
@classmethod
|
|
260
|
-
def from_markup(cls, s):
|
|
261
|
-
t, stack, pos = cls(), [], 0
|
|
262
|
-
for m in re.finditer(r"(?<!\\)\[(/?)([\w#. ]*)\]", s):
|
|
263
|
-
close, tag = m.group(1), m.group(2)
|
|
264
|
-
if not close and not _is_style(tag):
|
|
265
|
-
continue
|
|
266
|
-
t.append(s[pos:m.start()].replace("\\[", "["), " ".join(stack))
|
|
267
|
-
if close:
|
|
268
|
-
if stack:
|
|
269
|
-
stack.pop()
|
|
270
|
-
else:
|
|
271
|
-
stack.append(tag)
|
|
272
|
-
pos = m.end()
|
|
273
|
-
return t.append(s[pos:].replace("\\[", "["), " ".join(stack))
|
|
274
|
-
|
|
275
|
-
def with_base(self, base):
|
|
276
|
-
if not base:
|
|
277
|
-
return self
|
|
278
|
-
t = Text(no_wrap=self.no_wrap)
|
|
279
|
-
t.spans = [(x, f"{base} {s}".strip()) for x, s in self.spans]
|
|
280
|
-
return t
|
|
281
|
-
|
|
282
|
-
def lines(self, width, wrap=True):
|
|
283
|
-
"""Wrapped lines as lists of (text, style) spans."""
|
|
284
|
-
out, cur, cw = [], [], 0
|
|
285
|
-
words = []
|
|
286
|
-
for txt, st in self.spans: # split into (chunk, style) where chunk is a word, a space run or a newline
|
|
287
|
-
for piece in re.findall(r"\n|[^\S\n]+|[^\s]+", txt):
|
|
288
|
-
words.append((piece, st))
|
|
289
|
-
for piece, st in words:
|
|
290
|
-
if piece == "\n":
|
|
291
|
-
out.append(cur)
|
|
292
|
-
cur, cw = [], 0
|
|
293
|
-
continue
|
|
294
|
-
w = cell_width(piece)
|
|
295
|
-
if wrap and cw + w > width and cw > 0:
|
|
296
|
-
if piece.isspace():
|
|
297
|
-
continue
|
|
298
|
-
out.append(cur)
|
|
299
|
-
cur, cw = [], 0
|
|
300
|
-
if wrap and w > width: # one long word: split by characters
|
|
301
|
-
for ch in piece:
|
|
302
|
-
if cw + cell_width(ch) > width:
|
|
303
|
-
out.append(cur)
|
|
304
|
-
cur, cw = [], 0
|
|
305
|
-
cur.append((ch, st))
|
|
306
|
-
cw += cell_width(ch)
|
|
307
|
-
continue
|
|
308
|
-
if not wrap and cw + w > width:
|
|
309
|
-
piece = "".join(_take_cells(piece, width - cw))
|
|
310
|
-
w = cell_width(piece)
|
|
311
|
-
if piece:
|
|
312
|
-
cur.append((piece, st))
|
|
313
|
-
cw += w
|
|
314
|
-
out.append(cur)
|
|
315
|
-
return out
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
def _take_cells(s, n):
|
|
319
|
-
out, w = [], 0
|
|
320
|
-
for ch in s:
|
|
321
|
-
if w + cell_width(ch) > n:
|
|
322
|
-
break
|
|
323
|
-
out.append(ch)
|
|
324
|
-
w += cell_width(ch)
|
|
325
|
-
return out
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
def _ansi(spans):
|
|
329
|
-
out = []
|
|
330
|
-
for txt, st in spans:
|
|
331
|
-
code = sgr(st)
|
|
332
|
-
out.append(f"{code}{txt}\x1b[0m" if code else txt)
|
|
333
|
-
return "".join(out)
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
def _spans_width(spans):
|
|
337
|
-
return sum(cell_width(t) for t, _ in spans)
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
def render_lines(obj, width):
|
|
341
|
-
"""Any renderable → list of span-lists, each at most `width` cells."""
|
|
342
|
-
if isinstance(obj, str):
|
|
343
|
-
obj = Text.from_markup(obj)
|
|
344
|
-
if isinstance(obj, Text):
|
|
345
|
-
return obj.lines(width, wrap=not obj.no_wrap)
|
|
346
|
-
if hasattr(obj, "render_lines"):
|
|
347
|
-
return obj.render_lines(width)
|
|
348
|
-
if hasattr(obj, "__rich__"):
|
|
349
|
-
return render_lines(obj.__rich__(), width)
|
|
350
|
-
return Text(str(obj)).lines(width)
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
def measure(obj):
|
|
354
|
-
if isinstance(obj, str):
|
|
355
|
-
obj = Text.from_markup(obj)
|
|
356
|
-
if isinstance(obj, Text):
|
|
357
|
-
return max((cell_width(line) for line in obj.plain.split("\n")), default=0)
|
|
358
|
-
if hasattr(obj, "measure"):
|
|
359
|
-
return obj.measure()
|
|
360
|
-
if hasattr(obj, "__rich__"):
|
|
361
|
-
return measure(obj.__rich__())
|
|
362
|
-
return cell_width(str(obj))
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
class box:
|
|
366
|
-
ROUNDED = "╭╮╰╯─│"
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
class Table:
|
|
370
|
-
def __init__(self, padding=(0, 1), **kw):
|
|
371
|
-
self.pad = padding[1] if isinstance(padding, tuple) else padding
|
|
372
|
-
self.cols, self.rows = [], []
|
|
373
|
-
|
|
374
|
-
@classmethod
|
|
375
|
-
def grid(cls, padding=0, **kw):
|
|
376
|
-
return cls(padding=padding)
|
|
377
|
-
|
|
378
|
-
def add_column(self, style=None, no_wrap=False, width=None, max_width=None, overflow=None, **kw):
|
|
379
|
-
self.cols.append({"style": style or "", "no_wrap": no_wrap, "width": width, "max": max_width})
|
|
380
|
-
|
|
381
|
-
def add_row(self, *cells):
|
|
382
|
-
while len(self.cols) < len(cells):
|
|
383
|
-
self.add_column()
|
|
384
|
-
row = []
|
|
385
|
-
for c, col in zip(cells, self.cols):
|
|
386
|
-
if isinstance(c, str):
|
|
387
|
-
c = Text.from_markup(c)
|
|
388
|
-
if isinstance(c, Text):
|
|
389
|
-
c = c.with_base(col["style"])
|
|
390
|
-
row.append(c)
|
|
391
|
-
self.rows.append(row)
|
|
392
|
-
|
|
393
|
-
def _widths(self, width):
|
|
394
|
-
ws = []
|
|
395
|
-
for i, col in enumerate(self.cols):
|
|
396
|
-
w = col["width"] or max((measure(r[i]) for r in self.rows if i < len(r)), default=0)
|
|
397
|
-
ws.append(min(w, col["max"]) if col["max"] else w)
|
|
398
|
-
over = sum(ws) + self.pad * (len(ws) - 1) - width
|
|
399
|
-
for i in reversed(range(len(ws))): # shrink from the last (usually the wrapping) column
|
|
400
|
-
if over <= 0:
|
|
401
|
-
break
|
|
402
|
-
if self.cols[i]["no_wrap"] and i != len(ws) - 1:
|
|
403
|
-
continue
|
|
404
|
-
cut = min(over, max(0, ws[i] - 4))
|
|
405
|
-
ws[i] -= cut
|
|
406
|
-
over -= cut
|
|
407
|
-
return ws
|
|
408
|
-
|
|
409
|
-
def measure(self):
|
|
410
|
-
return sum(self._widths(10 ** 6)) + self.pad * max(0, len(self.cols) - 1)
|
|
411
|
-
|
|
412
|
-
def render_lines(self, width):
|
|
413
|
-
ws, out = self._widths(width), []
|
|
414
|
-
for row in self.rows:
|
|
415
|
-
cells = [render_lines(c, ws[i]) if ws[i] > 0 else [[]] for i, c in enumerate(row)]
|
|
416
|
-
for k in range(max(len(c) for c in cells)):
|
|
417
|
-
line = []
|
|
418
|
-
for i, c in enumerate(cells):
|
|
419
|
-
spans = c[k] if k < len(c) else []
|
|
420
|
-
line += spans
|
|
421
|
-
if i < len(cells) - 1:
|
|
422
|
-
line.append((" " * (ws[i] - _spans_width(spans) + self.pad), ""))
|
|
423
|
-
out.append(line)
|
|
424
|
-
return out
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
class Panel:
|
|
428
|
-
def __init__(self, renderable, title=None, subtitle=None, border_style="", box=None, padding=(0, 1),
|
|
429
|
-
expand=True, title_align="center", subtitle_align="center", **kw):
|
|
430
|
-
self.r, self.title, self.subtitle, self.border = renderable, title, subtitle, border_style or ""
|
|
431
|
-
self.pv, self.ph = (padding if isinstance(padding, tuple) else (padding, padding))[:2]
|
|
432
|
-
self.expand, self.ta, self.sa = expand, title_align, subtitle_align
|
|
433
|
-
|
|
434
|
-
def measure(self):
|
|
435
|
-
return measure(self.r) + 2 + 2 * self.ph
|
|
436
|
-
|
|
437
|
-
def _edge(self, left, right, label, align, inner):
|
|
438
|
-
b = self.border
|
|
439
|
-
if label is None:
|
|
440
|
-
return [(left + "─" * inner + right, b)]
|
|
441
|
-
lab = (label if isinstance(label, Text) else Text.from_markup(str(label)))
|
|
442
|
-
lw = cell_width(lab.plain) + 2
|
|
443
|
-
if lw > inner - 2:
|
|
444
|
-
return [(left + "─" * inner + right, b)]
|
|
445
|
-
before = 1 if align == "left" else inner - lw - 1 if align == "right" else (inner - lw) // 2
|
|
446
|
-
return [(left + "─" * before + " ", b)] + lab.spans + [(" " + "─" * (inner - lw - before) + right, b)]
|
|
447
|
-
|
|
448
|
-
def render_lines(self, width):
|
|
449
|
-
inner = (width - 2) if self.expand else min(width - 2, self.measure() - 2)
|
|
450
|
-
body_w = max(1, inner - 2 * self.ph)
|
|
451
|
-
body = [[]] * self.pv + render_lines(self.r, body_w) + [[]] * self.pv
|
|
452
|
-
out = [self._edge("╭", "╮", self.title, self.ta, inner)]
|
|
453
|
-
for spans in body:
|
|
454
|
-
out.append([("│", self.border), (" " * self.ph, "")] + spans +
|
|
455
|
-
[(" " * (body_w - _spans_width(spans) + self.ph), ""), ("│", self.border)])
|
|
456
|
-
out.append(self._edge("╰", "╯", self.subtitle, self.sa, inner))
|
|
457
|
-
return out
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
class Markdown:
|
|
461
|
-
"""Headings, bullets, numbered lists, code blocks, **bold**, *italic*, `code`, [links](url)."""
|
|
462
|
-
|
|
463
|
-
def __init__(self, text, **kw):
|
|
464
|
-
self.text = text
|
|
465
|
-
|
|
466
|
-
def measure(self):
|
|
467
|
-
return 10 ** 6
|
|
468
|
-
|
|
469
|
-
@staticmethod
|
|
470
|
-
def inline(s, base=""):
|
|
471
|
-
t, pos = Text(), 0
|
|
472
|
-
for m in re.finditer(r"`([^`]+)`|\*\*(.+?)\*\*|(?<![\w*])\*([^*\n]+)\*(?!\w)|\[([^\]]+)\]\((\S+?)\)", s):
|
|
473
|
-
t.append(s[pos:m.start()], base)
|
|
474
|
-
if m.group(1) is not None:
|
|
475
|
-
t.append(m.group(1), f"{base} bold {ACCENT2}".strip())
|
|
476
|
-
elif m.group(2) is not None:
|
|
477
|
-
t.append(Markdown.inline(m.group(2), f"{base} bold".strip()))
|
|
478
|
-
elif m.group(3) is not None:
|
|
479
|
-
t.append(m.group(3), f"{base} italic".strip())
|
|
480
|
-
else:
|
|
481
|
-
t.append(m.group(4), f"{base} underline".strip())
|
|
482
|
-
t.append(f" ({m.group(5)})", FAINT)
|
|
483
|
-
pos = m.end()
|
|
484
|
-
return t.append(s[pos:], base)
|
|
485
|
-
|
|
486
|
-
def render_lines(self, width):
|
|
487
|
-
out, code, para = [], None, []
|
|
488
|
-
|
|
489
|
-
def flush():
|
|
490
|
-
if para:
|
|
491
|
-
out.extend(Markdown.inline(" ".join(para), "grey85").lines(width))
|
|
492
|
-
para.clear()
|
|
493
|
-
|
|
494
|
-
for raw in self.text.split("\n"):
|
|
495
|
-
if raw.strip().startswith("```"):
|
|
496
|
-
flush()
|
|
497
|
-
if code is None:
|
|
498
|
-
code = []
|
|
499
|
-
else:
|
|
500
|
-
for line in code or [""]:
|
|
501
|
-
out.extend(Text(" " + line, style="#d7d7d7 on grey15").lines(width))
|
|
502
|
-
code = None
|
|
503
|
-
continue
|
|
504
|
-
if code is not None:
|
|
505
|
-
code.append(raw)
|
|
506
|
-
continue
|
|
507
|
-
m = re.match(r"^(\s*)([-*•+]|\d+[.)])\s+(.*)", raw)
|
|
508
|
-
h = re.match(r"^(#{1,6})\s+(.*)", raw)
|
|
509
|
-
if h:
|
|
510
|
-
flush()
|
|
511
|
-
out.extend(Markdown.inline(h.group(2), f"bold {ACCENT2}").lines(width))
|
|
512
|
-
elif m:
|
|
513
|
-
flush()
|
|
514
|
-
indent = len(m.group(1)) // 2 * 2
|
|
515
|
-
bullet = "•" if not m.group(2)[0].isdigit() else m.group(2)
|
|
516
|
-
pre = " " * indent + bullet + " "
|
|
517
|
-
body = Markdown.inline(m.group(3), "grey85").lines(max(8, width - len(pre)))
|
|
518
|
-
for k, spans in enumerate(body):
|
|
519
|
-
out.append([(pre if k == 0 else " " * len(pre), ACCENT if k == 0 else "")] + spans)
|
|
520
|
-
elif re.match(r"^\s*(---+|\*\*\*+)\s*$", raw):
|
|
521
|
-
flush()
|
|
522
|
-
out.append([("─" * min(width, 40), FAINT)])
|
|
523
|
-
elif not raw.strip():
|
|
524
|
-
flush()
|
|
525
|
-
if out and out[-1]:
|
|
526
|
-
out.append([])
|
|
527
|
-
elif raw.lstrip().startswith("|") or raw.startswith(" "):
|
|
528
|
-
flush()
|
|
529
|
-
out.extend(Text(raw, style="grey85", no_wrap=True).lines(width, wrap=False))
|
|
530
|
-
elif raw.startswith(">"):
|
|
531
|
-
flush()
|
|
532
|
-
for spans in Markdown.inline(raw.lstrip("> "), "italic grey70").lines(width - 2):
|
|
533
|
-
out.append([("▌ ", FAINT)] + spans)
|
|
534
|
-
else:
|
|
535
|
-
para.append(raw.strip())
|
|
536
|
-
if code is not None:
|
|
537
|
-
for line in code:
|
|
538
|
-
out.extend(Text(" " + line, style="#d7d7d7 on grey15").lines(width))
|
|
539
|
-
flush()
|
|
540
|
-
while out and not out[-1]:
|
|
541
|
-
out.pop()
|
|
542
|
-
return out or [[]]
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
class _Size:
|
|
546
|
-
def __init__(self, w, h):
|
|
547
|
-
self.width = self.columns = w
|
|
548
|
-
self.height = self.lines = h
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
class Console:
|
|
552
|
-
def __init__(self, **kw):
|
|
553
|
-
self.live = None
|
|
554
|
-
|
|
555
|
-
@property
|
|
556
|
-
def is_terminal(self):
|
|
557
|
-
return sys.stdout.isatty()
|
|
558
|
-
|
|
559
|
-
@property
|
|
560
|
-
def size(self):
|
|
561
|
-
s = shutil.get_terminal_size((80, 24))
|
|
562
|
-
return _Size(s.columns, s.lines)
|
|
563
|
-
|
|
564
|
-
@property
|
|
565
|
-
def width(self):
|
|
566
|
-
return self.size.columns
|
|
567
|
-
|
|
568
|
-
@staticmethod
|
|
569
|
-
def write(s):
|
|
570
|
-
with _OUT:
|
|
571
|
-
try:
|
|
572
|
-
sys.stdout.write(s)
|
|
573
|
-
sys.stdout.flush()
|
|
574
|
-
except (OSError, ValueError):
|
|
575
|
-
pass
|
|
576
|
-
|
|
577
|
-
def print(self, *objs, markup=True, style=None, end="\n", soft_wrap=False, no_wrap=False, crop=True,
|
|
578
|
-
highlight=None, **kw):
|
|
579
|
-
parts = []
|
|
580
|
-
for o in objs:
|
|
581
|
-
if isinstance(o, str):
|
|
582
|
-
o = Text.from_markup(o) if markup else Text(o)
|
|
583
|
-
parts.append(o)
|
|
584
|
-
if len(parts) > 1 and all(isinstance(p, Text) for p in parts):
|
|
585
|
-
parts = [Text(" ").join(parts)]
|
|
586
|
-
width = 10 ** 6 if soft_wrap or no_wrap else max(10, self.width - (1 if IS_WIN else 0))
|
|
587
|
-
lines = []
|
|
588
|
-
for p in parts:
|
|
589
|
-
if style and isinstance(p, Text):
|
|
590
|
-
p = p.with_base(style)
|
|
591
|
-
lines += render_lines(p, width)
|
|
592
|
-
text = "\n".join(_ansi(spans) for spans in lines) if parts else ""
|
|
593
|
-
with _OUT:
|
|
594
|
-
live = self.live
|
|
595
|
-
if live:
|
|
596
|
-
live.clear()
|
|
597
|
-
self.write(text + end)
|
|
598
|
-
if live:
|
|
599
|
-
live.refresh()
|
|
600
|
-
|
|
601
|
-
def clear(self):
|
|
602
|
-
self.write("\x1b[2J\x1b[H")
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
class Live:
|
|
606
|
-
"""Redraws a renderable in place (spinners, menus) or full screen (HUD, rain)."""
|
|
607
|
-
|
|
608
|
-
def __init__(self, renderable=None, console=None, refresh_per_second=10, transient=False, auto_refresh=True,
|
|
609
|
-
screen=False, **kw):
|
|
610
|
-
self.r, self.rps, self.transient, self.auto, self.screen = renderable, refresh_per_second, transient, \
|
|
611
|
-
auto_refresh, screen
|
|
612
|
-
self.drawn, self.stop, self.last = 0, threading.Event(), None
|
|
613
|
-
self.off = not sys.stdout.isatty() # piped / systemd: no animations, like rich
|
|
614
|
-
|
|
615
|
-
def __enter__(self):
|
|
616
|
-
if self.off:
|
|
617
|
-
return self
|
|
618
|
-
console.write(("\x1b[?1049h\x1b[H" if self.screen else "") + "\x1b[?25l")
|
|
619
|
-
console.live = None if self.screen else self
|
|
620
|
-
if self.r is not None:
|
|
621
|
-
self.refresh()
|
|
622
|
-
if self.auto and self.r is not None:
|
|
623
|
-
threading.Thread(target=self._loop, daemon=True).start()
|
|
624
|
-
return self
|
|
625
|
-
|
|
626
|
-
def _loop(self):
|
|
627
|
-
while not self.stop.wait(1 / max(1, self.rps)):
|
|
628
|
-
self.refresh()
|
|
629
|
-
|
|
630
|
-
def update(self, renderable, refresh=False):
|
|
631
|
-
self.r = renderable
|
|
632
|
-
if refresh:
|
|
633
|
-
self.refresh()
|
|
634
|
-
|
|
635
|
-
def clear(self):
|
|
636
|
-
with _OUT:
|
|
637
|
-
if self.drawn:
|
|
638
|
-
console.write("\r\x1b[2K" + "\x1b[1A\x1b[2K" * (self.drawn - 1))
|
|
639
|
-
self.drawn, self.last = 0, None
|
|
640
|
-
|
|
641
|
-
def refresh(self):
|
|
642
|
-
if self.r is None or self.off:
|
|
643
|
-
return
|
|
644
|
-
size = console.size
|
|
645
|
-
with _OUT:
|
|
646
|
-
lines = render_lines(self.r, max(10, size.columns - 1))
|
|
647
|
-
if self.screen:
|
|
648
|
-
lines = lines[:size.lines - 1]
|
|
649
|
-
console.write("\x1b[H" + "".join(f"{_ansi(s)}\x1b[K\n" for s in lines) + "\x1b[J")
|
|
650
|
-
return
|
|
651
|
-
frame = [_ansi(s) for s in lines]
|
|
652
|
-
if frame == self.last and self.drawn:
|
|
653
|
-
return
|
|
654
|
-
# overwrite in place (no blank flash between frames): back to the first line, write each line and
|
|
655
|
-
# erase what's left of it, then erase leftover lines below
|
|
656
|
-
out = "\r" + (f"\x1b[{self.drawn - 1}A" if self.drawn > 1 else "")
|
|
657
|
-
out += "\x1b[K\n".join(frame) + "\x1b[K" + ("\x1b[J" if len(frame) < self.drawn else "")
|
|
658
|
-
console.write(out)
|
|
659
|
-
self.drawn, self.last = len(frame), frame
|
|
660
|
-
|
|
661
|
-
def __exit__(self, *exc):
|
|
662
|
-
self.stop.set()
|
|
663
|
-
if self.off:
|
|
664
|
-
return
|
|
665
|
-
with _OUT:
|
|
666
|
-
if self.screen:
|
|
667
|
-
console.write("\x1b[?1049l")
|
|
668
|
-
elif self.transient:
|
|
669
|
-
self.clear()
|
|
670
|
-
elif self.drawn:
|
|
671
|
-
console.write("\n")
|
|
672
|
-
console.live = None
|
|
673
|
-
console.write("\x1b[?25h")
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
# ── keys ──
|
|
677
|
-
|
|
678
|
-
_WIN_KEYS = {"H": "up", "P": "down", "K": "left", "M": "right", "G": "home", "O": "end", "S": "delete",
|
|
679
|
-
"I": "pageup", "Q": "pagedown", "<": "f2", "R": "insert"}
|
|
680
|
-
_SEQ = {"[A": "up", "[B": "down", "[C": "right", "[D": "left", "[H": "home", "[F": "end", "OH": "home",
|
|
681
|
-
"OF": "end", "[1~": "home", "[7~": "home", "[4~": "end", "[8~": "end", "[3~": "delete", "[5~": "pageup",
|
|
682
|
-
"[6~": "pagedown", "OQ": "f2", "[12~": "f2", "[Z": "s-tab", "[2~": "insert"}
|
|
683
|
-
_CTRL = {"\r": "enter", "\n": "enter", "\x7f": "backspace", "\x08": "backspace", "\t": "tab", "\x03": "c-c",
|
|
684
|
-
"\x04": "c-d", "\x00": "c-space", "\x01": "home", "\x05": "end", "\x15": "c-u", "\x17": "c-w",
|
|
685
|
-
"\x0c": "c-l", "\x1b": "escape", "\x0b": "c-k"}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
class Keys:
|
|
689
|
-
"""Raw keyboard input as names: 'up', 'enter', 'c-c', 'f2' … or the typed character."""
|
|
690
|
-
|
|
691
|
-
def __enter__(self):
|
|
692
|
-
self.old = None
|
|
693
|
-
if not IS_WIN and sys.stdin.isatty():
|
|
694
|
-
import termios
|
|
695
|
-
self.fd = sys.stdin.fileno()
|
|
696
|
-
self.old = termios.tcgetattr(self.fd)
|
|
697
|
-
new = termios.tcgetattr(self.fd)
|
|
698
|
-
new[0] &= ~(termios.IXON | termios.ICRNL)
|
|
699
|
-
new[3] &= ~(termios.ICANON | termios.ECHO | termios.ISIG | termios.IEXTEN)
|
|
700
|
-
new[6][termios.VMIN], new[6][termios.VTIME] = 1, 0
|
|
701
|
-
termios.tcsetattr(self.fd, termios.TCSANOW, new)
|
|
702
|
-
return self
|
|
703
|
-
|
|
704
|
-
def __exit__(self, *exc):
|
|
705
|
-
if self.old is not None:
|
|
706
|
-
import termios
|
|
707
|
-
termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old)
|
|
708
|
-
|
|
709
|
-
def get(self, timeout=None):
|
|
710
|
-
try:
|
|
711
|
-
return self._win(timeout) if IS_WIN else self._unix(timeout)
|
|
712
|
-
except KeyboardInterrupt:
|
|
713
|
-
return "c-c"
|
|
714
|
-
|
|
715
|
-
@staticmethod
|
|
716
|
-
def _win(timeout):
|
|
717
|
-
import msvcrt
|
|
718
|
-
end = None if timeout is None else time.monotonic() + timeout
|
|
719
|
-
while not msvcrt.kbhit():
|
|
720
|
-
if end is not None and time.monotonic() >= end:
|
|
721
|
-
return None
|
|
722
|
-
time.sleep(0.015)
|
|
723
|
-
ch = msvcrt.getwch()
|
|
724
|
-
if ch in ("\x00", "\xe0"):
|
|
725
|
-
return _WIN_KEYS.get(msvcrt.getwch())
|
|
726
|
-
return _CTRL.get(ch, ch)
|
|
727
|
-
|
|
728
|
-
def _unix(self, timeout):
|
|
729
|
-
import select
|
|
730
|
-
fd = sys.stdin.fileno()
|
|
731
|
-
if not select.select([fd], [], [], timeout)[0]:
|
|
732
|
-
return None
|
|
733
|
-
b = os.read(fd, 1)
|
|
734
|
-
if b == b"\x1b":
|
|
735
|
-
if not select.select([fd], [], [], 0.03)[0]:
|
|
736
|
-
return "escape"
|
|
737
|
-
seq = ""
|
|
738
|
-
while len(seq) < 8 and select.select([fd], [], [], 0.03)[0]:
|
|
739
|
-
seq += os.read(fd, 1).decode(errors="replace")
|
|
740
|
-
if len(seq) >= 2 and "@" <= seq[-1] <= "~" and seq[-1] not in "[;0123456789":
|
|
741
|
-
break
|
|
742
|
-
return _SEQ.get(seq)
|
|
743
|
-
n = 1 if b[0] < 0x80 else 2 if b[0] >> 5 == 6 else 3 if b[0] >> 4 == 14 else 4
|
|
744
|
-
while len(b) < n:
|
|
745
|
-
b += os.read(fd, 1)
|
|
746
|
-
ch = b.decode(errors="replace")
|
|
747
|
-
return _CTRL.get(ch, ch)
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
# ── prompt_toolkit-shaped pieces: styles, key bindings, small apps, the prompt ──
|
|
751
|
-
|
|
752
|
-
class Style(dict):
|
|
753
|
-
@classmethod
|
|
754
|
-
def from_dict(cls, d):
|
|
755
|
-
return cls(d)
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
class DynamicStyle:
|
|
759
|
-
def __init__(self, fn):
|
|
760
|
-
self.fn = fn
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
def _frag_style(cls):
|
|
764
|
-
styles = STYLE.fn() if isinstance(STYLE, DynamicStyle) else {}
|
|
765
|
-
out = []
|
|
766
|
-
for part in cls.split():
|
|
767
|
-
if part.startswith("class:"):
|
|
768
|
-
for name in part[6:].split(","):
|
|
769
|
-
out.append(styles.get(name, ""))
|
|
770
|
-
else:
|
|
771
|
-
out.append(part)
|
|
772
|
-
s = " ".join(out).replace("fg:", "").replace("bg:", "on ").replace("noreverse", "")
|
|
773
|
-
return " ".join(s.split())
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
def fragments(frags):
|
|
777
|
-
t = Text()
|
|
778
|
-
for f in frags:
|
|
779
|
-
t.append(f[1], _frag_style(f[0]) if f[0] else "")
|
|
780
|
-
return t
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
class KeyBindings:
|
|
784
|
-
def __init__(self):
|
|
785
|
-
self.map = {}
|
|
786
|
-
|
|
787
|
-
def add(self, *keys, eager=False, **kw):
|
|
788
|
-
def deco(fn):
|
|
789
|
-
for k in keys:
|
|
790
|
-
self.map[k] = fn
|
|
791
|
-
return fn
|
|
792
|
-
return deco
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
class FormattedTextControl:
|
|
796
|
-
def __init__(self, fn, **kw):
|
|
797
|
-
self.fn = fn
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
class Window:
|
|
801
|
-
def __init__(self, content, **kw):
|
|
802
|
-
self.content = content
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
class Layout:
|
|
806
|
-
def __init__(self, window, **kw):
|
|
807
|
-
self.window = window
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
class _Buffer:
|
|
811
|
-
def __init__(self):
|
|
812
|
-
self.text = ""
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
class _Event:
|
|
816
|
-
def __init__(self, app, data):
|
|
817
|
-
self.app, self.data, self.current_buffer = app, data, getattr(app, "current_buffer", _Buffer())
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
class Application:
|
|
821
|
-
def __init__(self, layout, key_bindings=None, refresh_interval=None, **kw):
|
|
822
|
-
self.render = layout.window.content.fn
|
|
823
|
-
self.kb, self.interval = key_bindings or KeyBindings(), refresh_interval
|
|
824
|
-
self.done, self.result = False, None
|
|
825
|
-
|
|
826
|
-
def exit(self, result=None):
|
|
827
|
-
self.done, self.result = True, result
|
|
828
|
-
|
|
829
|
-
def run(self):
|
|
830
|
-
if not sys.stdin.isatty():
|
|
831
|
-
return None
|
|
832
|
-
with Keys() as keys, Live(transient=True, auto_refresh=False) as live:
|
|
833
|
-
while not self.done:
|
|
834
|
-
live.update(fragments(self.render()), refresh=True)
|
|
835
|
-
k = keys.get(self.interval)
|
|
836
|
-
if k is None:
|
|
837
|
-
continue
|
|
838
|
-
fn = self.kb.map.get(k) or (self.kb.map.get("<any>") if len(k) == 1 else None)
|
|
839
|
-
if fn:
|
|
840
|
-
fn(_Event(self, k))
|
|
841
|
-
elif k == "c-c":
|
|
842
|
-
raise KeyboardInterrupt
|
|
843
|
-
return self.result
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
class Completer:
|
|
847
|
-
def get_completions(self, document, event):
|
|
848
|
-
return []
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
class Completion:
|
|
852
|
-
def __init__(self, text, start_position=0, display_meta=None, **kw):
|
|
853
|
-
self.text, self.start, self.meta = text, start_position, display_meta or ""
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
class _Doc:
|
|
857
|
-
def __init__(self, text):
|
|
858
|
-
self.text = self.text_before_cursor = text
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
class FileHistory:
|
|
862
|
-
"""Same file format as prompt_toolkit's, so the old history keeps working."""
|
|
863
|
-
|
|
864
|
-
def __init__(self, path):
|
|
865
|
-
self.path, self.items = path, []
|
|
866
|
-
try:
|
|
867
|
-
entry = []
|
|
868
|
-
for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines():
|
|
869
|
-
if line.startswith("+"):
|
|
870
|
-
entry.append(line[1:])
|
|
871
|
-
elif entry:
|
|
872
|
-
self.items.append("\n".join(entry))
|
|
873
|
-
entry = []
|
|
874
|
-
if entry:
|
|
875
|
-
self.items.append("\n".join(entry))
|
|
876
|
-
except OSError:
|
|
877
|
-
pass
|
|
878
|
-
self.items = self.items[-1000:]
|
|
879
|
-
|
|
880
|
-
def append(self, text):
|
|
881
|
-
if not text or (self.items and self.items[-1] == text):
|
|
882
|
-
return
|
|
883
|
-
self.items.append(text)
|
|
884
|
-
try:
|
|
885
|
-
with open(self.path, "a", encoding="utf-8") as f:
|
|
886
|
-
f.write(f"\n# {datetime.now()}\n" + "".join(f"+{x}\n" for x in text.split("\n")))
|
|
887
|
-
except OSError:
|
|
888
|
-
pass
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
class _Loop:
|
|
892
|
-
def __init__(self, prompt):
|
|
893
|
-
self.prompt = prompt
|
|
894
|
-
|
|
895
|
-
def call_soon_threadsafe(self, fn):
|
|
896
|
-
self.prompt.calls.append(fn)
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
class _PromptApp:
|
|
900
|
-
def __init__(self, prompt):
|
|
901
|
-
self.is_running, self.loop, self.current_buffer = False, _Loop(prompt), _Buffer()
|
|
902
|
-
self.prompt = prompt
|
|
903
|
-
|
|
904
|
-
def exit(self, result=None):
|
|
905
|
-
self.prompt.forced = result
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
_EDITOR = {"active": None}
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
def run_in_terminal(fn):
|
|
912
|
-
"""Print something above the prompt that is being edited, then redraw it."""
|
|
913
|
-
ed = _EDITOR["active"]
|
|
914
|
-
if ed is None:
|
|
915
|
-
return fn()
|
|
916
|
-
ed.clear()
|
|
917
|
-
fn()
|
|
918
|
-
ed.draw()
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
class PromptSession:
|
|
922
|
-
"""A line editor: history (↑↓), slash-command completion menu (tab), a bottom toolbar, hotkeys."""
|
|
923
|
-
|
|
924
|
-
def __init__(self, history=None, completer=None, complete_while_typing=False, style=None, bottom_toolbar=None,
|
|
925
|
-
key_bindings=None, **kw):
|
|
926
|
-
self.history, self.completer, self.live_complete = history, completer, complete_while_typing
|
|
927
|
-
self.toolbar, self.kb = bottom_toolbar, key_bindings or KeyBindings()
|
|
928
|
-
self.app, self.calls, self.forced = _PromptApp(self), deque(), None
|
|
929
|
-
|
|
930
|
-
def prompt(self, message, default="", is_password=False):
|
|
931
|
-
if not sys.stdin.isatty():
|
|
932
|
-
line = sys.stdin.readline()
|
|
933
|
-
if not line:
|
|
934
|
-
raise EOFError
|
|
935
|
-
return line.rstrip("\n")
|
|
936
|
-
self.msg = fragments(message if isinstance(message, list) else [("", message)])
|
|
937
|
-
self.buf, self.pos, self.pw = list(default), len(default), is_password
|
|
938
|
-
self.hist, self.hpos, self.saved = (self.history.items if self.history else []), None, ""
|
|
939
|
-
self.menu, self.sel, self.below = [], -1, 0
|
|
940
|
-
self.app.current_buffer.text, self.forced, self.app.is_running = default, None, True
|
|
941
|
-
_EDITOR["active"] = self
|
|
942
|
-
try:
|
|
943
|
-
with Keys() as keys:
|
|
944
|
-
self.update_menu()
|
|
945
|
-
self.draw()
|
|
946
|
-
while True:
|
|
947
|
-
while self.calls:
|
|
948
|
-
self.calls.popleft()()
|
|
949
|
-
if self.forced is not None:
|
|
950
|
-
self.finish()
|
|
951
|
-
return self.forced
|
|
952
|
-
k = keys.get(0.1)
|
|
953
|
-
if k is None:
|
|
954
|
-
continue
|
|
955
|
-
res = self.key(k)
|
|
956
|
-
if res is not None:
|
|
957
|
-
return res
|
|
958
|
-
self.app.current_buffer.text = "".join(self.buf)
|
|
959
|
-
self.draw()
|
|
960
|
-
finally:
|
|
961
|
-
_EDITOR["active"], self.app.is_running = None, False
|
|
962
|
-
|
|
963
|
-
def text(self):
|
|
964
|
-
return "".join(self.buf)
|
|
965
|
-
|
|
966
|
-
def finish(self):
|
|
967
|
-
self.clear()
|
|
968
|
-
shown = "*" * len(self.buf) if self.pw else self.text()
|
|
969
|
-
console.write(_ansi(self.msg.spans) + shown + "\n")
|
|
970
|
-
|
|
971
|
-
def key(self, k):
|
|
972
|
-
if k in self.kb.map:
|
|
973
|
-
self.kb.map[k](_Event(self.app, k))
|
|
974
|
-
if self.forced is not None:
|
|
975
|
-
self.finish()
|
|
976
|
-
return self.forced
|
|
977
|
-
return None
|
|
978
|
-
if k == "enter":
|
|
979
|
-
if self.menu and self.sel >= 0: # like prompt_toolkit: enter takes the highlighted completion
|
|
980
|
-
self.accept_completion()
|
|
981
|
-
return None
|
|
982
|
-
text = self.text()
|
|
983
|
-
self.finish()
|
|
984
|
-
if self.history and text.strip() and not self.pw:
|
|
985
|
-
self.history.append(text)
|
|
986
|
-
return text
|
|
987
|
-
if k == "c-c":
|
|
988
|
-
self.finish()
|
|
989
|
-
raise KeyboardInterrupt
|
|
990
|
-
if k == "c-d":
|
|
991
|
-
if not self.buf:
|
|
992
|
-
self.finish()
|
|
993
|
-
raise EOFError
|
|
994
|
-
if self.pos < len(self.buf):
|
|
995
|
-
del self.buf[self.pos]
|
|
996
|
-
elif k == "tab" and self.menu:
|
|
997
|
-
self.sel = max(self.sel, 0)
|
|
998
|
-
self.accept_completion()
|
|
999
|
-
elif k in ("up", "down") and self.menu and self.live_menu_open():
|
|
1000
|
-
self.sel = (self.sel + (1 if k == "down" else -1)) % len(self.menu)
|
|
1001
|
-
return None
|
|
1002
|
-
elif k == "up" and self.hist:
|
|
1003
|
-
if self.hpos is None:
|
|
1004
|
-
self.hpos, self.saved = len(self.hist), self.text()
|
|
1005
|
-
if self.hpos > 0:
|
|
1006
|
-
self.hpos -= 1
|
|
1007
|
-
self.set_text(self.hist[self.hpos])
|
|
1008
|
-
self.menu = []
|
|
1009
|
-
return None
|
|
1010
|
-
elif k == "down" and self.hpos is not None:
|
|
1011
|
-
self.hpos += 1
|
|
1012
|
-
self.set_text(self.saved if self.hpos >= len(self.hist) else self.hist[self.hpos])
|
|
1013
|
-
if self.hpos >= len(self.hist):
|
|
1014
|
-
self.hpos = None
|
|
1015
|
-
self.menu = []
|
|
1016
|
-
return None
|
|
1017
|
-
elif k == "left":
|
|
1018
|
-
self.pos = max(0, self.pos - 1)
|
|
1019
|
-
elif k == "right":
|
|
1020
|
-
self.pos = min(len(self.buf), self.pos + 1)
|
|
1021
|
-
elif k == "home":
|
|
1022
|
-
self.pos = 0
|
|
1023
|
-
elif k == "end":
|
|
1024
|
-
self.pos = len(self.buf)
|
|
1025
|
-
elif k == "backspace":
|
|
1026
|
-
if self.pos:
|
|
1027
|
-
self.pos -= 1
|
|
1028
|
-
del self.buf[self.pos]
|
|
1029
|
-
elif k == "delete":
|
|
1030
|
-
if self.pos < len(self.buf):
|
|
1031
|
-
del self.buf[self.pos]
|
|
1032
|
-
elif k == "c-u":
|
|
1033
|
-
del self.buf[:self.pos]
|
|
1034
|
-
self.pos = 0
|
|
1035
|
-
elif k == "c-k":
|
|
1036
|
-
del self.buf[self.pos:]
|
|
1037
|
-
elif k == "c-w":
|
|
1038
|
-
i = self.pos
|
|
1039
|
-
while i and self.buf[i - 1] == " ":
|
|
1040
|
-
i -= 1
|
|
1041
|
-
while i and self.buf[i - 1] != " ":
|
|
1042
|
-
i -= 1
|
|
1043
|
-
del self.buf[i:self.pos]
|
|
1044
|
-
self.pos = i
|
|
1045
|
-
elif k == "escape":
|
|
1046
|
-
self.menu, self.sel = [], -1
|
|
1047
|
-
return None
|
|
1048
|
-
elif len(k) == 1 and (k.isprintable() or k == " "):
|
|
1049
|
-
self.buf.insert(self.pos, k)
|
|
1050
|
-
self.pos += 1
|
|
1051
|
-
self.hpos = None
|
|
1052
|
-
else:
|
|
1053
|
-
return None
|
|
1054
|
-
self.update_menu()
|
|
1055
|
-
return None
|
|
1056
|
-
|
|
1057
|
-
def live_menu_open(self):
|
|
1058
|
-
return self.hpos is None and (self.sel >= 0 or self.text().startswith("/"))
|
|
1059
|
-
|
|
1060
|
-
def set_text(self, s):
|
|
1061
|
-
self.buf, self.pos = list(s), len(s)
|
|
1062
|
-
|
|
1063
|
-
def update_menu(self):
|
|
1064
|
-
self.menu, self.sel = [], -1
|
|
1065
|
-
if self.completer and self.live_complete and not self.pw:
|
|
1066
|
-
self.menu = list(self.completer.get_completions(_Doc(self.text()[:self.pos]), None))[:8]
|
|
1067
|
-
|
|
1068
|
-
def accept_completion(self):
|
|
1069
|
-
c = self.menu[self.sel]
|
|
1070
|
-
before = self.text()[:self.pos]
|
|
1071
|
-
new = before[:len(before) + c.start] + c.text
|
|
1072
|
-
self.set_text(new + self.text()[self.pos:])
|
|
1073
|
-
self.pos = len(new)
|
|
1074
|
-
self.menu, self.sel = [], -1
|
|
1075
|
-
|
|
1076
|
-
def clear(self):
|
|
1077
|
-
console.write("\r\x1b[J")
|
|
1078
|
-
|
|
1079
|
-
def draw(self):
|
|
1080
|
-
cols = max(20, console.width - 1)
|
|
1081
|
-
shown = "*" * len(self.buf) if self.pw else self.text()
|
|
1082
|
-
pw = cell_width(self.msg.plain)
|
|
1083
|
-
avail = max(5, cols - pw - 1)
|
|
1084
|
-
start = 0
|
|
1085
|
-
while cell_width(shown[start:self.pos]) > avail - 1:
|
|
1086
|
-
start += 1
|
|
1087
|
-
visible = "".join(_take_cells(shown[start:], avail))
|
|
1088
|
-
below = []
|
|
1089
|
-
for i, c in enumerate(self.menu):
|
|
1090
|
-
on = i == self.sel
|
|
1091
|
-
below.append(fragments([("class:completion-menu.completion" + (".current" if on else ""),
|
|
1092
|
-
f" {c.text:<12} "),
|
|
1093
|
-
("class:completion-menu.meta.completion" + (".current" if on else ""),
|
|
1094
|
-
f" {c.meta[:max(0, cols - 16)]} ")]))
|
|
1095
|
-
if self.toolbar:
|
|
1096
|
-
tb = self.toolbar()
|
|
1097
|
-
below.append(fragments(tb if isinstance(tb, list) else [("", str(tb))]))
|
|
1098
|
-
out = "\r\x1b[J" + _ansi(self.msg.spans) + visible
|
|
1099
|
-
for t in below:
|
|
1100
|
-
out += "\n" + _ansi(t.lines(cols, wrap=False)[0])
|
|
1101
|
-
if below:
|
|
1102
|
-
out += f"\x1b[{len(below)}A"
|
|
1103
|
-
col = pw + cell_width(shown[start:self.pos])
|
|
1104
|
-
out += "\r" + (f"\x1b[{col}C" if col else "")
|
|
1105
|
-
console.write(out)
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
107
|
# ── palette ──
|
|
1109
108
|
THEMES = { # accent: prompt/selection · accent2: secondary · glow: spinner/logo end · warn: permission boxes
|
|
1110
109
|
"ember": {"accent": "#ff6a1a", "accent2": "#ffb347", "glow": "#ff2e2e", "warn": "#ffd23f",
|
|
@@ -1130,7 +129,7 @@ THEME = "ember"
|
|
|
1130
129
|
|
|
1131
130
|
|
|
1132
131
|
def apply_theme(name):
|
|
1133
|
-
"""Recolor everything;
|
|
132
|
+
"""Recolor everything; prompt_toolkit picks it up live through STYLE (a DynamicStyle)."""
|
|
1134
133
|
global ACCENT, ACCENT2, GLOW, WARN, BORDER, MENU_BG, PT_STYLE, THEME
|
|
1135
134
|
THEME = name if name in THEMES else "ember"
|
|
1136
135
|
t = THEMES[THEME]
|
|
@@ -1295,6 +294,12 @@ def flush_input():
|
|
|
1295
294
|
termios.tcflush(sys.stdin, termios.TCIFLUSH)
|
|
1296
295
|
except Exception:
|
|
1297
296
|
pass
|
|
297
|
+
try:
|
|
298
|
+
from prompt_toolkit.application.current import get_app_session
|
|
299
|
+
from prompt_toolkit.input.typeahead import clear_typeahead
|
|
300
|
+
clear_typeahead(get_app_session().input)
|
|
301
|
+
except Exception:
|
|
302
|
+
pass
|
|
1298
303
|
|
|
1299
304
|
|
|
1300
305
|
def choose(options, title=None, body=None, start=0, hint="↑↓ move · enter select · esc cancel", on_move=None):
|
|
@@ -3368,7 +2373,7 @@ RAIN_CHARS = "0123456789ABCDEF<>/\\|{}[]=+*#$%&@:;"
|
|
|
3368
2373
|
|
|
3369
2374
|
def rain():
|
|
3370
2375
|
fps = 15 if (os.cpu_count() or 1) > 1 else 6
|
|
3371
|
-
w, h = console.size.width
|
|
2376
|
+
w, h = console.size.width, console.size.height - 1
|
|
3372
2377
|
heads = [random.randint(-h, h) for _ in range(w)]
|
|
3373
2378
|
speed = [random.choice((1, 1, 1, 2)) for _ in range(w)]
|
|
3374
2379
|
trail = [random.randint(5, max(6, h * 2 // 3)) for _ in range(w)]
|
package/bin/liagent.js
CHANGED
|
@@ -1,13 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// `npx liagent`: runs agent.py with Python 3.8+.
|
|
3
|
-
//
|
|
2
|
+
// `npx liagent`: runs agent.py with Python 3.8+. If rich + prompt_toolkit aren't installed, the first run makes
|
|
3
|
+
// a private venv for them (~12 MB, once). Nothing else is downloaded.
|
|
4
4
|
"use strict";
|
|
5
5
|
const { spawnSync } = require("child_process");
|
|
6
|
+
const fs = require("fs");
|
|
7
|
+
const os = require("os");
|
|
6
8
|
const path = require("path");
|
|
7
9
|
|
|
8
10
|
const WIN = process.platform === "win32";
|
|
9
11
|
const AGENT = path.join(__dirname, "..", "agent.py");
|
|
12
|
+
const DATA = WIN ? process.env.LOCALAPPDATA || os.homedir()
|
|
13
|
+
: process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local", "share");
|
|
14
|
+
const VENV = path.join(DATA, "liagent", "npm-venv");
|
|
15
|
+
const VPY = WIN ? path.join(VENV, "Scripts", "python.exe") : path.join(VENV, "bin", "python");
|
|
16
|
+
|
|
10
17
|
const ok = (cmd, args) => spawnSync(cmd, args, { stdio: "ignore" }).status === 0;
|
|
18
|
+
const run = (cmd, args) => spawnSync(cmd, args, { stdio: "inherit" });
|
|
19
|
+
const hasDeps = (py) => ok(py[0], [...py.slice(1), "-c", "import rich, prompt_toolkit"]);
|
|
11
20
|
|
|
12
21
|
function findPython() {
|
|
13
22
|
if (process.env.LIAGENT_PYTHON) return [process.env.LIAGENT_PYTHON]; // e.g. a specific python3.11
|
|
@@ -15,12 +24,28 @@ function findPython() {
|
|
|
15
24
|
return candidates.find((c) => ok(c[0], [...c.slice(1), "-c", "import sys; sys.exit(sys.version_info < (3, 8))"]));
|
|
16
25
|
}
|
|
17
26
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
console.error("liagent: needs Python 3.8+ — https://www.python.org/downloads/ (Raspberry Pi: sudo apt install python3)");
|
|
27
|
+
function fail(msg) {
|
|
28
|
+
console.error("liagent: " + msg);
|
|
21
29
|
process.exit(1);
|
|
22
30
|
}
|
|
31
|
+
|
|
32
|
+
let py = fs.existsSync(VPY) && hasDeps([VPY]) ? [VPY] : findPython();
|
|
33
|
+
if (!py) fail("needs Python 3.8+ — https://www.python.org/downloads/ (Raspberry Pi: sudo apt install python3)");
|
|
34
|
+
if (!hasDeps(py)) {
|
|
35
|
+
console.error(`liagent: first run — installing rich + prompt_toolkit into ${VENV} (~12 MB, once)…`);
|
|
36
|
+
// --system-site-packages: apt's gpiozero / lgpio stay visible for GPIO on a Pi
|
|
37
|
+
if (run(py[0], [...py.slice(1), "-m", "venv", "--system-site-packages", VENV]).status !== 0) {
|
|
38
|
+
fail("could not create a venv. On Debian / Raspberry Pi OS: sudo apt install python3-venv, " +
|
|
39
|
+
"or install the .deb: https://github.com/Kuloka/liagent#install");
|
|
40
|
+
}
|
|
41
|
+
const pkgs = ["rich>=13", "prompt_toolkit>=3", ...(WIN ? ["psutil"] : [])];
|
|
42
|
+
if (run(VPY, ["-m", "pip", "install", "-q", "--disable-pip-version-check", ...pkgs]).status !== 0) {
|
|
43
|
+
fail("pip install failed (offline?). Run it again, or install the .deb.");
|
|
44
|
+
}
|
|
45
|
+
py = [VPY];
|
|
46
|
+
}
|
|
47
|
+
|
|
23
48
|
// ctrl+c belongs to the agent (it stops a reply); keep this wrapper alive until the agent exits
|
|
24
49
|
process.on("SIGINT", () => {});
|
|
25
|
-
const r =
|
|
50
|
+
const r = run(py[0], [...py.slice(1), AGENT, ...process.argv.slice(2)]);
|
|
26
51
|
process.exit(r.status === null ? 1 : r.status);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "liagent",
|
|
3
|
-
"version": "0.9.0
|
|
4
|
-
"description": "Tiny terminal AI agent for Raspberry Pi cyberdecks: shell, files, GPIO, voice, web UI, Discord bot, calculators/LoRa/SMS. One Python file,
|
|
3
|
+
"version": "0.9.0",
|
|
4
|
+
"description": "Tiny terminal AI agent for Raspberry Pi cyberdecks: shell, files, GPIO, voice, web UI, Discord bot, calculators/LoRa/SMS. One Python file, ~240 KB.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"liagent": "bin/liagent.js"
|
|
7
7
|
},
|