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
@@ -0,0 +1,265 @@
1
+ """Integração do Krnell com o OpenCode (modelos + plugin system-prompt)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import shutil
8
+ from pathlib import Path
9
+
10
+
11
+ def candidatos_config_opencode() -> list[Path]:
12
+ home = Path.home()
13
+ lista = [
14
+ home / '.config' / 'opencode' / 'opencode.jsonc',
15
+ home / '.config' / 'opencode' / 'opencode.json',
16
+ ]
17
+ if os.name == 'nt':
18
+ appdata = os.environ.get('APPDATA') or str(home / 'AppData' / 'Roaming')
19
+ lista.append(Path(appdata) / 'opencode' / 'opencode.jsonc')
20
+ return lista
21
+
22
+
23
+ def _bloco_modelos_krnell(indent: str = ' ') -> str:
24
+ modelos = [
25
+ ('kimi-k3.1-pro', 'Kimi K3.1 Pro (NVIDIA)', 400000, 65536, ['text', 'image'], ['low', 'medium', 'high', 'max'], 'max'),
26
+ ('minimax-m3.1-flash', 'MiniMax M3.1 Flash (NVIDIA)', 400000, 65536, ['text', 'image'], ['low', 'medium', 'high', 'max'], 'max'),
27
+ ('claude-opus-5-5', 'Claude Opus 5.5 (Antigravity)', 1000000, 128000, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
28
+ ('claude-sonnet-5-5', 'Claude Sonnet 5.5 (Antigravity)', 1000000, 128000, ['text', 'image'], ['low', 'medium', 'high'], 'high'),
29
+ ('gemini-4-hydrogen', 'Gemini 4 Hydrogen (Antigravity)', 1000000, 262144, ['text', 'image', 'audio', 'video', 'pdf'], ['low', 'medium', 'high', 'xhigh'], 'xhigh'),
30
+ ('gemini-4-neon', 'Gemini 4 Neon (Antigravity)', 1000000, 262144, ['text', 'image', 'audio', 'video', 'pdf'], ['low', 'medium', 'high', 'xhigh'], 'xhigh'),
31
+ ('krnell', 'Krnell Active (dynamic route)', 1000000, 65536, ['text', 'image'], ['low', 'medium', 'high', 'xhigh', 'max'], 'max'),
32
+ ]
33
+ partes = []
34
+ for mid, nome, ctx, out, inp, efforts, default_eff in modelos:
35
+ variants = ', '.join(
36
+ f'{{ "id": "{e}", "body": {{ "reasoning_effort": "{e}" }} }}'
37
+ for e in efforts
38
+ )
39
+ partes.append(
40
+ f'{indent}"{mid}": {{\n'
41
+ f'{indent} "name": "{nome}",\n'
42
+ f'{indent} "capabilities": {{\n'
43
+ f'{indent} "tools": true,\n'
44
+ f'{indent} "reasoning": {{ "supported": true, "effort": {json.dumps(efforts)} }},\n'
45
+ f'{indent} "input": {json.dumps(inp)},\n'
46
+ f'{indent} "output": ["text"]\n'
47
+ f'{indent} }},\n'
48
+ f'{indent} "limit": {{ "context": {ctx}, "output": {out} }},\n'
49
+ f'{indent} "compatibility": {{\n'
50
+ f'{indent} "reasoningField": "reasoning_content",\n'
51
+ f'{indent} "maxTokensField": "max_tokens"\n'
52
+ f'{indent} }},\n'
53
+ f'{indent} "body": {{ "reasoning_effort": "{default_eff}" }},\n'
54
+ f'{indent} "variants": [{variants}]\n'
55
+ f'{indent}}}'
56
+ )
57
+ return ',\n'.join(partes)
58
+
59
+
60
+ def _garantir_plugin_no_texto(texto: str, plugin_dir: str) -> tuple[str, bool]:
61
+ lit = json.dumps(plugin_dir)
62
+ if lit in texto or 'plugins/system-prompt' in texto or 'plugins\\\\system-prompt' in texto:
63
+ return texto, False
64
+ m = re.search(r'"plugins"\s*:\s*\[', texto)
65
+ if m:
66
+ pos = m.end()
67
+ vazio = texto[pos:].lstrip().startswith(']')
68
+ ins = lit if vazio else f'{lit}, '
69
+ return texto[:pos] + ins + texto[pos:], True
70
+ m2 = re.search(r'"\$schema"\s*:\s*"[^"]*"\s*,?[ \t]*\r?\n?', texto)
71
+ if m2:
72
+ fim = m2.end()
73
+ antes = texto[:fim]
74
+ if not antes.rstrip().endswith(','):
75
+ antes = antes.rstrip() + ',\n'
76
+ return antes + f' "plugins": [{lit}],\n' + texto[fim:], True
77
+ abre = texto.find('{')
78
+ if abre >= 0:
79
+ return texto[:abre + 1] + f'\n "plugins": [{lit}],' + texto[abre + 1:], True
80
+ return texto, False
81
+
82
+
83
+ def _substituir_ou_inserir_provedor(texto: str, provider_id: str, bloco: str) -> tuple[str, bool]:
84
+ chave = f'"{provider_id}"'
85
+ if chave in texto:
86
+ # Localiza o objeto do provider respeitando chaves balanceadas
87
+ idx = texto.find(chave)
88
+ brace = texto.find('{', idx)
89
+ if brace >= 0:
90
+ prof = 0
91
+ in_str = False
92
+ esc = False
93
+ fim = -1
94
+ for i in range(brace, len(texto)):
95
+ ch = texto[i]
96
+ if in_str:
97
+ if esc:
98
+ esc = False
99
+ elif ch == '\\':
100
+ esc = True
101
+ elif ch == '"':
102
+ in_str = False
103
+ else:
104
+ if ch == '"':
105
+ in_str = True
106
+ elif ch == '{':
107
+ prof += 1
108
+ elif ch == '}':
109
+ prof -= 1
110
+ if prof == 0:
111
+ fim = i + 1
112
+ break
113
+ if fim > brace:
114
+ # Mantém linha inicial limpa
115
+ lin_ini = texto.rfind('\n', 0, idx)
116
+ inicio = lin_ini + 1 if lin_ini >= 0 else idx
117
+ novo = texto[:inicio] + bloco + texto[fim:]
118
+ return novo, novo != texto
119
+ m = re.search(r'"providers"\s*:\s*\{', texto)
120
+ if m:
121
+ pos = m.end()
122
+ vazio = texto[pos:].lstrip().startswith('}')
123
+ sep = '\n' if vazio else ',\n'
124
+ return texto[:pos] + '\n' + bloco + sep + texto[pos:], True
125
+ abre = texto.find('{')
126
+ if abre >= 0:
127
+ return texto[:abre + 1] + f'\n "providers": {{\n{bloco}\n }},' + texto[abre + 1:], True
128
+ return texto, False
129
+
130
+
131
+ def opencode_detectado() -> bool:
132
+ """Detecta se o OpenCode está instalado (binário ou pasta de config)."""
133
+ if shutil.which('opencode'):
134
+ return True
135
+ home = Path.home()
136
+ for p in (
137
+ home / '.opencode' / 'bin' / 'opencode',
138
+ home / '.opencode' / 'bin' / 'opencode.exe',
139
+ home / '.config' / 'opencode',
140
+ ):
141
+ if p.exists():
142
+ return True
143
+ if os.name == 'nt':
144
+ appdata = os.environ.get('APPDATA') or str(home / 'AppData' / 'Roaming')
145
+ if (Path(appdata) / 'opencode').exists():
146
+ return True
147
+ return False
148
+
149
+
150
+ def opencode_ja_configurado(porta: int = 8765) -> bool:
151
+ """True se opencode.json(c) já tem `krnell` atualizado na porta com visão NVIDIA."""
152
+ esperado = f'http://127.0.0.1:{int(porta)}/v1'
153
+ modelos_visao = ('kimi-k3.1-pro', 'minimax-m3.1-flash')
154
+ for arq in candidatos_config_opencode():
155
+ if not arq.is_file():
156
+ continue
157
+ try:
158
+ txt = arq.read_text(encoding='utf-8')
159
+ except OSError:
160
+ continue
161
+ if '"krnell"' not in txt or esperado not in txt:
162
+ continue
163
+ try:
164
+ import contexto
165
+ _, dados = contexto._jsonc(txt)
166
+ except Exception:
167
+ continue
168
+ bloco = ((dados.get('providers') or {}).get('krnell')
169
+ or (dados.get('provider') or {}).get('krnell'))
170
+ if not isinstance(bloco, dict):
171
+ continue
172
+ opts = bloco.get('settings') or bloco.get('options') or {}
173
+ if str((opts.get('baseURL') if isinstance(opts, dict) else '') or '').rstrip('/') != esperado:
174
+ continue
175
+ modelos = bloco.get('models')
176
+ if not isinstance(modelos, dict):
177
+ continue
178
+ if all(
179
+ isinstance(modelos.get(mid), dict)
180
+ and 'image' in ((modelos[mid].get('capabilities') or {}).get('input') or [])
181
+ for mid in modelos_visao
182
+ ):
183
+ return True
184
+ return False
185
+
186
+
187
+ def configurar_opencode(raiz: Path, porta: int = 8765, api_key: str = '') -> dict:
188
+ """Instala o plugin system-prompt e registra o provedor `krnell` no OpenCode."""
189
+ raiz = Path(raiz).resolve()
190
+ cands = candidatos_config_opencode()
191
+ arq = next((p for p in cands if p.exists()), cands[0])
192
+ cfg_dir = arq.parent
193
+ cfg_dir.mkdir(parents=True, exist_ok=True)
194
+
195
+ # 1) Plugin system-prompt
196
+ src_plugin = raiz / 'plugins' / 'system-prompt' / 'index.ts'
197
+ dst_plugin_dir = cfg_dir / 'plugins' / 'system-prompt'
198
+ dst_plugin = dst_plugin_dir / 'index.ts'
199
+ plugin_instalado = False
200
+ if src_plugin.exists():
201
+ dst_plugin_dir.mkdir(parents=True, exist_ok=True)
202
+ shutil.copy2(src_plugin, dst_plugin)
203
+ plugin_instalado = True
204
+
205
+ # 2) AGENTS.md se existir na raiz e ainda nao existir no OpenCode
206
+ src_agents = raiz / 'AGENTS.md'
207
+ dst_agents = cfg_dir / 'AGENTS.md'
208
+ if src_agents.exists() and not dst_agents.exists():
209
+ shutil.copy2(src_agents, dst_agents)
210
+
211
+ base_url = f'http://127.0.0.1:{int(porta)}/v1'
212
+ key_val = (api_key or 'local').strip()
213
+ bloco_krnell = (
214
+ f' "krnell": {{\n'
215
+ f' "name": "Krnell (local)",\n'
216
+ f' "package": "@opencode/ai/providers/openai-compatible",\n'
217
+ f' "settings": {{\n'
218
+ f' "baseURL": "{base_url}",\n'
219
+ f' "apiKey": "{key_val}"\n'
220
+ f' }},\n'
221
+ f' "models": {{\n'
222
+ f'{_bloco_modelos_krnell(" ")}\n'
223
+ f' }}\n'
224
+ f' }}'
225
+ )
226
+
227
+ if not arq.exists():
228
+ plugins_str = f'\n "plugins": [{json.dumps(str(dst_plugin_dir))}],' if plugin_instalado else ''
229
+ conteudo = (
230
+ '{\n'
231
+ ' "$schema": "https://opencode.ai/config.json",'
232
+ f'{plugins_str}\n'
233
+ ' "providers": {\n'
234
+ f'{bloco_krnell}\n'
235
+ ' }\n'
236
+ '}\n'
237
+ )
238
+ arq.write_text(conteudo, encoding='utf-8')
239
+ else:
240
+ texto = arq.read_text(encoding='utf-8')
241
+ if plugin_instalado or dst_plugin.exists():
242
+ texto, _ = _garantir_plugin_no_texto(texto, str(dst_plugin_dir))
243
+ # Se já havia o bloco antigo "nyxo", substitui in-place por "krnell"
244
+ if '"nyxo"' in texto and '"krnell"' not in texto:
245
+ texto, _ = _substituir_ou_inserir_provedor(texto, 'nyxo', bloco_krnell)
246
+ else:
247
+ texto, _ = _substituir_ou_inserir_provedor(texto, 'krnell', bloco_krnell)
248
+ # Atualiza tambem o baseURL e variants do kimibridge se existir, apontando pro krnell
249
+ if '"kimibridge"' in texto:
250
+ texto = re.sub(
251
+ r'("kimibridge"[\s\S]{0,600}?"baseURL"\s*:\s*")[^"]*(")',
252
+ rf'\g<1>{base_url}\2',
253
+ texto,
254
+ count=1,
255
+ )
256
+ arq.write_text(texto, encoding='utf-8')
257
+
258
+ return {
259
+ 'ok': True,
260
+ 'config': str(arq),
261
+ 'plugin': str(dst_plugin) if (plugin_instalado or dst_plugin.exists()) else '',
262
+ 'plugin_instalado': bool(plugin_instalado or dst_plugin.exists()),
263
+ 'baseURL': base_url,
264
+ 'base_url': base_url,
265
+ }
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "krnell",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "3.0.2",
4
+ "description": "Krnell — proxy multi-provedor local (NVIDIA Playground, Antigravity OAuth, WorkBuddy, OpenCode, 20+ APIs) com TUI estilo OpenCode",
5
+ "type": "module",
6
+ "bin": {
7
+ "krnell": "bin/krnell.mjs"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "bridge.py",
12
+ "painel.py",
13
+ "atualizador.py",
14
+ "painel_web.py",
15
+ "tui_core.py",
16
+ "opencode_sync.py",
17
+ "provedores_catalogo.py",
18
+ "kimi.py",
19
+ "workbuddy.py",
20
+ "contexto.py",
21
+ "dashboard_web.py",
22
+ "tls_proxy.py",
23
+ "dns_duck.py",
24
+ "iniciar.sh",
25
+ "Painel.cmd",
26
+ "Instalar_Atalho_Windows.cmd",
27
+ "Iniciar_Linux.sh",
28
+ "Instalar_Ubuntu.sh",
29
+ "config.example.json",
30
+ "keys.example.env",
31
+ "plugins/",
32
+ "provedores/kimi/bridge.mjs",
33
+ "provedores/kimi/package.json",
34
+ "web/dist/",
35
+ "ferramentas/install_windows.py",
36
+ "ferramentas/selecionar_provedor.py",
37
+ "ferramentas/Liberar_Firewall.ps1",
38
+ "ferramentas/firewall_linux.sh",
39
+ "README.md"
40
+ ],
41
+ "engines": {
42
+ "node": ">=18.0.0"
43
+ },
44
+ "scripts": {
45
+ "start": "node bin/krnell.mjs",
46
+ "build": "vite build --config vite.config.mjs",
47
+ "dev": "vite --config vite.config.mjs --host 127.0.0.1",
48
+ "lab": "node ferramentas/lab-dashboard.mjs",
49
+ "terminal": "node ferramentas/terminal-server.mjs",
50
+ "test:node": "node --test ferramentas/test-*.mjs",
51
+ "qa": "python -B ferramentas/qa_dashboard.py"
52
+ },
53
+ "dependencies": {},
54
+ "devDependencies": {
55
+ "vite": "7.1.7"
56
+ },
57
+ "keywords": [
58
+ "opencode",
59
+ "bridge",
60
+ "ai",
61
+ "nvidia",
62
+ "antigravity",
63
+ "claude",
64
+ "gemini",
65
+ "termux",
66
+ "tui",
67
+ "openai-compatible"
68
+ ],
69
+ "license": "MIT"
70
+ }