krnell 3.0.4 → 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.4';
80
+ return pkg.version || '3.0.6';
81
81
  } catch {
82
- return '3.0.4';
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.4'
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.4"
30
+ echo "krnell v3.0.6"
31
31
  exit 0
32
32
  ;;
33
33
  upgrade|update)
package/kimi.py CHANGED
@@ -30,6 +30,8 @@ FALHAS_PARA_REINICIAR = 3
30
30
  ESPERAS_DE_REINICIO = (3.0, 6.0, 15.0, 30.0, 60.0)
31
31
  ARQUIVO_LOG = 'kimi.log'
32
32
 
33
+ MODELO_PADRAO = 'kimi-k3.1-pro'
34
+ MODELO_ANTIGRAVITY_PADRAO = 'gemini-4-neon'
33
35
  PROVEDORES_MOTOR = ('kimi', 'nvidia', 'antigravity')
34
36
  MODELOS_NVIDIA = ('kimi-k3.1-pro', 'minimax-m3.1-flash')
35
37
  MODELOS_ANTIGRAVITY = (
@@ -315,6 +317,22 @@ def antigravity_ativar_conta(hint: str, porta: int = PORTA_PADRAO, timeout: floa
315
317
  return res
316
318
 
317
319
 
320
+ def antigravity_login_url(porta: int = PORTA_PADRAO, timeout: float = 5.0) -> tuple[str, str]:
321
+ """Inicia fluxo OAuth do Antigravity e retorna `(url, state)`."""
322
+ res = antigravity_iniciar_login(porta=porta, timeout=timeout)
323
+ return str(res.get('url') or ''), str(res.get('state') or '')
324
+
325
+
326
+ def antigravity_completar(entrada: str, state: str = '', porta: int = PORTA_PADRAO, timeout: float = 20.0) -> dict:
327
+ """Completa o OAuth do Antigravity com a URL/código colado."""
328
+ return antigravity_completar_login(state=state, entrada=entrada, porta=porta, timeout=timeout)
329
+
330
+
331
+ def antigravity_logout(email: str = '', porta: int = PORTA_PADRAO, timeout: float = 5.0) -> dict:
332
+ """Remove conta conectada do Antigravity."""
333
+ return antigravity_remover_conta(hint=email, porta=porta, timeout=timeout)
334
+
335
+
318
336
  def antigravity_remover_conta(hint: str, porta: int = PORTA_PADRAO, timeout: float = 5.0) -> dict:
319
337
  res = _pedir(
320
338
  porta,
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.4",
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": {