krnell 0.0.0-stage → 3.0.0
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/Iniciar_Linux.sh +129 -0
- package/Instalar_Atalho_Windows.cmd +40 -0
- package/Instalar_Ubuntu.sh +95 -0
- package/Painel.cmd +138 -0
- package/README.md +70 -2
- package/bin/nyxo.mjs +138 -0
- package/bridge.py +5196 -0
- package/config.example.json +57 -0
- package/contexto.py +184 -0
- package/dashboard_web.py +308 -0
- package/dns_duck.py +227 -0
- package/ferramentas/Liberar_Firewall.ps1 +96 -0
- package/ferramentas/firewall_linux.sh +67 -0
- package/ferramentas/install_windows.py +482 -0
- package/ferramentas/selecionar_provedor.py +70 -0
- package/iniciar.sh +255 -0
- package/keys.example.env +3 -0
- package/kimi.py +482 -0
- package/opencode_sync.py +239 -0
- package/package.json +69 -4
- package/painel.py +5227 -0
- package/painel_web.py +367 -0
- package/plugins/system-prompt/index.ts +409 -0
- package/provedores/kimi/bridge.mjs +4280 -0
- package/provedores/kimi/package.json +10 -0
- package/provedores_catalogo.py +155 -0
- package/tls_proxy.py +205 -0
- package/tui_core.py +600 -0
- package/web/dist/.vite/manifest.json +84 -0
- package/web/dist/assets/LogsPage-DkXN-I7o.js +2 -0
- package/web/dist/assets/LogsPage-OsSvuqxQ.js +2 -0
- package/web/dist/assets/TerminalPage-CZTPxVyx.js +1 -0
- package/web/dist/assets/TerminalPage-D208X99P.js +1 -0
- package/web/dist/assets/TerminalPage-DYGPu4ux.css +1 -0
- package/web/dist/assets/index-B5rIwous.js +1 -0
- package/web/dist/assets/index-CJE_a_Tn.js +27 -0
- package/web/dist/assets/index-COlDAcsY.js +1 -0
- package/web/dist/assets/index-Dzc8Obwp.css +1 -0
- package/web/dist/assets/index-LZadV7rx.js +27 -0
- package/web/dist/assets/index-o8xT03ZV.css +1 -0
- package/web/dist/assets/press-start-2p-2BZhbCiP.ttf +0 -0
- package/web/dist/assets/react-vendor-C475ILlI.js +49 -0
- package/web/dist/assets/terminal-vendor-DOrYoP_4.css +32 -0
- package/web/dist/assets/terminal-vendor-Dp03d74L.js +38 -0
- package/web/dist/assets/terminal-webgl-BRBWwLY7.js +75 -0
- package/web/dist/favicon.svg +1 -0
- package/web/dist/fonts/OFL.txt +93 -0
- package/web/dist/fonts/press-start-2p.ttf +0 -0
- package/web/dist/index.html +18 -0
- package/workbuddy.py +1965 -0
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""Instalador incremental: nunca substitui chaves já configuradas.
|
|
2
|
+
|
|
3
|
+
Usa apenas bibliotecas padrão do Python e não altera clientes externos.
|
|
4
|
+
"""
|
|
5
|
+
import argparse
|
|
6
|
+
import getpass
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import re
|
|
11
|
+
import tempfile
|
|
12
|
+
from typing import Callable
|
|
13
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
14
|
+
|
|
15
|
+
ROOT = Path(__file__).resolve().parents[1] # raiz do bridge (este arquivo vive em ferramentas\)
|
|
16
|
+
MAX_ACCOUNTS = 100
|
|
17
|
+
ACCOUNT_RE = re.compile(r'^UNOROUTER_KEY_(\d+)$')
|
|
18
|
+
TOKENHARBOR_RE = re.compile(r'^TOKENHARBOR_KEY_(\d+)$')
|
|
19
|
+
NAME_RE = re.compile(r'^conta_(\d+)$')
|
|
20
|
+
ENV_NAME_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
|
|
21
|
+
# Provedores que ja existem no bridge (nao podem ser recriados pelo /add).
|
|
22
|
+
PROVIDERS_NATIVOS = ('unorouter', 'tokenharbor', 'opencode', 'workbuddy')
|
|
23
|
+
MAX_PROVIDERS = 30
|
|
24
|
+
# Rotulos de dominio que nao identificam um provedor (usados so no nome).
|
|
25
|
+
ROTULOS_NEUTROS = ('www', 'com', 'net', 'org', 'io', 'ai', 'dev', 'app', 'api')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def read_env(path: Path):
|
|
29
|
+
raw = path.read_bytes()
|
|
30
|
+
source = raw.decode('utf-8-sig')
|
|
31
|
+
values = {}
|
|
32
|
+
for line in source.splitlines():
|
|
33
|
+
line = line.strip()
|
|
34
|
+
if not line or line.startswith('#'):
|
|
35
|
+
continue
|
|
36
|
+
name, sep, value = line.partition('=')
|
|
37
|
+
if not sep or not ENV_NAME_RE.fullmatch(name):
|
|
38
|
+
raise ValueError('keys.env existente tem linha inválida; nada foi alterado.')
|
|
39
|
+
if name in values:
|
|
40
|
+
raise ValueError(f'Variável duplicada em keys.env: {name}. Nada foi alterado.')
|
|
41
|
+
values[name] = value.strip().strip('"').strip("'")
|
|
42
|
+
return raw, values
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def atomic_replace(path: Path, payload: bytes, *, secret: bool = False):
|
|
46
|
+
"""Prepara escrita no mesmo volume; substituição não expõe arquivo parcial."""
|
|
47
|
+
fd, tmpname = tempfile.mkstemp(prefix='.' + path.name + '.', suffix='.tmp', dir=path.parent)
|
|
48
|
+
try:
|
|
49
|
+
if secret:
|
|
50
|
+
try:
|
|
51
|
+
os.fchmod(fd, 0o600)
|
|
52
|
+
except (AttributeError, OSError):
|
|
53
|
+
pass
|
|
54
|
+
with os.fdopen(fd, 'wb') as stream:
|
|
55
|
+
stream.write(payload)
|
|
56
|
+
stream.flush()
|
|
57
|
+
os.fsync(stream.fileno())
|
|
58
|
+
os.replace(tmpname, path)
|
|
59
|
+
finally:
|
|
60
|
+
if os.path.exists(tmpname):
|
|
61
|
+
os.unlink(tmpname)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def ask_keys(prompt: Callable[[str], str], known: set, start_index: int,
|
|
65
|
+
available_slots: int, *, allow_zero: bool):
|
|
66
|
+
additions = []
|
|
67
|
+
while len(additions) < available_slots:
|
|
68
|
+
index = start_index + len(additions)
|
|
69
|
+
value = prompt(f'Chave upstream {index}: ').strip()
|
|
70
|
+
if not value:
|
|
71
|
+
if not additions and not allow_zero:
|
|
72
|
+
print('Nenhuma chave cadastrada.')
|
|
73
|
+
break
|
|
74
|
+
if '\n' in value or '\r' in value or value.startswith('COLE_'):
|
|
75
|
+
print('Chave inválida. Não foi incluída.')
|
|
76
|
+
continue
|
|
77
|
+
if value in known:
|
|
78
|
+
print('Essa chave já está cadastrada. Nenhuma conta foi alterada.')
|
|
79
|
+
continue
|
|
80
|
+
known.add(value)
|
|
81
|
+
additions.append(value)
|
|
82
|
+
return additions
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def initialize(root: Path, prompt: Callable[[str], str] = getpass.getpass):
|
|
86
|
+
template = json.loads((root / 'config.example.json').read_text(encoding='utf-8'))
|
|
87
|
+
print('\nDeepSeek Universal Bridge: deepseek-v4.1-flash')
|
|
88
|
+
print('Nenhuma configuração anterior encontrada. Cadastre suas chaves; Enter encerra.')
|
|
89
|
+
keys = ask_keys(prompt, set(), 1, MAX_ACCOUNTS, allow_zero=False)
|
|
90
|
+
if not keys:
|
|
91
|
+
print('Nenhuma chave cadastrada. Nenhum arquivo foi criado.')
|
|
92
|
+
return 0
|
|
93
|
+
config = dict(template)
|
|
94
|
+
config['apis'] = [{'name': f'conta_{i:02d}', 'key_env': f'UNOROUTER_KEY_{i:02d}'}
|
|
95
|
+
for i in range(1, len(keys) + 1)]
|
|
96
|
+
# Sem BRIDGE_API_KEY: a API local abre apenas em 127.0.0.1 (loopback).
|
|
97
|
+
env_raw = ('BRIDGE_API_KEY=\n' + ''.join(
|
|
98
|
+
f'UNOROUTER_KEY_{i:02d}={key}\n' for i, key in enumerate(keys, 1))).encode('utf-8')
|
|
99
|
+
cfg_raw = (json.dumps(config, indent=2, ensure_ascii=False) + '\n').encode('utf-8')
|
|
100
|
+
envpath = root / 'keys.env'
|
|
101
|
+
cfgpath = root / 'config.json'
|
|
102
|
+
atomic_replace(envpath, env_raw, secret=True)
|
|
103
|
+
try:
|
|
104
|
+
atomic_replace(cfgpath, cfg_raw)
|
|
105
|
+
except BaseException:
|
|
106
|
+
# Se falhar após escrever keys.env, restaurar estado sem instalação parcial.
|
|
107
|
+
envpath.unlink(missing_ok=True)
|
|
108
|
+
raise
|
|
109
|
+
print(f'Configuração criada com {len(keys)} conta(s).')
|
|
110
|
+
return len(keys)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def add_keys(root: Path, prompt: Callable[[str], str] = getpass.getpass, *, provider='unorouter'):
|
|
114
|
+
if provider not in ('unorouter', 'tokenharbor'):
|
|
115
|
+
raise ValueError('Provedor desconhecido')
|
|
116
|
+
pool_field = 'apis' if provider == 'unorouter' else 'tokenharbor_apis'
|
|
117
|
+
key_prefix = 'UNOROUTER_KEY' if provider == 'unorouter' else 'TOKENHARBOR_KEY'
|
|
118
|
+
account_re = ACCOUNT_RE if provider == 'unorouter' else TOKENHARBOR_RE
|
|
119
|
+
name_prefix = 'conta' if provider == 'unorouter' else 'tokenharbor_conta'
|
|
120
|
+
cfgpath = root / 'config.json'
|
|
121
|
+
if not cfgpath.is_file():
|
|
122
|
+
raise ValueError('config.json não encontrado. Abra o Painel.cmd na pasta principal primeiro.')
|
|
123
|
+
config = json.loads(cfgpath.read_text(encoding='utf-8-sig'))
|
|
124
|
+
if not isinstance(config, dict) or not isinstance(config.get('apis'), list):
|
|
125
|
+
raise ValueError('config.json inválido. Nenhum arquivo foi alterado.')
|
|
126
|
+
accounts = config.get(pool_field, [])
|
|
127
|
+
if not isinstance(accounts, list) or len(accounts) > MAX_ACCOUNTS or (provider == 'unorouter' and not accounts):
|
|
128
|
+
raise ValueError('Lista de contas inválida. Nada alterado.')
|
|
129
|
+
filename = config.get('keys_file', 'keys.env')
|
|
130
|
+
if not isinstance(filename, str) or not filename.strip():
|
|
131
|
+
raise ValueError('keys_file inválido em config.json. Nada alterado.')
|
|
132
|
+
envpath = root / filename
|
|
133
|
+
if not envpath.is_file():
|
|
134
|
+
raise ValueError(f'Arquivo de chaves {filename} não encontrado. Nada alterado.')
|
|
135
|
+
existing_raw, env_values = read_env(envpath)
|
|
136
|
+
# BRIDGE_API_KEY é opcional: vazia/ausente = API local aberta no loopback.
|
|
137
|
+
known = {v for v in env_values.values() if v}
|
|
138
|
+
used_env = set(env_values)
|
|
139
|
+
used_names = set()
|
|
140
|
+
highest = 0
|
|
141
|
+
for key_name in used_env:
|
|
142
|
+
match = account_re.fullmatch(key_name)
|
|
143
|
+
if match:
|
|
144
|
+
highest = max(highest, int(match.group(1)))
|
|
145
|
+
for account in accounts:
|
|
146
|
+
if not isinstance(account, dict) or not isinstance(account.get('key_env'), str):
|
|
147
|
+
raise ValueError('Conta existente inválida. Nada alterado.')
|
|
148
|
+
key_name = account['key_env']
|
|
149
|
+
if key_name not in env_values and not os.environ.get(key_name):
|
|
150
|
+
raise ValueError(f'Chave referenciada {key_name} ausente. Nada alterado.')
|
|
151
|
+
if key_name in used_env and env_values[key_name].startswith('COLE_'):
|
|
152
|
+
raise ValueError(f'Conta {key_name} ainda tem chave de exemplo. Nada alterado.')
|
|
153
|
+
known.add(os.environ.get(key_name, env_values.get(key_name, '')))
|
|
154
|
+
used_env.add(key_name)
|
|
155
|
+
name = account.get('name')
|
|
156
|
+
if isinstance(name, str):
|
|
157
|
+
used_names.add(name)
|
|
158
|
+
match = re.fullmatch(re.escape(name_prefix) + r'_(\d+)', name)
|
|
159
|
+
if match:
|
|
160
|
+
highest = max(highest, int(match.group(1)))
|
|
161
|
+
match = account_re.fullmatch(key_name)
|
|
162
|
+
if match:
|
|
163
|
+
highest = max(highest, int(match.group(1)))
|
|
164
|
+
if len(accounts) >= MAX_ACCOUNTS:
|
|
165
|
+
print('Limite de 100 contas atingido. Nenhuma chave foi alterada.')
|
|
166
|
+
return 0
|
|
167
|
+
if highest >= MAX_ACCOUNTS:
|
|
168
|
+
raise ValueError('Numeração já alcançou 100. Requer reorganização manual segura, sem apagar contas.')
|
|
169
|
+
first = highest + 1
|
|
170
|
+
slots = min(MAX_ACCOUNTS - len(accounts), MAX_ACCOUNTS - highest)
|
|
171
|
+
print(f'\n{len(accounts)} conta(s) existente(s), todas preservadas.')
|
|
172
|
+
print(f'Provedor: {provider}. Proxima chave: {key_prefix}_{first:02d} ({name_prefix}_{first:02d}).')
|
|
173
|
+
print('Insira chaves NOVAS. Enter sem digitar encerra sem apagar as antigas.')
|
|
174
|
+
additions = ask_keys(prompt, known, first, slots, allow_zero=True)
|
|
175
|
+
if not additions:
|
|
176
|
+
print('Nenhuma chave nova; config.json e keys.env continuam inalterados.')
|
|
177
|
+
return 0
|
|
178
|
+
# Não reescreve conteúdo antigo de keys.env: anexação preserva comentários,
|
|
179
|
+
# BRIDGE_API_KEY, valores, ordem, BOM e quebras de linha originais.
|
|
180
|
+
newline = b'\r\n' if b'\r\n' in existing_raw else b'\n'
|
|
181
|
+
prefix = b'' if not existing_raw or existing_raw.endswith((b'\n', b'\r')) else newline
|
|
182
|
+
suffix = b''.join((f'{key_prefix}_{i:02d}={key}'.encode('utf-8') + newline)
|
|
183
|
+
for i, key in enumerate(additions, first))
|
|
184
|
+
new_env = existing_raw + prefix + suffix
|
|
185
|
+
new_config = dict(config)
|
|
186
|
+
new_config[pool_field] = list(accounts) + [
|
|
187
|
+
{'name': f'{name_prefix}_{i:02d}', 'key_env': f'{key_prefix}_{i:02d}'}
|
|
188
|
+
for i in range(first, first + len(additions))]
|
|
189
|
+
new_cfg = (json.dumps(new_config, ensure_ascii=False, indent=2) + '\n').encode('utf-8')
|
|
190
|
+
# Primeiro chaves, depois referências. Em erro de gravação da config,
|
|
191
|
+
# restauramos o arquivo de chaves anterior sem perder as contas antigas.
|
|
192
|
+
atomic_replace(envpath, new_env, secret=True)
|
|
193
|
+
try:
|
|
194
|
+
atomic_replace(cfgpath, new_cfg)
|
|
195
|
+
except BaseException:
|
|
196
|
+
atomic_replace(envpath, existing_raw, secret=True)
|
|
197
|
+
raise
|
|
198
|
+
print(f'Adicionadas {len(additions)} conta(s) em {provider}. Total: {len(new_config[pool_field])}.')
|
|
199
|
+
print('BRIDGE_API_KEY e todas as chaves anteriores preservadas.')
|
|
200
|
+
print('Bridge ativo detecta as novas contas automaticamente em aproximadamente 1 segundo.')
|
|
201
|
+
return len(additions)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# ---------------------------------------------------------------------------
|
|
205
|
+
# Provedores novos: base URL + chave opcional (comando /add do painel)
|
|
206
|
+
# ---------------------------------------------------------------------------
|
|
207
|
+
|
|
208
|
+
def normalizar_base_url(valor: str) -> str:
|
|
209
|
+
"""Aceita a URL como a pessoa digita e devolve a forma canonica do bridge.
|
|
210
|
+
|
|
211
|
+
Sem esquema entra https://; barra final sai; query, fragmento, credencial
|
|
212
|
+
na URL e '/chat/completions' no fim sao recusados (o bridge exige /v1).
|
|
213
|
+
"""
|
|
214
|
+
texto = (valor or '').strip()
|
|
215
|
+
if not texto:
|
|
216
|
+
raise ValueError('A base URL do provedor nao pode ficar vazia.')
|
|
217
|
+
if '://' not in texto:
|
|
218
|
+
texto = 'https://' + texto
|
|
219
|
+
partes = urlsplit(texto)
|
|
220
|
+
if partes.scheme not in ('http', 'https'):
|
|
221
|
+
raise ValueError('A base URL precisa comecar com http:// ou https://')
|
|
222
|
+
if not partes.hostname:
|
|
223
|
+
raise ValueError('A base URL precisa de um host (ex.: https://api.exemplo.com/v1).')
|
|
224
|
+
if partes.username or partes.password:
|
|
225
|
+
raise ValueError('A base URL nao pode ter usuario nem senha.')
|
|
226
|
+
if partes.query or partes.fragment:
|
|
227
|
+
raise ValueError('A base URL nao pode ter parametros nem #.')
|
|
228
|
+
caminho = partes.path.rstrip('/')
|
|
229
|
+
if caminho.endswith('/chat/completions'):
|
|
230
|
+
raise ValueError('A base URL deve terminar em /v1, nao em /chat/completions.')
|
|
231
|
+
if partes.scheme == 'http' and partes.hostname not in ('127.0.0.1', 'localhost', '::1'):
|
|
232
|
+
raise ValueError('Use https:// — http:// so vale para 127.0.0.1 ou localhost.')
|
|
233
|
+
return urlunsplit((partes.scheme, partes.netloc, caminho, '', ''))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _rotulo_do_host(host: str) -> str:
|
|
237
|
+
"""Nome curto do provedor a partir do host (api.groq.com -> groq)."""
|
|
238
|
+
if re.fullmatch(r'[\d.]+', host or ''):
|
|
239
|
+
return 'local'
|
|
240
|
+
partes = [p for p in (host or '').lower().split('.')
|
|
241
|
+
if p and p not in ROTULOS_NEUTROS]
|
|
242
|
+
return partes[0] if partes else 'provedor'
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def slug_do_provedor(base_url: str, existentes) -> str:
|
|
246
|
+
"""Nome unico do provedor no config.json (derivado do host da base URL)."""
|
|
247
|
+
host = urlsplit(base_url).hostname or ''
|
|
248
|
+
base = re.sub(r'[^a-z0-9]+', '_', _rotulo_do_host(host)).strip('_') or 'provedor'
|
|
249
|
+
if base[0].isdigit():
|
|
250
|
+
base = 'p_' + base
|
|
251
|
+
if base in PROVIDERS_NATIVOS:
|
|
252
|
+
base = base + '_custom'
|
|
253
|
+
slug = base
|
|
254
|
+
contador = 2
|
|
255
|
+
while slug in existentes:
|
|
256
|
+
slug = f'{base}_{contador}'
|
|
257
|
+
contador += 1
|
|
258
|
+
return slug
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _provedores_do_config(config: dict) -> dict:
|
|
262
|
+
provedores = config.get('provedores')
|
|
263
|
+
if provedores is None:
|
|
264
|
+
provedores = {}
|
|
265
|
+
if not isinstance(provedores, dict):
|
|
266
|
+
raise ValueError('A secao "provedores" do config.json esta invalida.')
|
|
267
|
+
return provedores
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _proximo_env_nome(prefixo: str, env_values: dict, contas: list) -> str:
|
|
271
|
+
"""Nome de variavel livre para a proxima chave do provedor (KEY_01, KEY_02...)."""
|
|
272
|
+
maior = 0
|
|
273
|
+
for nome in env_values:
|
|
274
|
+
achado = re.fullmatch(re.escape(prefixo) + r'KEY_(\d+)', nome)
|
|
275
|
+
if achado:
|
|
276
|
+
maior = max(maior, int(achado.group(1)))
|
|
277
|
+
for conta in contas:
|
|
278
|
+
nome = str((conta or {}).get('key_env') or '')
|
|
279
|
+
achado = re.fullmatch(re.escape(prefixo) + r'KEY_(\d+)', nome)
|
|
280
|
+
if achado:
|
|
281
|
+
maior = max(maior, int(achado.group(1)))
|
|
282
|
+
indice = maior + 1
|
|
283
|
+
while f'{prefixo}KEY_{indice:02d}' in env_values:
|
|
284
|
+
indice += 1
|
|
285
|
+
return f'{prefixo}KEY_{indice:02d}'
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _anexar_chave_no_provedor(root: Path, config: dict, slug: str, entrada: dict,
|
|
289
|
+
contas: list, chave: str, env_values: dict,
|
|
290
|
+
existing_raw: bytes, envpath: Path):
|
|
291
|
+
"""Grava a chave no keys.env e devolve (config novo, conta nova, env_name)."""
|
|
292
|
+
env_name = _proximo_env_nome(f'{slug.upper()}_', env_values, contas)
|
|
293
|
+
conta = {'name': f'{slug}_conta_{len(contas) + 1:02d}',
|
|
294
|
+
'key_env': env_name,
|
|
295
|
+
'base_url': entrada.get('base_url')}
|
|
296
|
+
nova_entrada = dict(entrada)
|
|
297
|
+
nova_entrada['base_url'] = entrada.get('base_url')
|
|
298
|
+
nova_entrada['apis'] = list(contas) + [conta]
|
|
299
|
+
novo_config = dict(config)
|
|
300
|
+
novo_config['provedores'] = dict(config.get('provedores') or {})
|
|
301
|
+
novo_config['provedores'][slug] = nova_entrada
|
|
302
|
+
newline = b'\r\n' if b'\r\n' in existing_raw else b'\n'
|
|
303
|
+
prefixo_bytes = b'' if not existing_raw or existing_raw.endswith((b'\n', b'\r')) else newline
|
|
304
|
+
new_env = existing_raw + prefixo_bytes + f'{env_name}={chave}'.encode('utf-8') + newline
|
|
305
|
+
# chaves primeiro; se a config falhar, o keys.env volta ao estado anterior
|
|
306
|
+
atomic_replace(envpath, new_env, secret=True)
|
|
307
|
+
try:
|
|
308
|
+
atomic_replace(root / 'config.json',
|
|
309
|
+
(json.dumps(novo_config, ensure_ascii=False, indent=2) + '\n').encode('utf-8'))
|
|
310
|
+
except BaseException:
|
|
311
|
+
atomic_replace(envpath, existing_raw, secret=True)
|
|
312
|
+
raise
|
|
313
|
+
return novo_config, conta, env_name
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def add_provider(root: Path, base_url: str, key: str = '', *, provider: str = None) -> dict:
|
|
317
|
+
"""Cadastra um provedor novo: base URL + chave opcional (vazio = sem chave).
|
|
318
|
+
|
|
319
|
+
Nao mexe nos provedores que ja existem: cada um ganha sua propria entrada
|
|
320
|
+
em config.json ("provedores") e, quando ha chave, sua propria variavel no
|
|
321
|
+
keys.env.
|
|
322
|
+
"""
|
|
323
|
+
cfgpath = root / 'config.json'
|
|
324
|
+
if not cfgpath.is_file():
|
|
325
|
+
raise ValueError('config.json nao encontrado. Abra o Painel.cmd na pasta principal primeiro.')
|
|
326
|
+
config = json.loads(cfgpath.read_text(encoding='utf-8-sig'))
|
|
327
|
+
if not isinstance(config, dict):
|
|
328
|
+
raise ValueError('config.json invalido. Nenhum arquivo foi alterado.')
|
|
329
|
+
base = normalizar_base_url(base_url)
|
|
330
|
+
provedores = _provedores_do_config(config)
|
|
331
|
+
config = dict(config)
|
|
332
|
+
config['provedores'] = provedores
|
|
333
|
+
slug = (provider or '').strip().lower()
|
|
334
|
+
if not slug:
|
|
335
|
+
# mesma base URL cadastrada antes? usa o provedor que ja existe.
|
|
336
|
+
for nome, item in provedores.items():
|
|
337
|
+
if (isinstance(item, dict)
|
|
338
|
+
and str(item.get('base_url') or '').rstrip('/') == base):
|
|
339
|
+
slug = nome
|
|
340
|
+
break
|
|
341
|
+
if not slug:
|
|
342
|
+
slug = slug_do_provedor(base, provedores)
|
|
343
|
+
if not re.fullmatch(r'[a-z][a-z0-9_]{0,39}', slug):
|
|
344
|
+
raise ValueError('Nome do provedor invalido (letras, numeros e _).')
|
|
345
|
+
if slug in PROVIDERS_NATIVOS:
|
|
346
|
+
raise ValueError(f'{slug} e um provedor nativo; use outro nome.')
|
|
347
|
+
if slug not in provedores and len(provedores) >= MAX_PROVIDERS:
|
|
348
|
+
raise ValueError(f'Limite de {MAX_PROVIDERS} provedores cadastrados.')
|
|
349
|
+
entrada = provedores.get(slug) or {}
|
|
350
|
+
if not isinstance(entrada, dict):
|
|
351
|
+
raise ValueError(f'O provedor {slug} esta malformado no config.json.')
|
|
352
|
+
contas = entrada.get('apis') or []
|
|
353
|
+
if not isinstance(contas, list) or len(contas) >= MAX_ACCOUNTS:
|
|
354
|
+
raise ValueError(f'O provedor {slug} ja tem o limite de contas.')
|
|
355
|
+
filename = config.get('keys_file', 'keys.env')
|
|
356
|
+
if not isinstance(filename, str) or not filename.strip():
|
|
357
|
+
raise ValueError('keys_file invalido em config.json. Nada alterado.')
|
|
358
|
+
envpath = root / filename
|
|
359
|
+
if not envpath.is_file():
|
|
360
|
+
raise ValueError(f'Arquivo de chaves {filename} nao encontrado. Nada alterado.')
|
|
361
|
+
existing_raw, env_values = read_env(envpath)
|
|
362
|
+
chave = (key or '').strip()
|
|
363
|
+
if chave:
|
|
364
|
+
if '\n' in chave or '\r' in chave or chave.startswith('COLE_'):
|
|
365
|
+
raise ValueError('Chave invalida. Nada foi alterado.')
|
|
366
|
+
if any(valor == chave for valor in env_values.values()):
|
|
367
|
+
raise ValueError('Essa chave ja esta cadastrada. Nenhum arquivo foi alterado.')
|
|
368
|
+
if not chave:
|
|
369
|
+
# sem credencial: a conta entra sem key_env e o bridge fala sem Authorization
|
|
370
|
+
conta = {'name': f'{slug}_conta_{len(contas) + 1:02d}', 'base_url': base}
|
|
371
|
+
nova_entrada = dict(entrada)
|
|
372
|
+
nova_entrada['base_url'] = base
|
|
373
|
+
nova_entrada['apis'] = list(contas) + [conta]
|
|
374
|
+
novo_config = dict(config)
|
|
375
|
+
novo_config['provedores'] = dict(provedores)
|
|
376
|
+
novo_config['provedores'][slug] = nova_entrada
|
|
377
|
+
atomic_replace(cfgpath, (json.dumps(novo_config, ensure_ascii=False, indent=2)
|
|
378
|
+
+ '\n').encode('utf-8'))
|
|
379
|
+
return {'provider': slug, 'base_url': base, 'key_env': '',
|
|
380
|
+
'name': conta['name'], 'tem_chave': False,
|
|
381
|
+
'total_contas': len(nova_entrada['apis'])}
|
|
382
|
+
novo_config, conta, env_name = _anexar_chave_no_provedor(
|
|
383
|
+
root, config, slug, dict(entrada, base_url=base), contas, chave,
|
|
384
|
+
env_values, existing_raw, envpath)
|
|
385
|
+
return {'provider': slug, 'base_url': base, 'key_env': env_name,
|
|
386
|
+
'name': conta['name'], 'tem_chave': True,
|
|
387
|
+
'total_contas': len(novo_config['provedores'][slug]['apis'])}
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def add_provider_key(root: Path, provider: str, key: str) -> dict:
|
|
391
|
+
"""Cadastra uma chave nova em um provedor que ja existe no config.json."""
|
|
392
|
+
cfgpath = root / 'config.json'
|
|
393
|
+
if not cfgpath.is_file():
|
|
394
|
+
raise ValueError('config.json nao encontrado. Abra o Painel.cmd na pasta principal primeiro.')
|
|
395
|
+
config = json.loads(cfgpath.read_text(encoding='utf-8-sig'))
|
|
396
|
+
if not isinstance(config, dict):
|
|
397
|
+
raise ValueError('config.json invalido. Nenhum arquivo foi alterado.')
|
|
398
|
+
provedores = _provedores_do_config(config)
|
|
399
|
+
config = dict(config)
|
|
400
|
+
config['provedores'] = provedores
|
|
401
|
+
slug = (provider or '').strip().lower()
|
|
402
|
+
entrada = provedores.get(slug)
|
|
403
|
+
if not isinstance(entrada, dict):
|
|
404
|
+
raise ValueError(f'Provedor {slug} nao cadastrado. Use /add para cria-lo.')
|
|
405
|
+
contas = entrada.get('apis') or []
|
|
406
|
+
if not isinstance(contas, list) or len(contas) >= MAX_ACCOUNTS:
|
|
407
|
+
raise ValueError('Lista de contas invalida. Nada alterado.')
|
|
408
|
+
filename = config.get('keys_file', 'keys.env')
|
|
409
|
+
envpath = root / filename
|
|
410
|
+
if not envpath.is_file():
|
|
411
|
+
raise ValueError(f'Arquivo de chaves {filename} nao encontrado. Nada alterado.')
|
|
412
|
+
existing_raw, env_values = read_env(envpath)
|
|
413
|
+
chave = (key or '').strip()
|
|
414
|
+
if not chave:
|
|
415
|
+
raise ValueError('Chave vazia. Nada foi alterado.')
|
|
416
|
+
if '\n' in chave or '\r' in chave or chave.startswith('COLE_'):
|
|
417
|
+
raise ValueError('Chave invalida. Nada foi alterado.')
|
|
418
|
+
if any(valor == chave for valor in env_values.values()):
|
|
419
|
+
raise ValueError('Essa chave ja esta cadastrada. Nenhum arquivo foi alterado.')
|
|
420
|
+
base = str(entrada.get('base_url') or '').rstrip('/')
|
|
421
|
+
if not base:
|
|
422
|
+
raise ValueError(f'O provedor {slug} nao tem base URL. Nada alterado.')
|
|
423
|
+
novo_config, conta, env_name = _anexar_chave_no_provedor(
|
|
424
|
+
root, config, slug, dict(entrada, base_url=base), contas, chave,
|
|
425
|
+
env_values, existing_raw, envpath)
|
|
426
|
+
return {'provider': slug, 'base_url': base, 'key_env': env_name,
|
|
427
|
+
'name': conta['name'], 'tem_chave': True,
|
|
428
|
+
'total_contas': len(novo_config['provedores'][slug]['apis'])}
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def main():
|
|
432
|
+
parser = argparse.ArgumentParser(description='Instalar ou adicionar chaves sem sobrescrever contas.')
|
|
433
|
+
parser.add_argument('--add', action='store_true', help='Exigir instalação existente e adicionar chaves.')
|
|
434
|
+
parser.add_argument('--provider', choices=['unorouter', 'tokenharbor'], default=None,
|
|
435
|
+
help='Provedor para receber novas chaves; sem esta opcao usa o selecionado.')
|
|
436
|
+
parser.add_argument('--add-provider', action='store_true',
|
|
437
|
+
help='Cadastrar um provedor novo (base URL e chave opcional).')
|
|
438
|
+
parser.add_argument('--base-url', default=None, help='Base URL do provedor novo.')
|
|
439
|
+
parser.add_argument('--key', default=None, help='Chave do provedor novo (vazio = sem chave).')
|
|
440
|
+
args = parser.parse_args()
|
|
441
|
+
cfgpath = ROOT / 'config.json'
|
|
442
|
+
envpath = ROOT / 'keys.env'
|
|
443
|
+
try:
|
|
444
|
+
if args.add_provider:
|
|
445
|
+
base = args.base_url or input('Base URL do provedor (ex.: https://api.exemplo.com/v1): ').strip()
|
|
446
|
+
chave = args.key
|
|
447
|
+
if chave is None:
|
|
448
|
+
tem = input('Tem alguma API key? (s/n): ').strip().lower()
|
|
449
|
+
chave = getpass.getpass('API key (Enter deixa sem chave): ') if tem in ('s', 'sim', 'y', 'yes') else ''
|
|
450
|
+
resultado = add_provider(ROOT, base, chave)
|
|
451
|
+
print(f"Provedor {resultado['provider']} cadastrado: {resultado['base_url']}")
|
|
452
|
+
print(f"Chave salva em {resultado['key_env']}" if resultado['tem_chave']
|
|
453
|
+
else 'Sem chave: o bridge fala sem Authorization.')
|
|
454
|
+
print('Ative com /provedor no painel.')
|
|
455
|
+
return 0
|
|
456
|
+
if cfgpath.exists():
|
|
457
|
+
current = json.loads(cfgpath.read_text(encoding='utf-8-sig'))
|
|
458
|
+
ativo = args.provider or current.get('provider', 'unorouter')
|
|
459
|
+
if ativo in (current.get('provedores') or {}):
|
|
460
|
+
# provedor novo (cadastrado pelo /add): a chave entra na pool dele
|
|
461
|
+
chave = getpass.getpass(f'Chave {ativo}: ').strip()
|
|
462
|
+
if not chave:
|
|
463
|
+
print('Nenhuma chave cadastrada; nada foi alterado.')
|
|
464
|
+
else:
|
|
465
|
+
resultado = add_provider_key(ROOT, ativo, chave)
|
|
466
|
+
print(f"Chave salva em {resultado['key_env']} ({ativo}).")
|
|
467
|
+
else:
|
|
468
|
+
add_keys(ROOT, getpass.getpass, provider=ativo)
|
|
469
|
+
elif args.add or envpath.exists():
|
|
470
|
+
raise ValueError('Instalação parcial ou inexistente. Arquivos atuais foram preservados.')
|
|
471
|
+
else:
|
|
472
|
+
initialize(ROOT, getpass.getpass)
|
|
473
|
+
print('Base URL: http://127.0.0.1:8765/v1')
|
|
474
|
+
print('Modelo para os agentes: nyxo')
|
|
475
|
+
return 0
|
|
476
|
+
except (ValueError, OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
477
|
+
print(f'ERRO: {exc}')
|
|
478
|
+
return 1
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
if __name__ == '__main__':
|
|
482
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Escolhe upstream sem sobrescrever keys.env ou apagar contas do outro provedor."""
|
|
2
|
+
import argparse
|
|
3
|
+
import getpass
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
9
|
+
|
|
10
|
+
from install_windows import ROOT, read_env, atomic_replace, add_keys
|
|
11
|
+
|
|
12
|
+
PROVIDERS = {'1': 'unorouter', '2': 'tokenharbor'}
|
|
13
|
+
|
|
14
|
+
def select(root: Path, provider: str, *, prompt=None, allow_add=True):
|
|
15
|
+
if prompt is None:
|
|
16
|
+
prompt = getpass.getpass
|
|
17
|
+
if provider not in ('unorouter', 'tokenharbor'):
|
|
18
|
+
raise ValueError('Provedor inválido')
|
|
19
|
+
cfgpath = root / 'config.json'
|
|
20
|
+
if not cfgpath.is_file():
|
|
21
|
+
raise ValueError('Instale o bridge antes de selecionar um provedor.')
|
|
22
|
+
config = json.loads(cfgpath.read_text(encoding='utf-8-sig'))
|
|
23
|
+
field = 'apis' if provider == 'unorouter' else 'tokenharbor_apis'
|
|
24
|
+
accounts = config.get(field, [])
|
|
25
|
+
if not accounts and provider == 'tokenharbor' and allow_add:
|
|
26
|
+
print('Ainda nao ha chaves TokenHarbor; cadastre agora. Enter cancela.')
|
|
27
|
+
add_keys(root, prompt, provider='tokenharbor')
|
|
28
|
+
config = json.loads(cfgpath.read_text(encoding='utf-8-sig'))
|
|
29
|
+
accounts = config.get(field, [])
|
|
30
|
+
if not isinstance(accounts, list) or not accounts:
|
|
31
|
+
raise ValueError(f'Nenhuma conta cadastrada para {provider}. Nenhum provedor foi trocado.')
|
|
32
|
+
envpath = root / config.get('keys_file', 'keys.env')
|
|
33
|
+
if not envpath.is_file():
|
|
34
|
+
raise ValueError('Arquivo de chaves nao encontrado; nao foi alterado o provedor.')
|
|
35
|
+
_, values = read_env(envpath)
|
|
36
|
+
import os
|
|
37
|
+
for account in accounts:
|
|
38
|
+
name = account.get('key_env', '')
|
|
39
|
+
key = os.environ.get(name) or values.get(name, '')
|
|
40
|
+
expected = 'UNOROUTER_KEY_' if provider == 'unorouter' else 'TOKENHARBOR_KEY_'
|
|
41
|
+
if not name.startswith(expected) or not key or key.startswith('COLE_'):
|
|
42
|
+
raise ValueError(f'Credencial {name} invalida para {provider}; selecao nao alterada.')
|
|
43
|
+
previous = config.get('provider', 'unorouter')
|
|
44
|
+
if previous == provider:
|
|
45
|
+
print(f'{provider} ja estava selecionado; {len(accounts)} contas.')
|
|
46
|
+
return False
|
|
47
|
+
config['provider'] = provider
|
|
48
|
+
atomic_replace(cfgpath, (json.dumps(config, ensure_ascii=False, indent=2)+'\n').encode('utf-8'))
|
|
49
|
+
print(f'Provedor selecionado: {provider} ({len(accounts)} contas). Reinicie pelo Painel.cmd.')
|
|
50
|
+
print('Modelo mostrado aos agentes: nyxo')
|
|
51
|
+
return True
|
|
52
|
+
|
|
53
|
+
def main():
|
|
54
|
+
parser = argparse.ArgumentParser()
|
|
55
|
+
parser.add_argument('--provider', choices=['unorouter', 'tokenharbor'])
|
|
56
|
+
parser.add_argument('--no-add', action='store_true')
|
|
57
|
+
args = parser.parse_args()
|
|
58
|
+
try:
|
|
59
|
+
print('1 - UnoRouter | 2 - TokenHarbor')
|
|
60
|
+
choice = args.provider or PROVIDERS.get(input('Selecione o provedor (1/2): ').strip())
|
|
61
|
+
if not choice:
|
|
62
|
+
raise ValueError('Opcao invalida; nenhuma alteracao realizada.')
|
|
63
|
+
select(ROOT, choice, allow_add=not args.no_add)
|
|
64
|
+
except (ValueError, OSError, json.JSONDecodeError) as exc:
|
|
65
|
+
print('ERRO:', exc)
|
|
66
|
+
return 1
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
if __name__ == '__main__':
|
|
70
|
+
sys.exit(main())
|