krnell 3.0.6 → 3.0.7

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/bin/krnell.mjs CHANGED
@@ -77,9 +77,9 @@ prepararPastaUsuario();
77
77
  function lerVersao() {
78
78
  try {
79
79
  const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
80
- return pkg.version || '3.0.6';
80
+ return pkg.version || '3.0.7';
81
81
  } catch {
82
- return '3.0.6';
82
+ return '3.0.7';
83
83
  }
84
84
  }
85
85
 
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.6'
62
+ BRIDGE_VERSION = '3.0.7'
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
@@ -464,6 +464,7 @@ def canonical_route(path: str) -> str:
464
464
  def known_route(path: str) -> bool:
465
465
  static = ('/', '/healthz', '/_bridge/status', '/_bridge/model-status', '/_bridge/queue', '/_bridge/routes', '/v1/models',
466
466
  '/_bridge/workbuddy', '/_bridge/reload',
467
+ '/workbuddy/login/start', '/workbuddy/login/status', '/workbuddy/logout',
467
468
  '/v1/chat/completions', '/v1/responses', '/v1/messages',
468
469
  '/v1/messages/count_tokens', '/v1/responses/compact',
469
470
  '/v1/responses/input_tokens')
@@ -890,13 +891,20 @@ def load_config(path: Path) -> dict:
890
891
  elif cfg['provider'] == 'tokenharbor':
891
892
  pool = cfg.get('tokenharbor_apis', [])
892
893
  elif cfg['provider'] in kimi.PROVEDORES_MOTOR:
893
- # Motor local Node (NVIDIA Playground / Antigravity): suporta rajadas
894
- # paralelas (ate 20 subagentes simultaneos sem fila 1-por-vez).
895
894
  base_motor = str((provedores.get(cfg['provider']) or {}).get('base_url') or kimi.url_base()).strip().rstrip('/')
896
895
  key_local = os.environ.get('KIMI_BRIDGE_KEY', '').strip() or 'local'
897
- pool = [{'name': f'{cfg["provider"]}_slot_{n:02d}', 'key_env': '',
898
- 'base_url': base_motor, '_key': key_local, '_motor_local': True}
899
- for n in range(1, 21)]
896
+ if cfg['provider'] == 'nvidia':
897
+ # Playground público: um destino lógico, sem transformar
898
+ # subagentes em um número fixo de slots no bridge Python.
899
+ pool = [{'name': 'nvidia_local', 'key_env': '', 'base_url': base_motor,
900
+ '_key': key_local, '_motor_local': True}]
901
+ else:
902
+ # Antigravity usa OAuth, cotas e contas da pessoa. O Node faz o
903
+ # failover; estes slots são apenas de transporte, não de ausência
904
+ # de autenticação nem de concorrência ilimitada.
905
+ pool = [{'name': f'antigravity_slot_{n:02d}', 'key_env': '',
906
+ 'base_url': base_motor, '_key': key_local, '_motor_local': True}
907
+ for n in range(1, 21)]
900
908
  else:
901
909
  pool = (provedores.get(cfg['provider']) or {}).get('apis') or []
902
910
  if not isinstance(pool, list) or not 1 <= len(pool) <= 100:
@@ -1599,11 +1607,11 @@ class ModelStatusMonitor:
1599
1607
 
1600
1608
 
1601
1609
  class ModelRequestQueue:
1602
- """Fila FIFO com um slot por conta: N chaves distintas -> até N upstreams.
1610
+ """FIFO por conta; somente NVIDIA Playground entra sem teto nem fila.
1603
1611
 
1604
- As requisições HTTP mantêm seus próprios payloads e sockets. A associação
1605
- request_id/conta existe apenas durante o atendimento. Uma chave ocupada ou
1606
- em 429 não recebe uma segunda requisição concorrente.
1612
+ As requisições HTTP mantêm seus próprios payloads e sockets. Nos provedores
1613
+ por chave/OAuth, request_id/conta controla a concorrência do transporte.
1614
+ No NVIDIA, `active` é apenas telemetria: nunca segura nem enfileira.
1607
1615
  """
1608
1616
 
1609
1617
  def __init__(self):
@@ -1613,27 +1621,40 @@ class ModelRequestQueue:
1613
1621
  self.sequence = 0
1614
1622
  self.closed = False
1615
1623
  self.completed = 0
1624
+ self.unlimited = False
1616
1625
 
1617
1626
  @contextmanager
1618
1627
  def turn(self, trace_id: str, route: str, on_hold=None, on_tick=None,
1619
1628
  stop_event=None, max_wait=0, heartbeat_interval=SSE_HEARTBEAT_SECONDS,
1620
1629
  state=None):
1630
+ acquired = False
1621
1631
  with self.cv:
1622
- if self.closed:
1632
+ if self.closed or (stop_event is not None and stop_event.is_set()):
1623
1633
  raise BridgeError(503, 'Fila encerrada', 'bridge_stopping')
1624
1634
  self.sequence += 1
1625
1635
  ticket = {'request_id': trace_id, 'sequence': self.sequence,
1626
1636
  'route': route, 'queued_at': time.monotonic(),
1627
1637
  'account_index': None}
1628
- self.pending.append(ticket)
1629
- position = len(self.pending) + len(self.active)
1630
- LOG.info('queue_received id=%s sequence=%s position=%s route=%s',
1631
- trace_id, ticket['sequence'], position, route)
1638
+ if self.unlimited:
1639
+ # NVIDIA: o ticket registra a atividade, mas nunca passa por
1640
+ # `pending` nem aguarda outra requisição terminar.
1641
+ ticket['account_index'] = 0 if state is not None else None
1642
+ self.active[ticket['sequence']] = ticket
1643
+ acquired = True
1644
+ LOG.info('request_started_unlimited id=%s sequence=%s active=%s route=%s',
1645
+ trace_id, ticket['sequence'], len(self.active), route)
1646
+ else:
1647
+ self.pending.append(ticket)
1648
+ position = len(self.pending) + len(self.active)
1649
+ LOG.info('queue_received id=%s sequence=%s position=%s route=%s',
1650
+ trace_id, ticket['sequence'], position, route)
1632
1651
  self.cv.notify_all()
1633
- acquired = False
1634
1652
  started = ticket['queued_at']
1635
1653
  last_tick = started
1636
1654
  try:
1655
+ if acquired:
1656
+ yield ticket
1657
+ return
1637
1658
  # A mensagem SSE só é enviada após identificar uma espera real.
1638
1659
  while True:
1639
1660
  with self.cv:
@@ -1736,8 +1757,8 @@ class ModelRequestQueue:
1736
1757
  now = time.monotonic()
1737
1758
  active = list(self.active.values())
1738
1759
  head = min(active, key=lambda t: t['sequence']) if active else None
1739
- return {'model': MODEL, 'policy': 'FIFO_per_account',
1740
- 'max_simultaneous_upstream': getattr(self, 'account_count', 1),
1760
+ return {'model': MODEL, 'policy': 'unlimited' if self.unlimited else 'FIFO_per_account',
1761
+ 'max_simultaneous_upstream': None if self.unlimited else getattr(self, 'account_count', 1),
1741
1762
  'active_request_id': head['request_id'] if head else None,
1742
1763
  'active_route': head['route'] if head else None,
1743
1764
  'active_seconds': round(now - head['queued_at'], 1) if head else None,
@@ -1892,6 +1913,9 @@ class BridgeState:
1892
1913
  self.cfg = cfg
1893
1914
  self.targets = cfg['apis']
1894
1915
  self.provider = cfg.get('provider', 'unorouter')
1916
+ # Loopback descreve o transporte, não a autenticação. Antigravity e
1917
+ # WorkBuddy usam contas/cotas; OpenCode free tier também é finito.
1918
+ self.unlimited = self.provider == 'nvidia'
1895
1919
  self.key_reloader = None
1896
1920
  self.ready = [0.0] * len(self.targets)
1897
1921
  self.in_flight = [0] * len(self.targets)
@@ -1902,6 +1926,7 @@ class BridgeState:
1902
1926
  self.responses = {}
1903
1927
  self.queue = ModelRequestQueue()
1904
1928
  self.queue.account_count = len(self.targets)
1929
+ self.queue.unlimited = self.unlimited
1905
1930
  self.recovery_waiting = 0
1906
1931
  self.recovery_cycles = 0
1907
1932
  self.started_at = time.time()
@@ -1914,6 +1939,8 @@ class BridgeState:
1914
1939
  self.request_log = None
1915
1940
  self.workbuddy_vigia = None
1916
1941
  self.workbuddy_convites = None
1942
+ self._wb_logins_lock = threading.Lock()
1943
+ self._wb_logins = {}
1917
1944
  status_model = cfg.get('upstream_model') or UPSTREAM_MODEL
1918
1945
  if self.provider == 'unorouter':
1919
1946
  status_model = str(cfg.get('model_enviado') or '').strip() or status_model
@@ -1927,7 +1954,7 @@ class BridgeState:
1927
1954
  now = time.monotonic()
1928
1955
  candidates = [i for i in range(len(self.targets)) if i not in excluded and self.ready[i] <= now]
1929
1956
  if preferred is not None:
1930
- candidates = [i for i in candidates if i == preferred and self.in_flight[i] == 0]
1957
+ candidates = [i for i in candidates if i == preferred and (self.unlimited or self.in_flight[i] == 0)]
1931
1958
  if not candidates:
1932
1959
  return None
1933
1960
  least = min(self.in_flight[i] for i in candidates)
@@ -3605,6 +3632,67 @@ def workbuddy_resumo(cfg: dict, state, force: bool = False) -> dict:
3605
3632
  return workbuddy.resumo(cfg, _raiz_do_estado(state), force=force)
3606
3633
 
3607
3634
 
3635
+ def workbuddy_login_start(cfg: dict, state) -> dict:
3636
+ """Inicia sessao de login do WorkBuddy para uso via /connect do OpenCode."""
3637
+ iniciado = workbuddy.iniciar_login(cfg)
3638
+ estado = str(iniciado.get('state') or '').strip()
3639
+ url = str(iniciado.get('auth_url') or '').strip()
3640
+ if not estado or not url:
3641
+ raise BridgeError(502, 'WorkBuddy nao devolveu state/URL de login', 'upstream_error')
3642
+ expira = time.time() + 600
3643
+ with state._wb_logins_lock:
3644
+ agora = time.time()
3645
+ for chave in [k for k, v in state._wb_logins.items() if v.get('expires_at', 0) < agora]:
3646
+ state._wb_logins.pop(chave, None)
3647
+ state._wb_logins[estado] = {'state': estado, 'url': url, 'expires_at': expira}
3648
+ return {'state': estado, 'url': url, 'expiresAt': int(expira * 1000)}
3649
+
3650
+
3651
+ def workbuddy_login_status(cfg: dict, state, estado: str) -> dict:
3652
+ """Consulta se o login do WorkBuddy foi concluido no navegador e salva a conta."""
3653
+ estado = str(estado or '').strip()
3654
+ if not estado:
3655
+ return {'status': 'expired', 'error': 'state ausente'}
3656
+ with state._wb_logins_lock:
3657
+ item = state._wb_logins.get(estado)
3658
+ if not item:
3659
+ return {'status': 'expired', 'error': 'state desconhecido ou expirado'}
3660
+ if item.get('status') == 'complete' and item.get('account'):
3661
+ return {'status': 'complete', 'account': item['account']}
3662
+ if item.get('expires_at', 0) < time.time():
3663
+ state._wb_logins.pop(estado, None)
3664
+ return {'status': 'expired', 'error': 'link de login expirado'}
3665
+ try:
3666
+ auth = workbuddy.consultar_token(estado, cfg)
3667
+ except workbuddy.ErroWorkBuddy as exc:
3668
+ return {'status': 'failed', 'error': str(exc)}
3669
+ if not auth:
3670
+ return {'status': 'pending'}
3671
+ raiz = _raiz_do_estado(state)
3672
+ conta = workbuddy.obter_conta(estado, auth, cfg)
3673
+ registro = workbuddy.adicionar_conta(raiz, auth, conta)
3674
+ resumo_conta = {
3675
+ 'id': registro.get('id') or '',
3676
+ 'nome': registro.get('nome') or '',
3677
+ 'uid': registro.get('uid') or '',
3678
+ 'email': registro.get('email') or '',
3679
+ 'apelido': registro.get('apelido') or '',
3680
+ 'empresa': registro.get('empresa') or '',
3681
+ 'plano': registro.get('plano') or '',
3682
+ }
3683
+ with state._wb_logins_lock:
3684
+ if estado in state._wb_logins:
3685
+ state._wb_logins[estado]['status'] = 'complete'
3686
+ state._wb_logins[estado]['account'] = resumo_conta
3687
+ return {'status': 'complete', 'account': resumo_conta}
3688
+
3689
+
3690
+ def workbuddy_logout(state, alvo: str) -> dict:
3691
+ raiz = _raiz_do_estado(state)
3692
+ removida = workbuddy.remover_conta(raiz, alvo)
3693
+ return {'ok': True, 'removed': removida.get('nome') if isinstance(removida, dict) else None}
3694
+
3695
+
3608
3696
  def open_upstream(cfg: dict, state: BridgeState, chat: dict, trace_id: str, preferred: int | None = None):
3609
3697
  """Tenta as contas disponíveis; o laço resiliente decide a espera e repetição.
3610
3698
 
@@ -3678,6 +3766,8 @@ def open_upstream(cfg: dict, state: BridgeState, chat: dict, trace_id: str, pref
3678
3766
  conta_id = str((wb or {}).get('id') or '')
3679
3767
  # O gateway do WorkBuddy e stream-first: pedimos SSE e agregamos quando
3680
3768
  # o cliente pediu JSON, em vez de arriscar um stream:false sem suporte.
3769
+ # Relay Node em loopback não implica ausência de login: Antigravity
3770
+ # carrega OAuth/cotas; somente NVIDIA dispensa conta e API do usuário.
3681
3771
  eh_motor_local = cfg.get('provider') in kimi.PROVEDORES_MOTOR
3682
3772
  # O motor local (NVIDIA/Antigravity) tambem e stream-first e suporta
3683
3773
  # multiplos modelos pelo campo `model` enviado pelo cliente (ex.: OpenCode
@@ -4672,6 +4762,11 @@ class Handler(BaseHTTPRequestHandler):
4672
4762
  self.emit(200, jbytes({'status': 'ok', 'service': SERVICE_NAME,
4673
4763
  'version': BRIDGE_VERSION, 'model': MODEL}))
4674
4764
  return
4765
+ if path == '/workbuddy/login/status':
4766
+ query = parse_qs(urlsplit(self.path).query)
4767
+ estado = (query.get('state') or [''])[0]
4768
+ self.emit(200, jbytes(workbuddy_login_status(cfg, state, estado)))
4769
+ return
4675
4770
  self.authorized(cfg)
4676
4771
  if path == '/_bridge/routes':
4677
4772
  self.emit(200, jbytes({'service': SERVICE_NAME, 'version': BRIDGE_VERSION,
@@ -4805,6 +4900,15 @@ class Handler(BaseHTTPRequestHandler):
4805
4900
  self._bridge_stage = 'request_validation'
4806
4901
  try:
4807
4902
  cfg, state = self.runtime()
4903
+ raw_path = urlsplit(self.path).path
4904
+ if raw_path == '/workbuddy/login/start':
4905
+ self.emit(200, jbytes(workbuddy_login_start(cfg, state)))
4906
+ return
4907
+ if raw_path == '/workbuddy/logout':
4908
+ body = self.read_payload() if int(self.headers.get('Content-Length', '0') or '0') > 0 else {}
4909
+ alvo = str(body.get('alvo') or body.get('id') or body.get('uid') or body.get('nome') or '').strip()
4910
+ self.emit(200, jbytes(workbuddy_logout(state, alvo)))
4911
+ return
4808
4912
  self.authorized(cfg)
4809
4913
  path = self.resolve_route(trace)
4810
4914
  self._bridge_logged_path = path
@@ -5173,6 +5277,9 @@ class BridgeHTTPServer(ThreadingHTTPServer):
5173
5277
  erros de verdade continuam indo para o log padrão do socketserver."""
5174
5278
 
5175
5279
  allow_reuse_address = True
5280
+ # Backlog alto para rajadas de 50/100/200+ subagentes simultâneos sem
5281
+ # descartar SYN no listen() (o default do Python é apenas 5).
5282
+ request_queue_size = 512
5176
5283
 
5177
5284
  def handle_error(self, request, client_address):
5178
5285
  exc = sys.exc_info()[1]
package/dashboard_web.py CHANGED
@@ -25,7 +25,7 @@ SECURITY_HEADERS = {
25
25
  LOG_FILES = ('bridge-errors.log', 'painel-bridge.log', 'firewall.log', 'autostart.log',
26
26
  'dns_duck.log', 'tls_nyxo.log')
27
27
  REQUEST_FIELDS = ('ts', 'id', 'method', 'path', 'status', 'ms', 'stream', 'provider',
28
- 'account', 'attempts', 'error')
28
+ 'account', 'model', 'attempts', 'error')
29
29
 
30
30
 
31
31
  def local_dashboard_url(cfg: dict) -> str:
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.6"
30
+ echo "krnell v3.0.7"
31
31
  exit 0
32
32
  ;;
33
33
  upgrade|update)
package/opencode_sync.py CHANGED
@@ -65,16 +65,7 @@ def candidatos_config_opencode() -> list[Path]:
65
65
  return lista
66
66
 
67
67
 
68
- def _bloco_modelos_krnell(indent: str = ' ') -> str:
69
- modelos = [
70
- ('kimi-k3.1-pro', 'Kimi K3.1 Pro (NVIDIA)', 400000, 65536, ['text', 'image'], ['low', 'medium', 'high', 'max'], 'max'),
71
- ('minimax-m3.1-flash', 'MiniMax M3.1 Flash (NVIDIA)', 400000, 65536, ['text', 'image'], ['low', 'medium', 'high', 'max'], 'max'),
72
- ('claude-opus-5-5', 'Claude Opus 5.5 (Antigravity)', 1000000, 128000, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
73
- ('claude-sonnet-5-5', 'Claude Sonnet 5.5 (Antigravity)', 1000000, 128000, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
74
- ('gemini-4-hydrogen', 'Gemini 4 Hydrogen (Antigravity)', 1000000, 262144, ['text', 'image', 'audio', 'video', 'pdf'], ['low', 'medium', 'high', 'xhigh'], 'xhigh'),
75
- ('gemini-4-neon', 'Gemini 4 Neon (Antigravity)', 1000000, 262144, ['text', 'image', 'audio', 'video', 'pdf'], ['low', 'medium', 'high', 'xhigh'], 'xhigh'),
76
- ('krnell', 'Krnell Active (dynamic route)', 1000000, 65536, ['text', 'image'], ['low', 'medium', 'high', 'xhigh', 'max'], 'max'),
77
- ]
68
+ def _bloco_modelos_lista(modelos: list[tuple], indent: str = ' ') -> str:
78
69
  partes = []
79
70
  for mid, nome, ctx, out, inp, efforts, default_eff in modelos:
80
71
  variants = ', '.join(
@@ -102,6 +93,45 @@ def _bloco_modelos_krnell(indent: str = ' ') -> str:
102
93
  return ',\n'.join(partes)
103
94
 
104
95
 
96
+ def _bloco_modelos_krnell(indent: str = ' ') -> str:
97
+ # Apenas os modelos gratuitos do NVIDIA Playground (sem login/API key).
98
+ # O nome do provedor ("NVIDIA Free") já aparece ao lado no /model.
99
+ modelos = [
100
+ ('kimi-k3.1-pro', 'Kimi K3.1 Pro', 400000, 65536, ['text', 'image'], ['low', 'medium', 'high', 'max'], 'max'),
101
+ ('minimax-m3.1-flash', 'MiniMax M3.1 Flash', 400000, 65536, ['text', 'image'], ['low', 'medium', 'high', 'max'], 'max'),
102
+ ]
103
+ return _bloco_modelos_lista(modelos, indent)
104
+
105
+
106
+ def _bloco_modelos_antigravity(indent: str = ' ') -> str:
107
+ modelos = [
108
+ ('claude-opus-5-5', 'Claude Opus 5.5', 1000000, 128000, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
109
+ ('claude-sonnet-5-5', 'Claude Sonnet 5.5', 1000000, 128000, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
110
+ ('gemini-4-hydrogen', 'Gemini 4 Hydrogen', 1000000, 262144, ['text', 'image', 'audio', 'video', 'pdf'], ['low', 'medium', 'high', 'xhigh'], 'xhigh'),
111
+ ('gemini-4-neon', 'Gemini 4 Neon', 1000000, 262144, ['text', 'image', 'audio', 'video', 'pdf'], ['low', 'medium', 'high', 'xhigh'], 'xhigh'),
112
+ ]
113
+ return _bloco_modelos_lista(modelos, indent)
114
+
115
+
116
+ def _bloco_modelos_workbuddy(indent: str = ' ') -> str:
117
+ modelos = [
118
+ ('deepseek-v4.1-flash', 'DeepSeek V4.1 Flash', 1000000, 128000, ['text', 'image'], ['low', 'medium', 'high', 'max'], 'max'),
119
+ ('minimax-m3.1-flash', 'MiniMax M3.1 Flash', 1000000, 128000, ['text', 'image'], ['low', 'medium', 'high', 'max'], 'max'),
120
+ ('kimi-k3', 'Kimi K3', 1000000, 32000, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
121
+ ('glm-5.3-flash', 'GLM 5.3 Flash', 1000000, 32000, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
122
+ ('grok-4.7', 'Grok 4.7', 500000, 128000, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
123
+ ('gemini-3.8-flash', 'Gemini 3.8 Flash', 1000000, 65536, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
124
+ ]
125
+ return _bloco_modelos_lista(modelos, indent)
126
+
127
+
128
+ def _bloco_modelos_tokenharbor(indent: str = ' ') -> str:
129
+ modelos = [
130
+ ('deepseek-v4.1-flash:free', 'DeepSeek V4.1 Flash Free', 200000, 32768, ['text'], ['low', 'medium', 'high', 'max'], 'max'),
131
+ ]
132
+ return _bloco_modelos_lista(modelos, indent)
133
+
134
+
105
135
  def _garantir_plugin_no_texto(texto: str, plugin_dir: str) -> tuple[str, bool]:
106
136
  lit = json.dumps(plugin_dir)
107
137
  if lit in texto or 'plugins/system-prompt' in texto or 'plugins\\\\system-prompt' in texto:
@@ -125,6 +155,55 @@ def _garantir_plugin_no_texto(texto: str, plugin_dir: str) -> tuple[str, bool]:
125
155
  return texto, False
126
156
 
127
157
 
158
+ def _remover_provedor(texto: str, provider_id: str) -> tuple[str, bool]:
159
+ chave = f'"{provider_id}"'
160
+ idx = texto.find(chave)
161
+ if idx < 0:
162
+ return texto, False
163
+ brace = texto.find('{', idx)
164
+ if brace < 0:
165
+ return texto, False
166
+ prof = 0
167
+ in_str = False
168
+ esc = False
169
+ fim = -1
170
+ for i in range(brace, len(texto)):
171
+ ch = texto[i]
172
+ if in_str:
173
+ if esc:
174
+ esc = False
175
+ elif ch == '\\':
176
+ esc = True
177
+ elif ch == '"':
178
+ in_str = False
179
+ else:
180
+ if ch == '"':
181
+ in_str = True
182
+ elif ch == '{':
183
+ prof += 1
184
+ elif ch == '}':
185
+ prof -= 1
186
+ if prof == 0:
187
+ fim = i + 1
188
+ break
189
+ if fim <= brace:
190
+ return texto, False
191
+ lin_ini = texto.rfind('\n', 0, idx)
192
+ inicio = (lin_ini + 1) if (lin_ini >= 0 and not texto[lin_ini + 1:idx].strip()) else idx
193
+ depois = texto[fim:]
194
+ antes = texto[:inicio]
195
+ if depois.lstrip().startswith(','):
196
+ pos_v = depois.find(',')
197
+ depois = depois[pos_v + 1:]
198
+ if depois.startswith('\r\n'):
199
+ depois = depois[2:]
200
+ elif depois.startswith('\n'):
201
+ depois = depois[1:]
202
+ elif antes.rstrip().endswith(','):
203
+ antes = antes.rstrip()[:-1] + '\n'
204
+ return antes + depois, True
205
+
206
+
128
207
  def _substituir_ou_inserir_provedor(texto: str, provider_id: str, bloco: str) -> tuple[str, bool]:
129
208
  chave = f'"{provider_id}"'
130
209
  if chave in texto:
@@ -300,7 +379,8 @@ def configurar_opencode(raiz: Path, porta: int = 8765, api_key: str = '') -> dic
300
379
  cfg_dir = arq.parent
301
380
  cfg_dir.mkdir(parents=True, exist_ok=True)
302
381
 
303
- # 1) Plugin unificado (server: system-prompt + auto-start sob demanda; TUI: botão ◈ krnell no footer)
382
+ # 1) Plugin unificado (server: system-prompt + auto-start sob demanda; TUI:
383
+ # painel no slot session.composer.top, sem substituir abas/prompt do OpenCode)
304
384
  src_plugin_dir = raiz / 'plugins' / 'system-prompt'
305
385
  src_plugin = src_plugin_dir / 'index.ts'
306
386
  dst_plugin_dir = cfg_dir / 'plugins' / 'system-prompt'
@@ -314,7 +394,7 @@ def configurar_opencode(raiz: Path, porta: int = 8765, api_key: str = '') -> dic
314
394
  if origem_p.is_file() and origem_p.resolve() != destino_p.resolve():
315
395
  shutil.copy2(origem_p, destino_p)
316
396
  plugin_instalado = True
317
- # Registra o plugin TUI também em cli.json (slot home.footer.status + comando /krnell)
397
+ # Registra o plugin TUI também em cli.json (footer nativo + /krnell).
318
398
  _registrar_plugin_tui_cli_json(cfg_dir, str(dst_plugin_dir))
319
399
 
320
400
  # 2) AGENTS.md se existir na raiz e ainda nao existir no OpenCode
@@ -327,7 +407,7 @@ def configurar_opencode(raiz: Path, porta: int = 8765, api_key: str = '') -> dic
327
407
  key_val = (api_key or 'local').strip()
328
408
  bloco_krnell = (
329
409
  f' "krnell": {{\n'
330
- f' "name": "Krnell (local)",\n'
410
+ f' "name": "NVIDIA Free",\n'
331
411
  f' "package": "@opencode/ai/providers/openai-compatible",\n'
332
412
  f' "settings": {{\n'
333
413
  f' "baseURL": "{base_url}",\n'
@@ -360,14 +440,13 @@ def configurar_opencode(raiz: Path, porta: int = 8765, api_key: str = '') -> dic
360
440
  texto, _ = _substituir_ou_inserir_provedor(texto, 'nyxo', bloco_krnell)
361
441
  else:
362
442
  texto, _ = _substituir_ou_inserir_provedor(texto, 'krnell', bloco_krnell)
363
- # Atualiza tambem o baseURL e variants do kimibridge se existir, apontando pro krnell
364
- if '"kimibridge"' in texto:
365
- texto = re.sub(
366
- r'("kimibridge"[\s\S]{0,600}?"baseURL"\s*:\s*")[^"]*(")',
367
- rf'\g<1>{base_url}\2',
368
- texto,
369
- count=1,
370
- )
443
+ # Remove blocos estáticos que antes forçavam Antigravity/WorkBuddy/TokenHarbor
444
+ # no /model mesmo sem login (agora o plugin os registra dinamicamente com
445
+ # activation:"auto", aparecendo no /connect e entrando em /model só quando
446
+ # há conta/chave conectada). Remove também o legado duplicado "kimibridge".
447
+ for pid in ('antigravity', 'workbuddy', 'tokenharbor', 'kimibridge'):
448
+ if f'"{pid}"' in texto:
449
+ texto, _ = _remover_provedor(texto, pid)
371
450
  arq.write_text(texto, encoding='utf-8')
372
451
 
373
452
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "krnell",
3
- "version": "3.0.6",
3
+ "version": "3.0.7",
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": {