liagent 0.9.1-zero → 0.9.2

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