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
package/kimi.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""Motor NVIDIA Playground + Antigravity: bridge Node local supervisionado pelo nyxo.
|
|
2
|
+
|
|
3
|
+
O código do motor mora em `provedores/kimi/bridge.mjs` — versão otimizada com:
|
|
4
|
+
- NVIDIA Playground: `kimi-k3.1-pro` e `minimax-m3.1-flash` via pool paralelo
|
|
5
|
+
leve (`chromium_headless_shell`, sob demanda, 0 MB ocioso);
|
|
6
|
+
- Antigravity (Google): `claude-opus-5-5`, `claude-sonnet-5-5`,
|
|
7
|
+
`gemini-4-hydrogen`, `gemini-4-neon` (multi-conta OAuth com troca de quota).
|
|
8
|
+
|
|
9
|
+
O nyxo fala com ele por HTTP em `127.0.0.1:<porta>/v1`. Este módulo encontra o
|
|
10
|
+
Node (Windows, Linux, Ubuntu e Termux), sobe o processo, acompanha saúde/cota,
|
|
11
|
+
expõe login/contas/logout do Antigravity e encerra de forma limpa.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import shutil
|
|
18
|
+
import subprocess
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from urllib.error import HTTPError, URLError
|
|
23
|
+
from urllib.request import ProxyHandler, Request, build_opener
|
|
24
|
+
|
|
25
|
+
PORTA_PADRAO = 9098
|
|
26
|
+
ESPERA_PRONTO = 30.0 # o browser sobe sob demanda; /healthz fica ok em ~1-3s
|
|
27
|
+
INTERVALO_VIGIA = 5.0
|
|
28
|
+
FALHAS_PARA_REINICIAR = 3
|
|
29
|
+
ESPERAS_DE_REINICIO = (3.0, 6.0, 15.0, 30.0, 60.0)
|
|
30
|
+
ARQUIVO_LOG = 'kimi.log'
|
|
31
|
+
|
|
32
|
+
PROVEDORES_MOTOR = ('kimi', 'nvidia', 'antigravity')
|
|
33
|
+
MODELOS_NVIDIA = ('kimi-k3.1-pro', 'minimax-m3.1-flash')
|
|
34
|
+
MODELOS_ANTIGRAVITY = (
|
|
35
|
+
'gemini-4-neon',
|
|
36
|
+
'gemini-4-hydrogen',
|
|
37
|
+
'claude-opus-5-5',
|
|
38
|
+
'claude-sonnet-5-5',
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Sem proxy: o processo é local. O proxy do sistema transformava loopback em 502.
|
|
42
|
+
ABRIDOR = build_opener(ProxyHandler({}))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def pasta(raiz: Path) -> Path:
|
|
46
|
+
return Path(raiz) / 'provedores' / 'kimi'
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def url_base(porta: int = PORTA_PADRAO) -> str:
|
|
50
|
+
return f'http://127.0.0.1:{int(porta)}/v1'
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def porta_de(url: str, padrao: int = PORTA_PADRAO) -> int:
|
|
54
|
+
"""Porta do `base_url` cadastrado (`http://127.0.0.1:9098/v1` -> 9098)."""
|
|
55
|
+
from urllib.parse import urlsplit
|
|
56
|
+
try:
|
|
57
|
+
porta = urlsplit(str(url or '')).port
|
|
58
|
+
except ValueError:
|
|
59
|
+
porta = None
|
|
60
|
+
return int(porta or padrao)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _candidatos_de_node(raiz: Path) -> list[str]:
|
|
64
|
+
"""Node do pacote, do PATH, Termux, NVM e Windows."""
|
|
65
|
+
candidatos: list[str] = []
|
|
66
|
+
local = pasta(raiz) / 'node' / ('node.exe' if os.name == 'nt' else 'node')
|
|
67
|
+
if local.exists():
|
|
68
|
+
candidatos.append(str(local))
|
|
69
|
+
achado = shutil.which('node')
|
|
70
|
+
if achado:
|
|
71
|
+
candidatos.append(achado)
|
|
72
|
+
prefix = os.environ.get('PREFIX', '')
|
|
73
|
+
if prefix:
|
|
74
|
+
termux_node = Path(prefix) / 'bin' / 'node'
|
|
75
|
+
if termux_node.exists():
|
|
76
|
+
candidatos.append(str(termux_node))
|
|
77
|
+
home = Path.home()
|
|
78
|
+
if os.name == 'nt':
|
|
79
|
+
base = Path(os.environ.get('USERPROFILE') or home)
|
|
80
|
+
for raiz_node in (
|
|
81
|
+
base / '.workbuddy-ai' / 'binaries' / 'node' / 'versions',
|
|
82
|
+
base / 'AppData' / 'Local' / 'Programs' / 'nodejs',
|
|
83
|
+
Path(r'C:\Program Files\nodejs'),
|
|
84
|
+
):
|
|
85
|
+
if not raiz_node.exists():
|
|
86
|
+
continue
|
|
87
|
+
if raiz_node.name == 'nodejs':
|
|
88
|
+
exe = raiz_node / 'node.exe'
|
|
89
|
+
if exe.exists():
|
|
90
|
+
candidatos.append(str(exe))
|
|
91
|
+
continue
|
|
92
|
+
for versao in sorted(raiz_node.iterdir(), reverse=True):
|
|
93
|
+
exe = versao / 'node.exe'
|
|
94
|
+
if exe.exists():
|
|
95
|
+
candidatos.append(str(exe))
|
|
96
|
+
else:
|
|
97
|
+
for fixo in ('/usr/bin/node', '/usr/local/bin/node'):
|
|
98
|
+
if Path(fixo).exists():
|
|
99
|
+
candidatos.append(fixo)
|
|
100
|
+
nvm = home / '.nvm' / 'versions' / 'node'
|
|
101
|
+
if nvm.exists():
|
|
102
|
+
for versao in sorted(nvm.iterdir(), reverse=True):
|
|
103
|
+
exe = versao / 'bin' / 'node'
|
|
104
|
+
if exe.exists():
|
|
105
|
+
candidatos.append(str(exe))
|
|
106
|
+
# remove duplicados preservando ordem
|
|
107
|
+
vistos: set[str] = set()
|
|
108
|
+
unicos: list[str] = []
|
|
109
|
+
for c in candidatos:
|
|
110
|
+
if c not in vistos:
|
|
111
|
+
vistos.add(c)
|
|
112
|
+
unicos.append(c)
|
|
113
|
+
return unicos
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def achar_node(raiz: Path) -> str:
|
|
117
|
+
for caminho in _candidatos_de_node(raiz):
|
|
118
|
+
if Path(caminho).exists():
|
|
119
|
+
return caminho
|
|
120
|
+
raise RuntimeError(
|
|
121
|
+
'node não encontrado: instale o Node.js 20+ ou coloque o binário em '
|
|
122
|
+
f'{pasta(raiz) / "node"}'
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _pedir(
|
|
127
|
+
porta: int,
|
|
128
|
+
caminho: str,
|
|
129
|
+
timeout: float = 4.0,
|
|
130
|
+
metodo: str = 'GET',
|
|
131
|
+
corpo: dict | None = None,
|
|
132
|
+
) -> dict | None:
|
|
133
|
+
dados_bytes = None
|
|
134
|
+
headers = {'accept': 'application/json'}
|
|
135
|
+
if corpo is not None:
|
|
136
|
+
dados_bytes = json.dumps(corpo).encode('utf-8')
|
|
137
|
+
headers['content-type'] = 'application/json'
|
|
138
|
+
req = Request(
|
|
139
|
+
f'http://127.0.0.1:{int(porta)}{caminho}',
|
|
140
|
+
data=dados_bytes,
|
|
141
|
+
headers=headers,
|
|
142
|
+
method=metodo,
|
|
143
|
+
)
|
|
144
|
+
try:
|
|
145
|
+
with ABRIDOR.open(req, timeout=timeout) as resp:
|
|
146
|
+
return json.loads(resp.read(400_000).decode('utf-8', 'replace'))
|
|
147
|
+
except HTTPError as err:
|
|
148
|
+
try:
|
|
149
|
+
txt = err.read(200_000).decode('utf-8', 'replace')
|
|
150
|
+
parsed = json.loads(txt)
|
|
151
|
+
if isinstance(parsed, dict):
|
|
152
|
+
parsed.setdefault('_status', err.code)
|
|
153
|
+
return parsed
|
|
154
|
+
except Exception:
|
|
155
|
+
pass
|
|
156
|
+
return {'ok': False, 'error': f'HTTP {err.code}', '_status': err.code}
|
|
157
|
+
except (URLError, OSError, ValueError):
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def estado(porta: int = PORTA_PADRAO, timeout: float = 3.0) -> dict:
|
|
162
|
+
"""Resumo completo do /healthz do motor (NVIDIA captcha + Antigravity)."""
|
|
163
|
+
dados = _pedir(porta, '/healthz', timeout)
|
|
164
|
+
if not isinstance(dados, dict) or not dados.get('ok'):
|
|
165
|
+
return {
|
|
166
|
+
'rodando': False,
|
|
167
|
+
'pronto': False,
|
|
168
|
+
'porta': int(porta),
|
|
169
|
+
'tokens': 0,
|
|
170
|
+
'erro': '',
|
|
171
|
+
'modelo': '',
|
|
172
|
+
'navegador': '',
|
|
173
|
+
'captcha': {},
|
|
174
|
+
'antigravity': {},
|
|
175
|
+
'modelos': [],
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
'rodando': True,
|
|
179
|
+
'pronto': bool(dados.get('ok')),
|
|
180
|
+
'captcha_pronto': bool(dados.get('ready')),
|
|
181
|
+
'porta': int(porta),
|
|
182
|
+
'tokens': int(dados.get('tokens') or 0),
|
|
183
|
+
'erro': str(dados.get('lastError') or ''),
|
|
184
|
+
'modelo': str(dados.get('model') or ''),
|
|
185
|
+
'navegador': str(dados.get('browser') or ''),
|
|
186
|
+
'captcha': dados.get('captcha') or {},
|
|
187
|
+
'antigravity': dados.get('antigravity') or {},
|
|
188
|
+
'modelos': dados.get('models') or [],
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def ler_contas_antigravity_disco(raiz: Path) -> list[dict]:
|
|
193
|
+
"""Lê antigravity.json direto do disco (funciona mesmo com o motor parado)."""
|
|
194
|
+
arq = pasta(raiz) / 'antigravity.json'
|
|
195
|
+
if not arq.exists():
|
|
196
|
+
return []
|
|
197
|
+
try:
|
|
198
|
+
dados = json.loads(arq.read_text(encoding='utf-8'))
|
|
199
|
+
except (OSError, ValueError):
|
|
200
|
+
return []
|
|
201
|
+
if isinstance(dados, dict):
|
|
202
|
+
contas = dados.get('accounts')
|
|
203
|
+
if isinstance(contas, list):
|
|
204
|
+
ativo = dados.get('active')
|
|
205
|
+
saida = []
|
|
206
|
+
for c in contas:
|
|
207
|
+
if not isinstance(c, dict):
|
|
208
|
+
continue
|
|
209
|
+
cid = str(c.get('id') or c.get('email') or '').strip()
|
|
210
|
+
if not cid:
|
|
211
|
+
continue
|
|
212
|
+
saida.append({
|
|
213
|
+
'id': cid,
|
|
214
|
+
'email': str(c.get('email') or cid),
|
|
215
|
+
'projectId': str(c.get('projectId') or ''),
|
|
216
|
+
'paidTier': str(c.get('paidTierName') or c.get('paidTier') or c.get('tier') or ''),
|
|
217
|
+
'active': cid == ativo,
|
|
218
|
+
})
|
|
219
|
+
return saida
|
|
220
|
+
if dados.get('refreshToken') or dados.get('accessToken'):
|
|
221
|
+
email = str(dados.get('email') or 'antigravity')
|
|
222
|
+
return [{
|
|
223
|
+
'id': email,
|
|
224
|
+
'email': email,
|
|
225
|
+
'projectId': str(dados.get('projectId') or ''),
|
|
226
|
+
'paidTier': str(dados.get('paidTierName') or dados.get('paidTier') or ''),
|
|
227
|
+
'active': True,
|
|
228
|
+
}]
|
|
229
|
+
return []
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
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)."""
|
|
234
|
+
dados = _pedir(porta, '/antigravity/status', timeout)
|
|
235
|
+
if isinstance(dados, dict) and 'loggedIn' in dados:
|
|
236
|
+
dados['online'] = True
|
|
237
|
+
return dados
|
|
238
|
+
contas = ler_contas_antigravity_disco(raiz) if raiz else []
|
|
239
|
+
ativa = next((c for c in contas if c.get('active')), contas[0] if contas else None)
|
|
240
|
+
return {
|
|
241
|
+
'online': False,
|
|
242
|
+
'loggedIn': bool(contas),
|
|
243
|
+
'email': (ativa or {}).get('email'),
|
|
244
|
+
'projectId': (ativa or {}).get('projectId'),
|
|
245
|
+
'accountsCount': len(contas),
|
|
246
|
+
'accounts': contas,
|
|
247
|
+
'quota': {},
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def antigravity_iniciar_login(porta: int = PORTA_PADRAO, timeout: float = 5.0) -> dict:
|
|
252
|
+
res = _pedir(porta, '/antigravity/login/start', timeout=timeout, metodo='POST', corpo={})
|
|
253
|
+
if not isinstance(res, dict) or not res.get('url'):
|
|
254
|
+
raise RuntimeError(str((res or {}).get('error') or 'motor local não respondeu em /antigravity/login/start'))
|
|
255
|
+
return res
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def antigravity_status_login(state: str, porta: int = PORTA_PADRAO, timeout: float = 3.0) -> dict:
|
|
259
|
+
from urllib.parse import quote
|
|
260
|
+
res = _pedir(porta, f'/antigravity/login/status?state={quote(str(state or ""))}', timeout=timeout)
|
|
261
|
+
return res if isinstance(res, dict) else {'status': 'pending'}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def antigravity_completar_login(state: str, entrada: str, porta: int = PORTA_PADRAO, timeout: float = 20.0) -> dict:
|
|
265
|
+
res = _pedir(
|
|
266
|
+
porta,
|
|
267
|
+
'/antigravity/login/complete',
|
|
268
|
+
timeout=timeout,
|
|
269
|
+
metodo='POST',
|
|
270
|
+
corpo={'state': state, 'input': entrada},
|
|
271
|
+
)
|
|
272
|
+
if not isinstance(res, dict):
|
|
273
|
+
raise RuntimeError('motor local não respondeu ao completar o login')
|
|
274
|
+
return res
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def antigravity_ativar_conta(hint: str, porta: int = PORTA_PADRAO, timeout: float = 5.0) -> dict:
|
|
278
|
+
res = _pedir(
|
|
279
|
+
porta,
|
|
280
|
+
'/antigravity/accounts/active',
|
|
281
|
+
timeout=timeout,
|
|
282
|
+
metodo='POST',
|
|
283
|
+
corpo={'email': hint, 'id': hint},
|
|
284
|
+
)
|
|
285
|
+
if not isinstance(res, dict):
|
|
286
|
+
raise RuntimeError('motor local não respondeu ao trocar conta')
|
|
287
|
+
return res
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def antigravity_remover_conta(hint: str, porta: int = PORTA_PADRAO, timeout: float = 5.0) -> dict:
|
|
291
|
+
res = _pedir(
|
|
292
|
+
porta,
|
|
293
|
+
'/antigravity/logout',
|
|
294
|
+
timeout=timeout,
|
|
295
|
+
metodo='POST',
|
|
296
|
+
corpo={'email': hint, 'id': hint},
|
|
297
|
+
)
|
|
298
|
+
if not isinstance(res, dict):
|
|
299
|
+
raise RuntimeError('motor local não respondeu ao remover conta')
|
|
300
|
+
return res
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def recarregar_captcha(porta: int = PORTA_PADRAO, timeout: float = 30.0) -> bool:
|
|
304
|
+
res = _pedir(porta, '/admin/reload', timeout=timeout, metodo='POST', corpo={})
|
|
305
|
+
return bool(isinstance(res, dict) and res.get('ok'))
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def garantir_motor_ativo(raiz: Path, porta: int = PORTA_PADRAO, timeout: float = 15.0) -> tuple[bool, subprocess.Popen | None, str]:
|
|
309
|
+
"""Garante o motor Node de pé para login/gestão mesmo se o bridge principal estiver parado."""
|
|
310
|
+
if estado(porta, timeout=1.5).get('rodando'):
|
|
311
|
+
return True, None, ''
|
|
312
|
+
script = pasta(raiz) / 'bridge.mjs'
|
|
313
|
+
if not script.exists():
|
|
314
|
+
return False, None, f'bridge.mjs ausente em {script}'
|
|
315
|
+
try:
|
|
316
|
+
node = achar_node(raiz)
|
|
317
|
+
except RuntimeError as exc:
|
|
318
|
+
return False, None, str(exc)
|
|
319
|
+
log_dir = Path(raiz) / 'logs'
|
|
320
|
+
log_dir.mkdir(exist_ok=True)
|
|
321
|
+
log_fp = (log_dir / ARQUIVO_LOG).open('a', encoding='utf-8', errors='replace')
|
|
322
|
+
env = dict(os.environ)
|
|
323
|
+
env.update({'KIMI_SUPERVISADO': '1', 'HOST': '127.0.0.1', 'PORT': str(int(porta))})
|
|
324
|
+
opcoes: dict = {}
|
|
325
|
+
if os.name == 'nt':
|
|
326
|
+
opcoes['creationflags'] = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
|
|
327
|
+
try:
|
|
328
|
+
proc = subprocess.Popen(
|
|
329
|
+
[node, str(script)],
|
|
330
|
+
cwd=str(script.parent),
|
|
331
|
+
env=env,
|
|
332
|
+
stdin=subprocess.DEVNULL,
|
|
333
|
+
stdout=log_fp,
|
|
334
|
+
stderr=subprocess.STDOUT,
|
|
335
|
+
**opcoes,
|
|
336
|
+
)
|
|
337
|
+
except OSError as exc:
|
|
338
|
+
log_fp.close()
|
|
339
|
+
return False, None, f'{type(exc).__name__}: {exc}'
|
|
340
|
+
limite = time.time() + timeout
|
|
341
|
+
while time.time() < limite:
|
|
342
|
+
if proc.poll() is not None:
|
|
343
|
+
log_fp.close()
|
|
344
|
+
return False, None, f'motor saiu com código {proc.returncode}'
|
|
345
|
+
if estado(porta, timeout=1.5).get('rodando'):
|
|
346
|
+
return True, proc, ''
|
|
347
|
+
time.sleep(0.4)
|
|
348
|
+
return False, proc, 'motor local não respondeu a tempo'
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
class Vigia(threading.Thread):
|
|
352
|
+
"""Mantém o motor local (NVIDIA + Antigravity) de pé enquanto o nyxo precisar dele."""
|
|
353
|
+
|
|
354
|
+
def __init__(self, raiz: Path, porta: int = PORTA_PADRAO,
|
|
355
|
+
espera_pronto: float = ESPERA_PRONTO):
|
|
356
|
+
super().__init__(name='kimi-vigia', daemon=True)
|
|
357
|
+
self.raiz = Path(raiz)
|
|
358
|
+
self.porta = int(porta)
|
|
359
|
+
self.espera_pronto = float(espera_pronto)
|
|
360
|
+
self.processo: subprocess.Popen | None = None
|
|
361
|
+
self._parar = threading.Event()
|
|
362
|
+
self._log = None
|
|
363
|
+
self.erro = ''
|
|
364
|
+
self.reinicios = 0
|
|
365
|
+
|
|
366
|
+
def _abrir_log(self):
|
|
367
|
+
if self._log is None:
|
|
368
|
+
destino = self.raiz / 'logs'
|
|
369
|
+
destino.mkdir(exist_ok=True)
|
|
370
|
+
self._log = (destino / ARQUIVO_LOG).open('a', encoding='utf-8', errors='replace')
|
|
371
|
+
|
|
372
|
+
def _subir(self) -> bool:
|
|
373
|
+
if self.processo is not None and self.processo.poll() is None:
|
|
374
|
+
return True
|
|
375
|
+
script = pasta(self.raiz) / 'bridge.mjs'
|
|
376
|
+
if not script.exists():
|
|
377
|
+
self.erro = f'bridge.mjs ausente em {script}'
|
|
378
|
+
return False
|
|
379
|
+
try:
|
|
380
|
+
node = achar_node(self.raiz)
|
|
381
|
+
except RuntimeError as exc:
|
|
382
|
+
self.erro = str(exc)
|
|
383
|
+
return False
|
|
384
|
+
self._abrir_log()
|
|
385
|
+
ambiente = dict(os.environ)
|
|
386
|
+
ambiente.update({
|
|
387
|
+
'KIMI_SUPERVISADO': '1',
|
|
388
|
+
'HOST': '127.0.0.1',
|
|
389
|
+
'PORT': str(self.porta),
|
|
390
|
+
})
|
|
391
|
+
opcoes: dict = {}
|
|
392
|
+
if os.name == 'nt':
|
|
393
|
+
opcoes['creationflags'] = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
|
|
394
|
+
try:
|
|
395
|
+
self.processo = subprocess.Popen(
|
|
396
|
+
[node, str(script)],
|
|
397
|
+
cwd=str(script.parent),
|
|
398
|
+
env=ambiente,
|
|
399
|
+
stdin=subprocess.DEVNULL,
|
|
400
|
+
stdout=self._log,
|
|
401
|
+
stderr=subprocess.STDOUT,
|
|
402
|
+
**opcoes,
|
|
403
|
+
)
|
|
404
|
+
except OSError as exc:
|
|
405
|
+
self.erro = f'{type(exc).__name__}: {exc}'
|
|
406
|
+
return False
|
|
407
|
+
self.erro = ''
|
|
408
|
+
return True
|
|
409
|
+
|
|
410
|
+
def _esperar_pronto(self) -> bool:
|
|
411
|
+
limite = time.time() + self.espera_pronto
|
|
412
|
+
while time.time() < limite and not self._parar.is_set():
|
|
413
|
+
if self.processo is not None and self.processo.poll() is not None:
|
|
414
|
+
self.erro = f'bridge saiu com código {self.processo.returncode}'
|
|
415
|
+
return False
|
|
416
|
+
if estado(self.porta, timeout=2.0).get('rodando'):
|
|
417
|
+
return True
|
|
418
|
+
time.sleep(0.5)
|
|
419
|
+
if not self._parar.is_set():
|
|
420
|
+
self.erro = self.erro or 'o motor local não respondeu a tempo'
|
|
421
|
+
return False
|
|
422
|
+
|
|
423
|
+
def run(self):
|
|
424
|
+
while not self._parar.is_set():
|
|
425
|
+
if not estado(self.porta).get('rodando'):
|
|
426
|
+
if self._subir():
|
|
427
|
+
self._esperar_pronto()
|
|
428
|
+
else:
|
|
429
|
+
espera = ESPERAS_DE_REINICIO[min(self.reinicios, len(ESPERAS_DE_REINICIO) - 1)]
|
|
430
|
+
self.reinicios += 1
|
|
431
|
+
self._parar.wait(espera)
|
|
432
|
+
continue
|
|
433
|
+
falhas = 0
|
|
434
|
+
while not self._parar.is_set():
|
|
435
|
+
self._parar.wait(INTERVALO_VIGIA)
|
|
436
|
+
if self._parar.is_set():
|
|
437
|
+
break
|
|
438
|
+
if estado(self.porta).get('rodando'):
|
|
439
|
+
falhas = 0
|
|
440
|
+
continue
|
|
441
|
+
falhas += 1
|
|
442
|
+
if falhas >= FALHAS_PARA_REINICIAR:
|
|
443
|
+
self.reinicios += 1
|
|
444
|
+
break
|
|
445
|
+
self.encerrar()
|
|
446
|
+
|
|
447
|
+
def encerrar(self):
|
|
448
|
+
self._parar.set()
|
|
449
|
+
processo, self.processo = self.processo, None
|
|
450
|
+
if processo is not None and processo.poll() is None:
|
|
451
|
+
if os.name == 'nt':
|
|
452
|
+
try:
|
|
453
|
+
subprocess.run(['taskkill', '/T', '/F', '/PID', str(processo.pid)],
|
|
454
|
+
capture_output=True, timeout=15)
|
|
455
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
456
|
+
pass
|
|
457
|
+
else:
|
|
458
|
+
try:
|
|
459
|
+
processo.terminate()
|
|
460
|
+
except OSError:
|
|
461
|
+
pass
|
|
462
|
+
try:
|
|
463
|
+
processo.wait(timeout=10)
|
|
464
|
+
except subprocess.TimeoutExpired:
|
|
465
|
+
try:
|
|
466
|
+
processo.kill()
|
|
467
|
+
except OSError:
|
|
468
|
+
pass
|
|
469
|
+
except OSError:
|
|
470
|
+
pass
|
|
471
|
+
if self._log is not None:
|
|
472
|
+
try:
|
|
473
|
+
self._log.close()
|
|
474
|
+
finally:
|
|
475
|
+
self._log = None
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def iniciar(raiz: Path, porta: int = PORTA_PADRAO) -> Vigia:
|
|
479
|
+
"""Sobe o vigia (idempotente: se já houver um motor na porta, ele adota)."""
|
|
480
|
+
vigia = Vigia(raiz, porta)
|
|
481
|
+
vigia.start()
|
|
482
|
+
return vigia
|