krnell 3.0.0 → 3.0.3

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/bridge.py CHANGED
@@ -46,9 +46,9 @@ from urllib.parse import urlsplit, unquote, parse_qs
46
46
  from urllib.request import HTTPHandler, HTTPRedirectHandler, HTTPSHandler, Request, build_opener
47
47
  from typing import Any
48
48
 
49
- LOG = logging.getLogger('nyxo_bridge')
50
- MODEL = 'nyxo' # ID publico usado por todos os agentes
51
- SERVICE_NAME = 'nyxo' # marca que aparece em /healthz e /_bridge/routes
49
+ LOG = logging.getLogger('krnell_bridge')
50
+ MODEL = 'krnell' # ID publico usado por todos os agentes
51
+ SERVICE_NAME = 'krnell' # marca que aparece em /healthz e /_bridge/routes
52
52
  MODEL_ALIASES = ('duck.space', 'deepseek-v4.1-flash')
53
53
  ALIASES_EXTRA = () # IDs reais do provedor ativo (WorkBuddy) para descoberta
54
54
  UPSTREAM_MODEL = 'deepseek-v4.1-flash:free' # ID real enviado aos provedores
@@ -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.0'
62
+ BRIDGE_VERSION = '3.0.3'
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
@@ -330,7 +330,7 @@ def model_entry(model_id: str) -> dict:
330
330
  # é o que o cliente lê para compactar antes de estourar, em vez de descobrir
331
331
  # no 400 do gateway.
332
332
  entry = {'id': model_id, 'object': 'model', 'created': 0,
333
- 'owned_by': 'nyxo', 'input_modalities': ['text', 'image'],
333
+ 'owned_by': 'krnell', 'input_modalities': ['text', 'image'],
334
334
  'output_modalities': ['text']}
335
335
  if MODEL_CONTEXT_ANUNCIADO > 0:
336
336
  entry.update({
@@ -463,7 +463,7 @@ def canonical_route(path: str) -> str:
463
463
 
464
464
  def known_route(path: str) -> bool:
465
465
  static = ('/', '/healthz', '/_bridge/status', '/_bridge/model-status', '/_bridge/queue', '/_bridge/routes', '/v1/models',
466
- '/_bridge/workbuddy',
466
+ '/_bridge/workbuddy', '/_bridge/reload',
467
467
  '/v1/chat/completions', '/v1/responses', '/v1/messages',
468
468
  '/v1/messages/count_tokens', '/v1/responses/compact',
469
469
  '/v1/responses/input_tokens')
@@ -981,8 +981,8 @@ def load_config(path: Path) -> dict:
981
981
  raise ValueError('Porta inválida')
982
982
  if type(cfg['max_attempts']) is not int or not 1 <= cfg['max_attempts'] <= 100:
983
983
  raise ValueError('max_attempts precisa estar entre 1 e 100')
984
- if cfg['reasoning_effort'] != 'max' or cfg['thinking_enabled'] is not True:
985
- raise ValueError('Esta versão fixa o raciocínio em max e thinking habilitado')
984
+ if cfg['reasoning_effort'] not in ('low', 'medium', 'high', 'xhigh', 'max') or cfg['thinking_enabled'] is not True:
985
+ raise ValueError('reasoning_effort deve ser low, medium, high, xhigh ou max (com thinking habilitado)')
986
986
  if cfg['opencode_variant'] not in OPENCODE_VARIANTS:
987
987
  raise ValueError('opencode_variant deve ser default, low, high ou max')
988
988
  if not isinstance(cfg['opencode_poll_interval_seconds'], (int, float)) or not 0.2 <= cfg['opencode_poll_interval_seconds'] <= 5:
@@ -2130,6 +2130,7 @@ class BridgeState:
2130
2130
  motor_info = None
2131
2131
  return {'status': 'ok', 'model': MODEL, 'provider': self.provider, 'apis': apis,
2132
2132
  'version': BRIDGE_VERSION, 'pid': os.getpid(),
2133
+ 'hot_reload': True,
2133
2134
  'started_at': int(self.started_at),
2134
2135
  'host': self.cfg.get('host') or '127.0.0.1',
2135
2136
  'porta': self.cfg.get('port') or 8765,
@@ -3684,19 +3685,37 @@ def open_upstream(cfg: dict, state: BridgeState, chat: dict, trace_id: str, pref
3684
3685
  if eh_motor_local:
3685
3686
  req_model = str(chat.get('_requested_model') or '').strip()
3686
3687
  modelos_motor = set(kimi.MODELOS_NVIDIA) | set(kimi.MODELOS_ANTIGRAVITY)
3688
+ modelo_efetivo = req_model if req_model in modelos_motor else str(corpo.get('model') or cfg.get('model_enviado') or '')
3687
3689
  if req_model in modelos_motor:
3688
3690
  corpo = {**corpo, 'model': req_model}
3689
3691
  prov_cfg = (cfg.get('provedores') or {}).get(cfg.get('provider')) or {}
3690
- nivel = str(chat.get('_requested_reasoning') or prov_cfg.get('reasoning') or cfg.get('reasoning_effort') or 'max').strip().lower()
3691
- if nivel not in ('low', 'medium', 'high', 'xhigh', 'max'):
3692
- nivel = 'max'
3692
+ nivel_req = str(chat.get('_requested_reasoning') or '').strip().lower()
3693
+ esforco_modelo = ((cfg.get('esforco_modelos') or {}).get(cfg.get('provider')) or {}).get(modelo_efetivo)
3694
+ nivel = str(
3695
+ nivel_req
3696
+ or esforco_modelo
3697
+ or prov_cfg.get('reasoning')
3698
+ or cfg.get('reasoning_effort')
3699
+ or 'max'
3700
+ ).strip().lower()
3701
+ aceitos = kimi.esforcos_do_modelo(modelo_efetivo)
3702
+ if nivel not in aceitos:
3703
+ raise BridgeError(
3704
+ 400,
3705
+ f'{modelo_efetivo} não suporta reasoning "{nivel}" — níveis válidos: {", ".join(aceitos)}',
3706
+ 'invalid_request_error',
3707
+ )
3693
3708
  corpo = {**corpo, 'reasoning_effort': nivel}
3694
3709
  corpo.pop('_requested_model', None)
3695
3710
  corpo.pop('_requested_reasoning', None)
3696
3711
  if wb:
3697
3712
  # Thinking: escolha por modelo (/thinking) vence o padrao do bridge.
3698
- desejado = (((cfg.get('esforco_modelos') or {}).get('workbuddy') or {})
3699
- .get(modelo_wb) or cfg.get('reasoning_effort') or 'max')
3713
+ desejado = str(
3714
+ chat.get('_requested_reasoning')
3715
+ or (((cfg.get('esforco_modelos') or {}).get('workbuddy') or {}).get(modelo_wb))
3716
+ or cfg.get('reasoning_effort')
3717
+ or 'max'
3718
+ ).strip().lower()
3700
3719
  corpo = workbuddy.chat_payload(
3701
3720
  chat, modelo=modelo_wb, stream=stream_upstream,
3702
3721
  esforco=workbuddy.esforco_do_modelo(modelo_wb, desejado,
@@ -3705,10 +3724,21 @@ def open_upstream(cfg: dict, state: BridgeState, chat: dict, trace_id: str, pref
3705
3724
  'domain': wb.get('domain') or ''},
3706
3725
  stream=stream_upstream)
3707
3726
  else:
3727
+ if not eh_motor_local:
3728
+ req_r = str(chat.get('_requested_reasoning') or '').strip().lower()
3729
+ salvo_r = str(
3730
+ ((cfg.get('esforco_modelos') or {}).get(cfg.get('provider')) or {}).get(str(corpo.get('model') or ''))
3731
+ or cfg.get('reasoning_effort')
3732
+ or 'max'
3733
+ ).strip().lower()
3734
+ if req_r in ('low', 'medium', 'high', 'xhigh', 'max'):
3735
+ corpo = {**corpo, 'reasoning_effort': req_r}
3736
+ elif salvo_r in ('low', 'medium', 'high', 'xhigh', 'max'):
3737
+ corpo = {**corpo, 'reasoning_effort': salvo_r}
3708
3738
  corpo = {k: v for k, v in corpo.items() if not str(k).startswith('_')}
3709
3739
  cabecalhos = {'Content-Type': 'application/json',
3710
3740
  'Accept': 'text/event-stream' if chat['stream'] else 'application/json',
3711
- 'Accept-Encoding': 'identity', 'User-Agent': 'DeepSeekUniversalBridge/3.0.0'}
3741
+ 'Accept-Encoding': 'identity', 'User-Agent': 'DeepSeekUniversalBridge/3.0.2'}
3712
3742
  if key:
3713
3743
  # Provedor novo sem credencial: o pedido sai sem Authorization.
3714
3744
  cabecalhos['Authorization'] = 'Bearer ' + key
@@ -4775,6 +4805,52 @@ class Handler(BaseHTTPRequestHandler):
4775
4805
  self.authorized(cfg)
4776
4806
  path = self.resolve_route(trace)
4777
4807
  self._bridge_logged_path = path
4808
+ if path == '/_bridge/reload':
4809
+ # Hot-reload ao vivo de modelo / provedor / contexto sem derrubar o bridge!
4810
+ config_path = getattr(self.server, 'bridge_config_path', None)
4811
+ if not config_path:
4812
+ raise BridgeError(501, 'Reload não disponível neste contexto', 'reload_unavailable')
4813
+ novo_cfg = load_config(config_path)
4814
+ if novo_cfg['host'] != cfg['host'] or novo_cfg['port'] != cfg['port']:
4815
+ raise BridgeError(409, 'Troca de host ou porta requer reiniciar o bridge', 'restart_required')
4816
+ novo_state = BridgeState(novo_cfg)
4817
+ novo_state.logs_dir = getattr(state, 'logs_dir', None) or (config_path.parent / 'logs')
4818
+ novo_state.request_log = getattr(state, 'request_log', None)
4819
+ novo_state.started_at = state.started_at
4820
+ novo_state.sessao = dict(state.sessao)
4821
+ novo_state._taxas = list(state._taxas)
4822
+ novo_state.ultima = state.ultima
4823
+ novo_state.kimi_vigia = getattr(state, 'kimi_vigia', None)
4824
+ if novo_cfg['provider'] in kimi.PROVEDORES_MOTOR and novo_state.kimi_vigia is None:
4825
+ porta_kimi = kimi.porta_de(novo_cfg.get('upstream_base_url') or '')
4826
+ novo_state.kimi_vigia = kimi.iniciar(config_path.parent, porta_kimi)
4827
+ if novo_cfg['provider'] == 'workbuddy':
4828
+ vigia = workbuddy.Vigia(config_path.parent, novo_cfg, novo_state)
4829
+ novo_state.workbuddy_vigia = vigia
4830
+ vigia.start()
4831
+ if novo_cfg.get('workbuddy_convites', True):
4832
+ convites = workbuddy.VigiaConvites(
4833
+ config_path.parent, novo_cfg,
4834
+ intervalo_pendente=float(novo_cfg.get('workbuddy_convites_intervalo')
4835
+ or workbuddy.CONVITE_INTERVALO_PENDENTE))
4836
+ novo_state.workbuddy_convites = convites
4837
+ convites.start()
4838
+ reloader = AccountHotReloader(config_path, novo_cfg, novo_state)
4839
+ novo_state.key_reloader = reloader
4840
+ novo_state.model_status.start()
4841
+ reloader.start()
4842
+ antigo_reloader = getattr(state, 'key_reloader', None)
4843
+ self.server.bridge_runtime = (novo_cfg, novo_state)
4844
+ if antigo_reloader is not None:
4845
+ antigo_reloader.stop()
4846
+ state.model_status.stop()
4847
+ LOG.info('bridge_hot_reloaded provider=%s model=%s apis=%d',
4848
+ novo_cfg['provider'],
4849
+ novo_cfg.get('model_enviado') or novo_cfg.get('upstream_model') or novo_cfg.get('opencode_model') or MODEL,
4850
+ len(novo_cfg['apis']))
4851
+ self.emit(200, jbytes({'status': 'reloaded', 'provider': novo_cfg['provider'],
4852
+ 'model': novo_cfg.get('model_enviado') or novo_cfg.get('upstream_model') or novo_cfg.get('opencode_model') or MODEL}))
4853
+ return
4778
4854
  if path not in ('/v1/chat/completions', '/v1/responses', '/v1/messages',
4779
4855
  '/v1/messages/count_tokens', '/v1/responses/input_tokens',
4780
4856
  '/v1/responses/compact'):
@@ -5091,6 +5167,8 @@ class BridgeHTTPServer(ThreadingHTTPServer):
5091
5167
  geraria um traceback inofensivo no stderr. Aqui só esse ruído é ignorado —
5092
5168
  erros de verdade continuam indo para o log padrão do socketserver."""
5093
5169
 
5170
+ allow_reuse_address = True
5171
+
5094
5172
  def handle_error(self, request, client_address):
5095
5173
  exc = sys.exc_info()[1]
5096
5174
  if isinstance(exc, (ConnectionResetError, ConnectionAbortedError,
@@ -5117,6 +5195,7 @@ def run(config_path: Path):
5117
5195
  raise SystemExit(2) from None
5118
5196
  raise
5119
5197
  with server:
5198
+ server.bridge_config_path = config_path
5120
5199
  server.bridge_runtime = (cfg, BridgeState(cfg))
5121
5200
  vigia_kimi = None
5122
5201
  server.bridge_runtime[1].logs_dir = config_path.parent / 'logs'
@@ -5141,7 +5220,7 @@ def run(config_path: Path):
5141
5220
  convites.start()
5142
5221
  if cfg['provider'] in kimi.PROVEDORES_MOTOR:
5143
5222
  # Motor local Node (NVIDIA Playground + Antigravity OAuth): sobe e
5144
- # vigia provedores/kimi/bridge.mjs sob supervisao do nyxo.
5223
+ # vigia provedores/kimi/bridge.mjs sob supervisao do krnell.
5145
5224
  porta_kimi = kimi.porta_de(cfg.get('upstream_base_url') or '')
5146
5225
  vigia_kimi = kimi.iniciar(config_path.parent, porta_kimi)
5147
5226
  server.bridge_runtime[1].kimi_vigia = vigia_kimi
@@ -5176,17 +5255,22 @@ def run(config_path: Path):
5176
5255
  if https_server is not None:
5177
5256
  https_server.shutdown()
5178
5257
  https_server.server_close()
5179
- reloader.stop()
5258
+ _, final_state = server.bridge_runtime
5259
+ if getattr(final_state, 'key_reloader', None) is not None:
5260
+ final_state.key_reloader.stop()
5261
+ elif reloader is not None:
5262
+ reloader.stop()
5180
5263
  if respondedor is not None:
5181
5264
  respondedor.stop()
5182
- server.bridge_runtime[1].queue.shutdown()
5183
- server.bridge_runtime[1].model_status.stop()
5184
- if vigia_kimi is not None:
5185
- vigia_kimi.encerrar()
5265
+ final_state.queue.shutdown()
5266
+ final_state.model_status.stop()
5267
+ final_vigia = getattr(final_state, 'kimi_vigia', None) or vigia_kimi
5268
+ if final_vigia is not None:
5269
+ final_vigia.encerrar()
5186
5270
 
5187
5271
 
5188
5272
  def main():
5189
- parser = argparse.ArgumentParser(description='nyxo bridge, OpenAI + Anthropic')
5273
+ parser = argparse.ArgumentParser(description='krnell bridge, OpenAI + Anthropic')
5190
5274
  parser.add_argument('--config', default='config.json', help='Caminho do config.json')
5191
5275
  args = parser.parse_args()
5192
5276
  run(Path(args.config).resolve())
@@ -3,7 +3,7 @@
3
3
  "nome_local": "bridge",
4
4
  "link_publico": "",
5
5
  "port": 8765,
6
- "model": "nyxo",
6
+ "model": "krnell",
7
7
  "model_enviado": "kimi-k3.1-pro",
8
8
  "upstream_base_url": "http://127.0.0.1:9098/v1",
9
9
  "keys_file": "keys.env",
@@ -20,7 +20,7 @@
20
20
  "max_recovery_wait_seconds": 0,
21
21
  "upstream_model": "kimi-k3.1-pro",
22
22
  "provider": "nvidia",
23
- "panel_theme": "nyxo",
23
+ "panel_theme": "krnell",
24
24
  "contextos_modelos": {},
25
25
  "tokenharbor_apis": [],
26
26
  "provedores": {
package/contexto.py CHANGED
@@ -103,7 +103,12 @@ def restaurar_clientes(changes):
103
103
 
104
104
 
105
105
  def sincronizar_opencode(cfg, tokens):
106
- """Atualiza so os aliases que apontam a este bridge; guarda o valor anterior."""
106
+ """Atualiza no opencode.json(c) os modelos que apontam a este bridge; guarda o valor anterior.
107
+
108
+ Suporta tanto o schema antigo (`provider.<id>.options.baseURL`) quanto o
109
+ OpenCode v2 (`providers.<id>.settings.baseURL`), atualizando tanto o alias
110
+ dinâmico quanto o modelo ativo (`model_enviado` / `upstream_model` / `opencode_model`).
111
+ """
107
112
  if tokens is None and not cfg.get('contexto_opencode_padrao'):
108
113
  return []
109
114
  port = cfg.get('port', 8765)
@@ -112,7 +117,10 @@ def sincronizar_opencode(cfg, tokens):
112
117
  urls.add(f'http://{host}:{port}/v1')
113
118
  if port == 80:
114
119
  urls.add(f'http://{host}/v1')
115
- aliases = {'nyxo', 'duck.space', 'deepseek-v4.1-flash'}
120
+ aliases = {'krnell', 'nyxo', 'duck.space', 'deepseek-v4.1-flash'}
121
+ modelo_atual = str(cfg.get('model_enviado') or cfg.get('upstream_model') or cfg.get('opencode_model') or '').strip()
122
+ if modelo_atual:
123
+ aliases.add(modelo_atual)
116
124
  changes = []
117
125
  defaults = cfg.get('contexto_opencode_padrao', {})
118
126
  try:
@@ -123,46 +131,58 @@ def sincronizar_opencode(cfg, tokens):
123
131
  text = path.read_bytes().decode('utf-8-sig')
124
132
  clean, original = _jsonc(text)
125
133
  replacements = []
126
- for provider, entry in original.get('provider', {}).items():
127
- url = str(entry.get('options', {}).get('baseURL') or '')
128
- url = re.sub(r'\{env:([^}]+)\}', lambda m: os.environ.get(m[1], ''), url)
129
- if not url or url.rstrip('/').lower() not in urls:
130
- continue
131
- for model, definition in entry.get('models', {}).items():
132
- if model not in aliases and definition.get('id') not in aliases:
133
- continue
134
- base = ('provider', provider, 'models', model)
135
- key = str(path.resolve()) + '|' + provider + '|' + model
136
- old = definition.get('limit', {}).get('context')
137
- if tokens is not None:
138
- cfg['contexto_opencode_padrao'] = defaults
139
- defaults.setdefault(key, old)
140
- target = tokens
141
- elif key in defaults:
142
- target = defaults[key]
143
- else:
134
+ # Percorre schema v1 ("provider" + "options") e v2 ("providers" + "settings")
135
+ blocos_raiz = []
136
+ if isinstance(original.get('provider'), dict):
137
+ blocos_raiz.append(('provider', 'options', original['provider']))
138
+ if isinstance(original.get('providers'), dict):
139
+ blocos_raiz.append(('providers', 'settings', original['providers']))
140
+ for root_key, url_key, mapa_provs in blocos_raiz:
141
+ for provider, entry in mapa_provs.items():
142
+ if not isinstance(entry, dict):
144
143
  continue
145
- if target == old:
144
+ opts = entry.get(url_key) or entry.get('options') or entry.get('settings') or {}
145
+ url = str((opts.get('baseURL') if isinstance(opts, dict) else '') or '')
146
+ url = re.sub(r'\{env:([^}]+)\}', lambda m: os.environ.get(m[1], ''), url)
147
+ if not url or url.rstrip('/').lower() not in urls:
146
148
  continue
147
- try:
148
- span = _span(clean, base + ('limit', 'context'))
149
- if target is not None:
150
- replacements.append((*span, str(target)))
149
+ for model, definition in (entry.get('models') or {}).items():
150
+ if not isinstance(definition, dict):
151
+ continue
152
+ if model not in aliases and definition.get('id') not in aliases:
153
+ continue
154
+ base = (root_key, provider, 'models', model)
155
+ key = str(path.resolve()) + '|' + provider + '|' + model
156
+ old = (definition.get('limit') or {}).get('context')
157
+ if tokens is not None:
158
+ cfg['contexto_opencode_padrao'] = defaults
159
+ defaults.setdefault(key, old)
160
+ target = tokens
161
+ elif key in defaults:
162
+ target = defaults[key]
163
+ else:
164
+ continue
165
+ if target == old:
151
166
  continue
152
- except KeyError:
153
- pass
154
- limit = dict(definition.get('limit', {}))
155
- if target is None:
156
- limit.pop('context', None)
157
- else:
158
- limit['context'] = target
159
- try:
160
- span = _span(clean, base + ('limit',))
161
- value = limit
162
- except KeyError:
163
- span = _span(clean, base)
164
- value = dict(definition, limit=limit)
165
- replacements.append((*span, json.dumps(value, ensure_ascii=False)))
167
+ try:
168
+ span = _span(clean, base + ('limit', 'context'))
169
+ if target is not None:
170
+ replacements.append((*span, str(target)))
171
+ continue
172
+ except KeyError:
173
+ pass
174
+ limit = dict(definition.get('limit') or {})
175
+ if target is None:
176
+ limit.pop('context', None)
177
+ else:
178
+ limit['context'] = target
179
+ try:
180
+ span = _span(clean, base + ('limit',))
181
+ value = limit
182
+ except KeyError:
183
+ span = _span(clean, base)
184
+ value = dict(definition, limit=limit)
185
+ replacements.append((*span, json.dumps(value, ensure_ascii=False)))
166
186
  if not replacements:
167
187
  continue
168
188
  for start, end, value in sorted(replacements, reverse=True):
@@ -84,7 +84,7 @@ def ask_keys(prompt: Callable[[str], str], known: set, start_index: int,
84
84
 
85
85
  def initialize(root: Path, prompt: Callable[[str], str] = getpass.getpass):
86
86
  template = json.loads((root / 'config.example.json').read_text(encoding='utf-8'))
87
- print('\nDeepSeek Universal Bridge: deepseek-v4.1-flash')
87
+ print('\nKrnell: bridge multi-provedor')
88
88
  print('Nenhuma configuração anterior encontrada. Cadastre suas chaves; Enter encerra.')
89
89
  keys = ask_keys(prompt, set(), 1, MAX_ACCOUNTS, allow_zero=False)
90
90
  if not keys:
@@ -471,7 +471,7 @@ def main():
471
471
  else:
472
472
  initialize(ROOT, getpass.getpass)
473
473
  print('Base URL: http://127.0.0.1:8765/v1')
474
- print('Modelo para os agentes: nyxo')
474
+ print('Modelo para os agentes: krnell')
475
475
  return 0
476
476
  except (ValueError, OSError, UnicodeError, json.JSONDecodeError) as exc:
477
477
  print(f'ERRO: {exc}')
@@ -45,9 +45,15 @@ def select(root: Path, provider: str, *, prompt=None, allow_add=True):
45
45
  print(f'{provider} ja estava selecionado; {len(accounts)} contas.')
46
46
  return False
47
47
  config['provider'] = provider
48
+ # Motores com catálogo próprio não podem vazar Kimi/MiniMax para os legados.
49
+ # Entre UnoRouter e TokenHarbor, preserva o modelo configurado se já existir.
50
+ if previous in ('nvidia', 'kimi', 'antigravity', 'workbuddy', 'opencode') \
51
+ or not str(config.get('upstream_model') or '').strip():
52
+ config['upstream_model'] = 'deepseek-v4.1-flash:free'
53
+ config['model_enviado'] = str(config.get('upstream_model') or '').strip()
48
54
  atomic_replace(cfgpath, (json.dumps(config, ensure_ascii=False, indent=2)+'\n').encode('utf-8'))
49
55
  print(f'Provedor selecionado: {provider} ({len(accounts)} contas). Reinicie pelo Painel.cmd.')
50
- print('Modelo mostrado aos agentes: nyxo')
56
+ print('Modelo mostrado aos agentes: krnell')
51
57
  return True
52
58
 
53
59
  def main():
package/iniciar.sh CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bash
2
2
  # ==============================================================================
3
- # Nyxo Bridge v3 — Instalador e Launcher Unificado (Termux / Ubuntu / Linux)
3
+ # Krnell v3 — Instalador e Launcher Unificado (Termux / Ubuntu / Linux)
4
4
  #
5
5
  # Uso:
6
6
  # ./iniciar.sh # instala o que faltar e abre a TUI interativa
@@ -27,19 +27,19 @@ case "${1:-}" in
27
27
  --once) MODO="once" ;;
28
28
  --repl) MODO="repl" ;;
29
29
  -v|--version)
30
- echo "nyxo v3.0.0"
30
+ echo "krnell v3.0.3"
31
31
  exit 0
32
32
  ;;
33
33
  upgrade|update)
34
- if command -v node >/dev/null 2>&1 && [[ -f "$ROOT/bin/nyxo.mjs" ]]; then
35
- exec node "$ROOT/bin/nyxo.mjs" upgrade
34
+ if command -v node >/dev/null 2>&1 && [[ -f "$ROOT/bin/krnell.mjs" ]]; then
35
+ exec node "$ROOT/bin/krnell.mjs" upgrade
36
36
  fi
37
- echo "Instale o Node.js para usar 'nyxo upgrade'." >&2
37
+ echo "Instale o Node.js para usar 'krnell upgrade'." >&2
38
38
  exit 1
39
39
  ;;
40
40
  -h|--help)
41
41
  cat <<'EOF'
42
- Nyxo Bridge v3 — launcher multiplataforma (Termux / Ubuntu / Linux)
42
+ Krnell v3 — launcher multiplataforma (Termux / Ubuntu / Linux)
43
43
 
44
44
  ./iniciar.sh abre a TUI interativa (auto-instala o que faltar)
45
45
  ./iniciar.sh --instalar prepara Python + rich + Node + Playwright Chromium
@@ -57,8 +57,8 @@ EOF
57
57
  ;;
58
58
  esac
59
59
 
60
- log() { printf '\033[38;5;216m◈ nyxo\033[0m %s\n' "$*"; }
61
- warn() { printf '\033[38;5;221m! nyxo\033[0m %s\n' "$*" >&2; }
60
+ log() { printf '\033[38;5;216m◈ krnell\033[0m %s\n' "$*"; }
61
+ warn() { printf '\033[38;5;221m! krnell\033[0m %s\n' "$*" >&2; }
62
62
 
63
63
  # 1) Detecta ou instala Python 3.10+
64
64
  pick_python() {
@@ -166,16 +166,16 @@ if [[ ! -f "$ROOT/keys.env" && -f "$ROOT/keys.example.env" ]]; then
166
166
  chmod 600 "$ROOT/keys.env" 2>/dev/null || true
167
167
  fi
168
168
 
169
- # 6) Instala atalho global `nyxo` no Linux / Ubuntu / Termux (sem sudo quando possivel)
169
+ # 6) Instala atalho global `krnell` no Linux / Ubuntu / Termux (sem sudo quando possivel)
170
170
  instalar_atalho_global() {
171
171
  local alvo=""
172
172
  if (( IS_TERMUX )) && [[ -n "${PREFIX:-}" && -w "${PREFIX}/bin" ]]; then
173
- alvo="${PREFIX}/bin/nyxo"
173
+ alvo="${PREFIX}/bin/krnell"
174
174
  elif [[ -w "/usr/local/bin" ]]; then
175
- alvo="/usr/local/bin/nyxo"
175
+ alvo="/usr/local/bin/krnell"
176
176
  else
177
177
  mkdir -p "$HOME/.local/bin"
178
- alvo="$HOME/.local/bin/nyxo"
178
+ alvo="$HOME/.local/bin/krnell"
179
179
  case ":$PATH:" in
180
180
  *":$HOME/.local/bin:"*) ;;
181
181
  *)
@@ -213,12 +213,12 @@ except Exception:
213
213
  if not opencode_sync.opencode_detectado() or opencode_sync.opencode_ja_configurado(porta):
214
214
  raise SystemExit(0)
215
215
  try:
216
- resp = input('\033[38;5;216m◈ nyxo\033[0m OpenCode detectado! Configurar modelos do Nyxo + plugin system-prompt agora? [S/n] ').strip().lower()
216
+ resp = input('\033[38;5;216m◈ krnell\033[0m OpenCode detectado! Configurar modelos do Krnell + plugin system-prompt agora? [S/n] ').strip().lower()
217
217
  except (EOFError, KeyboardInterrupt):
218
218
  raise SystemExit(0)
219
219
  if resp in ('', 's', 'sim', 'y', 'yes'):
220
220
  res = opencode_sync.configurar_opencode(root, porta=porta)
221
- print(f"\033[38;5;114m✓ nyxo\033[0m OpenCode configurado: {res['config']} -> {res['base_url']}")
221
+ print(f"\033[38;5;114m✓ krnell\033[0m OpenCode configurado: {res['config']} -> {res['base_url']}")
222
222
  PY
223
223
  }
224
224
 
@@ -231,7 +231,7 @@ case "$MODO" in
231
231
  instalar)
232
232
  checar_opencode_interativo
233
233
  log "Ambiente pronto ($PYTHON · $(node -v 2>/dev/null || echo 'sem node'))."
234
- log "Agora voce pode digitar 'nyxo' em qualquer terminal."
234
+ log "Agora voce pode digitar 'krnell' em qualquer terminal."
235
235
  ;;
236
236
  opencode)
237
237
  "$PYTHON" -B -c "import opencode_sync, pathlib, json
package/kimi.py CHANGED
@@ -1,4 +1,4 @@
1
- """Motor NVIDIA Playground + Antigravity: bridge Node local supervisionado pelo nyxo.
1
+ """Motor NVIDIA Playground + Antigravity: bridge Node local supervisionado pelo krnell.
2
2
 
3
3
  O código do motor mora em `provedores/kimi/bridge.mjs` — versão otimizada com:
4
4
  - NVIDIA Playground: `kimi-k3.1-pro` e `minimax-m3.1-flash` via pool paralelo
@@ -6,7 +6,7 @@ O código do motor mora em `provedores/kimi/bridge.mjs` — versão otimizada co
6
6
  - Antigravity (Google): `claude-opus-5-5`, `claude-sonnet-5-5`,
7
7
  `gemini-4-hydrogen`, `gemini-4-neon` (multi-conta OAuth com troca de quota).
8
8
 
9
- O nyxo fala com ele por HTTP em `127.0.0.1:<porta>/v1`. Este módulo encontra o
9
+ O krnell fala com ele por HTTP em `127.0.0.1:<porta>/v1`. Este módulo encontra o
10
10
  Node (Windows, Linux, Ubuntu e Termux), sobe o processo, acompanha saúde/cota,
11
11
  expõe login/contas/logout do Antigravity e encerra de forma limpa.
12
12
  """
@@ -15,6 +15,7 @@ from __future__ import annotations
15
15
  import json
16
16
  import os
17
17
  import shutil
18
+ import signal
18
19
  import subprocess
19
20
  import threading
20
21
  import time
@@ -38,6 +39,27 @@ MODELOS_ANTIGRAVITY = (
38
39
  'claude-sonnet-5-5',
39
40
  )
40
41
 
42
+ # Níveis de raciocínio reais suportados por cada modelo do motor local.
43
+ ESFORCOS_POR_MODELO: dict[str, tuple[str, ...]] = {
44
+ 'kimi-k3.1-pro': ('low', 'medium', 'high', 'max'),
45
+ 'minimax-m3.1-flash': ('low', 'medium', 'high', 'max'),
46
+ 'gemini-4-neon': ('low', 'medium', 'high', 'xhigh'),
47
+ 'gemini-4-hydrogen': ('low', 'medium', 'high', 'xhigh'),
48
+ 'claude-opus-5-5': ('low', 'medium', 'high'),
49
+ 'claude-sonnet-5-5': ('low', 'medium', 'high'),
50
+ }
51
+
52
+
53
+ def esforcos_do_modelo(modelo: str) -> tuple[str, ...]:
54
+ """Retorna os níveis de reasoning válidos para o modelo informado."""
55
+ chave = str(modelo or '').strip().lower()
56
+ if chave in ESFORCOS_POR_MODELO:
57
+ return ESFORCOS_POR_MODELO[chave]
58
+ for prefixo, niveis in ESFORCOS_POR_MODELO.items():
59
+ if chave.startswith(prefixo):
60
+ return niveis
61
+ return ('low', 'medium', 'high', 'xhigh', 'max')
62
+
41
63
  # Sem proxy: o processo é local. O proxy do sistema transformava loopback em 502.
42
64
  ABRIDOR = build_opener(ProxyHandler({}))
43
65
 
@@ -176,6 +198,7 @@ def estado(porta: int = PORTA_PADRAO, timeout: float = 3.0) -> dict:
176
198
  }
177
199
  return {
178
200
  'rodando': True,
201
+ 'pid': int(dados.get('pid') or 0),
179
202
  'pronto': bool(dados.get('ok')),
180
203
  'captcha_pronto': bool(dados.get('ready')),
181
204
  'porta': int(porta),
@@ -230,7 +253,12 @@ def ler_contas_antigravity_disco(raiz: Path) -> list[dict]:
230
253
 
231
254
 
232
255
  def antigravity_status(porta: int = PORTA_PADRAO, raiz: Path | None = None, timeout: float = 3.0) -> dict:
233
- """Status ao vivo do Antigravity (ou fallback lendo antigravity.json do disco)."""
256
+ """Status ao vivo do Antigravity com cota 5h + semanal de todas as contas."""
257
+ dados = _pedir(porta, '/antigravity/quota', timeout)
258
+ if isinstance(dados, dict) and 'accounts' in dados:
259
+ dados['online'] = True
260
+ dados['loggedIn'] = bool(dados.get('accounts'))
261
+ return dados
234
262
  dados = _pedir(porta, '/antigravity/status', timeout)
235
263
  if isinstance(dados, dict) and 'loggedIn' in dados:
236
264
  dados['online'] = True
@@ -305,6 +333,63 @@ def recarregar_captcha(porta: int = PORTA_PADRAO, timeout: float = 30.0) -> bool
305
333
  return bool(isinstance(res, dict) and res.get('ok'))
306
334
 
307
335
 
336
+ def parar_motor(raiz: Path, porta: int = PORTA_PADRAO) -> None:
337
+ """Encerra somente o bridge.mjs desta instalação, inclusive se foi adotado."""
338
+ alvo = str(pasta(raiz) / 'bridge.mjs')
339
+ pids = set()
340
+ atual = estado(porta, timeout=0.5)
341
+ try:
342
+ pid = int(atual.get('pid') or 0)
343
+ if pid > 1 and pid != os.getpid() and os.name != 'nt':
344
+ cmdline = Path(f'/proc/{pid}/cmdline').read_bytes().replace(b'\0', b' ').decode('utf-8', 'replace')
345
+ if alvo in cmdline:
346
+ pids.add(pid)
347
+ except (TypeError, ValueError, OSError):
348
+ pass
349
+ if os.name == 'nt':
350
+ script = (
351
+ "$alvo=$args[0]; Get-CimInstance Win32_Process | Where-Object { "
352
+ "$_.CommandLine -and $_.CommandLine.IndexOf($alvo, "
353
+ "[System.StringComparison]::OrdinalIgnoreCase) -ge 0 } | "
354
+ "ForEach-Object { $_.ProcessId }"
355
+ )
356
+ try:
357
+ res = subprocess.run(['powershell', '-NoProfile', '-NonInteractive', '-Command', script, alvo],
358
+ capture_output=True, text=True, timeout=8, check=False)
359
+ pids.update(int(x) for x in res.stdout.split() if x.isdigit() and int(x) > 1)
360
+ except (OSError, subprocess.TimeoutExpired, ValueError):
361
+ pass
362
+ for pid in pids:
363
+ subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'],
364
+ capture_output=True, timeout=12, check=False)
365
+ return
366
+ try:
367
+ res = subprocess.run(['ps', '-eo', 'pid=,args='], capture_output=True, text=True,
368
+ timeout=5, check=False)
369
+ for linha in res.stdout.splitlines():
370
+ campos = linha.strip().split(None, 1)
371
+ if len(campos) == 2 and campos[0].isdigit() and alvo in campos[1]:
372
+ pid = int(campos[0])
373
+ if pid > 1 and pid != os.getpid():
374
+ pids.add(pid)
375
+ except (OSError, subprocess.TimeoutExpired):
376
+ pass
377
+ for pid in pids:
378
+ try:
379
+ os.kill(pid, signal.SIGTERM)
380
+ except (ProcessLookupError, PermissionError):
381
+ pass
382
+ limite = time.monotonic() + 5
383
+ while time.monotonic() < limite and estado(porta, timeout=0.25).get('rodando'):
384
+ time.sleep(0.1)
385
+ if estado(porta, timeout=0.25).get('rodando'):
386
+ for pid in pids:
387
+ try:
388
+ os.kill(pid, signal.SIGKILL)
389
+ except (ProcessLookupError, PermissionError):
390
+ pass
391
+
392
+
308
393
  def garantir_motor_ativo(raiz: Path, porta: int = PORTA_PADRAO, timeout: float = 15.0) -> tuple[bool, subprocess.Popen | None, str]:
309
394
  """Garante o motor Node de pé para login/gestão mesmo se o bridge principal estiver parado."""
310
395
  if estado(porta, timeout=1.5).get('rodando'):
@@ -349,7 +434,7 @@ def garantir_motor_ativo(raiz: Path, porta: int = PORTA_PADRAO, timeout: float =
349
434
 
350
435
 
351
436
  class Vigia(threading.Thread):
352
- """Mantém o motor local (NVIDIA + Antigravity) de pé enquanto o nyxo precisar dele."""
437
+ """Mantém o motor local (NVIDIA + Antigravity) de pé enquanto o krnell precisar dele."""
353
438
 
354
439
  def __init__(self, raiz: Path, porta: int = PORTA_PADRAO,
355
440
  espera_pronto: float = ESPERA_PRONTO):