krnell 3.0.5 → 3.0.6

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
@@ -44,7 +44,7 @@ class MonitorAtualizacao:
44
44
  """Checa em segundo plano; falha de rede nunca interfere na TUI."""
45
45
 
46
46
  def __init__(self, versao_atual: str, pacote: str = 'krnell', *,
47
- intervalo: float = 6 * 60 * 60, abridor=None):
47
+ intervalo: float = 90.0, abridor=None):
48
48
  self.versao_atual = str(versao_atual)
49
49
  self.pacote = pacote
50
50
  self.intervalo = float(intervalo)
@@ -55,11 +55,17 @@ class MonitorAtualizacao:
55
55
  self._disponivel = None
56
56
  self._estado = 'unknown'
57
57
  self._verificando = False
58
+ self._revisao = 0
58
59
  self._url = os.environ.get(
59
60
  'KRNELL_UPDATE_URL',
60
61
  f'https://registry.npmjs.org/{quote(pacote, safe="@")}/latest',
61
62
  )
62
63
 
64
+ @property
65
+ def revisao(self) -> int:
66
+ with self._lock:
67
+ return self._revisao
68
+
63
69
  @property
64
70
  def estado(self) -> str:
65
71
  with self._lock:
@@ -109,10 +115,13 @@ class MonitorAtualizacao:
109
115
  if not _SEMVER.fullmatch(candidata):
110
116
  raise ValueError('registry sem versão semver')
111
117
  with self._lock:
112
- self._disponivel = (
118
+ novo = (
113
119
  {'version': candidata, 'current': self.versao_atual}
114
120
  if versao_mais_nova(self.versao_atual, candidata) else None
115
121
  )
122
+ if novo != self._disponivel:
123
+ self._revisao += 1
124
+ self._disponivel = novo
116
125
  self._estado = 'available' if self._disponivel else 'up_to_date'
117
126
  except Exception:
118
127
  # Update é opcional: DNS, TLS e registry fora do ar ficam invisíveis.
package/bin/krnell.mjs CHANGED
@@ -12,7 +12,7 @@
12
12
  * krnell upgrade atualiza o pacote via npm (`npm i -g krnell@latest`)
13
13
  * krnell --version exibe versao do Krnell
14
14
  */
15
- import { spawnSync } from 'node:child_process';
15
+ import { spawn, spawnSync } from 'node:child_process';
16
16
  import fs from 'node:fs';
17
17
  import path from 'node:path';
18
18
  import { fileURLToPath } from 'node:url';
@@ -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.5';
80
+ return pkg.version || '3.0.6';
81
81
  } catch {
82
- return '3.0.5';
82
+ return '3.0.6';
83
83
  }
84
84
  }
85
85
 
@@ -139,19 +139,67 @@ if (args[0] === 'upgrade' || args[0] === 'update') {
139
139
  return 'krnell';
140
140
  }
141
141
  })();
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)...`);
142
+ const atual = lerVersao();
143
+ const ehTty = Boolean(process.stdout.isTTY);
144
+ const cor = (c, s) => (ehTty ? `\x1b[${c}m${s}\x1b[0m` : s);
145
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
146
+
147
+ const comSpinner = async (texto, fn) => {
148
+ if (!ehTty) return await fn();
149
+ let i = 0;
150
+ process.stdout.write('\x1b[?25l');
151
+ const desenhar = () => {
152
+ const sp = cor('38;5;216', frames[i++ % frames.length]);
153
+ process.stdout.write(`\r\x1b[2K ${sp} ${texto}`);
154
+ };
155
+ desenhar();
156
+ const t = setInterval(desenhar, 80);
157
+ try {
158
+ return await fn();
159
+ } finally {
160
+ clearInterval(t);
161
+ process.stdout.write('\r\x1b[2K\x1b[?25h');
162
+ }
163
+ };
164
+
165
+ const alvoArg = (args[1] || '').trim().replace(/^v/, '');
166
+ const alvo = alvoArg || await comSpinner('Checking latest version…', () => resolverUltimaVersao(pkgName));
167
+ if (alvo && alvo === atual && !alvoArg) {
168
+ console.log(`\n ${cor('38;5;114', '✓')} ${cor('1', 'krnell')} ${cor('90', `v${atual} is already the latest`)}\n`);
169
+ process.exit(0);
170
+ }
171
+ const spec = alvo ? `${pkgName}@${alvo}` : `${pkgName}@latest`;
172
+ const destinoLabel = alvo ? `v${alvo}` : 'latest';
173
+ if (ehTty) {
174
+ console.log('');
175
+ console.log(` ${cor('1;38;5;216', '◈')} ${cor('1', 'krnell')} ${cor('90', `v${atual} → ${destinoLabel}`)}`);
176
+ }
177
+
145
178
  const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
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
- );
154
- process.exit(r.status ?? 1);
179
+ const res = await comSpinner(`Upgrading to ${destinoLabel}…`, () => new Promise((resolve) => {
180
+ const child = spawn(
181
+ npmCmd,
182
+ ['install', '-g', spec, '--prefer-online', '--no-audit', '--no-fund'],
183
+ {
184
+ stdio: ['ignore', 'pipe', 'pipe'],
185
+ env: { ...process.env, NO_UPDATE_NOTIFIER: '1', NPM_CONFIG_FUND: 'false', NPM_CONFIG_AUDIT: 'false' },
186
+ },
187
+ );
188
+ let out = '';
189
+ let err = '';
190
+ child.stdout.on('data', (d) => { out += d; });
191
+ child.stderr.on('data', (d) => { err += d; });
192
+ child.on('error', (e) => resolve({ status: 1, out, err: String(e?.message || e) }));
193
+ child.on('close', (status) => resolve({ status: status ?? 1, out, err }));
194
+ }));
195
+
196
+ if (res.status === 0) {
197
+ console.log(` ${cor('38;5;114', '✓')} Upgrade complete ${cor('90', `(${destinoLabel})`)}\n`);
198
+ process.exit(0);
199
+ }
200
+ const detalhe = (res.err || res.out || 'npm install failed').trim().split('\n').slice(-2).join(' · ');
201
+ console.error(` ${cor('38;5;203', '✗')} Upgrade failed ${cor('90', detalhe)}\n`);
202
+ process.exit(res.status || 1);
155
203
  }
156
204
 
157
205
  if (process.platform === 'win32') {
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.5'
62
+ BRIDGE_VERSION = '3.0.6'
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
@@ -2007,9 +2007,10 @@ class BridgeState:
2007
2007
  # -- contador ao vivo (painel) ------------------------------------------
2008
2008
  # Mesma semântica do opencode (session.tps): saída exata vem do usage do
2009
2009
  # provedor; durante a geração o painel vê uma estimativa por caracteres.
2010
- def live_inicio(self, rid: str, rota: str, stream: bool):
2010
+ def live_inicio(self, rid: str, rota: str, stream: bool, modelo: str = ''):
2011
2011
  with self._live_lock:
2012
2012
  self.live[rid] = {'id': rid, 'rota': rota, 'stream': bool(stream),
2013
+ 'modelo': str(modelo or '').strip(),
2013
2014
  'inicio': time.monotonic(), 'primeiro': None,
2014
2015
  'chars': 0, 'uso': None, 'idx': None}
2015
2016
 
@@ -2079,6 +2080,7 @@ class BridgeState:
2079
2080
  conta = self.targets[item['idx']].get('name')
2080
2081
  ativas.append({'id': item['id'], 'rota': item['rota'],
2081
2082
  'stream': item['stream'], 'conta': conta,
2083
+ 'modelo': item.get('modelo') or '',
2082
2084
  'segundos': round(agora - item['inicio'], 1),
2083
2085
  'tokens_out': saida, 'exato': bool(saida_exata),
2084
2086
  'tok_s': round(saida / dur, 1) if saida else None})
@@ -4497,6 +4499,7 @@ class Handler(BaseHTTPRequestHandler):
4497
4499
  'ms': int((time.monotonic() - started) * 1000) if started else None,
4498
4500
  'stream': bool(fields.get('stream', getattr(self, '_bridge_stream', False))),
4499
4501
  'provider': cfg.get('provider'),
4502
+ 'model': fields.get('model') or getattr(self, '_bridge_req_model', None) or cfg.get('model_enviado') or cfg.get('upstream_model'),
4500
4503
  'account': fields.get('account'),
4501
4504
  'attempts': fields.get('attempts'),
4502
4505
  'tokens': fields.get('tokens'),
@@ -4892,8 +4895,10 @@ class Handler(BaseHTTPRequestHandler):
4892
4895
  chat = anthropic_request(payload)
4893
4896
  messages = None
4894
4897
  self._bridge_stream = bool(chat['stream'])
4898
+ modelo_req = str(chat.get('model') or payload.get('model') or cfg.get('model_enviado') or '').strip()
4899
+ self._bridge_req_model = modelo_req
4895
4900
  self._bridge_stage = 'upstream_connect'
4896
- state.live_inicio(trace, route, chat['stream'])
4901
+ state.live_inicio(trace, route, chat['stream'], modelo=modelo_req)
4897
4902
  # Modo streaming: com o modelo em 'error', envia comentarios SSE
4898
4903
  # (heartbeats) durante as esperas de 60s para reduzir timeouts idle.
4899
4904
  # Nunca tenta inferencia enquanto o painel estiver em 'error'.
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.5"
30
+ echo "krnell v3.0.6"
31
31
  exit 0
32
32
  ;;
33
33
  upgrade|update)
package/opencode_sync.py CHANGED
@@ -156,10 +156,13 @@ def _substituir_ou_inserir_provedor(texto: str, provider_id: str, bloco: str) ->
156
156
  fim = i + 1
157
157
  break
158
158
  if fim > brace:
159
- # Mantém linha inicial limpa
159
+ # Substitui apenas o trecho `"provider_id": { ... }`, preservando
160
+ # qualquer texto na mesma linha antes da chave (ex.: JSON em 1 linha).
160
161
  lin_ini = texto.rfind('\n', 0, idx)
161
- inicio = lin_ini + 1 if lin_ini >= 0 else idx
162
- novo = texto[:inicio] + bloco + texto[fim:]
162
+ prefixo_linha = texto[lin_ini + 1:idx] if lin_ini >= 0 else texto[:idx]
163
+ inicio = (lin_ini + 1) if (lin_ini >= 0 and not prefixo_linha.strip()) else idx
164
+ novo = texto[:inicio] + bloco.lstrip() if inicio == idx else texto[:inicio] + bloco
165
+ novo += texto[fim:]
163
166
  return novo, novo != texto
164
167
  m = re.search(r'"providers"\s*:\s*\{', texto)
165
168
  if m:
@@ -212,7 +215,7 @@ def opencode_detectado() -> bool:
212
215
 
213
216
 
214
217
  def opencode_ja_configurado(porta: int = 8765) -> bool:
215
- """True se opencode.json(c) já tem `krnell` atualizado na porta com visão NVIDIA."""
218
+ """True se opencode.json(c) já tem `krnell` atualizado na porta com visão NVIDIA + plugin TUI."""
216
219
  esperado = f'http://127.0.0.1:{int(porta)}/v1'
217
220
  modelos_visao = ('kimi-k3.1-pro', 'minimax-m3.1-flash')
218
221
  for arq in candidatos_config_opencode():
@@ -239,15 +242,56 @@ def opencode_ja_configurado(porta: int = 8765) -> bool:
239
242
  modelos = bloco.get('models')
240
243
  if not isinstance(modelos, dict):
241
244
  continue
242
- if all(
245
+ if not all(
243
246
  isinstance(modelos.get(mid), dict)
244
247
  and 'image' in ((modelos[mid].get('capabilities') or {}).get('input') or [])
245
248
  for mid in modelos_visao
249
+ ):
250
+ continue
251
+ # Exige também o plugin TUI instalado (tui.tsx + package.json) e registrado em cli.json
252
+ cfg_dir = arq.parent
253
+ plugin_dir = cfg_dir / 'plugins' / 'system-prompt'
254
+ if not ((plugin_dir / 'tui.tsx').is_file() and (plugin_dir / 'package.json').is_file()):
255
+ continue
256
+ cli_path = cfg_dir / 'cli.json'
257
+ if not cli_path.is_file():
258
+ continue
259
+ try:
260
+ cli_dados = json.loads(cli_path.read_text(encoding='utf-8'))
261
+ except Exception:
262
+ continue
263
+ lista_cli = cli_dados.get('plugins') if isinstance(cli_dados, dict) else None
264
+ alvo_dir = str(plugin_dir.resolve())
265
+ if isinstance(lista_cli, list) and any(
266
+ str(Path(x).resolve()) == alvo_dir for x in lista_cli if isinstance(x, str)
246
267
  ):
247
268
  return True
248
269
  return False
249
270
 
250
271
 
272
+ def _registrar_plugin_tui_cli_json(cfg_dir: Path, plugin_dir: str) -> None:
273
+ """Adiciona o plugin TUI do Krnell em cli.json sem apagar preferências existentes."""
274
+ cli_path = cfg_dir / 'cli.json'
275
+ try:
276
+ dados = json.loads(cli_path.read_text(encoding='utf-8')) if cli_path.is_file() else {
277
+ '$schema': 'https://opencode.ai/v2/cli.json',
278
+ }
279
+ if not isinstance(dados, dict):
280
+ return
281
+ except Exception:
282
+ return
283
+ lista = dados.get('plugins')
284
+ if not isinstance(lista, list):
285
+ lista = []
286
+ if plugin_dir not in lista:
287
+ lista.append(plugin_dir)
288
+ dados['plugins'] = lista
289
+ try:
290
+ cli_path.write_text(json.dumps(dados, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
291
+ except OSError:
292
+ pass
293
+
294
+
251
295
  def configurar_opencode(raiz: Path, porta: int = 8765, api_key: str = '') -> dict:
252
296
  """Instala o plugin system-prompt e registra o provedor `krnell` no OpenCode."""
253
297
  raiz = Path(raiz).resolve()
@@ -256,15 +300,22 @@ def configurar_opencode(raiz: Path, porta: int = 8765, api_key: str = '') -> dic
256
300
  cfg_dir = arq.parent
257
301
  cfg_dir.mkdir(parents=True, exist_ok=True)
258
302
 
259
- # 1) Plugin system-prompt
260
- src_plugin = raiz / 'plugins' / 'system-prompt' / 'index.ts'
303
+ # 1) Plugin unificado (server: system-prompt + auto-start sob demanda; TUI: botão ◈ krnell no footer)
304
+ src_plugin_dir = raiz / 'plugins' / 'system-prompt'
305
+ src_plugin = src_plugin_dir / 'index.ts'
261
306
  dst_plugin_dir = cfg_dir / 'plugins' / 'system-prompt'
262
307
  dst_plugin = dst_plugin_dir / 'index.ts'
263
308
  plugin_instalado = False
264
309
  if src_plugin.exists():
265
310
  dst_plugin_dir.mkdir(parents=True, exist_ok=True)
266
- shutil.copy2(src_plugin, dst_plugin)
311
+ for arq_p in ('index.ts', 'tui.tsx', 'package.json'):
312
+ origem_p = src_plugin_dir / arq_p
313
+ destino_p = dst_plugin_dir / arq_p
314
+ if origem_p.is_file() and origem_p.resolve() != destino_p.resolve():
315
+ shutil.copy2(origem_p, destino_p)
267
316
  plugin_instalado = True
317
+ # Registra o plugin TUI também em cli.json (slot home.footer.status + comando /krnell)
318
+ _registrar_plugin_tui_cli_json(cfg_dir, str(dst_plugin_dir))
268
319
 
269
320
  # 2) AGENTS.md se existir na raiz e ainda nao existir no OpenCode
270
321
  src_agents = raiz / 'AGENTS.md'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "krnell",
3
- "version": "3.0.5",
3
+ "version": "3.0.6",
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
@@ -526,7 +526,19 @@ def _fmt_bucket_curto(b: dict | None, prefixo: str, com_reset: bool = True) -> t
526
526
  _SPIN_BRAILLE = ('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏')
527
527
  _PULSO_ONLINE = ('●', '●', '●', '◉', '◉', '●')
528
528
  _ONDA_LIVE = ('▁▂▃▄', '▂▃▄▅', '▃▄▅▆', '▄▅▆▇', '▅▆▇▆', '▆▇▆▅', '▇▆▅▄', '▆▅▄▃', '▅▄▃▂', '▄▃▂▁')
529
- _GLIFO_MARCA = ('◈', '◈', '◇', '◈', '◈', '◈', '◈', '◈')
529
+ _GLIFO_MARCA = ('◈',)
530
+ # Wordmark pixel-block estilo OpenCode (duas cores: "krn" + "ell", 30 cols)
531
+ _LOGO_KRNELL = (
532
+ ('█ ▄▀ █▀▀▄ █▀▀▄ ', '█▀▀█ █ █ '),
533
+ ('█▄▀ █▄▄▀ █ █ ', '█▀▀ █ █ '),
534
+ ('█ ▀▄ █ █ █ █ ', '▀▀▀▀ ▀▀▀▀ ▀▀▀▀'),
535
+ )
536
+ _DICAS_HOME = (
537
+ '/ commands · /connect · /model',
538
+ 'Try "/model" to switch between NVIDIA & Antigravity',
539
+ 'Try "/quota" to inspect live 5h & 7d quotas',
540
+ 'Try "/connect" to add API keys or Google OAuth',
541
+ )
530
542
 
531
543
 
532
544
  def versao_local() -> str:
@@ -1133,6 +1145,7 @@ class Painel:
1133
1145
  self.proc = None
1134
1146
  self.tarefa_ativa = False
1135
1147
  self.saindo = False
1148
+ self._sair_em_background = False # Ctrl+C fecha TUI mantendo bridge vivo; /exit para tudo
1136
1149
  self.revisao_vista = -1
1137
1150
  self.scroll = 0
1138
1151
  self.ultima_acao = None
@@ -1169,12 +1182,20 @@ class Painel:
1169
1182
  self._ag_auth_state = ''
1170
1183
  self._anim_tick = 0
1171
1184
  self._anim_ultimo = 0.0
1185
+ self._intro_frame = 0 # animação de abertura do logo/tela (0..3)
1186
+ self._fechar_overlay_frame = 0 # animação rápida de fechamento (0=inativo)
1187
+ self._fechar_overlay_linhas: list[str] = []
1188
+ self._digito_pulso = 0.0 # timestamp do último caractere digitado (brilho no prompt ▸)
1189
+ self._dica_idx = 0
1190
+ self._dica_chars = 0
1191
+ self._dica_ultimo = 0.0
1172
1192
  self._dialogo_frame = 0 # animacao de abertura do dialogo
1173
1193
  self._dialogo_id = None
1174
1194
  self._reexec_solicitado = False # /restart na TUI reexecuta painel.py do zero
1175
1195
  self._reexec_comando = None # update reabre pelo entrypoint npm recém-instalado
1176
1196
  self._restart_overlay = None # estado da animacao de reinicio estilo OpenCode
1177
1197
  self.atualizacoes = atualizador.MonitorAtualizacao(versao_local())
1198
+ self._update_revisao_vista = -1
1178
1199
  self._update_zona = None # (y, x inicial, x final) do pill opcional no header
1179
1200
  self._update_hover = False
1180
1201
  self.modo = 'repl'
@@ -1275,7 +1296,7 @@ class Painel:
1275
1296
  cab.add_column(ratio=1, no_wrap=True)
1276
1297
  cab.add_column(justify='right', no_wrap=True)
1277
1298
  titulo = Text()
1278
- glifo = _GLIFO_MARCA[tick % len(_GLIFO_MARCA)] if online else '◇'
1299
+ glifo = '◈' if online else '◇'
1279
1300
  titulo.append(f'{glifo} ', style=f'bold {ACENTO}')
1280
1301
  titulo.append('krnell', style=f'bold {TEXTO}')
1281
1302
  if largura >= 34:
@@ -1303,17 +1324,42 @@ class Painel:
1303
1324
  self._update_zona = (0, inicio, inicio + cell_len(rotulo_update) - 1)
1304
1325
  cab.add_row(titulo, estado)
1305
1326
 
1327
+ # Wordmark pixel-block "krnell" centralizado estilo OpenCode (com espaço vertical)
1328
+ logo_blocos: list = []
1329
+ if largura >= 36 and altura >= 16:
1330
+ intro = getattr(self, '_intro_frame', 99)
1331
+ mostrar_linhas = 3 if intro >= 3 else max(1, intro + 1)
1332
+ pad_logo = ' ' * max(0, (largura - 30) // 2)
1333
+ for idx_l, (esq_l, dir_l) in enumerate(_LOGO_KRNELL[:mostrar_linhas]):
1334
+ tl = Text(no_wrap=True)
1335
+ tl.append(pad_logo)
1336
+ tl.append(esq_l, style=f'bold {FRACO if intro == 0 else TEXTO}')
1337
+ tl.append(dir_l, style=f'bold {ACENTO}')
1338
+ logo_blocos.append(tl)
1339
+ if disponivel:
1340
+ pill = f" ↑ update v{disponivel['version']} available · tap or /update "
1341
+ pill_vis = tui_core.truncate_vis(pill, max(16, largura - 2))
1342
+ pad_p = ' ' * max(0, (largura - cell_len(pill_vis)) // 2)
1343
+ tp = Text(no_wrap=True)
1344
+ tp.append(pad_p)
1345
+ tp.append(pill_vis, style=f'bold {ACENTO3 if self._update_hover else ACENTO} on {FUNDO}')
1346
+ logo_blocos.append(tp)
1347
+ logo_blocos.append(Text(''))
1348
+
1306
1349
  usar_overlay = self.modo == 'tui'
1307
1350
  menu_render = self._render_menu()
1308
1351
  modais_render = [] if usar_overlay else self._render_modais(largura)
1309
1352
  extra = sum(len(self._linhas(x, largura)) for x in (menu_render, modais_render) if x)
1310
- espaco_corpo = max(5, altura - 7 - extra)
1311
- info_compacta = self._info_compacta(snap, online, status, cfg, provedor) if largura < 96 else []
1312
- if espaco_corpo < len(info_compacta) + 5:
1353
+ # Só usa layout de 2 colunas quando houver largura real confortável para ambas
1354
+ # (evita quebrar "7d 20.9%" em 2 linhas no meio do zoom do celular).
1355
+ duas_colunas = largura >= 108
1356
+ espaco_corpo = max(4, altura - 7 - len(logo_blocos) - extra)
1357
+ info_compacta = self._info_compacta(snap, online, status, cfg, provedor) if not duas_colunas else []
1358
+ if espaco_corpo < len(info_compacta) + 4:
1313
1359
  info_compacta = info_compacta[:1]
1314
1360
  linhas_req = max(2, min(espaco_corpo - len(info_compacta), 48))
1315
- estreito = largura < 74
1316
- ultra_estreito = largura < 46
1361
+ estreito = largura < 78
1362
+ ultra_estreito = largura < 48
1317
1363
 
1318
1364
  reqs = snap.get('requests') or []
1319
1365
  visiveis = max(1, linhas_req - 1)
@@ -1359,8 +1405,9 @@ class Painel:
1359
1405
  obs = Text(str(evento.get('error') or ('stream' if evento.get('stream') else '')),
1360
1406
  style=ERRO if evento.get('error') else FRACO)
1361
1407
  hora = fmt_hora(evento.get('ts'))
1408
+ rotulo_ev = str(evento.get('model') or evento.get('account') or '—')
1362
1409
  linha_req(hora[:5] if estreito else hora, cel_codigo,
1363
- str(evento.get('account') or evento.get('model') or '—'),
1410
+ rotulo_ev,
1364
1411
  fmt_duracao(evento.get('ms')), fmt_tokens(evento.get('tokens')), obs)
1365
1412
  for item in em_voo:
1366
1413
  sp = _SPIN_BRAILLE[tick % len(_SPIN_BRAILLE)]
@@ -1369,8 +1416,9 @@ class Painel:
1369
1416
  style=ACENTO2 if item.get('tok_s') else AVISO)
1370
1417
  saida = (('~' if not item.get('exato') else '') + fmt_tokens_grande(item['tokens_out'])
1371
1418
  if item.get('tokens_out') else '—')
1419
+ rotulo_live = str(item.get('modelo') or item.get('model') or item.get('conta') or item.get('rota') or '—')
1372
1420
  linha_req(Text('now', style=ACENTO2), Text(f'{sp} live', style=ACENTO2),
1373
- str(item.get('conta') or item.get('rota') or '—'),
1421
+ rotulo_live,
1374
1422
  fmt_duracao((item.get('segundos') or 0) * 1000), saida, obs_live)
1375
1423
  vazio_row = ('', '', '', '', '', '')[:len(tabela.columns)]
1376
1424
  for _ in range(max(0, visiveis - len(fatia) - len(em_voo))):
@@ -1388,10 +1436,17 @@ class Painel:
1388
1436
  atividade.add_row(tabela)
1389
1437
 
1390
1438
  renderaveis = [cab, Text('')]
1391
- if largura >= 96:
1439
+ renderaveis.extend(logo_blocos)
1440
+ if disponivel and logo_blocos:
1441
+ # Guarda zona clicável do banner central de update também
1442
+ y_banner = 2 + len(_LOGO_KRNELL)
1443
+ self._update_banner_zona = (y_banner, 0, max(0, largura - 1))
1444
+ else:
1445
+ self._update_banner_zona = None
1446
+ if duas_colunas:
1392
1447
  grade = Table.grid(expand=True, padding=(0, 2, 0, 0))
1393
1448
  grade.add_column(ratio=3)
1394
- grade.add_column(ratio=1)
1449
+ grade.add_column(min_width=30, ratio=1)
1395
1450
  grade.add_row(atividade, self._lado_minimo(snap, online, status))
1396
1451
  renderaveis.append(grade)
1397
1452
  else:
@@ -1416,19 +1471,19 @@ class Painel:
1416
1471
 
1417
1472
  def _lado_minimo(self, snap: dict, online: bool, status: dict) -> Text:
1418
1473
  """Apenas dados vivos; diagnóstico e pool detalhado ficam em /status."""
1419
- lado = Text()
1474
+ lado = Text(no_wrap=True, overflow='ellipsis')
1420
1475
  ag_status = snap.get('ag_status') if isinstance(snap.get('ag_status'), dict) else {}
1421
1476
  resumo = _resumo_cota_antigravity(ag_status)
1422
1477
  if resumo:
1423
1478
  lado.append('Antigravity\n', style=FRACO)
1424
1479
  for item in resumo[:2]:
1425
- lado.append(f"{item['nome']:<8}", style=TEXTO)
1480
+ lado.append(f"{item['nome']:<7}", style=TEXTO)
1426
1481
  t5, c5 = _fmt_bucket_curto(item.get('b5h'), '5h', com_reset=False)
1427
1482
  ts, cs = _fmt_bucket_curto(item.get('bsem'), '7d', com_reset=False)
1428
1483
  if t5:
1429
1484
  lado.append(t5, style=c5)
1430
1485
  if t5 and ts:
1431
- lado.append(' ', style=BORDA)
1486
+ lado.append(' ', style=BORDA)
1432
1487
  if ts:
1433
1488
  lado.append(ts, style=cs)
1434
1489
  lado.append('\n')
@@ -2381,12 +2436,14 @@ class Painel:
2381
2436
  self.menu_off = False
2382
2437
  self.menu_sel = 0
2383
2438
  return True
2384
- # Tocar na linha de cotas da home (linha 3 em telas estreitas ou coluna direita) abre /quota
2439
+ # Tocar na linha de cotas da home (logo abaixo do cabeçalho/logo) abre /quota
2385
2440
  if not self._menu_aberto():
2386
- if self.largura < 96 and y == 3:
2441
+ y_cota = 3 + (len(_LOGO_KRNELL) + 1 + (1 if self.atualizacoes.disponivel else 0)
2442
+ if (self.largura >= 36 and self.altura >= 16) else 0)
2443
+ if self.largura < 108 and y == y_cota:
2387
2444
  self.mostrar_tokens()
2388
2445
  return True
2389
- if self.largura >= 96 and y in (2, 3, 4) and x >= int(self.largura * 0.72):
2446
+ if self.largura >= 108 and y >= 2 and x >= int(self.largura * 0.72):
2390
2447
  self.mostrar_tokens()
2391
2448
  return True
2392
2449
  return False
@@ -2427,11 +2484,19 @@ class Painel:
2427
2484
  return True
2428
2485
 
2429
2486
  def ponto_no_botao_update(self, x: int, y: int) -> bool:
2430
- zona = self._update_zona
2431
- if not zona or self.modal or self.wizard or self._restart_overlay:
2487
+ if self.modal or self.wizard or self._restart_overlay:
2432
2488
  return False
2433
- linha, inicio, fim = zona
2434
- return y == linha and inicio <= x <= fim
2489
+ zona = self._update_zona
2490
+ if zona:
2491
+ linha, inicio, fim = zona
2492
+ if y == linha and inicio <= x <= fim:
2493
+ return True
2494
+ banner = getattr(self, '_update_banner_zona', None)
2495
+ if banner:
2496
+ linha_b, ini_b, fim_b = banner
2497
+ if y == linha_b and ini_b <= x <= fim_b:
2498
+ return True
2499
+ return False
2435
2500
 
2436
2501
  def clicar_botao_update(self, x: int, y: int) -> bool:
2437
2502
  if not self.ponto_no_botao_update(x, y):
@@ -2557,9 +2622,10 @@ class Painel:
2557
2622
  buf.append(f'\x1b[{base + 3};1H\x1b[2K' + ansi('borda') + '╰' + regua + '╯' + RESET)
2558
2623
  self._status_y = base + 3
2559
2624
  buf.append(f'\x1b[{base + 4};1H\x1b[2K' + self._barra_status() + '\x1b[J')
2560
- # Quando um menu ou modal ocupa a caixa, oculta o cursor nativo para não
2561
- # deixar um bloquinho branco piscando no meio da tela.
2562
- if self.modal or (self.wizard and self._wizard_lista()):
2625
+ # Oculta o cursor nativo do terminal em listas/modais e quando a caixa está
2626
+ # vazia (evita o ponto/bloco branco piscando sozinho no Termux/celular).
2627
+ mostrar_cursor = bool(self.buf) or (self.wizard and not self._wizard_lista())
2628
+ if self.modal or not mostrar_cursor:
2563
2629
  buf.append('\x1b[?25l\x1b[?2026l')
2564
2630
  else:
2565
2631
  coluna = min(getattr(self, '_coluna_cursor', 5), max(2, largura - 1))
@@ -2817,22 +2883,34 @@ class Painel:
2817
2883
  visivel = self._texto_entrada()
2818
2884
  largura = self.largura
2819
2885
  contagem = cell_len(visivel)
2886
+ # Pulso visual sutil no "▸" enquanto o usuário digita
2887
+ pulso_ativo = (time.monotonic() - getattr(self, '_digito_pulso', 0.0)) < 0.16
2888
+ cor_prompt = 'acento3' if pulso_ativo else 'acento'
2820
2889
  partes = [
2821
2890
  f'\x1b[{linha};1H\x1b[2K',
2822
- ansi('borda'), '│', RESET, ' ', ansi('acento'), '▸ ', RESET,
2891
+ ansi('borda'), '│', RESET, ' ', ansi(cor_prompt), '▸ ', RESET,
2823
2892
  ]
2824
2893
  if visivel:
2825
2894
  partes.extend([ansi('texto'), visivel, RESET])
2895
+ # Cursor de digitação limpo (barra fina) quando há texto sendo digitado
2896
+ if pulso_ativo and contagem + 1 <= max(1, largura - 6):
2897
+ partes.extend([ansi('acento'), '▏', RESET])
2898
+ contagem += 1
2826
2899
  elif self._wizard_lista():
2827
2900
  dica = 'filtrar…'
2828
2901
  partes.extend([ansi('fraco'), dica, RESET])
2829
2902
  contagem = cell_len(dica)
2830
2903
  elif not self.wizard:
2831
- dica = '/ commands · Ctrl+L connect · Ctrl+P palette'
2832
- if cell_len(dica) > largura - 8:
2833
- dica = '/ commands · /connect'
2834
- if cell_len(dica) > largura - 8:
2835
- dica = '/help'
2904
+ dica_cheia = _DICAS_HOME[getattr(self, '_dica_idx', 0) % len(_DICAS_HOME)]
2905
+ if cell_len(dica_cheia) > largura - 8:
2906
+ dica_cheia = '/ commands · /connect'
2907
+ if cell_len(dica_cheia) > largura - 8:
2908
+ dica_cheia = '/help'
2909
+ n_chars = getattr(self, '_dica_chars', len(dica_cheia))
2910
+ if n_chars <= 0 or n_chars >= len(dica_cheia):
2911
+ dica = dica_cheia
2912
+ else:
2913
+ dica = dica_cheia[:n_chars] + '▏'
2836
2914
  dica = tui_core.truncate_vis(dica, max(1, largura - 7))
2837
2915
  partes.extend([ansi('fraco'), dica, RESET])
2838
2916
  contagem = cell_len(dica)
@@ -2862,8 +2940,8 @@ class Painel:
2862
2940
  # Cache do frame base: quando um diálogo está aberto e os dados não mudaram,
2863
2941
  # reaproveita o fundo esmaecido sem re-renderizar tabela/painéis Rich a cada seta/scroll.
2864
2942
  em_restart = bool(getattr(self, '_restart_overlay', None))
2865
- chave_base = (self.largura, self.altura, self.coletor.revisao, self.scroll,
2866
- TEMA_ATUAL, self._anim_tick if not tem_overlay else 0)
2943
+ chave_base = (self.largura, self.altura, self.coletor.revisao, self.atualizacoes.revisao,
2944
+ self.scroll, TEMA_ATUAL, self._anim_tick if not tem_overlay else 0)
2867
2945
  cache = getattr(self, '_cache_frame_base', None)
2868
2946
  if tem_overlay and cache and cache[0] == chave_base:
2869
2947
  frame = list(cache[1])
@@ -2884,15 +2962,19 @@ class Painel:
2884
2962
  self._overlay_width = 0
2885
2963
  self._overlay_height = 0
2886
2964
  self._overlay_clique = {}
2887
- # Quando um diálogo novo abre na TUI, anima brevemente a revelação (slide/expand)
2888
- # Em telas pequenas/estreitas (Termux/celular) ou após resize, pula o slide para
2889
- # nunca sobrepor dois quadros parciais.
2965
+ # Quando um diálogo novo abre na TUI, anima a abertura (2 frames rápidos,
2966
+ # inclusive no celular, pois cada linha agora usa \x1b[row;1H\x1b[2K limpo).
2890
2967
  modal_identidade = ('tokens-live' if (self.modal or {}).get('tipo') == 'tokens' else id(self.modal))
2891
2968
  dialogo_atual = (id(self.wizard), (self.wizard or {}).get('tipo'), (self.wizard or {}).get('passo'), modal_identidade, em_restart)
2892
2969
  if tem_overlay and dialogo_atual != getattr(self, '_dialogo_id', None):
2893
2970
  self._dialogo_id = dialogo_atual
2894
- self._dialogo_frame = 99 if (self.largura < 80 or self.altura < 24 or tui_core.is_termux()) else 0
2971
+ self._dialogo_frame = 0 if (self.altura >= 14 and not em_restart) else 99
2972
+ self._fechar_overlay_frame = 0
2895
2973
  elif not tem_overlay:
2974
+ if getattr(self, '_dialogo_id', None) is not None and getattr(self, '_ultimo_overlay_linhas', None):
2975
+ self._fechar_overlay_linhas = list(self._ultimo_overlay_linhas)
2976
+ self._fechar_overlay_frame = 1
2977
+ self._ultimo_overlay_linhas = []
2896
2978
  self._dialogo_id = None
2897
2979
  self._dialogo_frame = 99
2898
2980
  # Em telas baixas, garante que o frame do overlay nunca passe da area util
@@ -2903,11 +2985,12 @@ class Painel:
2903
2985
  if len(caixa_linhas) > limite and limite >= 4:
2904
2986
  caixa_linhas = caixa_linhas[:limite - 1] + [caixa_linhas[-1]]
2905
2987
  mapa_clique = {k: v for k, v in mapa_clique.items() if k < limite - 1}
2906
- # Animação de entrada suave (2 frames rápidos, sem travar teclado)
2907
- if getattr(self, '_dialogo_frame', 99) < 2 and len(caixa_linhas) > 6:
2988
+ self._ultimo_overlay_linhas = list(caixa_linhas)
2989
+ # Animação de abertura suave (2 frames rápidos, sem travar teclado)
2990
+ if getattr(self, '_dialogo_frame', 99) < 2 and len(caixa_linhas) > 5:
2908
2991
  passo_a = self._dialogo_frame
2909
2992
  self._dialogo_frame += 1
2910
- recorte = max(4, int(len(caixa_linhas) * (0.55 if passo_a == 0 else 0.82)))
2993
+ recorte = max(4, int(len(caixa_linhas) * (0.50 if passo_a == 0 else 0.80)))
2911
2994
  caixa_vis = caixa_linhas[:recorte - 1] + [caixa_linhas[-1]]
2912
2995
  else:
2913
2996
  caixa_vis = caixa_linhas
@@ -2938,12 +3021,27 @@ class Painel:
2938
3021
  self._registrar_menu(frame, cortado)
2939
3022
  self._registrar_wizard(frame, cortado)
2940
3023
  self._registrar_modal(frame, cortado)
3024
+ elif getattr(self, '_fechar_overlay_frame', 0) > 0 and getattr(self, '_fechar_overlay_linhas', None):
3025
+ # Transição rápida de fechamento (1 frame encolhendo a caixa antes de sumir)
3026
+ caixa_ant = self._fechar_overlay_linhas
3027
+ self._fechar_overlay_frame = 0
3028
+ self._fechar_overlay_linhas = []
3029
+ if len(caixa_ant) > 5 and limite >= 6:
3030
+ recorte = max(4, int(len(caixa_ant) * 0.48))
3031
+ caixa_vis = caixa_ant[:recorte - 1] + [caixa_ant[-1]]
3032
+ frame, _, _ = tui_core.desenhar_overlay_centrado(
3033
+ frame, caixa_vis, self.largura, limite, cor_fundo_ansi='', esmaecer_fundo=False
3034
+ )
3035
+ self._registrar_menu(frame, cortado)
3036
+ self._registrar_wizard(frame, cortado)
3037
+ self._registrar_modal(frame, cortado)
2941
3038
  else:
2942
3039
  self._registrar_menu(frame, cortado)
2943
3040
  self._registrar_wizard(frame, cortado)
2944
3041
  self._registrar_modal(frame, cortado)
2945
3042
  self.desenhar(frame)
2946
3043
  self.revisao_vista = self.coletor.revisao
3044
+ self._update_revisao_vista = self.atualizacoes.revisao
2947
3045
 
2948
3046
  # -- teclado e mouse ------------------------------------------------------
2949
3047
  def ler_tecla(self, timeout: float):
@@ -3067,9 +3165,15 @@ class Painel:
3067
3165
  return None
3068
3166
 
3069
3167
  def _precisa_animar(self) -> bool:
3070
- """Indica se ha algo vivo para animar (restart, abertura de dialogo, tarefa ou geracao em voo)."""
3168
+ """Indica se ha algo vivo para animar (abertura, fechamento, digitacao, restart, tarefa ou live)."""
3071
3169
  if getattr(self, '_restart_overlay', None):
3072
3170
  return True
3171
+ if getattr(self, '_intro_frame', 99) < 3:
3172
+ return True
3173
+ if getattr(self, '_fechar_overlay_frame', 0) > 0:
3174
+ return True
3175
+ if (time.monotonic() - getattr(self, '_digito_pulso', 0.0)) < 0.18:
3176
+ return True
3073
3177
  if self.modo == 'tui' and (self.wizard or self.modal) and getattr(self, '_dialogo_frame', 99) < 2:
3074
3178
  return True
3075
3179
  if self.tarefa_ativa:
@@ -3080,6 +3184,48 @@ class Painel:
3080
3184
  return True
3081
3185
  return False
3082
3186
 
3187
+ # Imersão rápida na abertura da TUI (funciona em `krnell` e ao abrir pelo OpenCode)
3188
+ def _animar_abertura_tui(self, saida) -> None:
3189
+ if os.environ.get('KRNELL_NO_INTRO') == '1' or not sys.stdout.isatty():
3190
+ self._intro_frame = 3
3191
+ return
3192
+ larg, alt = shutil.get_terminal_size((110, 30))
3193
+ if larg < 36 or alt < 14:
3194
+ self._intro_frame = 3
3195
+ return
3196
+ centro_y = max(2, (alt - 5) // 2)
3197
+ pad_x = max(0, (larg - 30) // 2)
3198
+ ver = f'v{versao_local()}'
3199
+ pad_v = max(0, (larg - len(ver) - 9) // 2)
3200
+ saida.write('\x1b[?25l\x1b[2J\x1b[H')
3201
+ for passo in range(1, 4):
3202
+ buf = ['\x1b[?2026h']
3203
+ for i in range(passo):
3204
+ esq_l, dir_l = _LOGO_KRNELL[i]
3205
+ buf.append(
3206
+ f'\x1b[{centro_y + i};1H\x1b[2K'
3207
+ + ' ' * pad_x
3208
+ + ansi('texto') + esq_l + ansi('acento') + dir_l + RESET
3209
+ )
3210
+ sub = '◈ krnell ' + ver
3211
+ bar = ('━' * (passo * 6)) + ('─' * ((3 - passo) * 6))
3212
+ buf.append(
3213
+ f'\x1b[{centro_y + 4};1H\x1b[2K'
3214
+ + ' ' * pad_v
3215
+ + ansi('acento') + sub + RESET
3216
+ )
3217
+ pad_b = max(0, (larg - len(bar)) // 2)
3218
+ buf.append(
3219
+ f'\x1b[{centro_y + 5};1H\x1b[2K'
3220
+ + ' ' * pad_b
3221
+ + ansi('acento2') + bar + RESET
3222
+ + '\x1b[?2026l'
3223
+ )
3224
+ saida.write(''.join(buf))
3225
+ saida.flush()
3226
+ time.sleep(0.055)
3227
+ self._intro_frame = 3
3228
+
3083
3229
  def rodar_tui(self) -> None:
3084
3230
  if not self.ativar_vt():
3085
3231
  self.modo = 'repl'
@@ -3091,9 +3237,10 @@ class Painel:
3091
3237
  self.iniciar_bridge_na_abertura()
3092
3238
  self.iniciar_dashboard_na_abertura()
3093
3239
  saida = sys.stdout
3094
- saida.write('\x1b[?1049h\x1b[?25h')
3240
+ saida.write('\x1b[?1049h\x1b[?25l')
3095
3241
  saida.write('\x1b[?7l')
3096
3242
  saida.flush()
3243
+ self._animar_abertura_tui(saida)
3097
3244
  self._precisa_limpar_tela = True
3098
3245
  try:
3099
3246
  self.atualizar_tela()
@@ -3104,12 +3251,37 @@ class Painel:
3104
3251
  if tecla is None:
3105
3252
  nova_larg, nova_alt = shutil.get_terminal_size((self.largura, self.altura))
3106
3253
  mudou_tamanho = (nova_larg != self.largura or nova_alt != self.altura)
3107
- mudou_dados = self.coletor.revisao != self.revisao_vista
3254
+ mudou_dados = (
3255
+ self.coletor.revisao != self.revisao_vista
3256
+ or self.atualizacoes.revisao != self._update_revisao_vista
3257
+ )
3108
3258
  expirou_msg = bool(self.msg and time.time() > self.msg_ate)
3109
3259
  if expirou_msg:
3110
3260
  self.msg = None
3111
- intervalo_anim = 0.03 if getattr(self, '_dialogo_frame', 99) < 2 else (0.09 if animando else 0.9)
3261
+ intervalo_anim = (
3262
+ 0.035 if (
3263
+ getattr(self, '_dialogo_frame', 99) < 2
3264
+ or getattr(self, '_fechar_overlay_frame', 0) > 0
3265
+ or getattr(self, '_intro_frame', 99) < 3
3266
+ ) else (0.08 if animando else 0.9)
3267
+ )
3112
3268
  tick_anim = (agora - self._anim_ultimo) >= intervalo_anim
3269
+ # Animação de digitação sutil no placeholder da home quando ocioso
3270
+ anim_dica = False
3271
+ if not self.buf and not self.wizard and not self.modal and not self._restart_overlay:
3272
+ dica_alvo = _DICAS_HOME[self._dica_idx % len(_DICAS_HOME)]
3273
+ if self._dica_chars < len(dica_alvo):
3274
+ if (agora - self._dica_ultimo) >= 0.045:
3275
+ self._dica_chars += 2
3276
+ self._dica_ultimo = agora
3277
+ anim_dica = True
3278
+ elif (agora - self._dica_ultimo) >= 5.5:
3279
+ self._dica_idx = (self._dica_idx + 1) % len(_DICAS_HOME)
3280
+ self._dica_chars = 0
3281
+ self._dica_ultimo = agora
3282
+ anim_dica = True
3283
+ if tick_anim and getattr(self, '_intro_frame', 99) < 3:
3284
+ self._intro_frame += 1
3113
3285
  if tick_anim and (animando or (not self.wizard and not self.modal)):
3114
3286
  self._anim_tick = (self._anim_tick + 1) % 100000
3115
3287
  self._anim_ultimo = agora
@@ -3117,8 +3289,10 @@ class Painel:
3117
3289
  self._cache_frame_base = None
3118
3290
  self._dialogo_frame = 99
3119
3291
  self._precisa_limpar_tela = True
3120
- if mudou_tamanho or mudou_dados or expirou_msg or (tick_anim and (animando or (not self.wizard and not self.modal))):
3292
+ if mudou_tamanho or mudou_dados or expirou_msg or (tick_anim and animando):
3121
3293
  self.atualizar_tela()
3294
+ elif anim_dica:
3295
+ self.desenhar_linha_entrada()
3122
3296
  continue
3123
3297
  # Coalescing de scroll/setas: drena eventos repetidos pendentes no buffer
3124
3298
  # para manter a rolagem lisa sem travar o terminal.
@@ -3191,11 +3365,30 @@ class Painel:
3191
3365
  print(f'não consegui reexecutar a TUI ({exc}). Execute: krnell')
3192
3366
  return
3193
3367
  return
3368
+ if getattr(self, '_sair_em_background', False):
3369
+ self.proc = None
3370
+ self._soltar_job()
3371
+ estado = ('bridge segue rodando em background — use /exit na TUI para desligar'
3372
+ if self.bridge_online() else 'bridge parado')
3373
+ print(f'painel fechado — {estado}.')
3374
+ return
3194
3375
  tinha_bridge = self._encerrar_com_o_painel()
3376
+ # /exit desliga o bridge de verdade (mesmo que tenha sido iniciado antes em background)
3377
+ if not tinha_bridge and self.bridge_online():
3378
+ try:
3379
+ self._parar_bridge()
3380
+ tinha_bridge = True
3381
+ except Exception:
3382
+ pass
3383
+ try:
3384
+ cfg_fim = ler_config()
3385
+ prov_cfg = ((cfg_fim.get('provedores') or {}).get(cfg_fim.get('provider')) or {})
3386
+ porta_m = kimi.porta_de(prov_cfg.get('base_url') or cfg_fim.get('upstream_base_url') or '')
3387
+ kimi.parar_motor(ROOT, porta_m)
3388
+ except Exception:
3389
+ pass
3195
3390
  if tinha_bridge:
3196
- estado = 'o bridge encerrou junto com o painel (portas fechadas)'
3197
- elif self.bridge_online():
3198
- estado = 'o bridge segue no ar — foi iniciado fora deste painel'
3391
+ estado = 'bridge e motor local encerrados (portas fechadas)'
3199
3392
  else:
3200
3393
  estado = 'bridge parado'
3201
3394
  print(f'painel encerrado — {estado}.')
@@ -3283,6 +3476,7 @@ class Painel:
3283
3476
  pass # modal fecha somente com Enter/Esc
3284
3477
  else:
3285
3478
  self.buf += tecla[1]
3479
+ self._digito_pulso = time.monotonic()
3286
3480
  redesenhar = True
3287
3481
  elif isinstance(tecla, tuple) and tecla[0] == 'mouse_clique':
3288
3482
  if self.clicar_botao_update(tecla[1], tecla[2]):
@@ -3340,6 +3534,9 @@ class Painel:
3340
3534
  elif self.modal or self.wizard:
3341
3535
  self.modal = self.wizard = None
3342
3536
  else:
3537
+ # Ctrl+C fecha somente a TUI e deixa o bridge rodando em background
3538
+ # (Windows, Linux, Ubuntu e Termux). Use /exit para desligar de verdade.
3539
+ self._sair_em_background = True
3343
3540
  self.saindo = True
3344
3541
  redesenhar = True
3345
3542
  elif tecla == 'cima':
@@ -3553,6 +3750,7 @@ class Painel:
3553
3750
  self.msg_ate = time.time() + segundos
3554
3751
 
3555
3752
  def fechar(self, arg: str = ''):
3753
+ self._sair_em_background = False
3556
3754
  self.saindo = True
3557
3755
 
3558
3756
  def _linhas_ajuda_colunas(self, itens) -> list:
@@ -5824,21 +6022,28 @@ class Painel:
5824
6022
  raise ValueError('o bridge já está no ar')
5825
6023
  BRIDGE_LOG.parent.mkdir(exist_ok=True)
5826
6024
  log = open(BRIDGE_LOG, 'ab')
5827
- flags = 0x08000000 if os.name == 'nt' else 0 # CREATE_NO_WINDOW
6025
+ # Processo destacado (cross-platform: Windows DETACHED/NEW_PROCESS_GROUP,
6026
+ # Linux/Ubuntu/Termux start_new_session) para que Ctrl+C na TUI deixe o
6027
+ # bridge vivo em background e somente /exit ou /stop encerre o servidor.
6028
+ opcoes: dict = {}
6029
+ if os.name == 'nt':
6030
+ opcoes['creationflags'] = (
6031
+ getattr(subprocess, 'CREATE_NO_WINDOW', 0x08000000)
6032
+ | getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0x00000200)
6033
+ | getattr(subprocess, 'DETACHED_PROCESS', 0x00000008)
6034
+ )
6035
+ else:
6036
+ opcoes['start_new_session'] = True
5828
6037
  self._soltar_job()
5829
6038
  try:
5830
6039
  self.proc = subprocess.Popen(
5831
6040
  [sys.executable, '-B', str(ROOT / 'bridge.py'), '--config', 'config.json'],
5832
- cwd=str(ROOT), stdout=log, stderr=subprocess.STDOUT, creationflags=flags)
6041
+ cwd=str(ROOT), stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, **opcoes)
5833
6042
  finally:
5834
6043
  try:
5835
6044
  log.close()
5836
6045
  except OSError:
5837
6046
  pass
5838
- # o bridge vive junto com o painel: X no console, /sair ou queda o encerram
5839
- self._job_bridge = prender_processo_ao_painel(self.proc.pid)
5840
- if os.name == 'nt' and not self._job_bridge:
5841
- self._instalar_guarda_ctrl()
5842
6047
  for _ in range(60):
5843
6048
  time.sleep(0.2)
5844
6049
  if self._bridge_online_direto():
@@ -10,14 +10,105 @@
10
10
  // Remove o prompt manual de API key do provider "kimibridge" e coloca no
11
11
  // lugar o login OAuth do Google Antigravity via bridge local, suportando
12
12
  // múltiplas contas com troca automática quando uma conta esgota a quota.
13
+ import { spawn } from "node:child_process"
13
14
  import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"
14
15
  import { homedir } from "node:os"
15
16
  import { join } from "node:path"
16
17
 
17
- const INTEGRATION_IDS = ["nyxo", "kimibridge"]
18
+ const INTEGRATION_IDS = ["krnell", "nyxo", "kimibridge"]
18
19
  const METHOD_ID = "antigravity-oauth"
19
20
  const DEFAULT_BRIDGE_ORIGIN = "http://127.0.0.1:8765"
20
21
 
22
+ let ensureBridgePromise: Promise<boolean> | null = null
23
+ let lastEnsureAttemptAt = 0
24
+
25
+ function isLocalBridgeOrigin(origin: string): boolean {
26
+ try {
27
+ const u = new URL(origin)
28
+ return u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "::1"
29
+ } catch {
30
+ return false
31
+ }
32
+ }
33
+
34
+ function findKrnellCommand(): { cmd: string; args: string[]; cwd?: string } | null {
35
+ const home = homedir()
36
+ const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
37
+ const dataHome = process.env.XDG_DATA_HOME || join(home, ".local", "share")
38
+ const dirs = [
39
+ process.env.KRNELL_HOME,
40
+ process.env.NYXO_HOME,
41
+ process.platform === "win32" ? join(localAppData, "Krnell") : join(dataHome, "krnell"),
42
+ join(home, "bridge-package", "nyxo"),
43
+ ].filter(Boolean) as string[]
44
+
45
+ for (const dir of dirs) {
46
+ const mjs = join(dir, "bin", "krnell.mjs")
47
+ if (existsSync(mjs)) {
48
+ return { cmd: process.execPath, args: [mjs, "--headless"], cwd: dir }
49
+ }
50
+ const bridgePy = join(dir, "bridge.py")
51
+ if (existsSync(bridgePy)) {
52
+ const py = process.platform === "win32" ? "python" : "python3"
53
+ return { cmd: py, args: ["-B", bridgePy, "--config", join(dir, "config.json")], cwd: dir }
54
+ }
55
+ }
56
+ return { cmd: process.platform === "win32" ? "krnell.cmd" : "krnell", args: ["--headless"] }
57
+ }
58
+
59
+ async function isBridgeAlive(origin: string, timeoutMs = 900): Promise<boolean> {
60
+ try {
61
+ const r = await fetch(`${origin}/healthz`, { signal: AbortSignal.timeout(timeoutMs) })
62
+ if (r.ok) return true
63
+ } catch {}
64
+ try {
65
+ const r = await fetch(`${origin}/_bridge/status`, { signal: AbortSignal.timeout(timeoutMs) })
66
+ return r.status < 500
67
+ } catch {
68
+ return false
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Inicialização inteligente sob demanda:
74
+ * só sobe o Krnell em background se o alvo for loopback local, o bridge estiver
75
+ * offline e houver uso real (chamada com modelo Krnell/KimiBridge ou /connect).
76
+ */
77
+ async function ensureKrnellRunning(origin: string, reason: string): Promise<boolean> {
78
+ if (!isLocalBridgeOrigin(origin)) return false
79
+ if (await isBridgeAlive(origin, 700)) return true
80
+ if (ensureBridgePromise) return ensureBridgePromise
81
+ const now = Date.now()
82
+ if (now - lastEnsureAttemptAt < 10_000) return false
83
+ lastEnsureAttemptAt = now
84
+
85
+ ensureBridgePromise = (async () => {
86
+ const launch = findKrnellCommand()
87
+ if (!launch) return false
88
+ try {
89
+ const child = spawn(launch.cmd, launch.args, {
90
+ cwd: launch.cwd,
91
+ detached: true,
92
+ stdio: "ignore",
93
+ windowsHide: true,
94
+ env: { ...process.env, KRNELL_STARTED_BY: `opencode-plugin:${reason}` },
95
+ })
96
+ child.unref()
97
+ } catch {
98
+ return false
99
+ }
100
+ const deadline = Date.now() + 12_000
101
+ while (Date.now() < deadline) {
102
+ if (await isBridgeAlive(origin, 600)) return true
103
+ await new Promise((r) => setTimeout(r, 350))
104
+ }
105
+ return false
106
+ })().finally(() => {
107
+ ensureBridgePromise = null
108
+ })
109
+ return ensureBridgePromise
110
+ }
111
+
21
112
  let cachedFile = ""
22
113
  let cachedMtimeMs = -1
23
114
  let cachedText = ""
@@ -123,7 +214,15 @@ export default {
123
214
  // -----------------------------------------------------------------
124
215
  // 1. Substituição do system prompt via AGENTS.md
125
216
  // -----------------------------------------------------------------
126
- const makeApply = (hook: string) => (event: any) => {
217
+ const makeApply = (hook: string) => async (event: any) => {
218
+ // Momento inteligente 1: se a chamada atual vai usar krnell/kimibridge/nyxo
219
+ // e o bridge local ainda não está no ar, sobe em background automaticamente.
220
+ const provID = String(event?.model?.providerID || event?.providerID || "").toLowerCase()
221
+ if (INTEGRATION_IDS.includes(provID)) {
222
+ const origin = await resolveBridgeOrigin(ctx, provID)
223
+ await ensureKrnellRunning(origin, `hook:${hook}`)
224
+ }
225
+
127
226
  const text = loadPrompt()
128
227
  if (!text) return
129
228
 
@@ -172,7 +271,7 @@ export default {
172
271
  if (ctx?.integration?.transform) {
173
272
  await ctx.integration.transform((reg: any) => {
174
273
  for (const integrationID of INTEGRATION_IDS) {
175
- const pretty = integrationID === "nyxo" ? "Nyxo Bridge (local)" : "Kimi Bridge (local)"
274
+ const pretty = integrationID === "krnell" ? "Krnell (local)" : integrationID === "nyxo" ? "Nyxo Bridge (local)" : "Kimi Bridge (local)"
176
275
  reg.update(integrationID, (ref: any) => {
177
276
  if (!ref.name || ref.name === integrationID) ref.name = pretty
178
277
  })
@@ -191,6 +290,8 @@ export default {
191
290
  },
192
291
  authorize: async () => {
193
292
  const base = await resolveBridgeOrigin(ctx, integrationID)
293
+ // Momento inteligente 2: ao abrir /connect para Antigravity, garante o Krnell no ar.
294
+ await ensureKrnellRunning(base, "connect-oauth")
194
295
  let started: any
195
296
  try {
196
297
  const res = await fetch(`${base}/antigravity/login/start`, {
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "krnell-opencode-plugin",
3
+ "version": "3.0.6",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./index.ts",
7
+ "./server": "./index.ts",
8
+ "./tui": "./tui.tsx"
9
+ }
10
+ }
@@ -0,0 +1,128 @@
1
+ import { spawn } from "node:child_process"
2
+ import { existsSync } from "node:fs"
3
+ import { homedir } from "node:os"
4
+ import { join } from "node:path"
5
+ import { createSignal, onCleanup } from "solid-js"
6
+
7
+ const BRIDGE_ORIGIN = (process.env.KRNELL_BRIDGE_URL || process.env.NYXO_BRIDGE_URL || "http://127.0.0.1:8765").replace(/\/+$/, "")
8
+
9
+ function findKrnellTuiCommand(): { cmd: string; args: string[]; cwd?: string } {
10
+ const home = homedir()
11
+ const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
12
+ const dataHome = process.env.XDG_DATA_HOME || join(home, ".local", "share")
13
+ const dirs = [
14
+ process.env.KRNELL_HOME,
15
+ process.env.NYXO_HOME,
16
+ process.platform === "win32" ? join(localAppData, "Krnell") : join(dataHome, "krnell"),
17
+ join(home, "bridge-package", "nyxo"),
18
+ ].filter(Boolean) as string[]
19
+
20
+ for (const dir of dirs) {
21
+ const mjs = join(dir, "bin", "krnell.mjs")
22
+ if (existsSync(mjs)) return { cmd: process.execPath, args: [mjs], cwd: dir }
23
+ const painelPy = join(dir, "painel.py")
24
+ if (existsSync(painelPy)) {
25
+ const py = process.platform === "win32" ? "python" : "python3"
26
+ return { cmd: py, args: ["-B", painelPy], cwd: dir }
27
+ }
28
+ }
29
+ return { cmd: process.platform === "win32" ? "krnell.cmd" : "krnell", args: [] }
30
+ }
31
+
32
+ async function pingKrnell(): Promise<boolean> {
33
+ try {
34
+ const r = await fetch(`${BRIDGE_ORIGIN}/healthz`, { signal: AbortSignal.timeout(700) })
35
+ if (r.ok) return true
36
+ } catch {}
37
+ try {
38
+ const r = await fetch(`${BRIDGE_ORIGIN}/_bridge/status`, { signal: AbortSignal.timeout(700) })
39
+ return r.status < 500
40
+ } catch {
41
+ return false
42
+ }
43
+ }
44
+
45
+ export default {
46
+ id: "krnell.tui",
47
+ setup(t: any) {
48
+ const [online, setOnline] = createSignal(false)
49
+ const [opening, setOpening] = createSignal(false)
50
+
51
+ const refresh = async () => {
52
+ setOnline(await pingKrnell())
53
+ }
54
+ void refresh()
55
+ const timer = setInterval(() => void refresh(), 5000)
56
+ onCleanup(() => clearInterval(timer))
57
+
58
+ const openKrnell = async () => {
59
+ if (opening()) return
60
+ setOpening(true)
61
+ try {
62
+ const launch = findKrnellTuiCommand()
63
+ await t.renderer.suspend()
64
+ try {
65
+ await new Promise<void>((resolve, reject) => {
66
+ const child = spawn(launch.cmd, launch.args, {
67
+ cwd: launch.cwd,
68
+ stdio: "inherit",
69
+ shell: false,
70
+ })
71
+ child.on("error", reject)
72
+ child.on("exit", () => resolve())
73
+ })
74
+ } finally {
75
+ await t.renderer.resume()
76
+ }
77
+ await refresh()
78
+ } catch (err: any) {
79
+ t.ui?.toast?.show?.({
80
+ title: "Krnell",
81
+ message: `Não foi possível abrir o painel (${err?.message || err})`,
82
+ variant: "error",
83
+ })
84
+ } finally {
85
+ setOpening(false)
86
+ }
87
+ }
88
+
89
+ // Comando `/krnell` na paleta e slash do OpenCode
90
+ t.keymap?.layer?.(() => ({
91
+ mode: "global",
92
+ commands: [
93
+ {
94
+ id: "krnell.panel.open",
95
+ title: "Open Krnell panel",
96
+ description: "Abre o painel do Krnell (Ctrl+C volta pro OpenCode mantendo em background)",
97
+ group: "Krnell",
98
+ palette: true,
99
+ slash: { name: "krnell" },
100
+ run: () => void openKrnell(),
101
+ },
102
+ ],
103
+ }))
104
+
105
+ // Botão clicável/tocável no footer da home do OpenCode (ao lado de "1 MCP /mcps")
106
+ t.ui.slot({
107
+ append: "home.footer.status",
108
+ render: () => (
109
+ <box
110
+ flexDirection="row"
111
+ flexShrink={0}
112
+ gap={1}
113
+ onMouseUp={() => void openKrnell()}
114
+ >
115
+ <text fg={online() ? t.theme.text.feedback.success.base : t.theme.text.muted}>
116
+ ◈
117
+ </text>
118
+ <text fg={t.theme.text.base}>
119
+ {opening() ? "krnell…" : "krnell"}
120
+ </text>
121
+ <text fg={t.theme.text.muted}>
122
+ /krnell
123
+ </text>
124
+ </box>
125
+ ),
126
+ })
127
+ },
128
+ }
@@ -812,88 +812,12 @@ ${opencodeModelsBlock(' ')}
812
812
  }
813
813
 
814
814
  // ---------- autostart ----------
815
- function startupDir() {
816
- return path.join(process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
817
- }
818
-
815
+ // Autostart no boot removido por segurança/controle: o Krnell agora sobe sob
816
+ // demanda (pelo `krnell` ou inteligentemente pelo plugin do OpenCode somente
817
+ // quando o usuário usa um modelo Krnell/KimiBridge ou clica no botão do footer).
819
818
  async function installAutostart() {
820
- const marker = path.join(APP_DIR, '.autostart-ok');
821
- if (fs.existsSync(marker)) return;
822
- const script = path.join(APP_DIR, 'bridge.mjs');
823
- const winNode = path.join(APP_DIR, 'node', 'node.exe');
824
- const nodePath = IS_WIN && fs.existsSync(winNode) ? winNode : process.execPath;
825
- try {
826
- if (IS_WIN) {
827
- const dir = startupDir();
828
- fs.mkdirSync(dir, { recursive: true });
829
- const vbs = path.join(dir, 'KimiBridge.vbs');
830
- if (!fs.existsSync(vbs)) {
831
- const bootBat = path.join(APP_DIR, 'iniciar_oculto.bat');
832
- fs.writeFileSync(bootBat, `@echo off\r\ncd /d "${APP_DIR}"\r\n"${nodePath}" "${script}" >> "${path.join(LOG_DIR, 'boot.log')}" 2>&1\r\n`);
833
- fs.writeFileSync(vbs, `Set sh = CreateObject("WScript.Shell")\r\nsh.Run """${bootBat}""", 0, False\r\n`);
834
- log('autostart: Windows (atalho oculto na inicializacao)');
835
- }
836
- } else {
837
- let done = false;
838
- if (!IS_TERMUX) {
839
- try {
840
- const r = await run('systemctl', ['--user', 'is-system-running']);
841
- if (/running|degraded/.test(r.stdout)) {
842
- const svcDir = path.join(HOME, '.config', 'systemd', 'user');
843
- fs.mkdirSync(svcDir, { recursive: true });
844
- const unit = path.join(svcDir, 'kimi-bridge.service');
845
- if (!fs.existsSync(unit)) {
846
- fs.writeFileSync(unit, `[Unit]
847
- Description=Kimi Bridge
848
- After=network-online.target
849
-
850
- [Service]
851
- Type=simple
852
- WorkingDirectory=${APP_DIR}
853
- ExecStart=${nodePath} ${script}
854
- Restart=on-failure
855
- RestartSec=10
856
-
857
- [Install]
858
- WantedBy=default.target
859
- `);
860
- await run('systemctl', ['--user', 'daemon-reload']);
861
- await run('systemctl', ['--user', 'enable', 'kimi-bridge.service']);
862
- log('autostart: servico systemd de usuario');
863
- }
864
- done = true;
865
- }
866
- } catch {}
867
- }
868
- if (!done && !IS_TERMUX && (await commandExists('crontab'))) {
869
- const current = (await run('crontab', ['-l'])).stdout || '';
870
- if (!current.includes(APP_DIR)) {
871
- const line = `@reboot cd ${APP_DIR} && ${nodePath} ${script} >> ${path.join(LOG_DIR, 'boot.log')} 2>&1`;
872
- await run('sh', ['-c', `(crontab -l 2>/dev/null; echo "${line}") | crontab -`]);
873
- log('autostart: cron @reboot');
874
- }
875
- done = true;
876
- }
877
- if (!done) {
878
- const prof = path.join(HOME, '.profile');
879
- const txt = fs.existsSync(prof) ? fs.readFileSync(prof, 'utf8') : '';
880
- if (!txt.includes('# kimi-bridge autostart')) {
881
- const sh = path.join(APP_DIR, 'iniciar.sh');
882
- const agFile = path.join(APP_DIR, 'antigravity.json');
883
- const bootLog = path.join(LOG_DIR, 'boot.log');
884
- fs.appendFileSync(
885
- prof,
886
- `\n# kimi-bridge autostart\nif ! curl -sf http://${CFG.host}:${CFG.port}/healthz >/dev/null 2>&1; then\n if [ -t 0 ] && [ ! -s "${agFile}" ]; then\n bash "${sh}"\n else\n nohup bash "${sh}" --background >> "${bootLog}" 2>&1 &\n fi\nfi\n`
887
- );
888
- log('autostart: login do shell (~/.profile)');
889
- }
890
- done = true;
891
- }
892
- }
893
- } catch (e) {
894
- log('autostart nao instalado:', e.message);
895
- }
896
- try { fs.writeFileSync(marker, new Date().toISOString()); } catch {}
819
+ // Não grava nada em Startup, systemd, crontab ou ~/.profile.
820
+ return;
897
821
  }
898
822
 
899
823
  // ---------- estado do browser/captcha (pool paralelo + auto-hibernacao) ----------