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.
Files changed (50) 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 +70 -2
  6. package/bin/nyxo.mjs +138 -0
  7. package/bridge.py +5196 -0
  8. package/config.example.json +57 -0
  9. package/contexto.py +184 -0
  10. package/dashboard_web.py +308 -0
  11. package/dns_duck.py +227 -0
  12. package/ferramentas/Liberar_Firewall.ps1 +96 -0
  13. package/ferramentas/firewall_linux.sh +67 -0
  14. package/ferramentas/install_windows.py +482 -0
  15. package/ferramentas/selecionar_provedor.py +70 -0
  16. package/iniciar.sh +255 -0
  17. package/keys.example.env +3 -0
  18. package/kimi.py +482 -0
  19. package/opencode_sync.py +239 -0
  20. package/package.json +69 -4
  21. package/painel.py +5227 -0
  22. package/painel_web.py +367 -0
  23. package/plugins/system-prompt/index.ts +409 -0
  24. package/provedores/kimi/bridge.mjs +4280 -0
  25. package/provedores/kimi/package.json +10 -0
  26. package/provedores_catalogo.py +155 -0
  27. package/tls_proxy.py +205 -0
  28. package/tui_core.py +600 -0
  29. package/web/dist/.vite/manifest.json +84 -0
  30. package/web/dist/assets/LogsPage-DkXN-I7o.js +2 -0
  31. package/web/dist/assets/LogsPage-OsSvuqxQ.js +2 -0
  32. package/web/dist/assets/TerminalPage-CZTPxVyx.js +1 -0
  33. package/web/dist/assets/TerminalPage-D208X99P.js +1 -0
  34. package/web/dist/assets/TerminalPage-DYGPu4ux.css +1 -0
  35. package/web/dist/assets/index-B5rIwous.js +1 -0
  36. package/web/dist/assets/index-CJE_a_Tn.js +27 -0
  37. package/web/dist/assets/index-COlDAcsY.js +1 -0
  38. package/web/dist/assets/index-Dzc8Obwp.css +1 -0
  39. package/web/dist/assets/index-LZadV7rx.js +27 -0
  40. package/web/dist/assets/index-o8xT03ZV.css +1 -0
  41. package/web/dist/assets/press-start-2p-2BZhbCiP.ttf +0 -0
  42. package/web/dist/assets/react-vendor-C475ILlI.js +49 -0
  43. package/web/dist/assets/terminal-vendor-DOrYoP_4.css +32 -0
  44. package/web/dist/assets/terminal-vendor-Dp03d74L.js +38 -0
  45. package/web/dist/assets/terminal-webgl-BRBWwLY7.js +75 -0
  46. package/web/dist/favicon.svg +1 -0
  47. package/web/dist/fonts/OFL.txt +93 -0
  48. package/web/dist/fonts/press-start-2p.ttf +0 -0
  49. package/web/dist/index.html +18 -0
  50. package/workbuddy.py +1965 -0
@@ -0,0 +1,57 @@
1
+ {
2
+ "host": "127.0.0.1",
3
+ "nome_local": "bridge",
4
+ "link_publico": "",
5
+ "port": 8765,
6
+ "model": "nyxo",
7
+ "model_enviado": "kimi-k3.1-pro",
8
+ "upstream_base_url": "http://127.0.0.1:9098/v1",
9
+ "keys_file": "keys.env",
10
+ "max_attempts": 25,
11
+ "retry_delay_seconds": 60,
12
+ "workbuddy_busy_retry_seconds": 3,
13
+ "read_timeout_seconds": 300,
14
+ "reasoning_effort": "max",
15
+ "thinking_enabled": true,
16
+ "apis": [],
17
+ "model_status_enabled": false,
18
+ "model_status_interval_seconds": 60,
19
+ "sse_queue_heartbeat_seconds": 5,
20
+ "max_recovery_wait_seconds": 0,
21
+ "upstream_model": "kimi-k3.1-pro",
22
+ "provider": "nvidia",
23
+ "panel_theme": "nyxo",
24
+ "contextos_modelos": {},
25
+ "tokenharbor_apis": [],
26
+ "provedores": {
27
+ "nvidia": {
28
+ "base_url": "http://127.0.0.1:9098/v1",
29
+ "model": "kimi-k3.1-pro",
30
+ "apis": [
31
+ {
32
+ "name": "nvidia-local",
33
+ "key_env": ""
34
+ }
35
+ ]
36
+ },
37
+ "antigravity": {
38
+ "base_url": "http://127.0.0.1:9098/v1",
39
+ "model": "claude-sonnet-5-5",
40
+ "apis": [
41
+ {
42
+ "name": "antigravity-local",
43
+ "key_env": ""
44
+ }
45
+ ]
46
+ }
47
+ },
48
+ "opencode_model": "deepseek-v4.1-flash-free",
49
+ "opencode_variant": "max",
50
+ "opencode_inject_tools": true,
51
+ "opencode_ip_rotation": true,
52
+ "opencode_ip_rotation_attempts": 2,
53
+ "opencode_ip_rotation_mode": "auto",
54
+ "opencode_ip_family": "auto",
55
+ "model_context_tokens": 300000,
56
+ "warp_cli_path": ""
57
+ }
package/contexto.py ADDED
@@ -0,0 +1,184 @@
1
+ """Contexto persistente por provedor/modelo e sincronizacao do alias OpenCode local."""
2
+ from decimal import Decimal, InvalidOperation
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import shutil
8
+ import time
9
+ import uuid
10
+
11
+ MAX_CONTEXT = 1_000_000
12
+ OPENCODE_CONFIG_DIR = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config')) / 'opencode'
13
+
14
+
15
+ def parse_contexto(text):
16
+ match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*([kKmM])\s*', str(text))
17
+ if not match:
18
+ raise ValueError('use um numero com k ou M: 200k, 256k ou 1M; sem a letra nao vale')
19
+ try:
20
+ value = Decimal(match[1].replace(',', '.')) * (1000 if match[2].lower() == 'k' else 1000000)
21
+ except InvalidOperation as exc:
22
+ raise ValueError('tamanho de contexto invalido') from exc
23
+ if value <= 0 or value > MAX_CONTEXT or value != value.to_integral_value():
24
+ raise ValueError('o contexto deve ser positivo, em tokens inteiros, com maximo de 1M')
25
+ return int(value)
26
+
27
+
28
+ def format_contexto(value):
29
+ if value is None:
30
+ return 'nao definido'
31
+ if value == MAX_CONTEXT:
32
+ return '1M'
33
+ if value % 1000 == 0:
34
+ return f'{value // 1000}k'
35
+ return format(Decimal(value) / 1000, 'f').rstrip('0').rstrip('.') + 'k'
36
+
37
+
38
+ def validar_contextos(cfg):
39
+ contexts = cfg.get('contextos_modelos', {})
40
+ if not isinstance(contexts, dict):
41
+ raise ValueError('contextos_modelos precisa ser um objeto')
42
+ for provider, models in contexts.items():
43
+ if not isinstance(provider, str) or not isinstance(models, dict):
44
+ raise ValueError('contextos_modelos deve mapear provedor para modelos')
45
+ for model, tokens in models.items():
46
+ if not isinstance(model, str) or type(tokens) is not int or not 1 <= tokens <= MAX_CONTEXT:
47
+ raise ValueError('contexto salvo invalido: use inteiro positivo ate 1M por modelo')
48
+
49
+
50
+ def contexto_salvo(cfg, provider, model):
51
+ return (cfg.get('contextos_modelos', {}).get(provider, {}) or {}).get(model)
52
+
53
+
54
+ def _jsonc(text):
55
+ # Mantem os offsets: permite editar so o campo escolhido sem perder comentarios.
56
+ pattern = r'"(?:[^"\\]|\\.)*"|//[^\r\n]*|/\*[\s\S]*?\*/'
57
+ clean = re.sub(pattern, lambda m: m[0] if m[0].startswith('"') else
58
+ ''.join('\n' if c == '\n' else ' ' for c in m[0]), text)
59
+ clean = re.sub(r'("(?:[^"\\]|\\.)*")|,(\s*[}\]])',
60
+ lambda m: m[1] if m[1] is not None else ' ' + m[2], clean)
61
+ return clean, json.loads(clean)
62
+
63
+
64
+ def _span(clean, path, start=0):
65
+ decoder = json.JSONDecoder()
66
+ while start < len(clean) and clean[start].isspace():
67
+ start += 1
68
+ if not path:
69
+ _, end = decoder.raw_decode(clean, start)
70
+ return start, end
71
+ if clean[start:start + 1] != '{':
72
+ raise KeyError(path)
73
+ pos = start + 1
74
+ while True:
75
+ while clean[pos].isspace():
76
+ pos += 1
77
+ if clean[pos] == '}':
78
+ raise KeyError(path)
79
+ key, pos = decoder.raw_decode(clean, pos)
80
+ while clean[pos].isspace():
81
+ pos += 1
82
+ if clean[pos] != ':':
83
+ raise ValueError('objeto JSON invalido')
84
+ pos += 1
85
+ while clean[pos].isspace():
86
+ pos += 1
87
+ if key == path[0]:
88
+ return _span(clean, path[1:], pos)
89
+ _, pos = decoder.raw_decode(clean, pos)
90
+ while clean[pos].isspace():
91
+ pos += 1
92
+ if clean[pos] == ',':
93
+ pos += 1
94
+ elif clean[pos] == '}':
95
+ raise KeyError(path)
96
+ else:
97
+ raise ValueError('separador JSON invalido')
98
+
99
+
100
+ def restaurar_clientes(changes):
101
+ for path, backup in reversed(changes):
102
+ shutil.copy2(backup, path)
103
+
104
+
105
+ def sincronizar_opencode(cfg, tokens):
106
+ """Atualiza so os aliases que apontam a este bridge; guarda o valor anterior."""
107
+ if tokens is None and not cfg.get('contexto_opencode_padrao'):
108
+ return []
109
+ port = cfg.get('port', 8765)
110
+ urls = {str(cfg.get('link_publico') or '').rstrip('/').lower()}
111
+ for host in ('127.0.0.1', 'localhost'):
112
+ urls.add(f'http://{host}:{port}/v1')
113
+ if port == 80:
114
+ urls.add(f'http://{host}/v1')
115
+ aliases = {'nyxo', 'duck.space', 'deepseek-v4.1-flash'}
116
+ changes = []
117
+ defaults = cfg.get('contexto_opencode_padrao', {})
118
+ try:
119
+ for filename in ('opencode.json', 'opencode.jsonc'):
120
+ path = OPENCODE_CONFIG_DIR / filename
121
+ if not path.is_file():
122
+ continue
123
+ text = path.read_bytes().decode('utf-8-sig')
124
+ clean, original = _jsonc(text)
125
+ replacements = []
126
+ for provider, entry in original.get('provider', {}).items():
127
+ url = str(entry.get('options', {}).get('baseURL') or '')
128
+ url = re.sub(r'\{env:([^}]+)\}', lambda m: os.environ.get(m[1], ''), url)
129
+ if not url or url.rstrip('/').lower() not in urls:
130
+ continue
131
+ for model, definition in entry.get('models', {}).items():
132
+ if model not in aliases and definition.get('id') not in aliases:
133
+ continue
134
+ base = ('provider', provider, 'models', model)
135
+ key = str(path.resolve()) + '|' + provider + '|' + model
136
+ old = definition.get('limit', {}).get('context')
137
+ if tokens is not None:
138
+ cfg['contexto_opencode_padrao'] = defaults
139
+ defaults.setdefault(key, old)
140
+ target = tokens
141
+ elif key in defaults:
142
+ target = defaults[key]
143
+ else:
144
+ continue
145
+ if target == old:
146
+ continue
147
+ try:
148
+ span = _span(clean, base + ('limit', 'context'))
149
+ if target is not None:
150
+ replacements.append((*span, str(target)))
151
+ continue
152
+ except KeyError:
153
+ pass
154
+ limit = dict(definition.get('limit', {}))
155
+ if target is None:
156
+ limit.pop('context', None)
157
+ else:
158
+ limit['context'] = target
159
+ try:
160
+ span = _span(clean, base + ('limit',))
161
+ value = limit
162
+ except KeyError:
163
+ span = _span(clean, base)
164
+ value = dict(definition, limit=limit)
165
+ replacements.append((*span, json.dumps(value, ensure_ascii=False)))
166
+ if not replacements:
167
+ continue
168
+ for start, end, value in sorted(replacements, reverse=True):
169
+ text = text[:start] + value + text[end:]
170
+ _jsonc(text)
171
+ suffix = time.strftime('%Y%m%d-%H%M%S') + '-' + uuid.uuid4().hex[:6]
172
+ backup = path.with_name(path.name + '.backup-contexto-' + suffix)
173
+ shutil.copy2(path, backup)
174
+ changes.append((path, backup))
175
+ tmp = path.with_name('.contexto-' + uuid.uuid4().hex + '.tmp')
176
+ try:
177
+ tmp.write_bytes(text.encode('utf-8'))
178
+ os.replace(tmp, path)
179
+ finally:
180
+ tmp.unlink(missing_ok=True)
181
+ except Exception:
182
+ restaurar_clientes(changes)
183
+ raise
184
+ return changes
@@ -0,0 +1,308 @@
1
+ """Interface web do bridge: arquivos fechados, métricas sem conteúdo e status público."""
2
+ from __future__ import annotations
3
+
4
+ from functools import lru_cache
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+ import re
9
+ import time
10
+ from urllib.parse import parse_qs, urlsplit
11
+
12
+ import workbuddy
13
+
14
+ WEB_ROOT = Path(__file__).resolve().parent / 'web'
15
+ DIST_ROOT = WEB_ROOT / 'dist'
16
+ PAGES = ('status', 'requests', 'models', 'logs', 'terminal', 'panel', 'lab')
17
+ SECURITY_HEADERS = {
18
+ 'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
19
+ "img-src 'self' data: blob:; font-src 'self'; connect-src 'self' ws://127.0.0.1:* ws://localhost:*; frame-ancestors 'none'; "
20
+ "base-uri 'none'; object-src 'none'; form-action 'self'",
21
+ 'X-Frame-Options': 'DENY',
22
+ 'Referrer-Policy': 'no-referrer',
23
+ 'X-Content-Type-Options': 'nosniff',
24
+ }
25
+ LOG_FILES = ('bridge-errors.log', 'painel-bridge.log', 'firewall.log', 'autostart.log',
26
+ 'dns_duck.log', 'tls_nyxo.log')
27
+ REQUEST_FIELDS = ('ts', 'id', 'method', 'path', 'status', 'ms', 'stream', 'provider',
28
+ 'account', 'attempts', 'error')
29
+
30
+
31
+ def local_dashboard_url(cfg: dict) -> str:
32
+ port = int(cfg.get('port') or 8765)
33
+ host = str(cfg.get('host') or '127.0.0.1')
34
+ if host in ('0.0.0.0', '::', 'localhost'):
35
+ host = '127.0.0.1'
36
+ return f'http://{host}{":" + str(port) if port != 80 else ""}/dashboard/'
37
+
38
+
39
+ def selected_model(cfg: dict) -> str:
40
+ default = (cfg.get('opencode_model') or 'deepseek-v4.1-flash-free'
41
+ if cfg.get('provider') == 'opencode'
42
+ else cfg.get('upstream_model') or 'deepseek-v4.1-flash:free')
43
+ return str(cfg.get('model_enviado') or default).strip()
44
+
45
+
46
+ def number(value, default=None):
47
+ return value if type(value) in (int, float) and math.isfinite(value) else default
48
+
49
+
50
+ @lru_cache(maxsize=2)
51
+ def _built_assets(manifest_stamp):
52
+ """Só arquivos explicitamente emitidos pelo Vite; nunca uma raiz estática aberta."""
53
+ manifest = json.loads((DIST_ROOT / '.vite' / 'manifest.json').read_text(encoding='utf-8'))
54
+ names = {'index.html', 'favicon.svg', 'fonts/press-start-2p.ttf'}
55
+ for entry in manifest.values():
56
+ names.add(entry['file'])
57
+ names.update(entry.get('css', []))
58
+ names.update(entry.get('assets', []))
59
+ allowed = {}
60
+ types = {'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
61
+ '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.ttf': 'font/ttf'}
62
+ for name in names:
63
+ relative = Path(name)
64
+ if relative.is_absolute() or '..' in relative.parts or relative.suffix not in types:
65
+ continue
66
+ allowed['/dashboard/' + name] = (DIST_ROOT / relative, types[relative.suffix])
67
+ for path in ('/dashboard', '/dashboard/', *('/dashboard/' + page for page in PAGES)):
68
+ allowed[path] = (DIST_ROOT / 'index.html', types['.html'])
69
+ return allowed
70
+
71
+
72
+ def built_assets():
73
+ try:
74
+ return _built_assets((DIST_ROOT / '.vite' / 'manifest.json').stat().st_mtime_ns)
75
+ except (OSError, ValueError, KeyError, TypeError):
76
+ return {}
77
+
78
+
79
+ def runtime_secrets(cfg, state):
80
+ targets = getattr(state, 'targets', [])
81
+ return [cfg.get('_local_key') or ''] + [str(item.get('_key') or '')
82
+ for item in [*cfg.get('apis', []), *targets] if isinstance(item, dict)]
83
+
84
+
85
+ def operational_logs(cfg, state, source):
86
+ if source not in LOG_FILES:
87
+ return None
88
+ result = {'source': source, 'files': list(LOG_FILES), 'available': False,
89
+ 'lines': [], 'truncated': False, 'updated_at': None}
90
+ logs = getattr(state, 'logs_dir', None)
91
+ if not logs:
92
+ return result
93
+ file = Path(logs) / source
94
+ # Não segue atalhos para arquivos fora do diretório de logs.
95
+ if file.is_symlink() or file.resolve().parent != Path(logs).resolve():
96
+ return result
97
+ try:
98
+ with file.open('rb') as stream:
99
+ stream.seek(0, 2)
100
+ offset = max(0, stream.tell() - 131072)
101
+ stream.seek(offset)
102
+ if offset:
103
+ stream.readline()
104
+ raw = stream.read(131072).decode('utf-8', errors='replace').splitlines()
105
+ stat = file.stat()
106
+ except OSError:
107
+ return result
108
+ secrets = runtime_secrets(cfg, state)
109
+ rows = []
110
+ for index, line in enumerate(raw[-300:]):
111
+ line = scrub(line, secrets)
112
+ line = re.sub(r'(?i)(bearer\s+)[A-Za-z0-9._~+/=-]+', r'\1[redigido]', line)
113
+ line = re.sub(r'(?i)((?:api[_-]?key|authorization|password|secret|access_token)\s*[=:]\s*)\S+',
114
+ r'\1[redigido]', line)
115
+ # Logs operacionais somente: dumps de payload e credenciais ficam fora da UI.
116
+ if re.search(r'(?i)["\'](?:messages|prompt|input|content|api_key|authorization)["\']\s*:', line):
117
+ line = '[conteúdo de payload omitido]'
118
+ line = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', line)
119
+ line = ''.join(c for c in line[:2000] if ord(c) >= 32 or c == '\t')
120
+ level = ('error' if re.search(r'(?i)\b(error|erro|exception|failed|falha)\b', line)
121
+ else 'warning' if re.search(r'(?i)\b(warning|warn|aviso)\b', line) else 'info')
122
+ rows.append({'id': index, 'level': level, 'text': line})
123
+ result.update(available=True, lines=rows, truncated=bool(offset or len(raw) > 300),
124
+ updated_at=stat.st_mtime)
125
+ return result
126
+
127
+
128
+ def scrub(value, secrets):
129
+ if isinstance(value, str):
130
+ for secret in secrets:
131
+ # Credencial de verdade tem dezenas de caracteres. Um segredo de 1
132
+ # ou 2 caracteres casaria com texto comum (nomes de conta/modelo) e
133
+ # trocaria conteudo legitimo por "[redigido]".
134
+ if secret and len(secret) >= 6:
135
+ value = value.replace(secret, '[redigido]')
136
+ return value
137
+ if isinstance(value, dict):
138
+ return {key: scrub(item, secrets) for key, item in value.items()}
139
+ if isinstance(value, list):
140
+ return [scrub(item, secrets) for item in value]
141
+ return value
142
+
143
+
144
+ def recent_requests(logs) -> list:
145
+ if not logs:
146
+ return []
147
+ file = Path(logs) / 'requests.jsonl'
148
+ try:
149
+ stat = file.stat()
150
+ except OSError:
151
+ return []
152
+ return _recent_requests_cached(str(file), stat.st_mtime_ns, stat.st_size)
153
+
154
+
155
+ @lru_cache(maxsize=4)
156
+ def _recent_requests_cached(path, stamp, size):
157
+ try:
158
+ with Path(path).open('rb') as stream:
159
+ stream.seek(0, 2)
160
+ offset = max(0, stream.tell() - 262144)
161
+ stream.seek(offset)
162
+ if offset:
163
+ stream.readline()
164
+ lines = stream.read(262144).splitlines()
165
+ except OSError:
166
+ return []
167
+ result = []
168
+ for line in reversed(lines):
169
+ try:
170
+ row = json.loads(line)
171
+ except (ValueError, UnicodeError):
172
+ continue
173
+ if not isinstance(row, dict):
174
+ continue
175
+ safe = {key: (number(row[key]) if type(row[key]) in (int, float) else row[key])
176
+ for key in REQUEST_FIELDS if key in row and
177
+ isinstance(row[key], (str, int, float, bool, type(None)))}
178
+ safe['path'] = str(safe.get('path') or '').split('?', 1)[0][:180]
179
+ if isinstance(row.get('tokens'), dict):
180
+ safe['tokens'] = {key: number(row['tokens'].get(key), 0) for key in ('in', 'out')}
181
+ result.append(safe)
182
+ if len(result) == 60:
183
+ break
184
+ return result
185
+
186
+
187
+ def month_tokens(logs) -> dict:
188
+ if not logs:
189
+ return {}
190
+ try:
191
+ with (Path(logs) / 'tokens_mes.json').open('rb') as stream:
192
+ raw = stream.read(32769)
193
+ if len(raw) > 32768:
194
+ return {}
195
+ data = json.loads(raw)
196
+ if not isinstance(data, dict):
197
+ return {}
198
+ return {'mes': str(data.get('mes') or '')[:7],
199
+ **{key: number(data.get(key), 0) for key in ('prompt', 'completion', 'total', 'pedidos')}}
200
+ except (OSError, ValueError, UnicodeError):
201
+ return {}
202
+
203
+
204
+ def dashboard_snapshot(cfg, state) -> dict:
205
+ logs = getattr(state, 'logs_dir', None)
206
+ api_base = str(cfg.get('link_publico') or '').strip()
207
+ if not api_base.startswith(('https://', 'http://')):
208
+ api_base = local_dashboard_url(cfg).removesuffix('dashboard/') + 'v1'
209
+ secrets = runtime_secrets(cfg, state)
210
+ result = {'mode': 'live', 'now': time.time(), 'selected_model': selected_model(cfg),
211
+ 'api_base': api_base, 'bridge': state.status(),
212
+ 'month': month_tokens(logs), 'requests': recent_requests(logs)}
213
+ # Quota de creditos: exclusiva do provedor WorkBuddy, que e o unico com
214
+ # medidor proprio. Nos demais provedores a chave simplesmente nao existe.
215
+ if cfg.get('provider') == 'workbuddy':
216
+ raiz = Path(logs).parent if logs else Path(__file__).resolve().parent
217
+ try:
218
+ result['workbuddy'] = workbuddy.resumo(cfg, raiz)
219
+ except Exception as exc: # o painel nunca cai por causa da leitura de quota
220
+ result['workbuddy'] = {'enabled': True, 'contas': [], 'resumo': None,
221
+ 'modelos': [], 'erro': f'{type(exc).__name__}: {exc}',
222
+ 'atualizado_em': int(time.time()),
223
+ 'modelo': selected_model(cfg), 'provider': 'workbuddy'}
224
+ return scrub(result, secrets)
225
+
226
+
227
+ def normalize_catalog(payload) -> list:
228
+ if not isinstance(payload, dict):
229
+ return []
230
+ bars = payload.get('bars')
231
+ bars = bars if isinstance(bars, dict) else {}
232
+ interval = number(payload.get('bucket_sec'), 60) or 60
233
+ start = number(payload.get('bucket_start'))
234
+ components = payload.get('components')
235
+ if not isinstance(components, list):
236
+ return []
237
+ result = []
238
+ for item in components[:2000]:
239
+ if not isinstance(item, dict) or not isinstance(item.get('name'), str):
240
+ continue
241
+ name = item['name'][:200]
242
+ entry = {'name': name, 'status': str(item.get('status') or 'unknown')[:30]}
243
+ entry.update({key: number(item.get(key)) for key in (
244
+ 'up_channels', 'total_channels', 'probe_latency_ms', 'uptime_24h', 'uptime_30d', 'sampled_at')})
245
+ timeline = bars.get(name)
246
+ rows = timeline.get('buckets') if isinstance(timeline, dict) else []
247
+ rows = rows if isinstance(rows, list) else []
248
+ skipped = max(0, len(rows) - 90)
249
+ # Preserva posições de lacunas e desloca a origem quando recorta pontos antigos.
250
+ entry['bucket_start'] = start + skipped * interval if start is not None else None
251
+ entry['bucket_sec'] = interval
252
+ entry['buckets'] = [([max(0, number(v, 0)) for v in row[:7]]
253
+ if isinstance(row, list) and len(row) >= 7 else None)
254
+ for row in rows[-90:]]
255
+ result.append(entry)
256
+ return result
257
+
258
+
259
+ def status_catalog(cfg, state) -> dict:
260
+ monitor = state.model_status
261
+ enabled = cfg.get('provider', 'unorouter') == 'unorouter' and monitor.enabled
262
+ result = {'enabled': bool(enabled), 'selected_model': selected_model(cfg),
263
+ 'check_ok': False, 'checked_at': None, 'components': [], 'error': None}
264
+ if not enabled:
265
+ return result
266
+ monitor.fetch() # Compartilha o intervalo, o lock e a consulta do bridge.
267
+ with monitor.lock:
268
+ result['check_ok'] = bool(getattr(monitor, 'public_page_ok', False))
269
+ result['checked_at'] = monitor.last_check or None
270
+ result['components'] = normalize_catalog(getattr(monitor, 'public_page', None))
271
+ if not result['check_ok']:
272
+ result['error'] = 'Não foi possível atualizar a fonte pública. As amostras anteriores podem estar desatualizadas.'
273
+ return result
274
+
275
+
276
+ def serve_get(handler) -> bool:
277
+ path = urlsplit(handler.path).path
278
+ asset = built_assets().get(path)
279
+ if asset:
280
+ try:
281
+ data = asset[0].read_bytes()
282
+ except OSError:
283
+ handler.emit(503, b'Interface web indisponivel', ctype='text/plain; charset=utf-8')
284
+ else:
285
+ handler.emit(200, data, ctype=asset[1], headers=SECURITY_HEADERS)
286
+ return True
287
+ if path in ('/dashboard', '/dashboard/', *('/dashboard/' + page for page in PAGES)):
288
+ handler.emit(503, b'Execute npm run build para preparar a interface React.',
289
+ ctype='text/plain; charset=utf-8', headers=SECURITY_HEADERS)
290
+ return True
291
+ if path.startswith('/dashboard/'):
292
+ handler.emit(404, b'Not found', ctype='text/plain; charset=utf-8')
293
+ return True
294
+ if path not in ('/_bridge/dashboard', '/_bridge/dashboard/status', '/_bridge/dashboard/logs'):
295
+ return False
296
+ cfg, state = handler.runtime()
297
+ handler.authorized(cfg)
298
+ if path.endswith('/logs'):
299
+ source = parse_qs(urlsplit(handler.path).query).get('source', ['bridge-errors.log'])[0]
300
+ result = operational_logs(cfg, state, source)
301
+ if result is None:
302
+ handler.emit(400, b'Fonte de log nao permitida', ctype='text/plain; charset=utf-8')
303
+ return True
304
+ else:
305
+ result = dashboard_snapshot(cfg, state) if path == '/_bridge/dashboard' else status_catalog(cfg, state)
306
+ handler.emit(200, json.dumps(result, ensure_ascii=False, separators=(',', ':'), allow_nan=False).encode('utf-8'),
307
+ headers=SECURITY_HEADERS)
308
+ return True