krnell 3.0.2 → 3.0.4

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/atualizador.py CHANGED
@@ -93,7 +93,12 @@ class MonitorAtualizacao:
93
93
  self._estado = 'checking'
94
94
  pedido = urllib.request.Request(
95
95
  self._url,
96
- headers={'Accept': 'application/json', 'User-Agent': f'krnell/{self.versao_atual}'},
96
+ headers={
97
+ 'Accept': 'application/json',
98
+ 'Cache-Control': 'no-cache',
99
+ 'Pragma': 'no-cache',
100
+ 'User-Agent': f'krnell/{self.versao_atual}',
101
+ },
97
102
  )
98
103
  try:
99
104
  with self._abrir(pedido, timeout=2.0) as resposta:
@@ -129,7 +134,7 @@ def instalar_e_localizar_cli(versao: str, *, executar=subprocess.run) -> list[st
129
134
  raise RuntimeError('Node.js e npm precisam estar no PATH para atualizar')
130
135
  ambiente = dict(os.environ, NO_UPDATE_NOTIFIER='1', NPM_CONFIG_FUND='false', NPM_CONFIG_AUDIT='false')
131
136
  instalado = executar(
132
- [npm, 'install', '-g', f'krnell@{versao}', '--no-audit', '--no-fund'],
137
+ [npm, 'install', '-g', f'krnell@{versao}', '--prefer-online', '--no-audit', '--no-fund'],
133
138
  capture_output=True, text=True, errors='replace', timeout=240,
134
139
  check=False, shell=False, env=ambiente,
135
140
  )
package/bin/krnell.mjs CHANGED
@@ -77,9 +77,9 @@ prepararPastaUsuario();
77
77
  function lerVersao() {
78
78
  try {
79
79
  const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
80
- return pkg.version || '3.0.2';
80
+ return pkg.version || '3.0.4';
81
81
  } catch {
82
- return '3.0.2';
82
+ return '3.0.4';
83
83
  }
84
84
  }
85
85
 
@@ -104,6 +104,33 @@ Uso:
104
104
  process.exit(0);
105
105
  }
106
106
 
107
+ async function resolverUltimaVersao(pkgName) {
108
+ const url = process.env.KRNELL_UPDATE_URL
109
+ || `https://registry.npmjs.org/${encodeURIComponent(pkgName)}/latest`;
110
+ const ac = new AbortController();
111
+ const timer = setTimeout(() => ac.abort(), 5000);
112
+ try {
113
+ const res = await fetch(url, {
114
+ signal: ac.signal,
115
+ headers: {
116
+ Accept: 'application/json',
117
+ 'Cache-Control': 'no-cache',
118
+ Pragma: 'no-cache',
119
+ },
120
+ });
121
+ if (!res.ok) return '';
122
+ const dados = await res.json();
123
+ const v = String(dados?.version || '').trim();
124
+ return /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(v)
125
+ ? v
126
+ : '';
127
+ } catch {
128
+ return '';
129
+ } finally {
130
+ clearTimeout(timer);
131
+ }
132
+ }
133
+
107
134
  if (args[0] === 'upgrade' || args[0] === 'update') {
108
135
  const pkgName = (() => {
109
136
  try {
@@ -112,9 +139,18 @@ if (args[0] === 'upgrade' || args[0] === 'update') {
112
139
  return 'krnell';
113
140
  }
114
141
  })();
115
- console.log(`◈ krnell: atualizando ${pkgName}@latest via npm...`);
142
+ const resolvida = await resolverUltimaVersao(pkgName);
143
+ const spec = resolvida ? `${pkgName}@${resolvida}` : `${pkgName}@latest`;
144
+ console.log(`◈ krnell: atualizando ${spec} via npm (chaves, provedores e contas serão preservados)...`);
116
145
  const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
117
- const r = spawnSync(npmCmd, ['install', '-g', `${pkgName}@latest`], { stdio: 'inherit' });
146
+ const r = spawnSync(
147
+ npmCmd,
148
+ ['install', '-g', spec, '--prefer-online', '--no-audit', '--no-fund'],
149
+ {
150
+ stdio: 'inherit',
151
+ env: { ...process.env, NO_UPDATE_NOTIFIER: '1', NPM_CONFIG_FUND: 'false', NPM_CONFIG_AUDIT: 'false' },
152
+ },
153
+ );
118
154
  process.exit(r.status ?? 1);
119
155
  }
120
156
 
package/bridge.py CHANGED
@@ -59,7 +59,7 @@ OPENCODE_CONTEXT_TOKENS = 300000
59
59
  OPENCODE_OUTPUT_TOKENS = 64000
60
60
  MODEL_CONTEXT_ANUNCIADO = 0 # 0 = nao ha limite de descoberta configurado
61
61
  MODEL_OUTPUT_ANUNCIADO = 0 # limite nativo conhecido; independente do contexto escolhido
62
- BRIDGE_VERSION = '3.0.2'
62
+ BRIDGE_VERSION = '3.0.4'
63
63
  PROVIDER_URLS = {'unorouter': 'https://api.unorouter.com/v1',
64
64
  'tokenharbor': 'https://tokenharbor.ai/v1',
65
65
  # Contas do app WorkBuddy: o fluxo real (login, headers de
package/iniciar.sh CHANGED
@@ -27,7 +27,7 @@ case "${1:-}" in
27
27
  --once) MODO="once" ;;
28
28
  --repl) MODO="repl" ;;
29
29
  -v|--version)
30
- echo "krnell v3.0.2"
30
+ echo "krnell v3.0.4"
31
31
  exit 0
32
32
  ;;
33
33
  upgrade|update)
package/opencode_sync.py CHANGED
@@ -8,15 +8,60 @@ import shutil
8
8
  from pathlib import Path
9
9
 
10
10
 
11
+ def _bases_home_opencode() -> list[Path]:
12
+ """Homes onde o OpenCode pode morar (atual, XDG, Termux e proot-distro)."""
13
+ bases: list[Path] = []
14
+ vistos: set[str] = set()
15
+
16
+ def add(p: Path | None):
17
+ if not p:
18
+ return
19
+ chave = str(p)
20
+ if chave not in vistos:
21
+ vistos.add(chave)
22
+ bases.append(p)
23
+
24
+ add(Path.home())
25
+ # No Termux nativo, o usuário frequentemente instala o OpenCode dentro de um
26
+ # container proot-distro (ex.: ubuntu/debian) em $PREFIX/var/lib/proot-distro.
27
+ prefix = os.environ.get('PREFIX', '')
28
+ if prefix and 'com.termux' in prefix:
29
+ containers = Path(prefix) / 'var' / 'lib' / 'proot-distro' / 'installed-rootfs'
30
+ containers_alt = Path(prefix) / 'var' / 'lib' / 'proot-distro' / 'containers'
31
+ for raiz_c in (containers, containers_alt):
32
+ if not raiz_c.is_dir():
33
+ continue
34
+ try:
35
+ for distro in sorted(raiz_c.iterdir()):
36
+ for sub in (distro / 'root', distro / 'rootfs' / 'root'):
37
+ if (sub / '.config' / 'opencode').exists() or (sub / '.opencode').exists():
38
+ add(sub)
39
+ except OSError:
40
+ pass
41
+ return bases
42
+
43
+
11
44
  def candidatos_config_opencode() -> list[Path]:
12
- home = Path.home()
13
- lista = [
14
- home / '.config' / 'opencode' / 'opencode.jsonc',
15
- home / '.config' / 'opencode' / 'opencode.json',
16
- ]
45
+ lista: list[Path] = []
46
+ vistos: set[str] = set()
47
+
48
+ def add(p: Path):
49
+ chave = str(p)
50
+ if chave not in vistos:
51
+ vistos.add(chave)
52
+ lista.append(p)
53
+
54
+ xdg = os.environ.get('XDG_CONFIG_HOME')
55
+ if xdg:
56
+ add(Path(xdg) / 'opencode' / 'opencode.jsonc')
57
+ add(Path(xdg) / 'opencode' / 'opencode.json')
58
+ for base in _bases_home_opencode():
59
+ add(base / '.config' / 'opencode' / 'opencode.jsonc')
60
+ add(base / '.config' / 'opencode' / 'opencode.json')
17
61
  if os.name == 'nt':
18
- appdata = os.environ.get('APPDATA') or str(home / 'AppData' / 'Roaming')
19
- lista.append(Path(appdata) / 'opencode' / 'opencode.jsonc')
62
+ appdata = os.environ.get('APPDATA') or str(Path.home() / 'AppData' / 'Roaming')
63
+ add(Path(appdata) / 'opencode' / 'opencode.jsonc')
64
+ add(Path(appdata) / 'opencode' / 'opencode.json')
20
65
  return lista
21
66
 
22
67
 
@@ -129,21 +174,40 @@ def _substituir_ou_inserir_provedor(texto: str, provider_id: str, bloco: str) ->
129
174
 
130
175
 
131
176
  def opencode_detectado() -> bool:
132
- """Detecta se o OpenCode está instalado (binário ou pasta de config)."""
177
+ """Detecta se o OpenCode está instalado (PATH, npm global, ~/.opencode, XDG ou proot)."""
133
178
  if shutil.which('opencode'):
134
179
  return True
135
- home = Path.home()
136
- for p in (
137
- home / '.opencode' / 'bin' / 'opencode',
138
- home / '.opencode' / 'bin' / 'opencode.exe',
139
- home / '.config' / 'opencode',
140
- ):
180
+ prefix = os.environ.get('PREFIX', '')
181
+ extras: list[Path] = []
182
+ if prefix:
183
+ extras.extend([
184
+ Path(prefix) / 'bin' / 'opencode',
185
+ Path(prefix) / 'lib' / 'node_modules' / '@opencode' / 'cli',
186
+ Path(prefix) / 'lib' / 'node_modules' / 'opencode-ai',
187
+ ])
188
+ xdg = os.environ.get('XDG_CONFIG_HOME')
189
+ if xdg:
190
+ extras.append(Path(xdg) / 'opencode')
191
+ for base in _bases_home_opencode():
192
+ extras.extend([
193
+ base / '.opencode' / 'bin' / 'opencode',
194
+ base / '.opencode' / 'bin' / 'opencode.exe',
195
+ base / '.local' / 'bin' / 'opencode',
196
+ base / '.bun' / 'bin' / 'opencode',
197
+ base / '.npm-global' / 'bin' / 'opencode',
198
+ base / '.config' / 'opencode',
199
+ ])
200
+ for p in extras:
141
201
  if p.exists():
142
202
  return True
143
203
  if os.name == 'nt':
144
- appdata = os.environ.get('APPDATA') or str(home / 'AppData' / 'Roaming')
145
- if (Path(appdata) / 'opencode').exists():
146
- return True
204
+ appdata = os.environ.get('APPDATA') or str(Path.home() / 'AppData' / 'Roaming')
205
+ for p in (
206
+ Path(appdata) / 'opencode',
207
+ Path(appdata) / 'npm' / 'opencode.cmd',
208
+ ):
209
+ if p.exists():
210
+ return True
147
211
  return False
148
212
 
149
213
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "krnell",
3
- "version": "3.0.2",
3
+ "version": "3.0.4",
4
4
  "description": "Krnell — proxy multi-provedor local (NVIDIA Playground, Antigravity OAuth, WorkBuddy, OpenCode, 20+ APIs) com TUI estilo OpenCode",
5
5
  "type": "module",
6
6
  "bin": {
package/painel.py CHANGED
@@ -350,6 +350,17 @@ def consultar_modelos_opencode() -> list[str]:
350
350
  from bridge import sanitize_diagnostic
351
351
 
352
352
  executavel = shutil.which('opencode')
353
+ if not executavel:
354
+ nome = 'opencode.exe' if os.name == 'nt' else 'opencode'
355
+ for cand in (
356
+ Path.home() / '.opencode' / 'bin' / nome,
357
+ Path.home() / '.local' / 'bin' / nome,
358
+ Path.home() / '.bun' / 'bin' / nome,
359
+ Path(os.environ.get('PREFIX', '')) / 'bin' / nome if os.environ.get('PREFIX') else None,
360
+ ):
361
+ if cand and cand.is_file():
362
+ executavel = str(cand)
363
+ break
353
364
  if not executavel:
354
365
  raise ValueError('OpenCode nao encontrado no PATH; instale-o ou informe /model ID manualmente')
355
366
  try:
@@ -1256,29 +1267,32 @@ class Painel:
1256
1267
  # Uma linha de marca, uma de respiro. O update é um pill persistente e
1257
1268
  # opcional, no mesmo lugar em todas as telas, como na TUI do OpenCode.
1258
1269
  cab = Table.grid(expand=True)
1259
- cab.add_column(ratio=1)
1260
- cab.add_column(justify='right')
1270
+ cab.add_column(ratio=1, no_wrap=True)
1271
+ cab.add_column(justify='right', no_wrap=True)
1261
1272
  titulo = Text()
1262
1273
  glifo = _GLIFO_MARCA[tick % len(_GLIFO_MARCA)] if online else '◇'
1263
1274
  titulo.append(f'{glifo} ', style=f'bold {ACENTO}')
1264
1275
  titulo.append('krnell', style=f'bold {TEXTO}')
1265
- titulo.append(f' v{versao_local()}', style=FRACO)
1276
+ if largura >= 34:
1277
+ titulo.append(f' v{versao_local()}' if largura < 48 else f' v{versao_local()}', style=FRACO)
1266
1278
  estado = Text()
1267
1279
  disponivel = self.atualizacoes.disponivel
1268
1280
  rotulo_update = ''
1269
1281
  self._update_zona = None
1270
1282
  if disponivel:
1271
- rotulo_update = f" ↑ update {disponivel['version']} "
1283
+ rotulo_update = (f" ↑{disponivel['version']} " if largura < 52
1284
+ else f" ↑ update {disponivel['version']} ")
1272
1285
  cor_update = ACENTO3 if self._update_hover else ACENTO
1273
1286
  estado.append(rotulo_update, style=f'bold {cor_update} on {FUNDO}')
1274
- estado.append(' ')
1287
+ estado.append(' ' if largura < 52 else ' ')
1275
1288
  if online:
1276
1289
  if (status.get('live') or {}).get('ativas'):
1277
- estado.append(f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} working', style=ACENTO2)
1290
+ rot_on = f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} live' if largura < 42 else f'{_SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]} working'
1291
+ estado.append(rot_on, style=ACENTO2)
1278
1292
  else:
1279
- estado.append('● online', style=OK)
1293
+ estado.append('● on' if largura < 38 else '● online', style=OK)
1280
1294
  else:
1281
- estado.append('○ offline', style=ERRO)
1295
+ estado.append('○ off' if largura < 38 else '○ offline', style=ERRO)
1282
1296
  if rotulo_update:
1283
1297
  inicio = max(0, largura - cell_len(estado.plain))
1284
1298
  self._update_zona = (0, inicio, inicio + cell_len(rotulo_update) - 1)
@@ -1294,6 +1308,7 @@ class Painel:
1294
1308
  info_compacta = info_compacta[:1]
1295
1309
  linhas_req = max(2, min(espaco_corpo - len(info_compacta), 48))
1296
1310
  estreito = largura < 74
1311
+ ultra_estreito = largura < 46
1297
1312
 
1298
1313
  reqs = snap.get('requests') or []
1299
1314
  visiveis = max(1, linhas_req - 1)
@@ -1313,16 +1328,17 @@ class Painel:
1313
1328
 
1314
1329
  tabela = Table(box=None, expand=True, padding=(0, 1), show_edge=False,
1315
1330
  show_header=False, pad_edge=False)
1316
- tabela.add_column(width=5 if estreito else 8, no_wrap=True)
1331
+ if not ultra_estreito:
1332
+ tabela.add_column(width=5 if estreito else 8, no_wrap=True)
1317
1333
  tabela.add_column(width=5, no_wrap=True)
1318
1334
  tabela.add_column(ratio=1, no_wrap=True, overflow='ellipsis')
1319
- tabela.add_column(width=6, justify='right', no_wrap=True)
1335
+ tabela.add_column(width=5 if ultra_estreito else 6, justify='right', no_wrap=True)
1320
1336
  if not estreito:
1321
1337
  tabela.add_column(width=9, justify='right', no_wrap=True)
1322
1338
  tabela.add_column(width=14, no_wrap=True, overflow='ellipsis')
1323
1339
 
1324
1340
  def linha_req(hora, codigo, conta, duracao, tokens='', obs=''):
1325
- valores = [hora, codigo, conta, duracao]
1341
+ valores = [codigo, conta, duracao] if ultra_estreito else [hora, codigo, conta, duracao]
1326
1342
  if not estreito:
1327
1343
  valores.extend([tokens, obs])
1328
1344
  tabela.add_row(*valores)
@@ -1376,7 +1392,20 @@ class Painel:
1376
1392
  else:
1377
1393
  renderaveis.extend(info_compacta)
1378
1394
  renderaveis.append(atividade)
1379
- renderaveis.extend(menu_render)
1395
+ if menu_render:
1396
+ # Mantém o popup "/" sempre colado logo acima da caixa de entrada
1397
+ # (em celular com tela alta ou baixa com teclado aberto).
1398
+ renderaveis_base = self._linhas(renderaveis, largura)
1399
+ linhas_menu = self._linhas(menu_render, largura)
1400
+ limite_frame = max(2, altura - 4)
1401
+ espaco_topo = max(2, limite_frame - len(linhas_menu))
1402
+ topo_pad = list(renderaveis_base[:espaco_topo])
1403
+ while len(topo_pad) < espaco_topo:
1404
+ topo_pad.append('')
1405
+ self._frame_menu_pronto = topo_pad + linhas_menu
1406
+ renderaveis.extend(menu_render)
1407
+ else:
1408
+ self._frame_menu_pronto = None
1380
1409
  renderaveis.extend(modais_render)
1381
1410
  return renderaveis
1382
1411
 
@@ -1416,17 +1445,19 @@ class Painel:
1416
1445
 
1417
1446
  def _info_compacta(self, snap, online, status, cfg, provedor) -> list:
1418
1447
  """Duas linhas no máximo em telas estreitas; o resto mora em /status e /quota."""
1419
- modelo = tui_core.truncate_vis(modelo_exibido(cfg, provedor, status), max(12, self.largura - 24))
1420
- primeira = Text()
1448
+ modelo = tui_core.truncate_vis(modelo_exibido(cfg, provedor, status), max(8, self.largura - len(provedor) - 14))
1449
+ primeira = Text(no_wrap=True, overflow='ellipsis')
1421
1450
  primeira.append(provedor, style=f'bold {ACENTO}')
1422
1451
  primeira.append(f' {modelo}', style=TEXTO)
1423
- primeira.append(f' · {variante_ativa(cfg, provedor)}', style=FRACO)
1424
- segunda = Text()
1452
+ var = variante_ativa(cfg, provedor)
1453
+ if cell_len(primeira.plain) + len(var) + 5 <= self.largura:
1454
+ primeira.append(f' · {var}', style=FRACO)
1455
+ segunda = Text(no_wrap=True, overflow='ellipsis')
1425
1456
  ag_status = snap.get('ag_status') if isinstance(snap.get('ag_status'), dict) else {}
1426
1457
  resumo = _resumo_cota_antigravity(ag_status)
1427
1458
  for idx, item in enumerate(resumo[:2]):
1428
1459
  if idx:
1429
- segunda.append(' · ', style=BORDA)
1460
+ segunda.append(' · ' if self.largura < 50 else ' · ', style=BORDA)
1430
1461
  segunda.append(item['nome'][0], style=FRACO)
1431
1462
  for bucket, prefixo in ((item.get('b5h'), '5h'), (item.get('bsem'), '7d')):
1432
1463
  texto, cor = _fmt_bucket_curto(bucket, prefixo, com_reset=False)
@@ -1676,7 +1707,7 @@ class Painel:
1676
1707
  self._menu_ini = None
1677
1708
  return
1678
1709
  altura_menu = len(self._linhas(itens, self.largura))
1679
- base = min(len(frame), max(3, self.altura - 4))
1710
+ base = min(len(frame), max(2, self.altura - 4))
1680
1711
  inicio = base - altura_menu
1681
1712
  self._menu_ini = inicio if inicio >= 0 else None
1682
1713
 
@@ -2256,25 +2287,32 @@ class Painel:
2256
2287
  def desenhar(self, frame: list) -> None:
2257
2288
  # Em modo TUI:
2258
2289
  # 1) Evita redesenho com flicker usando BSU/ESU (Synchronized Output DEC 2026)
2259
- # 2) Cache de frame base enquanto um dialogo esta aberto (scroll/busca no dialogo vira instantaneo)
2290
+ # 2) Posiciona cada linha explicitamente (\x1b[row;1H) em vez de depender de \n
2291
+ # — nunca produz escadinha nem lixo de frame antigo ao dar zoom no Termux/Linux
2292
+ # 3) Ancora o rodapé (caixa + status) no fundo real da tela para ficar confortável no celular
2260
2293
  saida = sys.stdout
2261
- altura = self.altura
2262
- largura = self.largura
2263
- max_frame = max(3, altura - 4)
2264
- if len(frame) > max_frame:
2265
- frame = frame[:max_frame]
2294
+ altura = max(6, self.altura)
2295
+ largura = max(20, self.largura)
2296
+ max_frame = max(2, altura - 4)
2297
+ frame = list(frame[:max_frame])
2298
+ # Preenche ate o topo da caixa de entrada para limpar linhas antigas apos zoom/resize
2299
+ while len(frame) < max_frame:
2300
+ frame.append('')
2266
2301
  self.ultima_contagem = len(frame)
2267
2302
  base = len(frame)
2268
2303
  buf = ['\x1b[?2026h\x1b[H']
2269
- for linha in frame:
2270
- buf.append(linha + '\x1b[0m\x1b[K\n')
2271
- regua = '─' * max(8, largura - 2)
2272
- buf.append(f'\x1b[{base + 1};1H' + ansi('borda') + '╭' + regua + '╮' + RESET + '\x1b[K')
2304
+ if getattr(self, '_precisa_limpar_tela', False):
2305
+ buf.append('\x1b[2J')
2306
+ self._precisa_limpar_tela = False
2307
+ for idx, linha in enumerate(frame, 1):
2308
+ buf.append(f'\x1b[{idx};1H\x1b[2K' + linha + '\x1b[0m\x1b[K')
2309
+ regua = '─' * max(6, largura - 2)
2310
+ buf.append(f'\x1b[{base + 1};1H\x1b[2K' + ansi('borda') + '╭' + regua + '╮' + RESET)
2273
2311
  buf.append(self._formatar_caixa(base + 2))
2274
- buf.append(f'\x1b[{base + 3};1H' + ansi('borda') + '╰' + regua + '╯' + RESET + '\x1b[K')
2312
+ buf.append(f'\x1b[{base + 3};1H\x1b[2K' + ansi('borda') + '╰' + regua + '╯' + RESET)
2275
2313
  self._status_y = base + 3
2276
2314
  buf.append(f'\x1b[{base + 4};1H\x1b[2K' + self._barra_status() + '\x1b[J')
2277
- coluna = min(getattr(self, '_coluna_cursor', 5), max(2, self.largura - 1))
2315
+ coluna = min(getattr(self, '_coluna_cursor', 5), max(2, largura - 1))
2278
2316
  buf.append(f'\x1b[{base + 2};{coluna}H\x1b[?2026l')
2279
2317
  saida.write(''.join(buf))
2280
2318
  saida.flush()
@@ -2296,8 +2334,9 @@ class Painel:
2296
2334
  r_ov = getattr(self, '_restart_overlay', None)
2297
2335
  if not self.modal and not self.wizard and not r_ov:
2298
2336
  return None
2299
- w_box = max(30, min(self.largura - 4, 78))
2300
- limite = max(4, min(14, self.altura - 12))
2337
+ w_box = max(22, min(self.largura - 2 if self.largura < 56 else self.largura - 4, 78))
2338
+ # Reserva espaço para cabeçalho/busca/rodapé do diálogo para nunca estourar telas baixas
2339
+ limite = max(2, min(14, self.altura - 11))
2301
2340
  cores = self._cores_dialogo()
2302
2341
 
2303
2342
  if r_ov:
@@ -2310,7 +2349,7 @@ class Painel:
2310
2349
  {'tipo': 'texto', 'rotulo': '', 'cor': FRACO},
2311
2350
  {'tipo': 'texto', 'rotulo': f' {atual}', 'cor': TEXTO},
2312
2351
  ]
2313
- w_r = min(max(44, self.largura - 14), 60)
2352
+ w_r = max(24, min(self.largura - 2, 60))
2314
2353
  rich_lines, _ = tui_core.construir_dialogo_opencode(
2315
2354
  titulo='◈ krnell',
2316
2355
  largura_caixa=w_r,
@@ -2338,13 +2377,14 @@ class Painel:
2338
2377
  'badge': '↳', 'badge_cor': ACENTO2, 'chave': str(idx)})
2339
2378
  else:
2340
2379
  itens.append({'tipo': 'texto', 'rotulo': txt, 'cor': TEXTO})
2380
+ limite_mod = max(2, min(len(itens), max(2, self.altura - 9)))
2341
2381
  rich_lines, mapa_clique = tui_core.construir_dialogo_opencode(
2342
2382
  titulo=titulo,
2343
2383
  largura_caixa=w_box,
2344
2384
  itens=itens,
2345
2385
  foco=-1,
2346
2386
  topo=0,
2347
- limite=max(limite, len(itens)),
2387
+ limite=limite_mod,
2348
2388
  rodape=dica,
2349
2389
  cores=cores,
2350
2390
  mostrar_busca=False,
@@ -2477,13 +2517,16 @@ class Painel:
2477
2517
  contagem = cell_len(dica)
2478
2518
  elif not self.wizard:
2479
2519
  dica = '/ commands · Ctrl+L connect · Ctrl+P palette'
2480
- if cell_len(dica) > largura - 10:
2481
- dica = '/connect · /help'
2520
+ if cell_len(dica) > largura - 8:
2521
+ dica = '/ commands · /connect'
2522
+ if cell_len(dica) > largura - 8:
2523
+ dica = '/help'
2524
+ dica = tui_core.truncate_vis(dica, max(1, largura - 7))
2482
2525
  partes.extend([ansi('fraco'), dica, RESET])
2483
2526
  contagem = cell_len(dica)
2484
- pad = max(1, largura - 5 - contagem)
2527
+ pad = max(0, largura - 6 - contagem)
2485
2528
  partes.extend([' ' * pad, ansi('borda'), '│', RESET])
2486
- self._coluna_cursor = 5 + cell_len(visivel)
2529
+ self._coluna_cursor = min(5 + cell_len(visivel), max(2, largura - 1))
2487
2530
  return ''.join(partes)
2488
2531
 
2489
2532
  def _escrever_caixa(self, saida, linha: int) -> None:
@@ -2495,6 +2538,8 @@ class Painel:
2495
2538
 
2496
2539
  def atualizar_tela(self) -> None:
2497
2540
  self.largura, self.altura = shutil.get_terminal_size((110, 30))
2541
+ self.largura = max(24, self.largura)
2542
+ self.altura = max(8, self.altura)
2498
2543
  snap = self.coletor.ler()
2499
2544
  self._snap_visto = snap
2500
2545
  if (self.modal or {}).get('tipo') == 'tokens' and \
@@ -2513,26 +2558,37 @@ class Painel:
2513
2558
  cortado = cache[2]
2514
2559
  else:
2515
2560
  renderaveis = self.render(snap)
2516
- frame = self._linhas(renderaveis, self.largura)
2517
- cortado = len(frame) > limite
2561
+ pronto = getattr(self, '_frame_menu_pronto', None)
2562
+ if pronto is not None:
2563
+ frame = list(pronto)
2564
+ cortado = False
2565
+ else:
2566
+ frame = self._linhas(renderaveis, self.largura)
2567
+ cortado = len(frame) > limite
2518
2568
  frame = frame[:limite]
2519
2569
  self._cache_frame_base = (chave_base, list(frame), cortado)
2520
2570
  self._overlay_top = None
2521
2571
  self._overlay_left = None
2522
2572
  self._overlay_clique = {}
2523
2573
  # Quando um diálogo novo abre na TUI, anima brevemente a revelação (slide/expand)
2574
+ # Em telas pequenas/estreitas (Termux/celular) ou após resize, pula o slide para
2575
+ # nunca sobrepor dois quadros parciais.
2524
2576
  modal_identidade = ('tokens-live' if (self.modal or {}).get('tipo') == 'tokens' else id(self.modal))
2525
2577
  dialogo_atual = (id(self.wizard), (self.wizard or {}).get('tipo'), (self.wizard or {}).get('passo'), modal_identidade, em_restart)
2526
2578
  if tem_overlay and dialogo_atual != getattr(self, '_dialogo_id', None):
2527
2579
  self._dialogo_id = dialogo_atual
2528
- self._dialogo_frame = 0
2580
+ self._dialogo_frame = 99 if (self.largura < 80 or self.altura < 24 or tui_core.is_termux()) else 0
2529
2581
  elif not tem_overlay:
2530
2582
  self._dialogo_id = None
2531
2583
  self._dialogo_frame = 99
2584
+ # Em telas baixas, garante que o frame do overlay nunca passe da area util
2532
2585
  if tem_overlay:
2533
2586
  ov = self._construir_overlay_linhas()
2534
2587
  if ov is not None:
2535
2588
  caixa_linhas, mapa_clique, _w_box = ov
2589
+ if len(caixa_linhas) > limite and limite >= 4:
2590
+ caixa_linhas = caixa_linhas[:limite - 1] + [caixa_linhas[-1]]
2591
+ mapa_clique = {k: v for k, v in mapa_clique.items() if k < limite - 1}
2536
2592
  # Animação de entrada suave (2 frames rápidos, sem travar teclado)
2537
2593
  if getattr(self, '_dialogo_frame', 99) < 2 and len(caixa_linhas) > 6:
2538
2594
  passo_a = self._dialogo_frame
@@ -2722,6 +2778,7 @@ class Painel:
2722
2778
  saida.write('\x1b[?1049h\x1b[?25h')
2723
2779
  saida.write('\x1b[?7l')
2724
2780
  saida.flush()
2781
+ self._precisa_limpar_tela = True
2725
2782
  try:
2726
2783
  self.atualizar_tela()
2727
2784
  while not self.saindo:
@@ -2729,6 +2786,8 @@ class Painel:
2729
2786
  tecla = self.ler_tecla(0.03 if getattr(self, '_dialogo_frame', 99) < 2 else (0.08 if animando else 0.25))
2730
2787
  agora = time.monotonic()
2731
2788
  if tecla is None:
2789
+ nova_larg, nova_alt = shutil.get_terminal_size((self.largura, self.altura))
2790
+ mudou_tamanho = (nova_larg != self.largura or nova_alt != self.altura)
2732
2791
  mudou_dados = self.coletor.revisao != self.revisao_vista
2733
2792
  expirou_msg = bool(self.msg and time.time() > self.msg_ate)
2734
2793
  if expirou_msg:
@@ -2738,7 +2797,11 @@ class Painel:
2738
2797
  if tick_anim and (animando or (not self.wizard and not self.modal)):
2739
2798
  self._anim_tick = (self._anim_tick + 1) % 100000
2740
2799
  self._anim_ultimo = agora
2741
- if mudou_dados or expirou_msg or (tick_anim and (animando or (not self.wizard and not self.modal))):
2800
+ if mudou_tamanho:
2801
+ self._cache_frame_base = None
2802
+ self._dialogo_frame = 99
2803
+ self._precisa_limpar_tela = True
2804
+ if mudou_tamanho or mudou_dados or expirou_msg or (tick_anim and (animando or (not self.wizard and not self.modal))):
2742
2805
  self.atualizar_tela()
2743
2806
  continue
2744
2807
  # Coalescing de scroll/setas: drena eventos repetidos pendentes no buffer
@@ -2826,6 +2889,9 @@ class Painel:
2826
2889
  buf_antes = self.buf
2827
2890
  menu_antes = self._menu_aberto()
2828
2891
  if tecla == 'resize':
2892
+ self._cache_frame_base = None
2893
+ self._dialogo_frame = 99
2894
+ self._precisa_limpar_tela = True
2829
2895
  self.atualizar_tela()
2830
2896
  return
2831
2897
  if tecla in ('ctrl_p', 'ctrl_k'):
@@ -3255,6 +3321,10 @@ class Painel:
3255
3321
  cfg = ler_config()
3256
3322
  if cfg.get('dashboard_auto_open', True) is False:
3257
3323
  return
3324
+ # No Termux não tenta abrir navegador automaticamente na abertura
3325
+ # (o usuário ainda pode usar /web quando quiser).
3326
+ if tui_core.is_termux():
3327
+ return
3258
3328
  try:
3259
3329
  url = dashboard_web.local_dashboard_url(cfg)
3260
3330
  except (TypeError, ValueError):
@@ -4829,9 +4899,18 @@ class Painel:
4829
4899
  if achado:
4830
4900
  return achado
4831
4901
  nome = 'opencode.exe' if os.name == 'nt' else 'opencode'
4832
- local = Path.home() / '.opencode' / 'bin' / nome
4833
- if local.is_file():
4834
- return str(local)
4902
+ prefix = os.environ.get('PREFIX', '')
4903
+ candidatos = [
4904
+ Path.home() / '.opencode' / 'bin' / nome,
4905
+ Path.home() / '.local' / 'bin' / nome,
4906
+ Path.home() / '.bun' / 'bin' / nome,
4907
+ Path.home() / '.npm-global' / 'bin' / nome,
4908
+ ]
4909
+ if prefix:
4910
+ candidatos.append(Path(prefix) / 'bin' / nome)
4911
+ for local in candidatos:
4912
+ if local.is_file():
4913
+ return str(local)
4835
4914
  raise ValueError('OpenCode não encontrado — instale em https://opencode.ai e tente de novo')
4836
4915
 
4837
4916
  def executar_login_oauth_opencode(self, alvo: str, metodo: str):
package/tui_core.py CHANGED
@@ -142,7 +142,21 @@ class TerminalPosix:
142
142
  try:
143
143
  self._fd = sys.stdin.fileno()
144
144
  self._orig = termios.tcgetattr(self._fd)
145
- tty.setraw(self._fd)
145
+ # Raw mode na entrada, preservando OPOST (traducao \n -> \r\n) na saida.
146
+ # Sem OPOST, todo '\n' impresso em Linux/Termux vira escadinha horizontal
147
+ # (cada linha comeca onde a anterior terminou) e o zoom/resize corrompe a tela.
148
+ modo = termios.tcgetattr(self._fd)
149
+ modo[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK | termios.ISTRIP
150
+ | termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IXON)
151
+ modo[1] |= termios.OPOST
152
+ if hasattr(termios, 'ONLCR'):
153
+ modo[1] |= termios.ONLCR
154
+ modo[2] &= ~(termios.CSIZE | termios.PARENB)
155
+ modo[2] |= termios.CS8
156
+ modo[3] &= ~(termios.ECHO | termios.ECHONL | termios.ICANON | termios.ISIG | termios.IEXTEN)
157
+ modo[6][termios.VMIN] = 1
158
+ modo[6][termios.VTIME] = 0
159
+ termios.tcsetattr(self._fd, termios.TCSAFLUSH, modo)
146
160
  # Mouse SGR (1000=clique/roda, 1006=SGR) + bracketed paste (2004).
147
161
  # Nao liga 1003 (any-event hover) no Termux para evitar flood no touch.
148
162
  sys.stdout.write('\x1b[?1000h\x1b[?1006h\x1b[?2004h')
@@ -391,8 +405,8 @@ def desenhar_overlay_centrado(
391
405
 
392
406
  h_box = len(caixa_linhas)
393
407
  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)
408
+ top = max(0, (altura_tela - h_box) // 2)
409
+ left = max(0, (largura_tela - w_box) // 2)
396
410
 
397
411
  for offset, linha_box in enumerate(caixa_linhas):
398
412
  y = top + offset
@@ -443,7 +457,7 @@ def construir_dialogo_opencode(
443
457
  fundo = c.get('fundo', '#1e1e1e')
444
458
  texto_acento = c.get('texto_acento', '#0a0a0a')
445
459
 
446
- w = max(28, largura_caixa)
460
+ w = max(20, largura_caixa)
447
461
  inner = w - 2 # entre ┃ ... ┃
448
462
  bg = f' on {fundo}'
449
463
  linhas: list[Text] = []
@@ -465,7 +479,7 @@ def construir_dialogo_opencode(
465
479
 
466
480
  # Cabeçalho: título à esquerda + "esc" à direita (assinatura visual do OpenCode)
467
481
  esc_tag = 'esc '
468
- tit_max = max(8, inner - cell_len(esc_tag) - 2)
482
+ tit_max = max(4, inner - cell_len(esc_tag) - 3)
469
483
  tit_vis = truncate_vis(titulo, tit_max)
470
484
  gap_hdr = max(1, inner - 2 - cell_len(tit_vis) - cell_len(esc_tag))
471
485
  hdr = Text()
@@ -476,7 +490,7 @@ def construir_dialogo_opencode(
476
490
  linhas.append(frame_line(hdr))
477
491
 
478
492
  if subtitulo:
479
- sub_vis = truncate_vis(subtitulo, inner - 4)
493
+ sub_vis = truncate_vis(subtitulo, max(4, inner - 4))
480
494
  sub = Text()
481
495
  sub.append(' ' + sub_vis, style=f'{fraco}{bg}')
482
496
  linhas.append(frame_line(sub, max(0, inner - 2 - cell_len(sub_vis))))
@@ -485,7 +499,7 @@ def construir_dialogo_opencode(
485
499
  if mostrar_busca:
486
500
  linhas.append(frame_line(Text(' ' * inner, style=bg.strip())))
487
501
  busca_vis = ('•' * min(len(busca), 36)) if mascarar_busca else busca
488
- campo_max = max(8, inner - 6)
502
+ campo_max = max(4, inner - 6)
489
503
  campo_txt = truncate_vis(busca_vis, campo_max) if busca_vis else truncate_vis(placeholder, campo_max)
490
504
  row_b = Text()
491
505
  row_b.append(' ', style=bg.strip())
@@ -493,7 +507,7 @@ def construir_dialogo_opencode(
493
507
  row_b.append(campo_txt, style=f'{texto if busca_vis else fraco}{bg}')
494
508
  rest = max(0, inner - 4 - cell_len(campo_txt))
495
509
  linhas.append(frame_line(row_b, rest))
496
- sep = Text(' ' + '─' * max(4, inner - 4) + ' ', style=f'{borda}{bg}')
510
+ sep = Text(' ' + '─' * max(2, inner - 4) + ' ', style=f'{borda}{bg}')
497
511
  linhas.append(frame_line(sep))
498
512
 
499
513
  # Extrai índices selecionáveis e janela visível
@@ -501,9 +515,10 @@ def construir_dialogo_opencode(
501
515
  total_sel = len(selecionaveis)
502
516
 
503
517
  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)
518
+ # Só texto informativo ou lista vazia (respeita `limite` em telas baixas)
519
+ vis_txt = itens[:max(1, limite)] if limite else itens
520
+ for it in vis_txt:
521
+ txt = truncate_vis(str(it.get('rotulo') or ''), max(4, inner - 4))
507
522
  cor = it.get('cor') or fraco
508
523
  t = Text()
509
524
  t.append(' ' + txt, style=f'{cor}{bg}')