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
package/dns_duck.py ADDED
@@ -0,0 +1,227 @@
1
+ """DNS local do duck.space.
2
+
3
+ Responde 'duck.space' (e os apelidos da rede) com o IP deste PC e repassa
4
+ todo o resto para o DNS de verdade. Serve para o celular enxergar o bridge
5
+ pelo nome: no aparelho, aponte o DNS do Wi-Fi para o IP deste PC.
6
+
7
+ python dns_duck.py # UDP+TCP 53, IP detectado sozinho
8
+ python dns_duck.py --ip 192.168.1.11 --porta 53
9
+
10
+ Somente stdlib, igual ao resto do projeto. Log em logs\\dns_duck.log.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import socket
16
+ import struct
17
+ import threading
18
+ import time
19
+ from pathlib import Path
20
+
21
+ RAIZ = Path(__file__).resolve().parent
22
+ LOG_PATH = RAIZ / 'logs' / 'dns_duck.log'
23
+
24
+ # Nomes que este servidor responde sozinho (tudo o mais vai pro upstream).
25
+ NOMES = ('duck.space', 'www.duck.space', 'bridge.local', 'bridge')
26
+ TTL = 60
27
+ UPSTREAMS = ('1.1.1.1', '8.8.8.8')
28
+ TIMEOUT_UPSTREAM = 4.0
29
+
30
+ TIPO_A = 1
31
+ TIPO_QUALQUER = 255
32
+ CLASSE_IN = 1
33
+
34
+ _log_lock = threading.Lock()
35
+
36
+
37
+ def registrar(mensagem: str) -> None:
38
+ """Anexa uma linha no log; nunca derruba o servidor."""
39
+ try:
40
+ with _log_lock:
41
+ LOG_PATH.parent.mkdir(exist_ok=True)
42
+ linha = time.strftime('%Y-%m-%d %H:%M:%S') + ' ' + mensagem + '\n'
43
+ with open(LOG_PATH, 'a', encoding='utf-8') as arquivo:
44
+ arquivo.write(linha)
45
+ except Exception:
46
+ pass
47
+
48
+
49
+ def ip_local() -> str:
50
+ """IP deste PC na rede (o mesmo que o painel mostra aos clientes)."""
51
+ sonda = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
52
+ try:
53
+ sonda.connect(('1.1.1.1', 80))
54
+ return sonda.getsockname()[0]
55
+ except OSError:
56
+ return '127.0.0.1'
57
+ finally:
58
+ sonda.close()
59
+
60
+
61
+ def ler_pergunta(dados: bytes):
62
+ """(nome, tipo, classe, bytes_da_pergunta) ou None se nao der para ler."""
63
+ if len(dados) < 12:
64
+ return None
65
+ if struct.unpack('!H', dados[4:6])[0] != 1:
66
+ return None
67
+ pos, rotulos = 12, []
68
+ while True:
69
+ if pos >= len(dados):
70
+ return None
71
+ tamanho = dados[pos]
72
+ if tamanho == 0:
73
+ pos += 1
74
+ break
75
+ if tamanho & 0xC0: # ponteiro nao aparece em pergunta: manda pro upstream
76
+ return None
77
+ pos += 1
78
+ if pos + tamanho > len(dados):
79
+ return None
80
+ rotulos.append(dados[pos:pos + tamanho].decode('latin-1'))
81
+ pos += tamanho
82
+ if pos + 4 > len(dados):
83
+ return None
84
+ tipo, classe = struct.unpack('!HH', dados[pos:pos + 4])
85
+ return '.'.join(rotulos), tipo, classe, dados[12:pos + 4]
86
+
87
+
88
+ def responder(dados: bytes, pergunta: bytes, ip: str | None) -> bytes:
89
+ """Resposta propria. ip=None vira NODATA (o nome existe, sem esse tipo)."""
90
+ rd = 0x0100 if dados[2] & 0x01 else 0
91
+ cabecalho = dados[:2] + struct.pack('!H', 0x8400 | rd)
92
+ if ip is None:
93
+ return cabecalho + struct.pack('!HHHH', 1, 0, 0, 0) + pergunta
94
+ registro = struct.pack('!HHHIH', 0xC00C, TIPO_A, CLASSE_IN, TTL, 4) + socket.inet_aton(ip)
95
+ return cabecalho + struct.pack('!HHHH', 1, 1, 0, 0) + pergunta + registro
96
+
97
+
98
+ def falha(dados: bytes) -> bytes:
99
+ """SERVFAIL quando o upstream inteiro ficou mudo."""
100
+ return dados[:2] + struct.pack('!H', 0x8182) + struct.pack('!HHHH', 0, 0, 0, 0)
101
+
102
+
103
+ def repassar(dados: bytes) -> bytes | None:
104
+ for servidor in UPSTREAMS:
105
+ sonda = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
106
+ sonda.settimeout(TIMEOUT_UPSTREAM)
107
+ try:
108
+ sonda.connect((servidor, 53))
109
+ sonda.send(dados)
110
+ return sonda.recv(4096)
111
+ except OSError as erro:
112
+ registrar(f'upstream {servidor} falhou: {erro}')
113
+ continue
114
+ finally:
115
+ sonda.close()
116
+ return None
117
+
118
+
119
+ def processar(dados: bytes, ip: str, origem: str) -> bytes:
120
+ pergunta = ler_pergunta(dados)
121
+ if pergunta is None:
122
+ return repassar(dados) or falha(dados)
123
+ nome, tipo, classe, bruto = pergunta
124
+ if classe == CLASSE_IN and nome.lower() in NOMES:
125
+ if tipo in (TIPO_A, TIPO_QUALQUER):
126
+ registrar(f'A {nome.lower()} -> {ip} (pedido de {origem})')
127
+ return responder(dados, bruto, ip)
128
+ registrar(f'tipo {tipo} {nome.lower()} -> NODATA (pedido de {origem})')
129
+ return responder(dados, bruto, None)
130
+ return repassar(dados) or falha(dados)
131
+
132
+
133
+ def servir_udp(porta: int, ip: str) -> None:
134
+ servidor = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
135
+ servidor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
136
+ servidor.bind(('0.0.0.0', porta))
137
+ while True:
138
+ try:
139
+ dados, origem = servidor.recvfrom(4096)
140
+ except OSError as erro:
141
+ registrar(f'erro lendo UDP: {erro}')
142
+ continue
143
+ try:
144
+ servidor.sendto(processar(dados, ip, origem[0]), origem)
145
+ except Exception as erro: # nunca derrubar o servidor por um pacote
146
+ registrar(f'erro respondendo {origem[0]}: {erro}')
147
+
148
+
149
+ def atender_tcp(conexao: socket.socket, ip: str) -> None:
150
+ with conexao:
151
+ conexao.settimeout(5)
152
+ try:
153
+ cabecalho = conexao.recv(2)
154
+ if len(cabecalho) < 2:
155
+ return
156
+ (tamanho,) = struct.unpack('!H', cabecalho)
157
+ dados = b''
158
+ while len(dados) < tamanho:
159
+ pedaco = conexao.recv(tamanho - len(dados))
160
+ if not pedaco:
161
+ return
162
+ dados += pedaco
163
+ try:
164
+ origem = conexao.getpeername()[0]
165
+ except OSError:
166
+ origem = '?'
167
+ resposta = processar(dados, ip, origem)
168
+ conexao.sendall(struct.pack('!H', len(resposta)) + resposta)
169
+ except OSError:
170
+ return
171
+
172
+
173
+ def servir_tcp(porta: int, ip: str) -> None:
174
+ servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
175
+ servidor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
176
+ servidor.bind(('0.0.0.0', porta))
177
+ servidor.listen(16)
178
+ while True:
179
+ try:
180
+ conexao, _ = servidor.accept()
181
+ except OSError as erro:
182
+ registrar(f'erro aceitando TCP: {erro}')
183
+ continue
184
+ threading.Thread(target=atender_tcp, args=(conexao, ip), daemon=True).start()
185
+
186
+
187
+ def main() -> int:
188
+ analisador = argparse.ArgumentParser(
189
+ description='DNS local: responde duck.space com o IP deste PC e repassa o resto.')
190
+ analisador.add_argument('--ip', default='',
191
+ help='IP a devolver para duck.space (padrao: o IPv4 desta maquina)')
192
+ analisador.add_argument('--porta', type=int, default=53, help='Porta UDP/TCP (padrao 53)')
193
+ argumentos = analisador.parse_args()
194
+
195
+ ip = argumentos.ip.strip() or ip_local()
196
+ try:
197
+ socket.inet_aton(ip)
198
+ except OSError:
199
+ print(f'IP invalido: {ip}')
200
+ return 2
201
+
202
+ print('')
203
+ print(f' duck.space -> {ip} (TCP e UDP na porta {argumentos.porta})')
204
+ print(f' apelidos -> {", ".join(NOMES[1:])}')
205
+ print(f' resto -> {", ".join(UPSTREAMS)}')
206
+ print('')
207
+ print(' No celular: DNS do Wi-Fi = este IP. No PC: nslookup duck.space 127.0.0.1')
208
+ print(' Log: logs\\dns_duck.log | Ctrl+C encerra.')
209
+ print('')
210
+ registrar(f'====== inicio ip={ip} porta={argumentos.porta} ======')
211
+
212
+ threading.Thread(target=servir_tcp, args=(argumentos.porta, ip), daemon=True).start()
213
+ try:
214
+ servir_udp(argumentos.porta, ip)
215
+ except KeyboardInterrupt:
216
+ pass
217
+ except OSError as erro:
218
+ print(f'Nao consegui abrir a porta {argumentos.porta}: {erro}')
219
+ print('Feche o que estiver usando a 53 (ou rode com --porta 5353).')
220
+ registrar(f'falha abrindo a porta: {erro}')
221
+ return 1
222
+ registrar('====== fim ======')
223
+ return 0
224
+
225
+
226
+ if __name__ == '__main__':
227
+ raise SystemExit(main())
@@ -0,0 +1,96 @@
1
+ # ============================================================
2
+ # Libera o bridge na REDE LOCAL (celular, outro PC).
3
+ # UMA unica regra de entrada, chamada "duck.space"
4
+ # (TCP 80 = API, TCP 443 = API com https, UDP 53 = DNS local).
5
+ # As regras antigas do projeto (TCP/mDNS/LLMNR) sao apagadas.
6
+ # O painel chama este script ja elevado (aceite o UAC).
7
+ # Manualmente: clique com o botao direito > Executar com
8
+ # PowerShell como administrador. Para remover as regras:
9
+ # powershell -ExecutionPolicy Bypass -File Liberar_Firewall.ps1 remover
10
+ # Tudo que este script faz vira log em logs\firewall.log
11
+ # ============================================================
12
+ param([string]$Acao = '')
13
+
14
+ $ErrorActionPreference = 'Continue'
15
+ $raiz = Split-Path -Parent $PSScriptRoot
16
+ $log = Join-Path $raiz 'logs\firewall.log'
17
+
18
+ function Gravar([string]$mensagem) {
19
+ try {
20
+ $pasta = Split-Path -Parent $log
21
+ if (-not (Test-Path -LiteralPath $pasta)) {
22
+ New-Item -ItemType Directory -Path $pasta -Force | Out-Null
23
+ }
24
+ Add-Content -LiteralPath $log -Encoding UTF8 -Value ((Get-Date -Format 'yyyy-MM-dd HH:mm:ss') + ' [script] ' + $mensagem)
25
+ } catch { }
26
+ }
27
+
28
+ $identidade = [Security.Principal.WindowsIdentity]::GetCurrent().Name
29
+ $elevado = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
30
+ if ($Acao -eq 'remover') { $modo = 'remover' } else { $modo = 'liberar' }
31
+ Gravar '====== inicio ======'
32
+ Gravar ("acao=$modo usuario=$identidade elevado=$elevado")
33
+
34
+ $porta = 8765
35
+ $cfg = Join-Path $raiz 'config.json'
36
+ if (Test-Path -LiteralPath $cfg) {
37
+ try {
38
+ $valor = (Get-Content -LiteralPath $cfg -Raw -Encoding UTF8 | ConvertFrom-Json).port
39
+ if ($valor) { $porta = [int]$valor }
40
+ } catch {
41
+ $porta = 8765
42
+ Gravar ('falha lendo config.json: ' + $_.Exception.Message)
43
+ }
44
+ if ($porta -lt 1 -or $porta -gt 65535) { $porta = 8765 }
45
+ }
46
+ Gravar ("porta=$porta")
47
+
48
+ # A unica regra deste projeto. As outras duas (mDNS e LLMNR) sairam: o nome
49
+ # curto na rede nao expoe mais nada no firewall.
50
+ $regra = 'duck.space'
51
+ $antigas = @('DeepSeek Universal Bridge (TCP)',
52
+ 'DeepSeek Universal Bridge (mDNS)',
53
+ 'DeepSeek Universal Bridge (LLMNR)')
54
+
55
+ # limpa o que existia (a regra atual tambem, para recriar do zero sem duplicar)
56
+ foreach ($nome in (@($antigas) + @($regra))) {
57
+ $saida = (netsh advfirewall firewall delete rule ('name="' + $nome + '"') 2>&1 | Out-String).Trim()
58
+ Gravar ('delete "' + $nome + '": codigo=' + $LASTEXITCODE + ' :: ' + $saida)
59
+ }
60
+
61
+ if ($modo -eq 'remover') {
62
+ Write-Host 'Removendo a regra do bridge...'
63
+ Write-Host 'Pronto.'
64
+ Gravar 'fim (remover)'
65
+ } else {
66
+ Write-Host "Liberando a porta $porta (TCP) e o DNS local (UDP 53) so na rede local, com UMA regra..."
67
+ $saida = (netsh advfirewall firewall add rule ('name="' + $regra + '"') dir=in action=allow protocol=TCP localport=$porta remoteip=localsubnet 2>&1 | Out-String).Trim()
68
+ $codigo = $LASTEXITCODE
69
+ Gravar ('add "' + $regra + '" TCP=' + $porta + ': codigo=' + $codigo + ' :: ' + $saida)
70
+ # Mesmo nome: o DNS local do dns_duck.py atende o celular pelo nome duck.space.
71
+ $saida = (netsh advfirewall firewall add rule ('name="' + $regra + '"') dir=in action=allow protocol=UDP localport=53 remoteip=localsubnet 2>&1 | Out-String).Trim()
72
+ $codigoDns = $LASTEXITCODE
73
+ Gravar ('add "' + $regra + '" UDP=53: codigo=' + $codigoDns + ' :: ' + $saida)
74
+
75
+ # Mesmo nome: HTTPS do mesmo bridge (terminador TLS do tls_proxy.py).
76
+ $saida = (netsh advfirewall firewall add rule ('name="' + $regra + '"') dir=in action=allow protocol=TCP localport=443 remoteip=localsubnet 2>&1 | Out-String).Trim()
77
+ $codigoHttps = $LASTEXITCODE
78
+ Gravar ('add "' + $regra + '" TCP=443: codigo=' + $codigoHttps + ' :: ' + $saida)
79
+
80
+ Write-Host 'Ativando o log do proprio Firewall do Windows (pfirewall.log, so quedas)...'
81
+ $saida = (netsh advfirewall set allprofiles logging droppedconnections enable 2>&1 | Out-String).Trim()
82
+ Gravar ('logging droppedconnections: codigo=' + $LASTEXITCODE + ' :: ' + $saida)
83
+
84
+ Write-Host ''
85
+ if ($codigo -eq 0) {
86
+ Write-Host "Pronto. Uma regra so: $regra (TCP $porta, rede local)."
87
+ Gravar 'fim (liberar) tudo certo'
88
+ } else {
89
+ Write-Host "Algo falhou. Codigo: tcp=$codigo"
90
+ Gravar ('fim (liberar) com falha: tcp=' + $codigo)
91
+ }
92
+ }
93
+ Write-Host ''
94
+ if (-not [Console]::IsInputRedirected) {
95
+ Read-Host 'Pressione Enter para fechar'
96
+ }
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env bash
2
+ # Uso explícito: bash ferramentas/firewall_linux.sh liberar|remover PORTA_BRIDGE
3
+ # Opcional: chmod +x ferramentas/firewall_linux.sh
4
+ # Nenhuma instalação, ativação global, reload ou abertura da porta do terminal.
5
+ set -euo pipefail
6
+ export LC_ALL=C
7
+
8
+ uso() {
9
+ printf '%s\n' 'Uso: firewall_linux.sh liberar|remover PORTA_BRIDGE (TCP; nunca 8767)' >&2
10
+ }
11
+
12
+ if [[ $# -ne 2 ]]; then uso; exit 2; fi
13
+ acao=$1
14
+ porta=$2
15
+ if [[ "$acao" != liberar && "$acao" != remover ]]; then uso; exit 2; fi
16
+ if [[ ! "$porta" =~ ^[0-9]{1,5}$ ]]; then uso; exit 2; fi
17
+ porta=$((10#$porta))
18
+ if (( porta < 1 || porta > 65535 || porta == 8767 )); then
19
+ printf '%s\n' 'Porta inválida ou reservada ao terminal (8767); nada foi alterado.' >&2
20
+ exit 2
21
+ fi
22
+ if [[ ! -t 0 || ! -t 1 ]]; then
23
+ printf '%s\n' 'Execute numa PTY interativa; a senha é solicitada somente pelo sudo.' >&2
24
+ exit 2
25
+ fi
26
+ if ! command -v sudo >/dev/null 2>&1; then
27
+ printf '%s\n' 'sudo ausente; instale/configure manualmente. Nenhuma alteração realizada.' >&2
28
+ exit 3
29
+ fi
30
+
31
+ ufw_bin=$(command -v ufw || true)
32
+ firewalld_bin=$(command -v firewall-cmd || true)
33
+ if [[ -n "$ufw_bin" ]]; then
34
+ # Captura somente o status; sudo usa a PTY, nunca stdin redirecionado ou -S.
35
+ if ! estado=$(sudo -- "$ufw_bin" status); then
36
+ printf '%s\n' 'Não foi possível consultar o UFW; operação cancelada.' >&2
37
+ exit 3
38
+ fi
39
+ if [[ "$estado" == *'Status: active'* ]]; then
40
+ if [[ "$acao" == liberar ]]; then
41
+ sudo -- "$ufw_bin" allow "$porta/tcp" comment 'DeepSeek bridge'
42
+ else
43
+ sudo -- "$ufw_bin" delete allow "$porta/tcp"
44
+ fi
45
+ printf 'UFW: comando aplicado somente a TCP/%s. Terminal 8767 não alterado.\n' "$porta"
46
+ exit 0
47
+ fi
48
+ fi
49
+
50
+ if [[ -n "$firewalld_bin" ]]; then
51
+ if ! sudo -- "$firewalld_bin" --state; then
52
+ printf '%s\n' 'firewalld não está ativo; ele não será iniciado por este script.' >&2
53
+ exit 3
54
+ fi
55
+ # Regra runtime na zona padrão, sem mudar serviços, outras portas ou zonas.
56
+ if [[ "$acao" == liberar ]]; then
57
+ sudo -- "$firewalld_bin" "--add-port=$porta/tcp"
58
+ else
59
+ sudo -- "$firewalld_bin" "--remove-port=$porta/tcp"
60
+ fi
61
+ printf 'firewalld: somente TCP/%s, regra runtime (não persistente).\n' "$porta"
62
+ exit 0
63
+ fi
64
+
65
+ printf '%s\n' 'Nenhum firewall compatível ativo. Configure UFW ou firewalld manualmente.' \
66
+ 'O script não ativa o firewall inteiro e não instala pacotes.' >&2
67
+ exit 3