krnell 3.0.5 → 3.0.7
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/atualizador.py +11 -2
- package/bin/krnell.mjs +63 -15
- package/bridge.py +133 -21
- package/dashboard_web.py +1 -1
- package/iniciar.sh +1 -1
- package/opencode_sync.py +157 -27
- package/package.json +1 -1
- package/painel.py +387 -74
- package/plugins/system-prompt/index.ts +713 -11
- package/plugins/system-prompt/package.json +10 -0
- package/plugins/system-prompt/tui.tsx +641 -0
- package/provedores/kimi/bridge.mjs +73 -104
- package/tui_core.py +15 -6
package/atualizador.py
CHANGED
|
@@ -44,7 +44,7 @@ class MonitorAtualizacao:
|
|
|
44
44
|
"""Checa em segundo plano; falha de rede nunca interfere na TUI."""
|
|
45
45
|
|
|
46
46
|
def __init__(self, versao_atual: str, pacote: str = 'krnell', *,
|
|
47
|
-
intervalo: float =
|
|
47
|
+
intervalo: float = 90.0, abridor=None):
|
|
48
48
|
self.versao_atual = str(versao_atual)
|
|
49
49
|
self.pacote = pacote
|
|
50
50
|
self.intervalo = float(intervalo)
|
|
@@ -55,11 +55,17 @@ class MonitorAtualizacao:
|
|
|
55
55
|
self._disponivel = None
|
|
56
56
|
self._estado = 'unknown'
|
|
57
57
|
self._verificando = False
|
|
58
|
+
self._revisao = 0
|
|
58
59
|
self._url = os.environ.get(
|
|
59
60
|
'KRNELL_UPDATE_URL',
|
|
60
61
|
f'https://registry.npmjs.org/{quote(pacote, safe="@")}/latest',
|
|
61
62
|
)
|
|
62
63
|
|
|
64
|
+
@property
|
|
65
|
+
def revisao(self) -> int:
|
|
66
|
+
with self._lock:
|
|
67
|
+
return self._revisao
|
|
68
|
+
|
|
63
69
|
@property
|
|
64
70
|
def estado(self) -> str:
|
|
65
71
|
with self._lock:
|
|
@@ -109,10 +115,13 @@ class MonitorAtualizacao:
|
|
|
109
115
|
if not _SEMVER.fullmatch(candidata):
|
|
110
116
|
raise ValueError('registry sem versão semver')
|
|
111
117
|
with self._lock:
|
|
112
|
-
|
|
118
|
+
novo = (
|
|
113
119
|
{'version': candidata, 'current': self.versao_atual}
|
|
114
120
|
if versao_mais_nova(self.versao_atual, candidata) else None
|
|
115
121
|
)
|
|
122
|
+
if novo != self._disponivel:
|
|
123
|
+
self._revisao += 1
|
|
124
|
+
self._disponivel = novo
|
|
116
125
|
self._estado = 'available' if self._disponivel else 'up_to_date'
|
|
117
126
|
except Exception:
|
|
118
127
|
# Update é opcional: DNS, TLS e registry fora do ar ficam invisíveis.
|
package/bin/krnell.mjs
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* krnell upgrade atualiza o pacote via npm (`npm i -g krnell@latest`)
|
|
13
13
|
* krnell --version exibe versao do Krnell
|
|
14
14
|
*/
|
|
15
|
-
import { spawnSync } from 'node:child_process';
|
|
15
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
16
16
|
import fs from 'node:fs';
|
|
17
17
|
import path from 'node:path';
|
|
18
18
|
import { fileURLToPath } from 'node:url';
|
|
@@ -77,9 +77,9 @@ prepararPastaUsuario();
|
|
|
77
77
|
function lerVersao() {
|
|
78
78
|
try {
|
|
79
79
|
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
|
|
80
|
-
return pkg.version || '3.0.
|
|
80
|
+
return pkg.version || '3.0.7';
|
|
81
81
|
} catch {
|
|
82
|
-
return '3.0.
|
|
82
|
+
return '3.0.7';
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
85
|
|
|
@@ -139,19 +139,67 @@ if (args[0] === 'upgrade' || args[0] === 'update') {
|
|
|
139
139
|
return 'krnell';
|
|
140
140
|
}
|
|
141
141
|
})();
|
|
142
|
-
const
|
|
143
|
-
const
|
|
144
|
-
|
|
142
|
+
const atual = lerVersao();
|
|
143
|
+
const ehTty = Boolean(process.stdout.isTTY);
|
|
144
|
+
const cor = (c, s) => (ehTty ? `\x1b[${c}m${s}\x1b[0m` : s);
|
|
145
|
+
const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
146
|
+
|
|
147
|
+
const comSpinner = async (texto, fn) => {
|
|
148
|
+
if (!ehTty) return await fn();
|
|
149
|
+
let i = 0;
|
|
150
|
+
process.stdout.write('\x1b[?25l');
|
|
151
|
+
const desenhar = () => {
|
|
152
|
+
const sp = cor('38;5;216', frames[i++ % frames.length]);
|
|
153
|
+
process.stdout.write(`\r\x1b[2K ${sp} ${texto}`);
|
|
154
|
+
};
|
|
155
|
+
desenhar();
|
|
156
|
+
const t = setInterval(desenhar, 80);
|
|
157
|
+
try {
|
|
158
|
+
return await fn();
|
|
159
|
+
} finally {
|
|
160
|
+
clearInterval(t);
|
|
161
|
+
process.stdout.write('\r\x1b[2K\x1b[?25h');
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const alvoArg = (args[1] || '').trim().replace(/^v/, '');
|
|
166
|
+
const alvo = alvoArg || await comSpinner('Checking latest version…', () => resolverUltimaVersao(pkgName));
|
|
167
|
+
if (alvo && alvo === atual && !alvoArg) {
|
|
168
|
+
console.log(`\n ${cor('38;5;114', '✓')} ${cor('1', 'krnell')} ${cor('90', `v${atual} is already the latest`)}\n`);
|
|
169
|
+
process.exit(0);
|
|
170
|
+
}
|
|
171
|
+
const spec = alvo ? `${pkgName}@${alvo}` : `${pkgName}@latest`;
|
|
172
|
+
const destinoLabel = alvo ? `v${alvo}` : 'latest';
|
|
173
|
+
if (ehTty) {
|
|
174
|
+
console.log('');
|
|
175
|
+
console.log(` ${cor('1;38;5;216', '◈')} ${cor('1', 'krnell')} ${cor('90', `v${atual} → ${destinoLabel}`)}`);
|
|
176
|
+
}
|
|
177
|
+
|
|
145
178
|
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
179
|
+
const res = await comSpinner(`Upgrading to ${destinoLabel}…`, () => new Promise((resolve) => {
|
|
180
|
+
const child = spawn(
|
|
181
|
+
npmCmd,
|
|
182
|
+
['install', '-g', spec, '--prefer-online', '--no-audit', '--no-fund'],
|
|
183
|
+
{
|
|
184
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
185
|
+
env: { ...process.env, NO_UPDATE_NOTIFIER: '1', NPM_CONFIG_FUND: 'false', NPM_CONFIG_AUDIT: 'false' },
|
|
186
|
+
},
|
|
187
|
+
);
|
|
188
|
+
let out = '';
|
|
189
|
+
let err = '';
|
|
190
|
+
child.stdout.on('data', (d) => { out += d; });
|
|
191
|
+
child.stderr.on('data', (d) => { err += d; });
|
|
192
|
+
child.on('error', (e) => resolve({ status: 1, out, err: String(e?.message || e) }));
|
|
193
|
+
child.on('close', (status) => resolve({ status: status ?? 1, out, err }));
|
|
194
|
+
}));
|
|
195
|
+
|
|
196
|
+
if (res.status === 0) {
|
|
197
|
+
console.log(` ${cor('38;5;114', '✓')} Upgrade complete ${cor('90', `(${destinoLabel})`)}\n`);
|
|
198
|
+
process.exit(0);
|
|
199
|
+
}
|
|
200
|
+
const detalhe = (res.err || res.out || 'npm install failed').trim().split('\n').slice(-2).join(' · ');
|
|
201
|
+
console.error(` ${cor('38;5;203', '✗')} Upgrade failed ${cor('90', detalhe)}\n`);
|
|
202
|
+
process.exit(res.status || 1);
|
|
155
203
|
}
|
|
156
204
|
|
|
157
205
|
if (process.platform === 'win32') {
|
package/bridge.py
CHANGED
|
@@ -59,7 +59,7 @@ OPENCODE_CONTEXT_TOKENS = 300000
|
|
|
59
59
|
OPENCODE_OUTPUT_TOKENS = 64000
|
|
60
60
|
MODEL_CONTEXT_ANUNCIADO = 0 # 0 = nao ha limite de descoberta configurado
|
|
61
61
|
MODEL_OUTPUT_ANUNCIADO = 0 # limite nativo conhecido; independente do contexto escolhido
|
|
62
|
-
BRIDGE_VERSION = '3.0.
|
|
62
|
+
BRIDGE_VERSION = '3.0.7'
|
|
63
63
|
PROVIDER_URLS = {'unorouter': 'https://api.unorouter.com/v1',
|
|
64
64
|
'tokenharbor': 'https://tokenharbor.ai/v1',
|
|
65
65
|
# Contas do app WorkBuddy: o fluxo real (login, headers de
|
|
@@ -464,6 +464,7 @@ def canonical_route(path: str) -> str:
|
|
|
464
464
|
def known_route(path: str) -> bool:
|
|
465
465
|
static = ('/', '/healthz', '/_bridge/status', '/_bridge/model-status', '/_bridge/queue', '/_bridge/routes', '/v1/models',
|
|
466
466
|
'/_bridge/workbuddy', '/_bridge/reload',
|
|
467
|
+
'/workbuddy/login/start', '/workbuddy/login/status', '/workbuddy/logout',
|
|
467
468
|
'/v1/chat/completions', '/v1/responses', '/v1/messages',
|
|
468
469
|
'/v1/messages/count_tokens', '/v1/responses/compact',
|
|
469
470
|
'/v1/responses/input_tokens')
|
|
@@ -890,13 +891,20 @@ def load_config(path: Path) -> dict:
|
|
|
890
891
|
elif cfg['provider'] == 'tokenharbor':
|
|
891
892
|
pool = cfg.get('tokenharbor_apis', [])
|
|
892
893
|
elif cfg['provider'] in kimi.PROVEDORES_MOTOR:
|
|
893
|
-
# Motor local Node (NVIDIA Playground / Antigravity): suporta rajadas
|
|
894
|
-
# paralelas (ate 20 subagentes simultaneos sem fila 1-por-vez).
|
|
895
894
|
base_motor = str((provedores.get(cfg['provider']) or {}).get('base_url') or kimi.url_base()).strip().rstrip('/')
|
|
896
895
|
key_local = os.environ.get('KIMI_BRIDGE_KEY', '').strip() or 'local'
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
896
|
+
if cfg['provider'] == 'nvidia':
|
|
897
|
+
# Playground público: um destino lógico, sem transformar
|
|
898
|
+
# subagentes em um número fixo de slots no bridge Python.
|
|
899
|
+
pool = [{'name': 'nvidia_local', 'key_env': '', 'base_url': base_motor,
|
|
900
|
+
'_key': key_local, '_motor_local': True}]
|
|
901
|
+
else:
|
|
902
|
+
# Antigravity usa OAuth, cotas e contas da pessoa. O Node faz o
|
|
903
|
+
# failover; estes slots são apenas de transporte, não de ausência
|
|
904
|
+
# de autenticação nem de concorrência ilimitada.
|
|
905
|
+
pool = [{'name': f'antigravity_slot_{n:02d}', 'key_env': '',
|
|
906
|
+
'base_url': base_motor, '_key': key_local, '_motor_local': True}
|
|
907
|
+
for n in range(1, 21)]
|
|
900
908
|
else:
|
|
901
909
|
pool = (provedores.get(cfg['provider']) or {}).get('apis') or []
|
|
902
910
|
if not isinstance(pool, list) or not 1 <= len(pool) <= 100:
|
|
@@ -1599,11 +1607,11 @@ class ModelStatusMonitor:
|
|
|
1599
1607
|
|
|
1600
1608
|
|
|
1601
1609
|
class ModelRequestQueue:
|
|
1602
|
-
"""
|
|
1610
|
+
"""FIFO por conta; somente NVIDIA Playground entra sem teto nem fila.
|
|
1603
1611
|
|
|
1604
|
-
As requisições HTTP mantêm seus próprios payloads e sockets.
|
|
1605
|
-
request_id/conta
|
|
1606
|
-
|
|
1612
|
+
As requisições HTTP mantêm seus próprios payloads e sockets. Nos provedores
|
|
1613
|
+
por chave/OAuth, request_id/conta controla a concorrência do transporte.
|
|
1614
|
+
No NVIDIA, `active` é apenas telemetria: nunca segura nem enfileira.
|
|
1607
1615
|
"""
|
|
1608
1616
|
|
|
1609
1617
|
def __init__(self):
|
|
@@ -1613,27 +1621,40 @@ class ModelRequestQueue:
|
|
|
1613
1621
|
self.sequence = 0
|
|
1614
1622
|
self.closed = False
|
|
1615
1623
|
self.completed = 0
|
|
1624
|
+
self.unlimited = False
|
|
1616
1625
|
|
|
1617
1626
|
@contextmanager
|
|
1618
1627
|
def turn(self, trace_id: str, route: str, on_hold=None, on_tick=None,
|
|
1619
1628
|
stop_event=None, max_wait=0, heartbeat_interval=SSE_HEARTBEAT_SECONDS,
|
|
1620
1629
|
state=None):
|
|
1630
|
+
acquired = False
|
|
1621
1631
|
with self.cv:
|
|
1622
|
-
if self.closed:
|
|
1632
|
+
if self.closed or (stop_event is not None and stop_event.is_set()):
|
|
1623
1633
|
raise BridgeError(503, 'Fila encerrada', 'bridge_stopping')
|
|
1624
1634
|
self.sequence += 1
|
|
1625
1635
|
ticket = {'request_id': trace_id, 'sequence': self.sequence,
|
|
1626
1636
|
'route': route, 'queued_at': time.monotonic(),
|
|
1627
1637
|
'account_index': None}
|
|
1628
|
-
self.
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1638
|
+
if self.unlimited:
|
|
1639
|
+
# NVIDIA: o ticket registra a atividade, mas nunca passa por
|
|
1640
|
+
# `pending` nem aguarda outra requisição terminar.
|
|
1641
|
+
ticket['account_index'] = 0 if state is not None else None
|
|
1642
|
+
self.active[ticket['sequence']] = ticket
|
|
1643
|
+
acquired = True
|
|
1644
|
+
LOG.info('request_started_unlimited id=%s sequence=%s active=%s route=%s',
|
|
1645
|
+
trace_id, ticket['sequence'], len(self.active), route)
|
|
1646
|
+
else:
|
|
1647
|
+
self.pending.append(ticket)
|
|
1648
|
+
position = len(self.pending) + len(self.active)
|
|
1649
|
+
LOG.info('queue_received id=%s sequence=%s position=%s route=%s',
|
|
1650
|
+
trace_id, ticket['sequence'], position, route)
|
|
1632
1651
|
self.cv.notify_all()
|
|
1633
|
-
acquired = False
|
|
1634
1652
|
started = ticket['queued_at']
|
|
1635
1653
|
last_tick = started
|
|
1636
1654
|
try:
|
|
1655
|
+
if acquired:
|
|
1656
|
+
yield ticket
|
|
1657
|
+
return
|
|
1637
1658
|
# A mensagem SSE só é enviada após identificar uma espera real.
|
|
1638
1659
|
while True:
|
|
1639
1660
|
with self.cv:
|
|
@@ -1736,8 +1757,8 @@ class ModelRequestQueue:
|
|
|
1736
1757
|
now = time.monotonic()
|
|
1737
1758
|
active = list(self.active.values())
|
|
1738
1759
|
head = min(active, key=lambda t: t['sequence']) if active else None
|
|
1739
|
-
return {'model': MODEL, 'policy': 'FIFO_per_account',
|
|
1740
|
-
'max_simultaneous_upstream': getattr(self, 'account_count', 1),
|
|
1760
|
+
return {'model': MODEL, 'policy': 'unlimited' if self.unlimited else 'FIFO_per_account',
|
|
1761
|
+
'max_simultaneous_upstream': None if self.unlimited else getattr(self, 'account_count', 1),
|
|
1741
1762
|
'active_request_id': head['request_id'] if head else None,
|
|
1742
1763
|
'active_route': head['route'] if head else None,
|
|
1743
1764
|
'active_seconds': round(now - head['queued_at'], 1) if head else None,
|
|
@@ -1892,6 +1913,9 @@ class BridgeState:
|
|
|
1892
1913
|
self.cfg = cfg
|
|
1893
1914
|
self.targets = cfg['apis']
|
|
1894
1915
|
self.provider = cfg.get('provider', 'unorouter')
|
|
1916
|
+
# Loopback descreve o transporte, não a autenticação. Antigravity e
|
|
1917
|
+
# WorkBuddy usam contas/cotas; OpenCode free tier também é finito.
|
|
1918
|
+
self.unlimited = self.provider == 'nvidia'
|
|
1895
1919
|
self.key_reloader = None
|
|
1896
1920
|
self.ready = [0.0] * len(self.targets)
|
|
1897
1921
|
self.in_flight = [0] * len(self.targets)
|
|
@@ -1902,6 +1926,7 @@ class BridgeState:
|
|
|
1902
1926
|
self.responses = {}
|
|
1903
1927
|
self.queue = ModelRequestQueue()
|
|
1904
1928
|
self.queue.account_count = len(self.targets)
|
|
1929
|
+
self.queue.unlimited = self.unlimited
|
|
1905
1930
|
self.recovery_waiting = 0
|
|
1906
1931
|
self.recovery_cycles = 0
|
|
1907
1932
|
self.started_at = time.time()
|
|
@@ -1914,6 +1939,8 @@ class BridgeState:
|
|
|
1914
1939
|
self.request_log = None
|
|
1915
1940
|
self.workbuddy_vigia = None
|
|
1916
1941
|
self.workbuddy_convites = None
|
|
1942
|
+
self._wb_logins_lock = threading.Lock()
|
|
1943
|
+
self._wb_logins = {}
|
|
1917
1944
|
status_model = cfg.get('upstream_model') or UPSTREAM_MODEL
|
|
1918
1945
|
if self.provider == 'unorouter':
|
|
1919
1946
|
status_model = str(cfg.get('model_enviado') or '').strip() or status_model
|
|
@@ -1927,7 +1954,7 @@ class BridgeState:
|
|
|
1927
1954
|
now = time.monotonic()
|
|
1928
1955
|
candidates = [i for i in range(len(self.targets)) if i not in excluded and self.ready[i] <= now]
|
|
1929
1956
|
if preferred is not None:
|
|
1930
|
-
candidates = [i for i in candidates if i == preferred and self.in_flight[i] == 0]
|
|
1957
|
+
candidates = [i for i in candidates if i == preferred and (self.unlimited or self.in_flight[i] == 0)]
|
|
1931
1958
|
if not candidates:
|
|
1932
1959
|
return None
|
|
1933
1960
|
least = min(self.in_flight[i] for i in candidates)
|
|
@@ -2007,9 +2034,10 @@ class BridgeState:
|
|
|
2007
2034
|
# -- contador ao vivo (painel) ------------------------------------------
|
|
2008
2035
|
# Mesma semântica do opencode (session.tps): saída exata vem do usage do
|
|
2009
2036
|
# provedor; durante a geração o painel vê uma estimativa por caracteres.
|
|
2010
|
-
def live_inicio(self, rid: str, rota: str, stream: bool):
|
|
2037
|
+
def live_inicio(self, rid: str, rota: str, stream: bool, modelo: str = ''):
|
|
2011
2038
|
with self._live_lock:
|
|
2012
2039
|
self.live[rid] = {'id': rid, 'rota': rota, 'stream': bool(stream),
|
|
2040
|
+
'modelo': str(modelo or '').strip(),
|
|
2013
2041
|
'inicio': time.monotonic(), 'primeiro': None,
|
|
2014
2042
|
'chars': 0, 'uso': None, 'idx': None}
|
|
2015
2043
|
|
|
@@ -2079,6 +2107,7 @@ class BridgeState:
|
|
|
2079
2107
|
conta = self.targets[item['idx']].get('name')
|
|
2080
2108
|
ativas.append({'id': item['id'], 'rota': item['rota'],
|
|
2081
2109
|
'stream': item['stream'], 'conta': conta,
|
|
2110
|
+
'modelo': item.get('modelo') or '',
|
|
2082
2111
|
'segundos': round(agora - item['inicio'], 1),
|
|
2083
2112
|
'tokens_out': saida, 'exato': bool(saida_exata),
|
|
2084
2113
|
'tok_s': round(saida / dur, 1) if saida else None})
|
|
@@ -3603,6 +3632,67 @@ def workbuddy_resumo(cfg: dict, state, force: bool = False) -> dict:
|
|
|
3603
3632
|
return workbuddy.resumo(cfg, _raiz_do_estado(state), force=force)
|
|
3604
3633
|
|
|
3605
3634
|
|
|
3635
|
+
def workbuddy_login_start(cfg: dict, state) -> dict:
|
|
3636
|
+
"""Inicia sessao de login do WorkBuddy para uso via /connect do OpenCode."""
|
|
3637
|
+
iniciado = workbuddy.iniciar_login(cfg)
|
|
3638
|
+
estado = str(iniciado.get('state') or '').strip()
|
|
3639
|
+
url = str(iniciado.get('auth_url') or '').strip()
|
|
3640
|
+
if not estado or not url:
|
|
3641
|
+
raise BridgeError(502, 'WorkBuddy nao devolveu state/URL de login', 'upstream_error')
|
|
3642
|
+
expira = time.time() + 600
|
|
3643
|
+
with state._wb_logins_lock:
|
|
3644
|
+
agora = time.time()
|
|
3645
|
+
for chave in [k for k, v in state._wb_logins.items() if v.get('expires_at', 0) < agora]:
|
|
3646
|
+
state._wb_logins.pop(chave, None)
|
|
3647
|
+
state._wb_logins[estado] = {'state': estado, 'url': url, 'expires_at': expira}
|
|
3648
|
+
return {'state': estado, 'url': url, 'expiresAt': int(expira * 1000)}
|
|
3649
|
+
|
|
3650
|
+
|
|
3651
|
+
def workbuddy_login_status(cfg: dict, state, estado: str) -> dict:
|
|
3652
|
+
"""Consulta se o login do WorkBuddy foi concluido no navegador e salva a conta."""
|
|
3653
|
+
estado = str(estado or '').strip()
|
|
3654
|
+
if not estado:
|
|
3655
|
+
return {'status': 'expired', 'error': 'state ausente'}
|
|
3656
|
+
with state._wb_logins_lock:
|
|
3657
|
+
item = state._wb_logins.get(estado)
|
|
3658
|
+
if not item:
|
|
3659
|
+
return {'status': 'expired', 'error': 'state desconhecido ou expirado'}
|
|
3660
|
+
if item.get('status') == 'complete' and item.get('account'):
|
|
3661
|
+
return {'status': 'complete', 'account': item['account']}
|
|
3662
|
+
if item.get('expires_at', 0) < time.time():
|
|
3663
|
+
state._wb_logins.pop(estado, None)
|
|
3664
|
+
return {'status': 'expired', 'error': 'link de login expirado'}
|
|
3665
|
+
try:
|
|
3666
|
+
auth = workbuddy.consultar_token(estado, cfg)
|
|
3667
|
+
except workbuddy.ErroWorkBuddy as exc:
|
|
3668
|
+
return {'status': 'failed', 'error': str(exc)}
|
|
3669
|
+
if not auth:
|
|
3670
|
+
return {'status': 'pending'}
|
|
3671
|
+
raiz = _raiz_do_estado(state)
|
|
3672
|
+
conta = workbuddy.obter_conta(estado, auth, cfg)
|
|
3673
|
+
registro = workbuddy.adicionar_conta(raiz, auth, conta)
|
|
3674
|
+
resumo_conta = {
|
|
3675
|
+
'id': registro.get('id') or '',
|
|
3676
|
+
'nome': registro.get('nome') or '',
|
|
3677
|
+
'uid': registro.get('uid') or '',
|
|
3678
|
+
'email': registro.get('email') or '',
|
|
3679
|
+
'apelido': registro.get('apelido') or '',
|
|
3680
|
+
'empresa': registro.get('empresa') or '',
|
|
3681
|
+
'plano': registro.get('plano') or '',
|
|
3682
|
+
}
|
|
3683
|
+
with state._wb_logins_lock:
|
|
3684
|
+
if estado in state._wb_logins:
|
|
3685
|
+
state._wb_logins[estado]['status'] = 'complete'
|
|
3686
|
+
state._wb_logins[estado]['account'] = resumo_conta
|
|
3687
|
+
return {'status': 'complete', 'account': resumo_conta}
|
|
3688
|
+
|
|
3689
|
+
|
|
3690
|
+
def workbuddy_logout(state, alvo: str) -> dict:
|
|
3691
|
+
raiz = _raiz_do_estado(state)
|
|
3692
|
+
removida = workbuddy.remover_conta(raiz, alvo)
|
|
3693
|
+
return {'ok': True, 'removed': removida.get('nome') if isinstance(removida, dict) else None}
|
|
3694
|
+
|
|
3695
|
+
|
|
3606
3696
|
def open_upstream(cfg: dict, state: BridgeState, chat: dict, trace_id: str, preferred: int | None = None):
|
|
3607
3697
|
"""Tenta as contas disponíveis; o laço resiliente decide a espera e repetição.
|
|
3608
3698
|
|
|
@@ -3676,6 +3766,8 @@ def open_upstream(cfg: dict, state: BridgeState, chat: dict, trace_id: str, pref
|
|
|
3676
3766
|
conta_id = str((wb or {}).get('id') or '')
|
|
3677
3767
|
# O gateway do WorkBuddy e stream-first: pedimos SSE e agregamos quando
|
|
3678
3768
|
# o cliente pediu JSON, em vez de arriscar um stream:false sem suporte.
|
|
3769
|
+
# Relay Node em loopback não implica ausência de login: Antigravity
|
|
3770
|
+
# carrega OAuth/cotas; somente NVIDIA dispensa conta e API do usuário.
|
|
3679
3771
|
eh_motor_local = cfg.get('provider') in kimi.PROVEDORES_MOTOR
|
|
3680
3772
|
# O motor local (NVIDIA/Antigravity) tambem e stream-first e suporta
|
|
3681
3773
|
# multiplos modelos pelo campo `model` enviado pelo cliente (ex.: OpenCode
|
|
@@ -4497,6 +4589,7 @@ class Handler(BaseHTTPRequestHandler):
|
|
|
4497
4589
|
'ms': int((time.monotonic() - started) * 1000) if started else None,
|
|
4498
4590
|
'stream': bool(fields.get('stream', getattr(self, '_bridge_stream', False))),
|
|
4499
4591
|
'provider': cfg.get('provider'),
|
|
4592
|
+
'model': fields.get('model') or getattr(self, '_bridge_req_model', None) or cfg.get('model_enviado') or cfg.get('upstream_model'),
|
|
4500
4593
|
'account': fields.get('account'),
|
|
4501
4594
|
'attempts': fields.get('attempts'),
|
|
4502
4595
|
'tokens': fields.get('tokens'),
|
|
@@ -4669,6 +4762,11 @@ class Handler(BaseHTTPRequestHandler):
|
|
|
4669
4762
|
self.emit(200, jbytes({'status': 'ok', 'service': SERVICE_NAME,
|
|
4670
4763
|
'version': BRIDGE_VERSION, 'model': MODEL}))
|
|
4671
4764
|
return
|
|
4765
|
+
if path == '/workbuddy/login/status':
|
|
4766
|
+
query = parse_qs(urlsplit(self.path).query)
|
|
4767
|
+
estado = (query.get('state') or [''])[0]
|
|
4768
|
+
self.emit(200, jbytes(workbuddy_login_status(cfg, state, estado)))
|
|
4769
|
+
return
|
|
4672
4770
|
self.authorized(cfg)
|
|
4673
4771
|
if path == '/_bridge/routes':
|
|
4674
4772
|
self.emit(200, jbytes({'service': SERVICE_NAME, 'version': BRIDGE_VERSION,
|
|
@@ -4802,6 +4900,15 @@ class Handler(BaseHTTPRequestHandler):
|
|
|
4802
4900
|
self._bridge_stage = 'request_validation'
|
|
4803
4901
|
try:
|
|
4804
4902
|
cfg, state = self.runtime()
|
|
4903
|
+
raw_path = urlsplit(self.path).path
|
|
4904
|
+
if raw_path == '/workbuddy/login/start':
|
|
4905
|
+
self.emit(200, jbytes(workbuddy_login_start(cfg, state)))
|
|
4906
|
+
return
|
|
4907
|
+
if raw_path == '/workbuddy/logout':
|
|
4908
|
+
body = self.read_payload() if int(self.headers.get('Content-Length', '0') or '0') > 0 else {}
|
|
4909
|
+
alvo = str(body.get('alvo') or body.get('id') or body.get('uid') or body.get('nome') or '').strip()
|
|
4910
|
+
self.emit(200, jbytes(workbuddy_logout(state, alvo)))
|
|
4911
|
+
return
|
|
4805
4912
|
self.authorized(cfg)
|
|
4806
4913
|
path = self.resolve_route(trace)
|
|
4807
4914
|
self._bridge_logged_path = path
|
|
@@ -4892,8 +4999,10 @@ class Handler(BaseHTTPRequestHandler):
|
|
|
4892
4999
|
chat = anthropic_request(payload)
|
|
4893
5000
|
messages = None
|
|
4894
5001
|
self._bridge_stream = bool(chat['stream'])
|
|
5002
|
+
modelo_req = str(chat.get('model') or payload.get('model') or cfg.get('model_enviado') or '').strip()
|
|
5003
|
+
self._bridge_req_model = modelo_req
|
|
4895
5004
|
self._bridge_stage = 'upstream_connect'
|
|
4896
|
-
state.live_inicio(trace, route, chat['stream'])
|
|
5005
|
+
state.live_inicio(trace, route, chat['stream'], modelo=modelo_req)
|
|
4897
5006
|
# Modo streaming: com o modelo em 'error', envia comentarios SSE
|
|
4898
5007
|
# (heartbeats) durante as esperas de 60s para reduzir timeouts idle.
|
|
4899
5008
|
# Nunca tenta inferencia enquanto o painel estiver em 'error'.
|
|
@@ -5168,6 +5277,9 @@ class BridgeHTTPServer(ThreadingHTTPServer):
|
|
|
5168
5277
|
erros de verdade continuam indo para o log padrão do socketserver."""
|
|
5169
5278
|
|
|
5170
5279
|
allow_reuse_address = True
|
|
5280
|
+
# Backlog alto para rajadas de 50/100/200+ subagentes simultâneos sem
|
|
5281
|
+
# descartar SYN no listen() (o default do Python é apenas 5).
|
|
5282
|
+
request_queue_size = 512
|
|
5171
5283
|
|
|
5172
5284
|
def handle_error(self, request, client_address):
|
|
5173
5285
|
exc = sys.exc_info()[1]
|
package/dashboard_web.py
CHANGED
|
@@ -25,7 +25,7 @@ SECURITY_HEADERS = {
|
|
|
25
25
|
LOG_FILES = ('bridge-errors.log', 'painel-bridge.log', 'firewall.log', 'autostart.log',
|
|
26
26
|
'dns_duck.log', 'tls_nyxo.log')
|
|
27
27
|
REQUEST_FIELDS = ('ts', 'id', 'method', 'path', 'status', 'ms', 'stream', 'provider',
|
|
28
|
-
'account', 'attempts', 'error')
|
|
28
|
+
'account', 'model', 'attempts', 'error')
|
|
29
29
|
|
|
30
30
|
|
|
31
31
|
def local_dashboard_url(cfg: dict) -> str:
|