krnell 0.0.0-stage → 3.0.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.
Files changed (51) hide show
  1. package/Iniciar_Linux.sh +129 -0
  2. package/Instalar_Atalho_Windows.cmd +40 -0
  3. package/Instalar_Ubuntu.sh +95 -0
  4. package/Painel.cmd +138 -0
  5. package/README.md +82 -2
  6. package/atualizador.py +148 -0
  7. package/bin/krnell.mjs +159 -0
  8. package/bridge.py +5280 -0
  9. package/config.example.json +57 -0
  10. package/contexto.py +204 -0
  11. package/dashboard_web.py +308 -0
  12. package/dns_duck.py +227 -0
  13. package/ferramentas/Liberar_Firewall.ps1 +96 -0
  14. package/ferramentas/firewall_linux.sh +67 -0
  15. package/ferramentas/install_windows.py +482 -0
  16. package/ferramentas/selecionar_provedor.py +76 -0
  17. package/iniciar.sh +255 -0
  18. package/keys.example.env +3 -0
  19. package/kimi.py +567 -0
  20. package/opencode_sync.py +265 -0
  21. package/package.json +68 -4
  22. package/painel.py +5612 -0
  23. package/painel_web.py +367 -0
  24. package/plugins/system-prompt/index.ts +409 -0
  25. package/provedores/kimi/bridge.mjs +4349 -0
  26. package/provedores/kimi/package.json +10 -0
  27. package/provedores_catalogo.py +27 -0
  28. package/tls_proxy.py +205 -0
  29. package/tui_core.py +604 -0
  30. package/web/dist/.vite/manifest.json +84 -0
  31. package/web/dist/assets/LogsPage-DkXN-I7o.js +2 -0
  32. package/web/dist/assets/LogsPage-OsSvuqxQ.js +2 -0
  33. package/web/dist/assets/TerminalPage-CZTPxVyx.js +1 -0
  34. package/web/dist/assets/TerminalPage-D208X99P.js +1 -0
  35. package/web/dist/assets/TerminalPage-DYGPu4ux.css +1 -0
  36. package/web/dist/assets/index-B5rIwous.js +1 -0
  37. package/web/dist/assets/index-CJE_a_Tn.js +27 -0
  38. package/web/dist/assets/index-COlDAcsY.js +1 -0
  39. package/web/dist/assets/index-Dzc8Obwp.css +1 -0
  40. package/web/dist/assets/index-LZadV7rx.js +27 -0
  41. package/web/dist/assets/index-o8xT03ZV.css +1 -0
  42. package/web/dist/assets/press-start-2p-2BZhbCiP.ttf +0 -0
  43. package/web/dist/assets/react-vendor-C475ILlI.js +49 -0
  44. package/web/dist/assets/terminal-vendor-DOrYoP_4.css +32 -0
  45. package/web/dist/assets/terminal-vendor-Dp03d74L.js +38 -0
  46. package/web/dist/assets/terminal-webgl-BRBWwLY7.js +75 -0
  47. package/web/dist/favicon.svg +1 -0
  48. package/web/dist/fonts/OFL.txt +93 -0
  49. package/web/dist/fonts/press-start-2p.ttf +0 -0
  50. package/web/dist/index.html +18 -0
  51. package/workbuddy.py +1965 -0
package/tui_core.py ADDED
@@ -0,0 +1,604 @@
1
+ """Núcleo visual e de entrada multiplataforma do Krnell TUI (estilo OpenCode).
2
+
3
+ Fornece:
4
+ - TerminalPosix: leitor raw-mode (termios + select) com suporte completo a
5
+ setas, Home/End, PgUp/PgDn, Tab, Backspace, Ctrl+P/K/M/L/R/T/C, bracketed
6
+ paste e mouse SGR (cliques + roda do mouse + hover) no Termux, Ubuntu e Linux;
7
+ - Compositor de overlays centrados (como DialogSelect / CommandPalette do OpenCode)
8
+ sobre o frame principal esmaecido, sem quebrar ou cortar a tela nem errar clique;
9
+ - Helpers de largura visual real (rich.cells.cell_len) para nunca estourar borda
10
+ com Unicode/emoji em telas estreitas do celular/Termux;
11
+ - Barras de progresso de cota, cards limpos estilo SplitBorder e toast discreto.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import re
17
+ import select
18
+ import shutil
19
+ import signal
20
+ import subprocess
21
+ import sys
22
+ import time
23
+ from typing import Callable
24
+
25
+ from rich.cells import cell_len
26
+ from rich.text import Text
27
+
28
+ try:
29
+ import termios
30
+ import tty
31
+ except ImportError: # Windows
32
+ termios = None
33
+ tty = None
34
+
35
+ ANSI_RE = re.compile(r'\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)')
36
+
37
+
38
+ def is_termux() -> bool:
39
+ return bool(os.environ.get('PREFIX') and 'com.termux' in os.environ.get('PREFIX', ''))
40
+
41
+
42
+ def abrir_url_sistema(url: str) -> bool:
43
+ """Abre URL no navegador nativo (Termux, Linux, macOS ou Windows)."""
44
+ if not url:
45
+ return False
46
+ if is_termux():
47
+ for cmd in (['termux-open-url', url], ['am', 'start', '-a', 'android.intent.action.VIEW', '-d', url]):
48
+ if shutil.which(cmd[0]):
49
+ try:
50
+ r = subprocess.run(cmd, capture_output=True, timeout=6)
51
+ if r.returncode == 0:
52
+ return True
53
+ except Exception:
54
+ pass
55
+ if os.name == 'nt':
56
+ try:
57
+ os.startfile(url) # type: ignore[attr-defined]
58
+ return True
59
+ except Exception:
60
+ pass
61
+ else:
62
+ for opener in ('xdg-open', 'open'):
63
+ if shutil.which(opener):
64
+ try:
65
+ p = subprocess.Popen(
66
+ [opener, url],
67
+ stdin=subprocess.DEVNULL,
68
+ stdout=subprocess.DEVNULL,
69
+ stderr=subprocess.DEVNULL,
70
+ )
71
+ if p.pid:
72
+ return True
73
+ except Exception:
74
+ pass
75
+ try:
76
+ import webbrowser
77
+ return bool(webbrowser.open(url, new=2))
78
+ except Exception:
79
+ return False
80
+
81
+
82
+ def strip_ansi(s: str) -> str:
83
+ return ANSI_RE.sub('', s)
84
+
85
+
86
+ def vis_len(s: str) -> int:
87
+ return cell_len(strip_ansi(s))
88
+
89
+
90
+ def truncate_vis(s: str, max_cols: int, suffix: str = '…') -> str:
91
+ """Corta texto simples respeitando largura visual (cell_len)."""
92
+ if max_cols <= 0:
93
+ return ''
94
+ if cell_len(s) <= max_cols:
95
+ return s
96
+ suf_w = cell_len(suffix)
97
+ alvo = max(0, max_cols - suf_w)
98
+ out = []
99
+ acc = 0
100
+ for ch in s:
101
+ w = cell_len(ch)
102
+ if acc + w > alvo:
103
+ break
104
+ out.append(ch)
105
+ acc += w
106
+ return ''.join(out) + (suffix if max_cols >= suf_w else '')
107
+
108
+
109
+ def pad_vis(s: str, largura: int) -> str:
110
+ """Preenche ou corta texto simples para exatamente `largura` colunas visuais."""
111
+ s = truncate_vis(s, largura)
112
+ faltam = max(0, largura - cell_len(s))
113
+ return s + (' ' * faltam)
114
+
115
+
116
+ def barra_progresso(fracao: float | None, largura: int = 10) -> str:
117
+ """Barrinha de cota limpa (blocos sólidos + trilha fina)."""
118
+ if fracao is None:
119
+ return '░' * largura
120
+ f = max(0.0, min(1.0, float(fracao)))
121
+ cheios = int(round(f * largura))
122
+ return '█' * cheios + '░' * max(0, largura - cheios)
123
+
124
+
125
+ class TerminalPosix:
126
+ """Leitor POSIX (Termux / Linux / Ubuntu / macOS) em raw mode com mouse SGR."""
127
+
128
+ def __init__(self):
129
+ self._fd = None
130
+ self._orig = None
131
+ self._buf = bytearray()
132
+ self._resized = False
133
+ self._prev_winch = None
134
+ self._in_paste = False
135
+ self._paste_chars: list[str] = []
136
+
137
+ def entrar(self) -> bool:
138
+ if os.name == 'nt' or termios is None or tty is None:
139
+ return False
140
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
141
+ return False
142
+ try:
143
+ self._fd = sys.stdin.fileno()
144
+ self._orig = termios.tcgetattr(self._fd)
145
+ tty.setraw(self._fd)
146
+ # Mouse SGR (1000=clique/roda, 1006=SGR) + bracketed paste (2004).
147
+ # Nao liga 1003 (any-event hover) no Termux para evitar flood no touch.
148
+ sys.stdout.write('\x1b[?1000h\x1b[?1006h\x1b[?2004h')
149
+ sys.stdout.flush()
150
+ if hasattr(signal, 'SIGWINCH'):
151
+ self._prev_winch = signal.getsignal(signal.SIGWINCH)
152
+ signal.signal(signal.SIGWINCH, self._on_winch)
153
+ return True
154
+ except Exception:
155
+ self.sair()
156
+ return False
157
+
158
+ def _on_winch(self, _sig, _frame):
159
+ self._resized = True
160
+
161
+ def consumir_resize(self) -> bool:
162
+ if self._resized:
163
+ self._resized = False
164
+ return True
165
+ return False
166
+
167
+ def sair(self) -> None:
168
+ try:
169
+ sys.stdout.write('\x1b[?2004l\x1b[?1006l\x1b[?1000l')
170
+ sys.stdout.flush()
171
+ except Exception:
172
+ pass
173
+ if self._fd is not None and self._orig is not None and termios is not None:
174
+ try:
175
+ termios.tcsetattr(self._fd, termios.TCSADRAIN, self._orig)
176
+ except Exception:
177
+ pass
178
+ if hasattr(signal, 'SIGWINCH') and self._prev_winch is not None:
179
+ try:
180
+ signal.signal(signal.SIGWINCH, self._prev_winch)
181
+ except Exception:
182
+ pass
183
+ self._fd = None
184
+ self._orig = None
185
+ self._prev_winch = None
186
+
187
+ def _ler_disponivel(self, timeout: float) -> bool:
188
+ if self._fd is None:
189
+ return False
190
+ try:
191
+ r, _, _ = select.select([self._fd], [], [], max(0.0, timeout))
192
+ except (OSError, ValueError, InterruptedError):
193
+ return False
194
+ if not r:
195
+ return False
196
+ try:
197
+ chunk = os.read(self._fd, 4096)
198
+ except OSError:
199
+ return False
200
+ if not chunk:
201
+ return False
202
+ self._buf.extend(chunk)
203
+ return True
204
+
205
+ def ler_evento(self, timeout: float):
206
+ if self._fd is None:
207
+ return None
208
+ if self.consumir_resize():
209
+ return 'resize'
210
+ if not self._buf:
211
+ if not self._ler_disponivel(timeout):
212
+ return 'resize' if self.consumir_resize() else None
213
+ if not self._buf:
214
+ return None
215
+
216
+ # Bracketed paste: junta o texto colado num unico evento ('paste', texto)
217
+ if self._in_paste:
218
+ return self._drenar_paste()
219
+
220
+ b0 = self._buf[0]
221
+ if b0 == 0x1B: # ESC ou sequencia ANSI
222
+ if len(self._buf) == 1:
223
+ self._ler_disponivel(0.03)
224
+ if len(self._buf) == 1:
225
+ del self._buf[0]
226
+ return 'esc'
227
+ return self._parse_escape()
228
+
229
+ del self._buf[0]
230
+ if b0 in (0x0D, 0x0A):
231
+ return 'enter'
232
+ if b0 in (0x7F, 0x08):
233
+ return 'backspace'
234
+ if b0 == 0x09:
235
+ return 'tab'
236
+ if b0 == 0x03:
237
+ return 'ctrl_c'
238
+ if b0 == 0x10:
239
+ return 'ctrl_p'
240
+ if b0 == 0x0B:
241
+ return 'ctrl_k'
242
+ if b0 == 0x0E:
243
+ return 'ctrl_n'
244
+ if b0 == 0x0C:
245
+ return 'ctrl_l'
246
+ if b0 == 0x12:
247
+ return 'ctrl_r'
248
+ if b0 == 0x14:
249
+ return 'ctrl_t'
250
+ if b0 == 0x15:
251
+ return 'ctrl_u'
252
+ if b0 == 0x17:
253
+ return 'ctrl_w'
254
+ if b0 < 0x20:
255
+ return None
256
+
257
+ # UTF-8 multi-byte
258
+ raw = bytearray([b0])
259
+ if b0 >= 0xC0:
260
+ need = 1 if b0 < 0xE0 else (2 if b0 < 0xF0 else 3)
261
+ while len(raw) < need + 1:
262
+ if not self._buf and not self._ler_disponivel(0.02):
263
+ break
264
+ if self._buf:
265
+ raw.append(self._buf.pop(0))
266
+ try:
267
+ ch = raw.decode('utf-8')
268
+ except UnicodeDecodeError:
269
+ return None
270
+ return ('char', ch)
271
+
272
+ def _drenar_paste(self):
273
+ fim_seq = b'\x1b[201~'
274
+ deadline = time.monotonic() + 0.15
275
+ while fim_seq not in self._buf and time.monotonic() < deadline:
276
+ if not self._ler_disponivel(0.02):
277
+ break
278
+ idx = self._buf.find(fim_seq)
279
+ if idx >= 0:
280
+ raw = bytes(self._buf[:idx])
281
+ del self._buf[:idx + len(fim_seq)]
282
+ self._in_paste = False
283
+ texto = raw.decode('utf-8', 'replace').replace('\r', '').replace('\n', '')
284
+ self._paste_chars.append(texto)
285
+ junto = ''.join(self._paste_chars)
286
+ self._paste_chars.clear()
287
+ return ('paste', junto) if junto else None
288
+ raw = bytes(self._buf)
289
+ self._buf.clear()
290
+ self._paste_chars.append(raw.decode('utf-8', 'replace').replace('\r', '').replace('\n', ''))
291
+ return None
292
+
293
+ def _parse_escape(self):
294
+ # Garante bytes suficientes para CSI/SS3
295
+ if len(self._buf) < 3:
296
+ self._ler_disponivel(0.02)
297
+ if len(self._buf) < 2:
298
+ del self._buf[0]
299
+ return 'esc'
300
+
301
+ b1 = self._buf[1]
302
+ if b1 == ord('O'): # SS3 (xterm/Termux Home/End/setas)
303
+ if len(self._buf) < 3:
304
+ self._ler_disponivel(0.02)
305
+ if len(self._buf) >= 3:
306
+ code = chr(self._buf[2])
307
+ del self._buf[:3]
308
+ return {'A': 'cima', 'B': 'baixo', 'C': 'direita', 'D': 'esquerda',
309
+ 'H': 'home', 'F': 'end'}.get(code)
310
+ del self._buf[:2]
311
+ return 'esc'
312
+
313
+ if b1 != ord('['):
314
+ del self._buf[:2]
315
+ return 'esc'
316
+
317
+ # CSI: consome ate byte final 0x40..0x7E
318
+ i = 2
319
+ while True:
320
+ while i < len(self._buf):
321
+ c = self._buf[i]
322
+ if 0x40 <= c <= 0x7E:
323
+ seq = bytes(self._buf[2:i + 1]).decode('ascii', 'ignore')
324
+ del self._buf[:i + 1]
325
+ return self._decodificar_csi(seq)
326
+ i += 1
327
+ if i > 32 or not self._ler_disponivel(0.02):
328
+ del self._buf[:min(len(self._buf), 2)]
329
+ return 'esc'
330
+
331
+ def _decodificar_csi(self, seq: str):
332
+ if seq == '200~':
333
+ self._in_paste = True
334
+ self._paste_chars.clear()
335
+ return self._drenar_paste()
336
+ if seq == '201~':
337
+ self._in_paste = False
338
+ return None
339
+ if seq.startswith('<'):
340
+ # Mouse SGR: <btn;x;yM ou <btn;x;ym
341
+ m = re.fullmatch(r'<(\d+);(\d+);(\d+)([Mm])', seq)
342
+ if not m:
343
+ return None
344
+ btn, x, y, kind = int(m.group(1)), int(m.group(2)) - 1, int(m.group(3)) - 1, m.group(4)
345
+ if btn == 64:
346
+ return ('mouse_roda', -1)
347
+ if btn == 65:
348
+ return ('mouse_roda', 1)
349
+ if kind == 'M' and (btn & 3) == 0 and not (btn & 32):
350
+ return ('mouse_clique', x, y)
351
+ if btn & 32:
352
+ return ('mouse_move', x, y)
353
+ return None
354
+ mapa = {
355
+ 'A': 'cima', 'B': 'baixo', 'C': 'direita', 'D': 'esquerda',
356
+ 'H': 'home', 'F': 'end', 'Z': 'shift_tab',
357
+ '1~': 'home', '4~': 'end', '7~': 'home', '8~': 'end',
358
+ '5~': 'pgup', '6~': 'pgdown', '3~': 'delete',
359
+ }
360
+ if seq in mapa:
361
+ return mapa[seq]
362
+ # Setas com modificador (ex: 1;5A)
363
+ if seq and seq[-1] in 'ABCDHF':
364
+ return {'A': 'cima', 'B': 'baixo', 'C': 'direita', 'D': 'esquerda',
365
+ 'H': 'home', 'F': 'end'}.get(seq[-1])
366
+ return None
367
+
368
+
369
+ def desenhar_overlay_centrado(
370
+ fundo_linhas: list[str],
371
+ caixa_linhas: list[str],
372
+ largura_tela: int,
373
+ altura_tela: int,
374
+ cor_fundo_ansi: str = '\x1b[48;5;234m',
375
+ esmaecer_fundo: bool = True,
376
+ ) -> tuple[list[str], int, int]:
377
+ """Compõe uma caixa de diálogo flutuante centralizada sobre o frame base.
378
+
379
+ Retorna `(linhas_finais, linha_inicio_0based, col_inicio_0based)`.
380
+ Como o diálogo substitui o miolo das linhas alvo com posicionamento exato,
381
+ o visual fica limpo como o DialogOverlay do OpenCode e o mapeamento de clique
382
+ do mouse fica 100% determinístico.
383
+ """
384
+ linhas = list(fundo_linhas)
385
+ while len(linhas) < altura_tela:
386
+ linhas.append('')
387
+ if esmaecer_fundo:
388
+ linhas = [f'\x1b[2m{strip_ansi(l)}\x1b[0m' for l in linhas[:altura_tela]]
389
+ else:
390
+ linhas = linhas[:altura_tela]
391
+
392
+ h_box = len(caixa_linhas)
393
+ w_box = max((vis_len(l) for l in caixa_linhas), default=0)
394
+ top = max(1, (altura_tela - h_box) // 2)
395
+ left = max(1, (largura_tela - w_box) // 2)
396
+
397
+ for offset, linha_box in enumerate(caixa_linhas):
398
+ y = top + offset
399
+ if 0 <= y < len(linhas):
400
+ # Mantém margem esquerda limpa e posiciona o overlay com CSI cursor-col
401
+ # para evitar drift de largura ANSI no fundo.
402
+ linhas[y] = (
403
+ f'{linhas[y]}\x1b[0m'
404
+ f'\x1b[{left + 1}G{cor_fundo_ansi}{linha_box}\x1b[0m'
405
+ )
406
+ return linhas, top, left
407
+
408
+
409
+ def construir_dialogo_opencode(
410
+ titulo: str,
411
+ largura_caixa: int,
412
+ itens: list[dict],
413
+ foco: int,
414
+ topo: int,
415
+ limite: int,
416
+ busca: str = '',
417
+ placeholder: str = 'buscar…',
418
+ subtitulo: str = '',
419
+ rodape: str = '↑↓ navegar · Enter selecionar · Esc voltar',
420
+ cores: dict[str, str] | None = None,
421
+ mascarar_busca: bool = False,
422
+ mostrar_busca: bool = True,
423
+ ) -> tuple[list[Text], dict[int, int]]:
424
+ """Monta um diálogo visual no estilo do OpenCode (DialogSelect / Connect).
425
+
426
+ Cada item em `itens` é um dict:
427
+ - `tipo`: 'item' (padrão) | 'secao' | 'texto' | 'vazio'
428
+ - `rotulo`: texto principal
429
+ - `detalhe`: metadado à direita (ex: '2 contas · 40% cota')
430
+ - `badge`: marcador colorido à esquerda (ex: '●', '○', '+')
431
+ - `badge_cor`: estilo Rich do badge
432
+ - `ativo`: bool (marca o item atual)
433
+ - `chave`: identificador retornado ao selecionar
434
+ Retorna `(rich_lines, mapa_y_relativo -> indice_no_array_selecionaveis)`.
435
+ """
436
+ c = cores or {}
437
+ acento = c.get('acento', '#fab283')
438
+ acento2 = c.get('acento2', '#5c9cf5')
439
+ ok = c.get('ok', '#7fd88f')
440
+ fraco = c.get('fraco', '#808080')
441
+ borda = c.get('borda', '#484848')
442
+ texto = c.get('texto', '#eeeeee')
443
+ fundo = c.get('fundo', '#1e1e1e')
444
+ texto_acento = c.get('texto_acento', '#0a0a0a')
445
+
446
+ w = max(28, largura_caixa)
447
+ inner = w - 2 # entre ┃ ... ┃
448
+ bg = f' on {fundo}'
449
+ linhas: list[Text] = []
450
+ mapa_clique: dict[int, int] = {}
451
+
452
+ def frame_line(miolo: Text, pad_right: int = 0) -> Text:
453
+ t = Text()
454
+ t.append('┃', style=f'{borda}{bg}')
455
+ t.append_text(miolo)
456
+ if pad_right > 0:
457
+ t.append(' ' * pad_right, style=bg.strip())
458
+ t.append('┃', style=f'{borda}{bg}')
459
+ return t
460
+
461
+ # Borda superior fina
462
+ topo_line = Text()
463
+ topo_line.append('┏' + '━' * inner + '┓', style=f'{borda}{bg}')
464
+ linhas.append(topo_line)
465
+
466
+ # Cabeçalho: título à esquerda + "esc" à direita (assinatura visual do OpenCode)
467
+ esc_tag = 'esc '
468
+ tit_max = max(8, inner - cell_len(esc_tag) - 2)
469
+ tit_vis = truncate_vis(titulo, tit_max)
470
+ gap_hdr = max(1, inner - 2 - cell_len(tit_vis) - cell_len(esc_tag))
471
+ hdr = Text()
472
+ hdr.append(' ', style=bg.strip())
473
+ hdr.append(tit_vis, style=f'bold {texto}{bg}')
474
+ hdr.append(' ' * gap_hdr, style=bg.strip())
475
+ hdr.append(esc_tag, style=f'{fraco}{bg}')
476
+ linhas.append(frame_line(hdr))
477
+
478
+ if subtitulo:
479
+ sub_vis = truncate_vis(subtitulo, inner - 4)
480
+ sub = Text()
481
+ sub.append(' ' + sub_vis, style=f'{fraco}{bg}')
482
+ linhas.append(frame_line(sub, max(0, inner - 2 - cell_len(sub_vis))))
483
+
484
+ # Campo de busca embutido no diálogo
485
+ if mostrar_busca:
486
+ linhas.append(frame_line(Text(' ' * inner, style=bg.strip())))
487
+ busca_vis = ('•' * min(len(busca), 36)) if mascarar_busca else busca
488
+ campo_max = max(8, inner - 6)
489
+ campo_txt = truncate_vis(busca_vis, campo_max) if busca_vis else truncate_vis(placeholder, campo_max)
490
+ row_b = Text()
491
+ row_b.append(' ', style=bg.strip())
492
+ row_b.append('▸ ', style=f'bold {acento}{bg}')
493
+ row_b.append(campo_txt, style=f'{texto if busca_vis else fraco}{bg}')
494
+ rest = max(0, inner - 4 - cell_len(campo_txt))
495
+ linhas.append(frame_line(row_b, rest))
496
+ sep = Text(' ' + '─' * max(4, inner - 4) + ' ', style=f'{borda}{bg}')
497
+ linhas.append(frame_line(sep))
498
+
499
+ # Extrai índices selecionáveis e janela visível
500
+ selecionaveis = [i for i, it in enumerate(itens) if it.get('tipo', 'item') == 'item']
501
+ total_sel = len(selecionaveis)
502
+
503
+ if total_sel == 0:
504
+ # Só texto informativo ou lista vazia
505
+ for it in itens:
506
+ txt = truncate_vis(str(it.get('rotulo') or ''), inner - 4)
507
+ cor = it.get('cor') or fraco
508
+ t = Text()
509
+ t.append(' ' + txt, style=f'{cor}{bg}')
510
+ linhas.append(frame_line(t, max(0, inner - 2 - cell_len(txt))))
511
+ else:
512
+ # Janela baseada nos selecionáveis, mantendo cabeçalho de seção acima do primeiro item dela
513
+ vis_sel_indices = selecionaveis[topo:topo + limite]
514
+ vis_set = set(vis_sel_indices)
515
+ # Mapeia cada selecionável para sua posição 0..total_sel-1
516
+ pos_sel = {idx_raw: pos for pos, idx_raw in enumerate(selecionaveis)}
517
+ ultima_secao_mostrada = None
518
+
519
+ # Descobre qual seção pertence a cada item
520
+ secao_de: dict[int, str] = {}
521
+ sec_atual = ''
522
+ for idx_raw, it in enumerate(itens):
523
+ if it.get('tipo') == 'secao':
524
+ sec_atual = str(it.get('rotulo') or '')
525
+ else:
526
+ secao_de[idx_raw] = sec_atual
527
+
528
+ for idx_raw in vis_sel_indices:
529
+ sec = secao_de.get(idx_raw, '')
530
+ if sec and sec != ultima_secao_mostrada:
531
+ if ultima_secao_mostrada is not None:
532
+ linhas.append(frame_line(Text(' ' * inner, style=bg.strip())))
533
+ ultima_secao_mostrada = sec
534
+ sec_vis = truncate_vis(sec.upper(), inner - 4)
535
+ st = Text()
536
+ st.append(' ' + sec_vis, style=f'bold {acento2}{bg}')
537
+ linhas.append(frame_line(st, max(0, inner - 2 - cell_len(sec_vis))))
538
+
539
+ it = itens[idx_raw]
540
+ pos = pos_sel[idx_raw]
541
+ focado = (pos == foco)
542
+ badge = str(it.get('badge') or ('●' if it.get('ativo') else ' '))
543
+ badge_cor = it.get('badge_cor') or (ok if it.get('ativo') else fraco)
544
+ rotulo = str(it.get('rotulo') or '')
545
+ detalhe = str(it.get('detalhe') or '')
546
+
547
+ # Larguras: ' ' + badge + ' ' + rotulo + gap + detalhe + ' '
548
+ prefix_w = 2 + cell_len(badge) + 1
549
+ max_det = max(0, (inner - prefix_w - 6) // 2) if detalhe else 0
550
+ det_vis = truncate_vis(detalhe, max_det) if (detalhe and max_det >= 6) else ''
551
+ max_rot = max(4, inner - prefix_w - 2 - (cell_len(det_vis) + 2 if det_vis else 0))
552
+ rot_vis = truncate_vis(rotulo, max_rot)
553
+ gap = max(1, inner - prefix_w - cell_len(rot_vis) - cell_len(det_vis) - 2) if det_vis else max(0, inner - prefix_w - cell_len(rot_vis))
554
+
555
+ t = Text()
556
+ if focado:
557
+ hi = f'bold {texto_acento} on {acento}'
558
+ hi_dim = f'{texto_acento} on {acento}'
559
+ t.append(f' {badge} ', style=hi)
560
+ t.append(rot_vis, style=hi)
561
+ if det_vis:
562
+ t.append(' ' * gap, style=hi)
563
+ t.append(det_vis, style=hi_dim)
564
+ t.append(' ', style=hi)
565
+ else:
566
+ t.append(' ' * gap, style=hi)
567
+ else:
568
+ t.append(' ', style=bg.strip())
569
+ t.append(badge + ' ', style=f'{badge_cor}{bg}')
570
+ t.append(rot_vis, style=f'{acento if it.get("ativo") else texto}{bg}')
571
+ if det_vis:
572
+ t.append(' ' * gap, style=bg.strip())
573
+ t.append(det_vis, style=f'{fraco}{bg}')
574
+ t.append(' ', style=bg.strip())
575
+ else:
576
+ t.append(' ' * gap, style=bg.strip())
577
+
578
+ mapa_clique[len(linhas)] = pos
579
+ linhas.append(frame_line(t))
580
+
581
+ # Indicador visual de barra de rolagem / posição quando a lista é maior que a janela
582
+ if total_sel > len(vis_sel_indices):
583
+ frac_pos = topo / max(1, total_sel - len(vis_sel_indices))
584
+ trilha = 12
585
+ pos_bar = min(trilha - 1, max(0, int(round(frac_pos * (trilha - 1)))))
586
+ barra_scroll = '─' * pos_bar + '━' * 2 + '─' * max(0, trilha - pos_bar - 1)
587
+ pag = f'{topo + 1}–{topo + len(vis_sel_indices)} de {total_sel} {barra_scroll}'
588
+ pag_vis = truncate_vis(pag, inner - 4)
589
+ pt = Text()
590
+ pt.append(' ' + pag_vis, style=f'{fraco}{bg}')
591
+ linhas.append(frame_line(pt, max(0, inner - 2 - cell_len(pag_vis))))
592
+
593
+ # Rodapé de atalhos
594
+ linhas.append(frame_line(Text(' ' * inner, style=bg.strip())))
595
+ rod_vis = truncate_vis(rodape, inner - 4)
596
+ rt = Text()
597
+ rt.append(' ' + rod_vis, style=f'{fraco}{bg}')
598
+ linhas.append(frame_line(rt, max(0, inner - 2 - cell_len(rod_vis))))
599
+
600
+ bot_line = Text()
601
+ bot_line.append('┗' + '━' * inner + '┛', style=f'{borda}{bg}')
602
+ linhas.append(bot_line)
603
+
604
+ return linhas, mapa_clique
@@ -0,0 +1,84 @@
1
+ {
2
+ "../node_modules/@heroui/dom-animation/dist/index.mjs": {
3
+ "file": "assets/index-COlDAcsY.js",
4
+ "name": "index",
5
+ "src": "../node_modules/@heroui/dom-animation/dist/index.mjs",
6
+ "isDynamicEntry": true,
7
+ "imports": [
8
+ "index.html",
9
+ "_react-vendor-C475ILlI.js"
10
+ ]
11
+ },
12
+ "../node_modules/@xterm/addon-webgl/lib/addon-webgl.mjs": {
13
+ "file": "assets/terminal-webgl-BRBWwLY7.js",
14
+ "name": "terminal-webgl",
15
+ "src": "../node_modules/@xterm/addon-webgl/lib/addon-webgl.mjs",
16
+ "isDynamicEntry": true
17
+ },
18
+ "_react-vendor-C475ILlI.js": {
19
+ "file": "assets/react-vendor-C475ILlI.js",
20
+ "name": "react-vendor"
21
+ },
22
+ "_terminal-vendor-DOrYoP_4.css": {
23
+ "file": "assets/terminal-vendor-DOrYoP_4.css",
24
+ "src": "_terminal-vendor-DOrYoP_4.css"
25
+ },
26
+ "_terminal-vendor-Dp03d74L.js": {
27
+ "file": "assets/terminal-vendor-Dp03d74L.js",
28
+ "name": "terminal-vendor",
29
+ "css": [
30
+ "assets/terminal-vendor-DOrYoP_4.css"
31
+ ]
32
+ },
33
+ "fonts/press-start-2p.ttf": {
34
+ "file": "assets/press-start-2p-2BZhbCiP.ttf",
35
+ "src": "fonts/press-start-2p.ttf"
36
+ },
37
+ "index.html": {
38
+ "file": "assets/index-CJE_a_Tn.js",
39
+ "name": "index",
40
+ "src": "index.html",
41
+ "isEntry": true,
42
+ "imports": [
43
+ "_react-vendor-C475ILlI.js"
44
+ ],
45
+ "dynamicImports": [
46
+ "../node_modules/@heroui/dom-animation/dist/index.mjs",
47
+ "src/TerminalPage.jsx",
48
+ "src/LogsPage.jsx"
49
+ ],
50
+ "css": [
51
+ "assets/index-o8xT03ZV.css"
52
+ ],
53
+ "assets": [
54
+ "assets/press-start-2p-2BZhbCiP.ttf"
55
+ ]
56
+ },
57
+ "src/LogsPage.jsx": {
58
+ "file": "assets/LogsPage-DkXN-I7o.js",
59
+ "name": "LogsPage",
60
+ "src": "src/LogsPage.jsx",
61
+ "isDynamicEntry": true,
62
+ "imports": [
63
+ "_react-vendor-C475ILlI.js",
64
+ "index.html"
65
+ ]
66
+ },
67
+ "src/TerminalPage.jsx": {
68
+ "file": "assets/TerminalPage-D208X99P.js",
69
+ "name": "TerminalPage",
70
+ "src": "src/TerminalPage.jsx",
71
+ "isDynamicEntry": true,
72
+ "imports": [
73
+ "index.html",
74
+ "_react-vendor-C475ILlI.js",
75
+ "_terminal-vendor-Dp03d74L.js"
76
+ ],
77
+ "dynamicImports": [
78
+ "../node_modules/@xterm/addon-webgl/lib/addon-webgl.mjs"
79
+ ],
80
+ "css": [
81
+ "assets/TerminalPage-DYGPu4ux.css"
82
+ ]
83
+ }
84
+ }