krnell 0.0.0-stage → 3.0.2

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.
Files changed (51) hide show
  1. package/Iniciar_Linux.sh +129 -0
  2. package/Instalar_Atalho_Windows.cmd +40 -0
  3. package/Instalar_Ubuntu.sh +95 -0
  4. package/Painel.cmd +138 -0
  5. package/README.md +82 -2
  6. package/atualizador.py +148 -0
  7. package/bin/krnell.mjs +159 -0
  8. package/bridge.py +5280 -0
  9. package/config.example.json +57 -0
  10. package/contexto.py +204 -0
  11. package/dashboard_web.py +308 -0
  12. package/dns_duck.py +227 -0
  13. package/ferramentas/Liberar_Firewall.ps1 +96 -0
  14. package/ferramentas/firewall_linux.sh +67 -0
  15. package/ferramentas/install_windows.py +482 -0
  16. package/ferramentas/selecionar_provedor.py +76 -0
  17. package/iniciar.sh +255 -0
  18. package/keys.example.env +3 -0
  19. package/kimi.py +567 -0
  20. package/opencode_sync.py +265 -0
  21. package/package.json +68 -4
  22. package/painel.py +5612 -0
  23. package/painel_web.py +367 -0
  24. package/plugins/system-prompt/index.ts +409 -0
  25. package/provedores/kimi/bridge.mjs +4349 -0
  26. package/provedores/kimi/package.json +10 -0
  27. package/provedores_catalogo.py +27 -0
  28. package/tls_proxy.py +205 -0
  29. package/tui_core.py +604 -0
  30. package/web/dist/.vite/manifest.json +84 -0
  31. package/web/dist/assets/LogsPage-DkXN-I7o.js +2 -0
  32. package/web/dist/assets/LogsPage-OsSvuqxQ.js +2 -0
  33. package/web/dist/assets/TerminalPage-CZTPxVyx.js +1 -0
  34. package/web/dist/assets/TerminalPage-D208X99P.js +1 -0
  35. package/web/dist/assets/TerminalPage-DYGPu4ux.css +1 -0
  36. package/web/dist/assets/index-B5rIwous.js +1 -0
  37. package/web/dist/assets/index-CJE_a_Tn.js +27 -0
  38. package/web/dist/assets/index-COlDAcsY.js +1 -0
  39. package/web/dist/assets/index-Dzc8Obwp.css +1 -0
  40. package/web/dist/assets/index-LZadV7rx.js +27 -0
  41. package/web/dist/assets/index-o8xT03ZV.css +1 -0
  42. package/web/dist/assets/press-start-2p-2BZhbCiP.ttf +0 -0
  43. package/web/dist/assets/react-vendor-C475ILlI.js +49 -0
  44. package/web/dist/assets/terminal-vendor-DOrYoP_4.css +32 -0
  45. package/web/dist/assets/terminal-vendor-Dp03d74L.js +38 -0
  46. package/web/dist/assets/terminal-webgl-BRBWwLY7.js +75 -0
  47. package/web/dist/favicon.svg +1 -0
  48. package/web/dist/fonts/OFL.txt +93 -0
  49. package/web/dist/fonts/press-start-2p.ttf +0 -0
  50. package/web/dist/index.html +18 -0
  51. package/workbuddy.py +1965 -0
package/kimi.py ADDED
@@ -0,0 +1,567 @@
1
+ """Motor NVIDIA Playground + Antigravity: bridge Node local supervisionado pelo krnell.
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 krnell 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 signal
19
+ import subprocess
20
+ import threading
21
+ import time
22
+ from pathlib import Path
23
+ from urllib.error import HTTPError, URLError
24
+ from urllib.request import ProxyHandler, Request, build_opener
25
+
26
+ PORTA_PADRAO = 9098
27
+ ESPERA_PRONTO = 30.0 # o browser sobe sob demanda; /healthz fica ok em ~1-3s
28
+ INTERVALO_VIGIA = 5.0
29
+ FALHAS_PARA_REINICIAR = 3
30
+ ESPERAS_DE_REINICIO = (3.0, 6.0, 15.0, 30.0, 60.0)
31
+ ARQUIVO_LOG = 'kimi.log'
32
+
33
+ PROVEDORES_MOTOR = ('kimi', 'nvidia', 'antigravity')
34
+ MODELOS_NVIDIA = ('kimi-k3.1-pro', 'minimax-m3.1-flash')
35
+ MODELOS_ANTIGRAVITY = (
36
+ 'gemini-4-neon',
37
+ 'gemini-4-hydrogen',
38
+ 'claude-opus-5-5',
39
+ 'claude-sonnet-5-5',
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
+
63
+ # Sem proxy: o processo é local. O proxy do sistema transformava loopback em 502.
64
+ ABRIDOR = build_opener(ProxyHandler({}))
65
+
66
+
67
+ def pasta(raiz: Path) -> Path:
68
+ return Path(raiz) / 'provedores' / 'kimi'
69
+
70
+
71
+ def url_base(porta: int = PORTA_PADRAO) -> str:
72
+ return f'http://127.0.0.1:{int(porta)}/v1'
73
+
74
+
75
+ def porta_de(url: str, padrao: int = PORTA_PADRAO) -> int:
76
+ """Porta do `base_url` cadastrado (`http://127.0.0.1:9098/v1` -> 9098)."""
77
+ from urllib.parse import urlsplit
78
+ try:
79
+ porta = urlsplit(str(url or '')).port
80
+ except ValueError:
81
+ porta = None
82
+ return int(porta or padrao)
83
+
84
+
85
+ def _candidatos_de_node(raiz: Path) -> list[str]:
86
+ """Node do pacote, do PATH, Termux, NVM e Windows."""
87
+ candidatos: list[str] = []
88
+ local = pasta(raiz) / 'node' / ('node.exe' if os.name == 'nt' else 'node')
89
+ if local.exists():
90
+ candidatos.append(str(local))
91
+ achado = shutil.which('node')
92
+ if achado:
93
+ candidatos.append(achado)
94
+ prefix = os.environ.get('PREFIX', '')
95
+ if prefix:
96
+ termux_node = Path(prefix) / 'bin' / 'node'
97
+ if termux_node.exists():
98
+ candidatos.append(str(termux_node))
99
+ home = Path.home()
100
+ if os.name == 'nt':
101
+ base = Path(os.environ.get('USERPROFILE') or home)
102
+ for raiz_node in (
103
+ base / '.workbuddy-ai' / 'binaries' / 'node' / 'versions',
104
+ base / 'AppData' / 'Local' / 'Programs' / 'nodejs',
105
+ Path(r'C:\Program Files\nodejs'),
106
+ ):
107
+ if not raiz_node.exists():
108
+ continue
109
+ if raiz_node.name == 'nodejs':
110
+ exe = raiz_node / 'node.exe'
111
+ if exe.exists():
112
+ candidatos.append(str(exe))
113
+ continue
114
+ for versao in sorted(raiz_node.iterdir(), reverse=True):
115
+ exe = versao / 'node.exe'
116
+ if exe.exists():
117
+ candidatos.append(str(exe))
118
+ else:
119
+ for fixo in ('/usr/bin/node', '/usr/local/bin/node'):
120
+ if Path(fixo).exists():
121
+ candidatos.append(fixo)
122
+ nvm = home / '.nvm' / 'versions' / 'node'
123
+ if nvm.exists():
124
+ for versao in sorted(nvm.iterdir(), reverse=True):
125
+ exe = versao / 'bin' / 'node'
126
+ if exe.exists():
127
+ candidatos.append(str(exe))
128
+ # remove duplicados preservando ordem
129
+ vistos: set[str] = set()
130
+ unicos: list[str] = []
131
+ for c in candidatos:
132
+ if c not in vistos:
133
+ vistos.add(c)
134
+ unicos.append(c)
135
+ return unicos
136
+
137
+
138
+ def achar_node(raiz: Path) -> str:
139
+ for caminho in _candidatos_de_node(raiz):
140
+ if Path(caminho).exists():
141
+ return caminho
142
+ raise RuntimeError(
143
+ 'node não encontrado: instale o Node.js 20+ ou coloque o binário em '
144
+ f'{pasta(raiz) / "node"}'
145
+ )
146
+
147
+
148
+ def _pedir(
149
+ porta: int,
150
+ caminho: str,
151
+ timeout: float = 4.0,
152
+ metodo: str = 'GET',
153
+ corpo: dict | None = None,
154
+ ) -> dict | None:
155
+ dados_bytes = None
156
+ headers = {'accept': 'application/json'}
157
+ if corpo is not None:
158
+ dados_bytes = json.dumps(corpo).encode('utf-8')
159
+ headers['content-type'] = 'application/json'
160
+ req = Request(
161
+ f'http://127.0.0.1:{int(porta)}{caminho}',
162
+ data=dados_bytes,
163
+ headers=headers,
164
+ method=metodo,
165
+ )
166
+ try:
167
+ with ABRIDOR.open(req, timeout=timeout) as resp:
168
+ return json.loads(resp.read(400_000).decode('utf-8', 'replace'))
169
+ except HTTPError as err:
170
+ try:
171
+ txt = err.read(200_000).decode('utf-8', 'replace')
172
+ parsed = json.loads(txt)
173
+ if isinstance(parsed, dict):
174
+ parsed.setdefault('_status', err.code)
175
+ return parsed
176
+ except Exception:
177
+ pass
178
+ return {'ok': False, 'error': f'HTTP {err.code}', '_status': err.code}
179
+ except (URLError, OSError, ValueError):
180
+ return None
181
+
182
+
183
+ def estado(porta: int = PORTA_PADRAO, timeout: float = 3.0) -> dict:
184
+ """Resumo completo do /healthz do motor (NVIDIA captcha + Antigravity)."""
185
+ dados = _pedir(porta, '/healthz', timeout)
186
+ if not isinstance(dados, dict) or not dados.get('ok'):
187
+ return {
188
+ 'rodando': False,
189
+ 'pronto': False,
190
+ 'porta': int(porta),
191
+ 'tokens': 0,
192
+ 'erro': '',
193
+ 'modelo': '',
194
+ 'navegador': '',
195
+ 'captcha': {},
196
+ 'antigravity': {},
197
+ 'modelos': [],
198
+ }
199
+ return {
200
+ 'rodando': True,
201
+ 'pid': int(dados.get('pid') or 0),
202
+ 'pronto': bool(dados.get('ok')),
203
+ 'captcha_pronto': bool(dados.get('ready')),
204
+ 'porta': int(porta),
205
+ 'tokens': int(dados.get('tokens') or 0),
206
+ 'erro': str(dados.get('lastError') or ''),
207
+ 'modelo': str(dados.get('model') or ''),
208
+ 'navegador': str(dados.get('browser') or ''),
209
+ 'captcha': dados.get('captcha') or {},
210
+ 'antigravity': dados.get('antigravity') or {},
211
+ 'modelos': dados.get('models') or [],
212
+ }
213
+
214
+
215
+ def ler_contas_antigravity_disco(raiz: Path) -> list[dict]:
216
+ """Lê antigravity.json direto do disco (funciona mesmo com o motor parado)."""
217
+ arq = pasta(raiz) / 'antigravity.json'
218
+ if not arq.exists():
219
+ return []
220
+ try:
221
+ dados = json.loads(arq.read_text(encoding='utf-8'))
222
+ except (OSError, ValueError):
223
+ return []
224
+ if isinstance(dados, dict):
225
+ contas = dados.get('accounts')
226
+ if isinstance(contas, list):
227
+ ativo = dados.get('active')
228
+ saida = []
229
+ for c in contas:
230
+ if not isinstance(c, dict):
231
+ continue
232
+ cid = str(c.get('id') or c.get('email') or '').strip()
233
+ if not cid:
234
+ continue
235
+ saida.append({
236
+ 'id': cid,
237
+ 'email': str(c.get('email') or cid),
238
+ 'projectId': str(c.get('projectId') or ''),
239
+ 'paidTier': str(c.get('paidTierName') or c.get('paidTier') or c.get('tier') or ''),
240
+ 'active': cid == ativo,
241
+ })
242
+ return saida
243
+ if dados.get('refreshToken') or dados.get('accessToken'):
244
+ email = str(dados.get('email') or 'antigravity')
245
+ return [{
246
+ 'id': email,
247
+ 'email': email,
248
+ 'projectId': str(dados.get('projectId') or ''),
249
+ 'paidTier': str(dados.get('paidTierName') or dados.get('paidTier') or ''),
250
+ 'active': True,
251
+ }]
252
+ return []
253
+
254
+
255
+ def antigravity_status(porta: int = PORTA_PADRAO, raiz: Path | None = None, timeout: float = 3.0) -> dict:
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
262
+ dados = _pedir(porta, '/antigravity/status', timeout)
263
+ if isinstance(dados, dict) and 'loggedIn' in dados:
264
+ dados['online'] = True
265
+ return dados
266
+ contas = ler_contas_antigravity_disco(raiz) if raiz else []
267
+ ativa = next((c for c in contas if c.get('active')), contas[0] if contas else None)
268
+ return {
269
+ 'online': False,
270
+ 'loggedIn': bool(contas),
271
+ 'email': (ativa or {}).get('email'),
272
+ 'projectId': (ativa or {}).get('projectId'),
273
+ 'accountsCount': len(contas),
274
+ 'accounts': contas,
275
+ 'quota': {},
276
+ }
277
+
278
+
279
+ def antigravity_iniciar_login(porta: int = PORTA_PADRAO, timeout: float = 5.0) -> dict:
280
+ res = _pedir(porta, '/antigravity/login/start', timeout=timeout, metodo='POST', corpo={})
281
+ if not isinstance(res, dict) or not res.get('url'):
282
+ raise RuntimeError(str((res or {}).get('error') or 'motor local não respondeu em /antigravity/login/start'))
283
+ return res
284
+
285
+
286
+ def antigravity_status_login(state: str, porta: int = PORTA_PADRAO, timeout: float = 3.0) -> dict:
287
+ from urllib.parse import quote
288
+ res = _pedir(porta, f'/antigravity/login/status?state={quote(str(state or ""))}', timeout=timeout)
289
+ return res if isinstance(res, dict) else {'status': 'pending'}
290
+
291
+
292
+ def antigravity_completar_login(state: str, entrada: str, porta: int = PORTA_PADRAO, timeout: float = 20.0) -> dict:
293
+ res = _pedir(
294
+ porta,
295
+ '/antigravity/login/complete',
296
+ timeout=timeout,
297
+ metodo='POST',
298
+ corpo={'state': state, 'input': entrada},
299
+ )
300
+ if not isinstance(res, dict):
301
+ raise RuntimeError('motor local não respondeu ao completar o login')
302
+ return res
303
+
304
+
305
+ def antigravity_ativar_conta(hint: str, porta: int = PORTA_PADRAO, timeout: float = 5.0) -> dict:
306
+ res = _pedir(
307
+ porta,
308
+ '/antigravity/accounts/active',
309
+ timeout=timeout,
310
+ metodo='POST',
311
+ corpo={'email': hint, 'id': hint},
312
+ )
313
+ if not isinstance(res, dict):
314
+ raise RuntimeError('motor local não respondeu ao trocar conta')
315
+ return res
316
+
317
+
318
+ def antigravity_remover_conta(hint: str, porta: int = PORTA_PADRAO, timeout: float = 5.0) -> dict:
319
+ res = _pedir(
320
+ porta,
321
+ '/antigravity/logout',
322
+ timeout=timeout,
323
+ metodo='POST',
324
+ corpo={'email': hint, 'id': hint},
325
+ )
326
+ if not isinstance(res, dict):
327
+ raise RuntimeError('motor local não respondeu ao remover conta')
328
+ return res
329
+
330
+
331
+ def recarregar_captcha(porta: int = PORTA_PADRAO, timeout: float = 30.0) -> bool:
332
+ res = _pedir(porta, '/admin/reload', timeout=timeout, metodo='POST', corpo={})
333
+ return bool(isinstance(res, dict) and res.get('ok'))
334
+
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
+
393
+ def garantir_motor_ativo(raiz: Path, porta: int = PORTA_PADRAO, timeout: float = 15.0) -> tuple[bool, subprocess.Popen | None, str]:
394
+ """Garante o motor Node de pé para login/gestão mesmo se o bridge principal estiver parado."""
395
+ if estado(porta, timeout=1.5).get('rodando'):
396
+ return True, None, ''
397
+ script = pasta(raiz) / 'bridge.mjs'
398
+ if not script.exists():
399
+ return False, None, f'bridge.mjs ausente em {script}'
400
+ try:
401
+ node = achar_node(raiz)
402
+ except RuntimeError as exc:
403
+ return False, None, str(exc)
404
+ log_dir = Path(raiz) / 'logs'
405
+ log_dir.mkdir(exist_ok=True)
406
+ log_fp = (log_dir / ARQUIVO_LOG).open('a', encoding='utf-8', errors='replace')
407
+ env = dict(os.environ)
408
+ env.update({'KIMI_SUPERVISADO': '1', 'HOST': '127.0.0.1', 'PORT': str(int(porta))})
409
+ opcoes: dict = {}
410
+ if os.name == 'nt':
411
+ opcoes['creationflags'] = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
412
+ try:
413
+ proc = subprocess.Popen(
414
+ [node, str(script)],
415
+ cwd=str(script.parent),
416
+ env=env,
417
+ stdin=subprocess.DEVNULL,
418
+ stdout=log_fp,
419
+ stderr=subprocess.STDOUT,
420
+ **opcoes,
421
+ )
422
+ except OSError as exc:
423
+ log_fp.close()
424
+ return False, None, f'{type(exc).__name__}: {exc}'
425
+ limite = time.time() + timeout
426
+ while time.time() < limite:
427
+ if proc.poll() is not None:
428
+ log_fp.close()
429
+ return False, None, f'motor saiu com código {proc.returncode}'
430
+ if estado(porta, timeout=1.5).get('rodando'):
431
+ return True, proc, ''
432
+ time.sleep(0.4)
433
+ return False, proc, 'motor local não respondeu a tempo'
434
+
435
+
436
+ class Vigia(threading.Thread):
437
+ """Mantém o motor local (NVIDIA + Antigravity) de pé enquanto o krnell precisar dele."""
438
+
439
+ def __init__(self, raiz: Path, porta: int = PORTA_PADRAO,
440
+ espera_pronto: float = ESPERA_PRONTO):
441
+ super().__init__(name='kimi-vigia', daemon=True)
442
+ self.raiz = Path(raiz)
443
+ self.porta = int(porta)
444
+ self.espera_pronto = float(espera_pronto)
445
+ self.processo: subprocess.Popen | None = None
446
+ self._parar = threading.Event()
447
+ self._log = None
448
+ self.erro = ''
449
+ self.reinicios = 0
450
+
451
+ def _abrir_log(self):
452
+ if self._log is None:
453
+ destino = self.raiz / 'logs'
454
+ destino.mkdir(exist_ok=True)
455
+ self._log = (destino / ARQUIVO_LOG).open('a', encoding='utf-8', errors='replace')
456
+
457
+ def _subir(self) -> bool:
458
+ if self.processo is not None and self.processo.poll() is None:
459
+ return True
460
+ script = pasta(self.raiz) / 'bridge.mjs'
461
+ if not script.exists():
462
+ self.erro = f'bridge.mjs ausente em {script}'
463
+ return False
464
+ try:
465
+ node = achar_node(self.raiz)
466
+ except RuntimeError as exc:
467
+ self.erro = str(exc)
468
+ return False
469
+ self._abrir_log()
470
+ ambiente = dict(os.environ)
471
+ ambiente.update({
472
+ 'KIMI_SUPERVISADO': '1',
473
+ 'HOST': '127.0.0.1',
474
+ 'PORT': str(self.porta),
475
+ })
476
+ opcoes: dict = {}
477
+ if os.name == 'nt':
478
+ opcoes['creationflags'] = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
479
+ try:
480
+ self.processo = subprocess.Popen(
481
+ [node, str(script)],
482
+ cwd=str(script.parent),
483
+ env=ambiente,
484
+ stdin=subprocess.DEVNULL,
485
+ stdout=self._log,
486
+ stderr=subprocess.STDOUT,
487
+ **opcoes,
488
+ )
489
+ except OSError as exc:
490
+ self.erro = f'{type(exc).__name__}: {exc}'
491
+ return False
492
+ self.erro = ''
493
+ return True
494
+
495
+ def _esperar_pronto(self) -> bool:
496
+ limite = time.time() + self.espera_pronto
497
+ while time.time() < limite and not self._parar.is_set():
498
+ if self.processo is not None and self.processo.poll() is not None:
499
+ self.erro = f'bridge saiu com código {self.processo.returncode}'
500
+ return False
501
+ if estado(self.porta, timeout=2.0).get('rodando'):
502
+ return True
503
+ time.sleep(0.5)
504
+ if not self._parar.is_set():
505
+ self.erro = self.erro or 'o motor local não respondeu a tempo'
506
+ return False
507
+
508
+ def run(self):
509
+ while not self._parar.is_set():
510
+ if not estado(self.porta).get('rodando'):
511
+ if self._subir():
512
+ self._esperar_pronto()
513
+ else:
514
+ espera = ESPERAS_DE_REINICIO[min(self.reinicios, len(ESPERAS_DE_REINICIO) - 1)]
515
+ self.reinicios += 1
516
+ self._parar.wait(espera)
517
+ continue
518
+ falhas = 0
519
+ while not self._parar.is_set():
520
+ self._parar.wait(INTERVALO_VIGIA)
521
+ if self._parar.is_set():
522
+ break
523
+ if estado(self.porta).get('rodando'):
524
+ falhas = 0
525
+ continue
526
+ falhas += 1
527
+ if falhas >= FALHAS_PARA_REINICIAR:
528
+ self.reinicios += 1
529
+ break
530
+ self.encerrar()
531
+
532
+ def encerrar(self):
533
+ self._parar.set()
534
+ processo, self.processo = self.processo, None
535
+ if processo is not None and processo.poll() is None:
536
+ if os.name == 'nt':
537
+ try:
538
+ subprocess.run(['taskkill', '/T', '/F', '/PID', str(processo.pid)],
539
+ capture_output=True, timeout=15)
540
+ except (OSError, subprocess.TimeoutExpired):
541
+ pass
542
+ else:
543
+ try:
544
+ processo.terminate()
545
+ except OSError:
546
+ pass
547
+ try:
548
+ processo.wait(timeout=10)
549
+ except subprocess.TimeoutExpired:
550
+ try:
551
+ processo.kill()
552
+ except OSError:
553
+ pass
554
+ except OSError:
555
+ pass
556
+ if self._log is not None:
557
+ try:
558
+ self._log.close()
559
+ finally:
560
+ self._log = None
561
+
562
+
563
+ def iniciar(raiz: Path, porta: int = PORTA_PADRAO) -> Vigia:
564
+ """Sobe o vigia (idempotente: se já houver um motor na porta, ele adota)."""
565
+ vigia = Vigia(raiz, porta)
566
+ vigia.start()
567
+ return vigia