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.
- package/Iniciar_Linux.sh +129 -0
- package/Instalar_Atalho_Windows.cmd +40 -0
- package/Instalar_Ubuntu.sh +95 -0
- package/Painel.cmd +138 -0
- package/README.md +70 -2
- package/bin/nyxo.mjs +138 -0
- package/bridge.py +5196 -0
- package/config.example.json +57 -0
- package/contexto.py +184 -0
- package/dashboard_web.py +308 -0
- package/dns_duck.py +227 -0
- package/ferramentas/Liberar_Firewall.ps1 +96 -0
- package/ferramentas/firewall_linux.sh +67 -0
- package/ferramentas/install_windows.py +482 -0
- package/ferramentas/selecionar_provedor.py +70 -0
- package/iniciar.sh +255 -0
- package/keys.example.env +3 -0
- package/kimi.py +482 -0
- package/opencode_sync.py +239 -0
- package/package.json +69 -4
- package/painel.py +5227 -0
- package/painel_web.py +367 -0
- package/plugins/system-prompt/index.ts +409 -0
- package/provedores/kimi/bridge.mjs +4280 -0
- package/provedores/kimi/package.json +10 -0
- package/provedores_catalogo.py +155 -0
- package/tls_proxy.py +205 -0
- package/tui_core.py +600 -0
- package/web/dist/.vite/manifest.json +84 -0
- package/web/dist/assets/LogsPage-DkXN-I7o.js +2 -0
- package/web/dist/assets/LogsPage-OsSvuqxQ.js +2 -0
- package/web/dist/assets/TerminalPage-CZTPxVyx.js +1 -0
- package/web/dist/assets/TerminalPage-D208X99P.js +1 -0
- package/web/dist/assets/TerminalPage-DYGPu4ux.css +1 -0
- package/web/dist/assets/index-B5rIwous.js +1 -0
- package/web/dist/assets/index-CJE_a_Tn.js +27 -0
- package/web/dist/assets/index-COlDAcsY.js +1 -0
- package/web/dist/assets/index-Dzc8Obwp.css +1 -0
- package/web/dist/assets/index-LZadV7rx.js +27 -0
- package/web/dist/assets/index-o8xT03ZV.css +1 -0
- package/web/dist/assets/press-start-2p-2BZhbCiP.ttf +0 -0
- package/web/dist/assets/react-vendor-C475ILlI.js +49 -0
- package/web/dist/assets/terminal-vendor-DOrYoP_4.css +32 -0
- package/web/dist/assets/terminal-vendor-Dp03d74L.js +38 -0
- package/web/dist/assets/terminal-webgl-BRBWwLY7.js +75 -0
- package/web/dist/favicon.svg +1 -0
- package/web/dist/fonts/OFL.txt +93 -0
- package/web/dist/fonts/press-start-2p.ttf +0 -0
- package/web/dist/index.html +18 -0
- package/workbuddy.py +1965 -0
|
@@ -0,0 +1,4280 @@
|
|
|
1
|
+
// Kimi Bridge — API OpenAI-compatible para o Kimi K3.1 Pro (playground NVIDIA).
|
|
2
|
+
// Executa sozinho: instala dependencias, baixa o Chromium se faltar, registra
|
|
3
|
+
// o modelo no opencode (se existir), instala autostart e sobe a API.
|
|
4
|
+
// Sem flags. Windows 11, Linux/Ubuntu e Termux.
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import https from 'node:https';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
|
|
14
|
+
const APP_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
15
|
+
const IS_WIN = process.platform === 'win32';
|
|
16
|
+
const IS_TERMUX = !!process.env.PREFIX && /com\.termux/.test(process.env.PREFIX);
|
|
17
|
+
const HOME = os.homedir();
|
|
18
|
+
|
|
19
|
+
const LOG_DIR = path.join(APP_DIR, 'logs');
|
|
20
|
+
const SSE_DIR = path.join(LOG_DIR, 'sse');
|
|
21
|
+
fs.mkdirSync(LOG_DIR, { recursive: true });
|
|
22
|
+
const LOG_FILE = path.join(LOG_DIR, 'bridge.log');
|
|
23
|
+
try {
|
|
24
|
+
const bootLog = path.join(LOG_DIR, 'boot.log');
|
|
25
|
+
if (fs.statSync(bootLog).size > 2 * 1024 * 1024) fs.renameSync(bootLog, bootLog + '.old');
|
|
26
|
+
} catch {}
|
|
27
|
+
|
|
28
|
+
const log = (...a) => {
|
|
29
|
+
const line = new Date().toISOString() + ' ' + a.map((x) => (typeof x === 'string' ? x : JSON.stringify(x))).join(' ');
|
|
30
|
+
console.log(line);
|
|
31
|
+
try {
|
|
32
|
+
if (fs.statSync(LOG_FILE).size > 8 * 1024 * 1024) fs.renameSync(LOG_FILE, LOG_FILE + '.old');
|
|
33
|
+
} catch {}
|
|
34
|
+
try { fs.appendFileSync(LOG_FILE, line + '\n'); } catch {}
|
|
35
|
+
};
|
|
36
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
37
|
+
const rid = () => crypto.randomBytes(4).toString('hex');
|
|
38
|
+
|
|
39
|
+
// ---------- configuracao ----------
|
|
40
|
+
const CFG = {
|
|
41
|
+
host: '127.0.0.1',
|
|
42
|
+
port: 9098,
|
|
43
|
+
upstream: 'https://buildapi.ngc.nvidia.com/v2/predict/models/qc69jvmznzxy/kimi-k3_1-pro',
|
|
44
|
+
model: 'moonshotai/kimi-k3.1-pro',
|
|
45
|
+
fnId: 'b79234a1-64e1-479e-87e7-1c8e3af74262',
|
|
46
|
+
sitekey: '0c6a1e45-75d7-43cc-b836-a0c9d886b8ee',
|
|
47
|
+
pageUrl: 'https://build.nvidia.com/moonshotai/kimi-k3_1-pro/playground',
|
|
48
|
+
browserPath: '',
|
|
49
|
+
profileDir: 'profile',
|
|
50
|
+
headless: false,
|
|
51
|
+
reasoning: 'max',
|
|
52
|
+
maxTokens: 65536,
|
|
53
|
+
contextTokens: 400000,
|
|
54
|
+
// Tempo maximo sem NENHUM byte vindo do upstream antes de desistir. O
|
|
55
|
+
// servidor as vezes fica minutos sem mandar nada no meio de uma resposta
|
|
56
|
+
// grande; 5 minutos cortava a escrita pela metade. 1 hora da folga.
|
|
57
|
+
idleTimeoutMs: 3600000,
|
|
58
|
+
// Otimizacao NVIDIA/hCaptcha:
|
|
59
|
+
// - captchaWorkers: quantidade de contextos isolados (cada um com cookie jar proprio)
|
|
60
|
+
// - captchaWidgetsPerWorker: widgets hCaptcha paralelos por contexto
|
|
61
|
+
// - captchaPoolSize: buffer de tokens frescos pre-mintados
|
|
62
|
+
// - browserIdleCloseMs: fecha o browser apos ocioso (0 MB RAM sem uso NVIDIA)
|
|
63
|
+
captchaWorkers: 2,
|
|
64
|
+
captchaWidgetsPerWorker: 2,
|
|
65
|
+
captchaPoolSize: 4,
|
|
66
|
+
browserIdleCloseMs: 120000,
|
|
67
|
+
locale: 'en-US',
|
|
68
|
+
answerMarker: '**[ENI]**',
|
|
69
|
+
};
|
|
70
|
+
try {
|
|
71
|
+
const f = path.join(APP_DIR, 'config.json');
|
|
72
|
+
if (fs.existsSync(f)) Object.assign(CFG, JSON.parse(fs.readFileSync(f, 'utf8')));
|
|
73
|
+
} catch (e) { log('config.json invalido:', e.message); }
|
|
74
|
+
if (process.env.PORT) CFG.port = Number(process.env.PORT);
|
|
75
|
+
if (process.env.HOST) CFG.host = process.env.HOST;
|
|
76
|
+
if (process.env.CHROME_BIN) CFG.browserPath = process.env.CHROME_BIN;
|
|
77
|
+
CFG.idleTimeoutMs = Math.max(60000, Number(CFG.idleTimeoutMs) || 3600000);
|
|
78
|
+
CFG.profileDir = path.isAbsolute(CFG.profileDir) ? CFG.profileDir : path.join(APP_DIR, CFG.profileDir);
|
|
79
|
+
|
|
80
|
+
// ---------- modelos ----------
|
|
81
|
+
// Duas famílias de upstream:
|
|
82
|
+
// - nvidia: playground do build.nvidia.com, com token de hCaptcha mintado
|
|
83
|
+
// no browser e nv-function-id por endpoint.
|
|
84
|
+
// - antigravity: Cloud Code do Google (OAuth da conta do LO), envelope
|
|
85
|
+
// proprio e streaming Gemini.
|
|
86
|
+
// Os campos extras (endpoint/fnId/pageUrl) sao da familia nvidia; agModel,
|
|
87
|
+
// maxOut e vision sao da antigravity.
|
|
88
|
+
const BUILDAPI = 'https://buildapi.ngc.nvidia.com/v2/predict/models/qc69jvmznzxy';
|
|
89
|
+
const MODELS = [
|
|
90
|
+
{
|
|
91
|
+
id: 'kimi-k3.1-pro',
|
|
92
|
+
name: 'Kimi K3.1 Pro (NVIDIA playground)',
|
|
93
|
+
apiModel: 'moonshotai/kimi-k3.1-pro',
|
|
94
|
+
endpoint: 'kimi-k3_1-pro',
|
|
95
|
+
fnId: 'b79234a1-64e1-479e-87e7-1c8e3af74262',
|
|
96
|
+
pageUrl: 'https://build.nvidia.com/moonshotai/kimi-k3_1-pro/playground',
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
id: 'minimax-m3.1-flash',
|
|
100
|
+
name: 'MiniMax M3.1 Flash (NVIDIA playground)',
|
|
101
|
+
apiModel: 'minimaxai/minimax-m3.1-flash',
|
|
102
|
+
endpoint: 'minimax-m3.1-flash',
|
|
103
|
+
fnId: 'eb8265c4-e47d-4047-918d-c12746cc2cee',
|
|
104
|
+
pageUrl: 'https://build.nvidia.com/minimaxai/minimax-m3.1-flash/playground',
|
|
105
|
+
},
|
|
106
|
+
];
|
|
107
|
+
|
|
108
|
+
// Catalogo do Antigravity: um modelo por familia, e o tier de reasoning vem
|
|
109
|
+
// do cliente (reasoning_effort), nao vira modelo separado no opencode.
|
|
110
|
+
//
|
|
111
|
+
// Somente as 4 familias Antigravity pedidas: Claude Opus/Sonnet 5.5,
|
|
112
|
+
// Gemini 4 Hydrogen e Gemini 4 Neon.
|
|
113
|
+
//
|
|
114
|
+
// Analise do binario /root/.local/bin/agy (1.5.13) + resposta real de
|
|
115
|
+
// daily-cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels:
|
|
116
|
+
// - O servidor exige o User-Agent completo do CLI (com aidev_client e
|
|
117
|
+
// cl=1025641825) para liberar Gemini 4 Neon/Hydrogen no daily. Sem esse
|
|
118
|
+
// cl=, o servidor esconde os modelos novos e devolve 404.
|
|
119
|
+
// - O id enviado no envelope SEMPRE inclui o sufixo de tier (ex.:
|
|
120
|
+
// gemini-4-neon-xhigh, claude-sonnet-5-5-high). Sem sufixo da 404.
|
|
121
|
+
// - Tiers servidos (confirmados em groupedModels):
|
|
122
|
+
// Claude 5.5 -> low, medium, high (max da 404 na conta Pro)
|
|
123
|
+
// Hydrogen -> low, medium, high, xhigh (maxOutputTokens 262144)
|
|
124
|
+
// Neon -> low, medium, high, xhigh (maxOutputTokens 262144)
|
|
125
|
+
// O esforco pedido e traduzido para o tier mais proximo do teto da familia.
|
|
126
|
+
const AG_CATALOG = [
|
|
127
|
+
{ id: 'claude-opus-5-5', name: 'Claude Opus 5.5', wire: 'claude-opus-5-5', tiers: ['low', 'medium', 'high'], maxOut: 128000, context: 400000, wireContext: 1000000, reasoning: true, vision: true, inputs: ['text', 'image'] },
|
|
128
|
+
{ id: 'claude-sonnet-5-5', name: 'Claude Sonnet 5.5', wire: 'claude-sonnet-5-5', tiers: ['low', 'medium', 'high'], maxOut: 128000, context: 400000, wireContext: 1000000, reasoning: true, vision: true, inputs: ['text', 'image'] },
|
|
129
|
+
{ id: 'gemini-4-hydrogen', name: 'Gemini 4 Hydrogen', wire: 'gemini-4-hydrogen', tiers: ['low', 'medium', 'high', 'xhigh'], maxOut: 262144, context: 400000, wireContext: 1048576, reasoning: true, vision: true, inputs: ['text', 'image', 'audio', 'video', 'pdf'] },
|
|
130
|
+
{ id: 'gemini-4-neon', name: 'Gemini 4 Neon', wire: 'gemini-4-neon', tiers: ['low', 'medium', 'high', 'xhigh'], maxOut: 262144, context: 400000, wireContext: 1048576, reasoning: true, vision: true, inputs: ['text', 'image', 'audio', 'video', 'pdf'] },
|
|
131
|
+
];
|
|
132
|
+
|
|
133
|
+
function agTierName(t) {
|
|
134
|
+
return t === 'xhigh' ? 'Extra High' : String(t).charAt(0).toUpperCase() + String(t).slice(1);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function modelAliases(m) {
|
|
138
|
+
const alias = [
|
|
139
|
+
m.id,
|
|
140
|
+
m.apiModel,
|
|
141
|
+
m.endpoint,
|
|
142
|
+
m.id.replace(/\./g, '_'),
|
|
143
|
+
m.provider === 'antigravity' ? `antigravity/${m.id}` : null,
|
|
144
|
+
m.endpoint ? m.endpoint.replace(/\./g, '_') : null,
|
|
145
|
+
].filter(Boolean);
|
|
146
|
+
if (m.provider === 'antigravity' && Array.isArray(m.tiers)) {
|
|
147
|
+
for (const t of [...m.tiers, 'max', 'xhigh']) {
|
|
148
|
+
alias.push(`${m.id}-${t}`, `antigravity/${m.id}-${t}`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
m.aliases = [...new Set(alias.map((s) => String(s).toLowerCase()))];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Ponto unico de entrada de modelo. Nao duplica id e recalcula os aliases.
|
|
155
|
+
function addModel(entry) {
|
|
156
|
+
if (!entry || !entry.id || MODELS.some((x) => x.id === entry.id)) return false;
|
|
157
|
+
const m = {
|
|
158
|
+
provider: 'antigravity',
|
|
159
|
+
maxOut: 65535,
|
|
160
|
+
context: 1048576,
|
|
161
|
+
reasoning: true,
|
|
162
|
+
vision: true,
|
|
163
|
+
...entry,
|
|
164
|
+
};
|
|
165
|
+
m.apiModel = m.apiModel || m.id;
|
|
166
|
+
if (m.provider === 'nvidia') m.upstream = `${BUILDAPI}/${m.endpoint}`;
|
|
167
|
+
modelAliases(m);
|
|
168
|
+
MODELS.push(m);
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
for (const m of AG_CATALOG) addModel({ ...m, name: `${m.name} (Antigravity)` });
|
|
173
|
+
|
|
174
|
+
for (const m of MODELS) {
|
|
175
|
+
if (!m.provider) m.provider = 'nvidia';
|
|
176
|
+
if (m.provider === 'nvidia' && !m.upstream) m.upstream = `${BUILDAPI}/${m.endpoint}`;
|
|
177
|
+
if (!m.aliases) modelAliases(m);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function resolveModel(name) {
|
|
181
|
+
const raw = String(name || '').trim().toLowerCase().replace(/^kimibridge\//, '').replace(/^antigravity\//, '');
|
|
182
|
+
for (const m of MODELS) {
|
|
183
|
+
if (m.aliases.includes(raw) || m.aliases.includes(`antigravity/${raw}`)) return m;
|
|
184
|
+
}
|
|
185
|
+
return MODELS[0];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Se o cliente mandou o tier no nome do modelo (ex.: "gemini-4-neon-xhigh"),
|
|
189
|
+
// extrai esse tier para usar quando reasoning_effort nao vier explicito.
|
|
190
|
+
function extractTierFromModelName(name, model) {
|
|
191
|
+
if (!model || model.provider !== 'antigravity') return '';
|
|
192
|
+
const raw = String(name || '').trim().toLowerCase().replace(/^kimibridge\//, '').replace(/^antigravity\//, '');
|
|
193
|
+
const prefix = `${String(model.id).toLowerCase()}-`;
|
|
194
|
+
if (!raw.startsWith(prefix)) return '';
|
|
195
|
+
const suffix = raw.slice(prefix.length);
|
|
196
|
+
return AG_TIER_ORDER.includes(suffix) ? suffix : '';
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function run(cmd, args = [], opts = {}) {
|
|
200
|
+
return new Promise((resolve, reject) => {
|
|
201
|
+
const p = spawn(cmd, args, {
|
|
202
|
+
cwd: opts.cwd || APP_DIR,
|
|
203
|
+
env: process.env,
|
|
204
|
+
shell: !!opts.shell,
|
|
205
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
206
|
+
});
|
|
207
|
+
let stdout = '';
|
|
208
|
+
let stderr = '';
|
|
209
|
+
p.stdout.on('data', (d) => { stdout += d; if (opts.echo) process.stdout.write(d); });
|
|
210
|
+
p.stderr.on('data', (d) => { stderr += d; if (opts.echo) process.stderr.write(d); });
|
|
211
|
+
p.on('close', (code) => resolve({ code, stdout, stderr }));
|
|
212
|
+
p.on('error', reject);
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function commandExists(name) {
|
|
217
|
+
return new Promise((resolve) => {
|
|
218
|
+
const p = spawn(IS_WIN ? 'where' : 'which', [name], { stdio: 'ignore' });
|
|
219
|
+
p.on('close', (code) => resolve(code === 0));
|
|
220
|
+
p.on('error', () => resolve(false));
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ---------- dependencias ----------
|
|
225
|
+
async function ensurePlaywright() {
|
|
226
|
+
const mod = path.join(APP_DIR, 'node_modules', 'playwright-core', 'index.js');
|
|
227
|
+
if (fs.existsSync(mod)) return;
|
|
228
|
+
log('instalando playwright-core (primeira vez)...');
|
|
229
|
+
const pkg = path.join(APP_DIR, 'package.json');
|
|
230
|
+
if (!fs.existsSync(pkg)) {
|
|
231
|
+
fs.writeFileSync(pkg, JSON.stringify({ name: 'kimi-bridge', private: true, type: 'module' }, null, 2));
|
|
232
|
+
}
|
|
233
|
+
const npm = IS_WIN ? 'npm.cmd' : 'npm';
|
|
234
|
+
const r = await run(npm, ['install', 'playwright-core', '--no-audit', '--no-fund'], { echo: true, shell: IS_WIN });
|
|
235
|
+
if (r.code !== 0) throw new Error('npm install falhou: ' + (r.stderr || '').slice(0, 400));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
await ensurePlaywright();
|
|
239
|
+
const { chromium } = await import('playwright-core');
|
|
240
|
+
|
|
241
|
+
// ---------- browser ----------
|
|
242
|
+
function chromiumCacheRoots() {
|
|
243
|
+
const roots = [path.join(HOME, '.cache', 'ms-playwright')];
|
|
244
|
+
if (IS_WIN) roots.push(path.join(process.env.LOCALAPPDATA || path.join(HOME, 'AppData', 'Local'), 'ms-playwright'));
|
|
245
|
+
if (IS_TERMUX) roots.push(path.join(process.env.PREFIX, 'lib', 'chromium'));
|
|
246
|
+
return roots;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Prefere o chromium_headless_shell (bem mais leve em RAM e sem precisar
|
|
250
|
+
// de Xvfb) quando existir; cai para o Chromium completo se nao houver.
|
|
251
|
+
function browserFromCache() {
|
|
252
|
+
const foundShell = [];
|
|
253
|
+
const foundFull = [];
|
|
254
|
+
for (const root of chromiumCacheRoots()) {
|
|
255
|
+
if (!fs.existsSync(root)) continue;
|
|
256
|
+
let entries = [];
|
|
257
|
+
try { entries = fs.readdirSync(root); } catch { continue; }
|
|
258
|
+
entries.sort().reverse();
|
|
259
|
+
for (const d of entries) {
|
|
260
|
+
if (d.startsWith('chromium_headless_shell')) {
|
|
261
|
+
for (const p of [
|
|
262
|
+
path.join(root, d, 'chrome-linux', 'headless_shell'),
|
|
263
|
+
path.join(root, d, 'chrome-linux64', 'chrome-headless-shell'),
|
|
264
|
+
path.join(root, d, 'chrome-linux-arm64', 'chrome-headless-shell'),
|
|
265
|
+
path.join(root, d, 'chrome-headless-shell-linux64', 'chrome-headless-shell'),
|
|
266
|
+
path.join(root, d, 'chrome-win', 'headless_shell.exe'),
|
|
267
|
+
path.join(root, d, 'chrome-win64', 'chrome-headless-shell.exe'),
|
|
268
|
+
path.join(root, d, 'chrome-headless-shell-win64', 'chrome-headless-shell.exe'),
|
|
269
|
+
]) if (fs.existsSync(p)) foundShell.push(p);
|
|
270
|
+
} else if (d.startsWith('chromium')) {
|
|
271
|
+
for (const p of [
|
|
272
|
+
path.join(root, d, 'chrome-linux', 'chrome'),
|
|
273
|
+
path.join(root, d, 'chrome-linux64', 'chrome'),
|
|
274
|
+
path.join(root, d, 'chrome-linux-arm64', 'chrome'),
|
|
275
|
+
path.join(root, d, 'chrome-win', 'chrome.exe'),
|
|
276
|
+
path.join(root, d, 'chrome-win64', 'chrome.exe'),
|
|
277
|
+
]) if (fs.existsSync(p)) foundFull.push(p);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return foundShell[0] || foundFull[0] || null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function isHeadlessShellPath(p) {
|
|
285
|
+
return !!p && /headless[_-]shell/i.test(path.basename(p));
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function findBrowser() {
|
|
289
|
+
if (CFG.browserPath && fs.existsSync(CFG.browserPath)) return CFG.browserPath;
|
|
290
|
+
// Chromium / headless-shell baixado pela propria bridge (fallback do Google CfT).
|
|
291
|
+
for (const p of [
|
|
292
|
+
path.join(APP_DIR, 'browser', 'chrome-headless-shell-win64', 'chrome-headless-shell.exe'),
|
|
293
|
+
path.join(APP_DIR, 'browser', 'chrome-headless-shell-linux64', 'chrome-headless-shell'),
|
|
294
|
+
path.join(APP_DIR, 'browser', 'chrome-win64', 'chrome.exe'),
|
|
295
|
+
path.join(APP_DIR, 'browser', 'chrome-linux64', 'chrome'),
|
|
296
|
+
]) {
|
|
297
|
+
if (fs.existsSync(p)) return p;
|
|
298
|
+
}
|
|
299
|
+
const fromCache = browserFromCache();
|
|
300
|
+
if (fromCache) return fromCache;
|
|
301
|
+
const local = process.env.LOCALAPPDATA || path.join(HOME, 'AppData', 'Local');
|
|
302
|
+
const win = [
|
|
303
|
+
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
|
304
|
+
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
|
|
305
|
+
'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
|
|
306
|
+
'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
|
|
307
|
+
// Instalacao por usuario (sem admin), a mais comum no Windows 11.
|
|
308
|
+
path.join(local, 'Google', 'Chrome', 'Application', 'chrome.exe'),
|
|
309
|
+
path.join(local, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
|
|
310
|
+
path.join(local, 'Chromium', 'Application', 'chrome.exe'),
|
|
311
|
+
'C:\\Program Files\\Chromium\\Application\\chrome.exe',
|
|
312
|
+
];
|
|
313
|
+
const linux = [
|
|
314
|
+
'/usr/bin/google-chrome',
|
|
315
|
+
'/usr/bin/google-chrome-stable',
|
|
316
|
+
'/usr/bin/chromium',
|
|
317
|
+
'/usr/bin/chromium-browser',
|
|
318
|
+
'/snap/bin/chromium',
|
|
319
|
+
];
|
|
320
|
+
if (IS_TERMUX) linux.unshift(path.join(process.env.PREFIX, 'bin', 'chromium'));
|
|
321
|
+
for (const p of IS_WIN ? win : linux) if (fs.existsSync(p)) return p;
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function chromiumVersion() {
|
|
326
|
+
try {
|
|
327
|
+
const b = JSON.parse(fs.readFileSync(path.join(APP_DIR, 'node_modules', 'playwright-core', 'browsers.json'), 'utf8'));
|
|
328
|
+
const c = b.browsers.find((x) => x.name === 'chromium');
|
|
329
|
+
if (c?.browserVersion) return c.browserVersion;
|
|
330
|
+
} catch {}
|
|
331
|
+
return '140.0.7339.82';
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// O CDN da Microsoft usado pelo Playwright as vezes responde
|
|
335
|
+
// GatewayExceptionResponse e o Chromium nunca chega. O Chrome for Testing
|
|
336
|
+
// do Google entrega o mesmo browser (ou o chrome-headless-shell, bem menor)
|
|
337
|
+
// por outra rota.
|
|
338
|
+
async function downloadChromium() {
|
|
339
|
+
// O Chrome for Testing so publica x86_64 para Windows/Linux. Em ARM
|
|
340
|
+
// (Termux, Raspberry) quem resolve e o pacote do sistema, ja tentado
|
|
341
|
+
// antes; baixar a build x86_64 so quebraria na execucao.
|
|
342
|
+
if (!IS_WIN && process.arch !== 'x64') {
|
|
343
|
+
throw new Error('Chrome for Testing nao tem build para ' + process.arch + '. Instale o chromium do sistema (pkg install chromium ou apt install chromium).');
|
|
344
|
+
}
|
|
345
|
+
const dest = path.join(APP_DIR, 'browser');
|
|
346
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
347
|
+
const plat = IS_WIN ? 'win64' : 'linux64';
|
|
348
|
+
const version = chromiumVersion();
|
|
349
|
+
const variants = [
|
|
350
|
+
{ folder: `chrome-headless-shell-${plat}`, exeName: IS_WIN ? 'chrome-headless-shell.exe' : 'chrome-headless-shell' },
|
|
351
|
+
{ folder: `chrome-${plat}`, exeName: IS_WIN ? 'chrome.exe' : 'chrome' },
|
|
352
|
+
];
|
|
353
|
+
for (const v of variants) {
|
|
354
|
+
const exe = path.join(dest, v.folder, v.exeName);
|
|
355
|
+
if (fs.existsSync(exe)) return exe;
|
|
356
|
+
}
|
|
357
|
+
let lastErr = null;
|
|
358
|
+
for (const v of variants) {
|
|
359
|
+
const exe = path.join(dest, v.folder, v.exeName);
|
|
360
|
+
const url = `https://storage.googleapis.com/chrome-for-testing-public/${version}/${plat}/${v.folder}.zip`;
|
|
361
|
+
const zip = path.join(dest, `${v.folder}.zip`);
|
|
362
|
+
try {
|
|
363
|
+
log('baixando browser leve do Chrome for Testing:', url);
|
|
364
|
+
const res = await fetch(url);
|
|
365
|
+
if (!res.ok || !res.body) throw new Error('HTTP ' + res.status);
|
|
366
|
+
const out = fs.createWriteStream(zip);
|
|
367
|
+
try {
|
|
368
|
+
for await (const chunk of res.body) {
|
|
369
|
+
if (!out.write(chunk)) await new Promise((r) => out.once('drain', r));
|
|
370
|
+
}
|
|
371
|
+
} finally {
|
|
372
|
+
await new Promise((resolve, reject) => { out.end(); out.on('finish', resolve); out.on('error', reject); });
|
|
373
|
+
}
|
|
374
|
+
log('download concluido, extraindo...');
|
|
375
|
+
if (IS_WIN) {
|
|
376
|
+
// Windows 10/11 ja traz tar.exe, que extrai zip.
|
|
377
|
+
const r = await run('tar', ['-xf', zip, '-C', dest], { echo: true });
|
|
378
|
+
if (r.code !== 0) throw new Error('tar falhou: ' + (r.stderr || '').slice(0, 300));
|
|
379
|
+
} else {
|
|
380
|
+
if (!(await commandExists('unzip'))) {
|
|
381
|
+
if (IS_TERMUX && (await commandExists('pkg'))) {
|
|
382
|
+
await run('pkg', ['install', '-y', 'unzip'], { echo: true }).catch(() => {});
|
|
383
|
+
} else if (await commandExists('apt-get')) {
|
|
384
|
+
await run('apt-get', ['update'], { echo: true }).catch(() => {});
|
|
385
|
+
await run('apt-get', ['install', '-y', 'unzip'], { echo: true }).catch(() => {});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
if (await commandExists('unzip')) {
|
|
389
|
+
const r = await run('unzip', ['-q', zip, '-d', dest], { echo: true });
|
|
390
|
+
if (r.code !== 0) throw new Error('unzip falhou');
|
|
391
|
+
} else if (await commandExists('python3')) {
|
|
392
|
+
const r = await run('python3', ['-c', 'import zipfile,sys; zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])', zip, dest]);
|
|
393
|
+
if (r.code !== 0) throw new Error('python zip falhou');
|
|
394
|
+
} else {
|
|
395
|
+
throw new Error('precisa de unzip ou python3 para extrair');
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
try { fs.unlinkSync(zip); } catch {}
|
|
399
|
+
if (!IS_WIN) { try { fs.chmodSync(exe, 0o755); } catch {} }
|
|
400
|
+
if (fs.existsSync(exe)) {
|
|
401
|
+
log('browser pronto em', exe);
|
|
402
|
+
return exe;
|
|
403
|
+
}
|
|
404
|
+
throw new Error('binario extraido nao encontrado em ' + exe);
|
|
405
|
+
} catch (e) {
|
|
406
|
+
lastErr = e;
|
|
407
|
+
try { fs.unlinkSync(zip); } catch {}
|
|
408
|
+
log('download falhou para ' + v.folder + ':', e.message);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
throw lastErr || new Error('download do Chromium falhou');
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function ensureBrowser() {
|
|
415
|
+
const found = findBrowser();
|
|
416
|
+
if (found) return found;
|
|
417
|
+
log('nenhum Chrome/Chromium encontrado; instalando Chromium headless-shell leve (primeira vez)...');
|
|
418
|
+
if (IS_TERMUX && (await commandExists('pkg'))) {
|
|
419
|
+
await run('pkg', ['install', '-y', 'chromium'], { echo: true }).catch(() => {});
|
|
420
|
+
}
|
|
421
|
+
if (!findBrowser()) {
|
|
422
|
+
const cli = path.join(APP_DIR, 'node_modules', 'playwright-core', 'cli.js');
|
|
423
|
+
const isRoot = !IS_WIN && typeof process.getuid === 'function' && process.getuid() === 0;
|
|
424
|
+
const withDeps = isRoot && (await commandExists('apt-get'));
|
|
425
|
+
// Tenta primeiro o headless-shell (menor e mais economico em RAM); se
|
|
426
|
+
// nao existir para a plataforma, instala o chromium completo.
|
|
427
|
+
const tries = [
|
|
428
|
+
withDeps ? [cli, 'install', 'chromium-headless-shell', '--with-deps'] : [cli, 'install', 'chromium-headless-shell'],
|
|
429
|
+
withDeps ? [cli, 'install', 'chromium', '--with-deps'] : [cli, 'install', 'chromium'],
|
|
430
|
+
];
|
|
431
|
+
for (const args of tries) {
|
|
432
|
+
if (findBrowser()) break;
|
|
433
|
+
const r = await run(process.execPath, args, { echo: true });
|
|
434
|
+
if (r.code !== 0) log('instalacao via Playwright falhou:', (r.stderr || r.stdout || '').slice(-500));
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
let p = findBrowser();
|
|
438
|
+
if (!p) p = await downloadChromium();
|
|
439
|
+
if (!p) throw new Error('nao consegui instalar o Chromium automaticamente. Instale o Chrome/Chromium e rode de novo.');
|
|
440
|
+
return p;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
let xvfbStarted = false;async function ensureDisplay() {
|
|
444
|
+
if (IS_WIN || process.env.DISPLAY) return;
|
|
445
|
+
if (!xvfbStarted) {
|
|
446
|
+
xvfbStarted = true;
|
|
447
|
+
if (await commandExists('Xvfb')) {
|
|
448
|
+
try {
|
|
449
|
+
const p = spawn('Xvfb', [':99', '-screen', '0', '1440x1000x24', '-nolisten', 'tcp'], { stdio: 'ignore', detached: true });
|
|
450
|
+
p.unref();
|
|
451
|
+
process.env.DISPLAY = ':99';
|
|
452
|
+
await sleep(800);
|
|
453
|
+
log('Xvfb iniciado em :99');
|
|
454
|
+
return;
|
|
455
|
+
} catch (e) { log('Xvfb falhou:', e.message); }
|
|
456
|
+
}
|
|
457
|
+
log('Xvfb ausente; o browser vai tentar headless');
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// ---------- opencode ----------
|
|
462
|
+
const MODEL_ID = MODELS[0].id;
|
|
463
|
+
|
|
464
|
+
// Entrada de um modelo no bloco do opencode. O bloco e texto, nao JSON
|
|
465
|
+
// serializado: o arquivo do opencode e JSONC e o resto dele nao e nosso.
|
|
466
|
+
function opencodeModelEntry(m, indent) {
|
|
467
|
+
const p = indent;
|
|
468
|
+
const q = indent + ' ';
|
|
469
|
+
const inputs = Array.isArray(m.inputs) && m.inputs.length
|
|
470
|
+
? JSON.stringify(m.inputs)
|
|
471
|
+
: (m.vision ? '["text", "image"]' : '["text"]');
|
|
472
|
+
const context = Number(m.context) > 0 ? Number(m.context) : CFG.contextTokens;
|
|
473
|
+
const output = Number(m.maxOut) > 0 ? Number(m.maxOut) : 65536;
|
|
474
|
+
const hasTiers = Array.isArray(m.tiers) && m.tiers.length > 0;
|
|
475
|
+
const tiers = hasTiers ? m.tiers : [CFG.reasoning];
|
|
476
|
+
const defTier = hasTiers ? m.tiers[m.tiers.length - 1] : CFG.reasoning;
|
|
477
|
+
const reasoningObj = m.reasoning === false
|
|
478
|
+
? '{ "supported": false }'
|
|
479
|
+
: (hasTiers ? `{ "supported": true, "effort": ${JSON.stringify(tiers)} }` : '{ "supported": true }');
|
|
480
|
+
const variants = tiers.map((t) => `${q} { "id": "${t}", "body": { "reasoning_effort": "${t}" } }`).join(',\n');
|
|
481
|
+
const compatCache = m.provider === 'antigravity' ? `,\n${q} "supportsPromptCacheKey": true` : '';
|
|
482
|
+
return `${p}"${m.id}": {
|
|
483
|
+
${q}"name": ${JSON.stringify(m.name)},
|
|
484
|
+
${q}"capabilities": {
|
|
485
|
+
${q} "tools": true,
|
|
486
|
+
${q} "reasoning": ${reasoningObj},
|
|
487
|
+
${q} "input": ${inputs},
|
|
488
|
+
${q} "output": ["text"]
|
|
489
|
+
${q}},
|
|
490
|
+
${q}"limit": { "context": ${context}, "output": ${output} },
|
|
491
|
+
${q}"compatibility": {
|
|
492
|
+
${q} "reasoningField": "reasoning_content",
|
|
493
|
+
${q} "maxTokensField": "max_tokens"${compatCache}
|
|
494
|
+
${q}},
|
|
495
|
+
${q}"body": { "reasoning_effort": "${defTier}" },
|
|
496
|
+
${q}"variants": [
|
|
497
|
+
${variants}
|
|
498
|
+
${q}]
|
|
499
|
+
${p}}`;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function opencodeModelsBlock(indent) {
|
|
503
|
+
return MODELS.map((m) => opencodeModelEntry(m, indent)).join(',\n');
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// Fim do objeto que abre em `open` (fecha no matching brace, respeitando
|
|
507
|
+
// string e escape). Necessario porque o config tem varios providers, cada um
|
|
508
|
+
// com o seu "models": procurar por texto cru pega o bloco do vizinho.
|
|
509
|
+
function objectEnd(text, open) {
|
|
510
|
+
let depth = 0;
|
|
511
|
+
let inStr = false;
|
|
512
|
+
let esc = false;
|
|
513
|
+
for (let i = open; i < text.length; i++) {
|
|
514
|
+
const c = text[i];
|
|
515
|
+
if (inStr) {
|
|
516
|
+
if (esc) esc = false;
|
|
517
|
+
else if (c === '\\') esc = true;
|
|
518
|
+
else if (c === '"') inStr = false;
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (c === '"') inStr = true;
|
|
522
|
+
else if (c === '{') depth++;
|
|
523
|
+
else if (c === '}') {
|
|
524
|
+
depth--;
|
|
525
|
+
if (depth === 0) return i;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return -1;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// Configuracao ja existente: substitui SOMENTE o objeto "models" dentro do
|
|
532
|
+
// bloco "kimibridge" para refletir o catalogo exato da bridge (remove
|
|
533
|
+
// modelos antigos e atualiza limits/variants). Nada fora do bloco e tocado.
|
|
534
|
+
function syncModelsInBlock(text) {
|
|
535
|
+
const at = text.indexOf('"kimibridge"');
|
|
536
|
+
if (at < 0) return { text, changed: false };
|
|
537
|
+
const provOpen = text.indexOf('{', at);
|
|
538
|
+
if (provOpen < 0) return { text, changed: false };
|
|
539
|
+
const provEnd = objectEnd(text, provOpen);
|
|
540
|
+
if (provEnd < 0) return { text, changed: false };
|
|
541
|
+
const prov = text.slice(provOpen, provEnd + 1);
|
|
542
|
+
const modelsAtLocal = prov.indexOf('"models"');
|
|
543
|
+
if (modelsAtLocal < 0) return { text, changed: false };
|
|
544
|
+
const modelsAt = provOpen + modelsAtLocal;
|
|
545
|
+
const open = text.indexOf('{', modelsAt);
|
|
546
|
+
if (open < 0 || open > provEnd) return { text, changed: false };
|
|
547
|
+
const modelsEnd = objectEnd(text, open);
|
|
548
|
+
if (modelsEnd < 0 || modelsEnd > provEnd) return { text, changed: false };
|
|
549
|
+
const lineStart = text.lastIndexOf('\n', modelsAt) + 1;
|
|
550
|
+
const modelsIndent = (text.slice(lineStart, modelsAt).match(/^[ \t]*/) || [''])[0];
|
|
551
|
+
const entryIndent = modelsIndent + ' ';
|
|
552
|
+
const nextInside = '\n' + opencodeModelsBlock(entryIndent) + '\n' + modelsIndent;
|
|
553
|
+
const curInside = text.slice(open + 1, modelsEnd);
|
|
554
|
+
if (curInside === nextInside) return { text, changed: false };
|
|
555
|
+
return {
|
|
556
|
+
text: text.slice(0, open + 1) + nextInside + text.slice(modelsEnd),
|
|
557
|
+
changed: true,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// Fim de um array JSON que abre em `open` (respeitando strings e escapes).
|
|
562
|
+
function arrayEnd(text, open) {
|
|
563
|
+
let depth = 0;
|
|
564
|
+
let inStr = false;
|
|
565
|
+
let esc = false;
|
|
566
|
+
for (let i = open; i < text.length; i++) {
|
|
567
|
+
const c = text[i];
|
|
568
|
+
if (inStr) {
|
|
569
|
+
if (esc) esc = false;
|
|
570
|
+
else if (c === '\\') esc = true;
|
|
571
|
+
else if (c === '"') inStr = false;
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
if (c === '"') inStr = true;
|
|
575
|
+
else if (c === '[') depth++;
|
|
576
|
+
else if (c === ']') {
|
|
577
|
+
depth--;
|
|
578
|
+
if (depth === 0) return i;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return -1;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function ensurePluginInConfig(text, pluginDir) {
|
|
585
|
+
if (!pluginDir) return { text, changed: false };
|
|
586
|
+
const norm = (s) => String(s || '').replace(/\\/g, '/').replace(/\/+$/, '');
|
|
587
|
+
const wantNorm = norm(pluginDir);
|
|
588
|
+
const literal = JSON.stringify(pluginDir);
|
|
589
|
+
const keyRe = /"plugins"\s*:\s*\[/;
|
|
590
|
+
const m = keyRe.exec(text);
|
|
591
|
+
if (m) {
|
|
592
|
+
const open = text.indexOf('[', m.index);
|
|
593
|
+
const close = arrayEnd(text, open);
|
|
594
|
+
if (open < 0 || close < 0) return { text, changed: false };
|
|
595
|
+
const inside = text.slice(open + 1, close);
|
|
596
|
+
const existing = [];
|
|
597
|
+
const strRe = /"((?:\\.|[^"\\])*)"/g;
|
|
598
|
+
let sm;
|
|
599
|
+
while ((sm = strRe.exec(inside))) {
|
|
600
|
+
try { existing.push(JSON.parse(`"${sm[1]}"`)); } catch { existing.push(sm[1]); }
|
|
601
|
+
}
|
|
602
|
+
if (existing.some((p) => norm(p) === wantNorm || norm(p).endsWith('/plugins/system-prompt'))) {
|
|
603
|
+
return { text, changed: false };
|
|
604
|
+
}
|
|
605
|
+
if (!inside.trim()) {
|
|
606
|
+
return {
|
|
607
|
+
text: text.slice(0, open + 1) + literal + text.slice(close),
|
|
608
|
+
changed: true,
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
const trimmed = inside.replace(/\s+$/, '');
|
|
612
|
+
const trailing = inside.slice(trimmed.length);
|
|
613
|
+
const sep = trimmed.endsWith(',') ? ' ' : ', ';
|
|
614
|
+
return {
|
|
615
|
+
text: text.slice(0, open + 1) + trimmed + sep + literal + trailing + text.slice(close),
|
|
616
|
+
changed: true,
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
// Nao ha campo "plugins": insere logo apos "$schema" ou apos a primeira "{".
|
|
620
|
+
const schemaRe = /"\$schema"\s*:\s*"(?:\\.|[^"\\])*"\s*,?[ \t]*\r?\n?/;
|
|
621
|
+
const sm = schemaRe.exec(text);
|
|
622
|
+
if (sm) {
|
|
623
|
+
const insertAt = sm.index + sm[0].length;
|
|
624
|
+
const before = text.slice(0, insertAt);
|
|
625
|
+
const needsComma = !/,\s*$/.test(before);
|
|
626
|
+
const prefix = needsComma ? before.replace(/(\r?\n)?$/, ',\n') : (before.endsWith('\n') ? before : before + '\n');
|
|
627
|
+
return {
|
|
628
|
+
text: prefix + ` "plugins": [${literal}],\n` + text.slice(insertAt),
|
|
629
|
+
changed: true,
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
const openBrace = text.indexOf('{');
|
|
633
|
+
if (openBrace < 0) return { text, changed: false };
|
|
634
|
+
return {
|
|
635
|
+
text: text.slice(0, openBrace + 1) + `\n "plugins": [${literal}],` + text.slice(openBrace + 1),
|
|
636
|
+
changed: true,
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function installOpencodePlugin(cfgDir) {
|
|
641
|
+
const candidates = [
|
|
642
|
+
path.join(APP_DIR, 'plugins', 'system-prompt', 'index.ts'),
|
|
643
|
+
path.resolve(APP_DIR, '..', '..', 'plugins', 'system-prompt', 'index.ts'),
|
|
644
|
+
];
|
|
645
|
+
const src = candidates.find((p) => fs.existsSync(p)) || candidates[0];
|
|
646
|
+
const dstDir = path.join(cfgDir, 'plugins', 'system-prompt');
|
|
647
|
+
const dst = path.join(dstDir, 'index.ts');
|
|
648
|
+
let installedDir = null;
|
|
649
|
+
if (fs.existsSync(src)) {
|
|
650
|
+
try {
|
|
651
|
+
fs.mkdirSync(dstDir, { recursive: true });
|
|
652
|
+
const forceUpdate = process.argv.includes('--setup-opencode');
|
|
653
|
+
if (!fs.existsSync(dst) || forceUpdate) {
|
|
654
|
+
fs.copyFileSync(src, dst);
|
|
655
|
+
log('opencode: plugin system-prompt instalado em', dst);
|
|
656
|
+
}
|
|
657
|
+
installedDir = dstDir;
|
|
658
|
+
} catch (e) {
|
|
659
|
+
log('opencode: nao consegui instalar plugin system-prompt:', e.message);
|
|
660
|
+
}
|
|
661
|
+
} else if (fs.existsSync(dst)) {
|
|
662
|
+
installedDir = dstDir;
|
|
663
|
+
}
|
|
664
|
+
// Se o usuario colocou um AGENTS.md junto com a pasta da bridge (ou na raiz do nyxo) e ainda nao
|
|
665
|
+
// existe AGENTS.md no OpenCode, copia automaticamente sem sobrescrever.
|
|
666
|
+
const promptCandidates = [
|
|
667
|
+
path.join(APP_DIR, 'AGENTS.md'),
|
|
668
|
+
path.resolve(APP_DIR, '..', '..', 'AGENTS.md'),
|
|
669
|
+
];
|
|
670
|
+
const bundledPrompt = promptCandidates.find((p) => fs.existsSync(p)) || '';
|
|
671
|
+
const dstPrompt = path.join(cfgDir, 'AGENTS.md');
|
|
672
|
+
if (bundledPrompt && !fs.existsSync(dstPrompt)) {
|
|
673
|
+
try {
|
|
674
|
+
fs.mkdirSync(cfgDir, { recursive: true });
|
|
675
|
+
fs.copyFileSync(bundledPrompt, dstPrompt);
|
|
676
|
+
log('opencode: AGENTS.md copiado para', dstPrompt);
|
|
677
|
+
} catch (e) {
|
|
678
|
+
log('opencode: nao consegui copiar AGENTS.md:', e.message);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
return installedDir;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
async function hasOpencodeBinary() {
|
|
685
|
+
if (await commandExists('opencode')) return true;
|
|
686
|
+
const bin = IS_WIN ? 'opencode.exe' : 'opencode';
|
|
687
|
+
const extra = [
|
|
688
|
+
path.join(HOME, '.opencode', 'bin', bin),
|
|
689
|
+
path.join(HOME, '.local', 'bin', bin),
|
|
690
|
+
path.join(HOME, '.bun', 'bin', bin),
|
|
691
|
+
];
|
|
692
|
+
return extra.some((p) => fs.existsSync(p));
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function opencodeConfigCandidates() {
|
|
696
|
+
const list = [
|
|
697
|
+
path.join(HOME, '.config', 'opencode', 'opencode.jsonc'),
|
|
698
|
+
path.join(HOME, '.config', 'opencode', 'opencode.json'),
|
|
699
|
+
];
|
|
700
|
+
if (IS_WIN) list.push(path.join(process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming'), 'opencode', 'opencode.jsonc'));
|
|
701
|
+
return list;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
function providerBlock() {
|
|
705
|
+
const baseURL = `http://${CFG.host}:${CFG.port}/v1`;
|
|
706
|
+
return ` "kimibridge": {
|
|
707
|
+
"name": "Kimi Bridge (local)",
|
|
708
|
+
"package": "@opencode/ai/providers/openai-compatible",
|
|
709
|
+
"settings": {
|
|
710
|
+
"baseURL": "${baseURL}",
|
|
711
|
+
"apiKey": "local"
|
|
712
|
+
},
|
|
713
|
+
"models": {
|
|
714
|
+
${opencodeModelsBlock(' ')}
|
|
715
|
+
}
|
|
716
|
+
}`;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
async function setupOpencode() {
|
|
720
|
+
if (process.env.BRIDGE_SKIP_OPENCODE === '1' && !process.argv.includes('--setup-opencode')) {
|
|
721
|
+
log('opencode: configuracao automatica pulada a pedido do usuario.');
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
let file = opencodeConfigCandidates().find((f) => fs.existsSync(f)) || null;
|
|
725
|
+
const hasBinary = await hasOpencodeBinary();
|
|
726
|
+
const cfgDirExists = fs.existsSync(path.join(HOME, '.config', 'opencode'));
|
|
727
|
+
if (!file && !hasBinary && !cfgDirExists) {
|
|
728
|
+
log('opencode nao encontrado; pulando registro do modelo e plugin.');
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
if (!file) {
|
|
732
|
+
file = opencodeConfigCandidates()[0];
|
|
733
|
+
const cfgDir = path.dirname(file);
|
|
734
|
+
fs.mkdirSync(cfgDir, { recursive: true });
|
|
735
|
+
const pluginDir = installOpencodePlugin(cfgDir);
|
|
736
|
+
const pluginsLine = pluginDir ? `\n "plugins": [${JSON.stringify(pluginDir)}],` : '';
|
|
737
|
+
const baseURL = `http://${CFG.host}:${CFG.port}/v1`;
|
|
738
|
+
fs.writeFileSync(file, `{
|
|
739
|
+
"$schema": "https://opencode.ai/config.json",${pluginsLine}
|
|
740
|
+
"providers": {
|
|
741
|
+
"kimibridge": {
|
|
742
|
+
"name": "Kimi Bridge (local)",
|
|
743
|
+
"package": "@opencode/ai/providers/openai-compatible",
|
|
744
|
+
"settings": { "baseURL": "${baseURL}", "apiKey": "local" },
|
|
745
|
+
"models": {
|
|
746
|
+
${opencodeModelsBlock(' ')}
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
`);
|
|
752
|
+
log('opencode: configuracao criada em', file);
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
try {
|
|
756
|
+
const cfgDir = path.dirname(file);
|
|
757
|
+
const pluginDir = installOpencodePlugin(cfgDir);
|
|
758
|
+
let text = fs.readFileSync(file, 'utf8');
|
|
759
|
+
let changed = false;
|
|
760
|
+
if (pluginDir) {
|
|
761
|
+
const pRes = ensurePluginInConfig(text, pluginDir);
|
|
762
|
+
if (pRes.changed) {
|
|
763
|
+
text = pRes.text;
|
|
764
|
+
changed = true;
|
|
765
|
+
log('opencode: plugin system-prompt registrado em', file);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
const baseURL = `http://${CFG.host}:${CFG.port}/v1`;
|
|
769
|
+
if (text.includes('"kimibridge"')) {
|
|
770
|
+
const re = /("kimibridge"[\s\S]{0,1600}?"baseURL"\s*:\s*")[^"]*(")/;
|
|
771
|
+
const nextUrl = text.replace(re, `$1${baseURL}$2`);
|
|
772
|
+
if (nextUrl !== text) { text = nextUrl; changed = true; }
|
|
773
|
+
const sync = syncModelsInBlock(text);
|
|
774
|
+
text = sync.text;
|
|
775
|
+
if (sync.changed) changed = true;
|
|
776
|
+
if (changed) {
|
|
777
|
+
fs.writeFileSync(file, text);
|
|
778
|
+
log(`opencode: bloco kimibridge sincronizado (${MODELS.map((m) => m.id).join(', ')})`);
|
|
779
|
+
} else {
|
|
780
|
+
log(`opencode: modelos ja sincronizados (${MODELS.map((m) => m.id).join(', ')})`);
|
|
781
|
+
}
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
const provRe = /"providers"\s*:\s*\{/;
|
|
785
|
+
const pm = provRe.exec(text);
|
|
786
|
+
if (pm) {
|
|
787
|
+
const open = text.indexOf('{', pm.index);
|
|
788
|
+
const close = objectEnd(text, open);
|
|
789
|
+
const inside = open >= 0 && close > open ? text.slice(open + 1, close) : '';
|
|
790
|
+
if (open >= 0 && close > open && !inside.trim()) {
|
|
791
|
+
text = text.slice(0, open + 1) + '\n' + providerBlock() + '\n ' + text.slice(close);
|
|
792
|
+
} else {
|
|
793
|
+
text = text.replace(provRe, (m) => m + '\n' + providerBlock() + ',');
|
|
794
|
+
}
|
|
795
|
+
} else {
|
|
796
|
+
const idx = text.lastIndexOf('}');
|
|
797
|
+
const head = text.slice(0, idx).replace(/\s*$/, '');
|
|
798
|
+
const tail = head.endsWith(',') ? '' : ',';
|
|
799
|
+
text = head + tail + `\n "providers": {\n${providerBlock()}\n }\n` + text.slice(idx);
|
|
800
|
+
}
|
|
801
|
+
fs.writeFileSync(file, text);
|
|
802
|
+
log('opencode: modelo registrado em', file);
|
|
803
|
+
} catch (e) {
|
|
804
|
+
log('opencode: nao consegui registrar o modelo:', e.message);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// ---------- autostart ----------
|
|
809
|
+
function startupDir() {
|
|
810
|
+
return path.join(process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
async function installAutostart() {
|
|
814
|
+
const marker = path.join(APP_DIR, '.autostart-ok');
|
|
815
|
+
if (fs.existsSync(marker)) return;
|
|
816
|
+
const script = path.join(APP_DIR, 'bridge.mjs');
|
|
817
|
+
const winNode = path.join(APP_DIR, 'node', 'node.exe');
|
|
818
|
+
const nodePath = IS_WIN && fs.existsSync(winNode) ? winNode : process.execPath;
|
|
819
|
+
try {
|
|
820
|
+
if (IS_WIN) {
|
|
821
|
+
const dir = startupDir();
|
|
822
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
823
|
+
const vbs = path.join(dir, 'KimiBridge.vbs');
|
|
824
|
+
if (!fs.existsSync(vbs)) {
|
|
825
|
+
const bootBat = path.join(APP_DIR, 'iniciar_oculto.bat');
|
|
826
|
+
fs.writeFileSync(bootBat, `@echo off\r\ncd /d "${APP_DIR}"\r\n"${nodePath}" "${script}" >> "${path.join(LOG_DIR, 'boot.log')}" 2>&1\r\n`);
|
|
827
|
+
fs.writeFileSync(vbs, `Set sh = CreateObject("WScript.Shell")\r\nsh.Run """${bootBat}""", 0, False\r\n`);
|
|
828
|
+
log('autostart: Windows (atalho oculto na inicializacao)');
|
|
829
|
+
}
|
|
830
|
+
} else {
|
|
831
|
+
let done = false;
|
|
832
|
+
if (!IS_TERMUX) {
|
|
833
|
+
try {
|
|
834
|
+
const r = await run('systemctl', ['--user', 'is-system-running']);
|
|
835
|
+
if (/running|degraded/.test(r.stdout)) {
|
|
836
|
+
const svcDir = path.join(HOME, '.config', 'systemd', 'user');
|
|
837
|
+
fs.mkdirSync(svcDir, { recursive: true });
|
|
838
|
+
const unit = path.join(svcDir, 'kimi-bridge.service');
|
|
839
|
+
if (!fs.existsSync(unit)) {
|
|
840
|
+
fs.writeFileSync(unit, `[Unit]
|
|
841
|
+
Description=Kimi Bridge
|
|
842
|
+
After=network-online.target
|
|
843
|
+
|
|
844
|
+
[Service]
|
|
845
|
+
Type=simple
|
|
846
|
+
WorkingDirectory=${APP_DIR}
|
|
847
|
+
ExecStart=${nodePath} ${script}
|
|
848
|
+
Restart=on-failure
|
|
849
|
+
RestartSec=10
|
|
850
|
+
|
|
851
|
+
[Install]
|
|
852
|
+
WantedBy=default.target
|
|
853
|
+
`);
|
|
854
|
+
await run('systemctl', ['--user', 'daemon-reload']);
|
|
855
|
+
await run('systemctl', ['--user', 'enable', 'kimi-bridge.service']);
|
|
856
|
+
log('autostart: servico systemd de usuario');
|
|
857
|
+
}
|
|
858
|
+
done = true;
|
|
859
|
+
}
|
|
860
|
+
} catch {}
|
|
861
|
+
}
|
|
862
|
+
if (!done && !IS_TERMUX && (await commandExists('crontab'))) {
|
|
863
|
+
const current = (await run('crontab', ['-l'])).stdout || '';
|
|
864
|
+
if (!current.includes(APP_DIR)) {
|
|
865
|
+
const line = `@reboot cd ${APP_DIR} && ${nodePath} ${script} >> ${path.join(LOG_DIR, 'boot.log')} 2>&1`;
|
|
866
|
+
await run('sh', ['-c', `(crontab -l 2>/dev/null; echo "${line}") | crontab -`]);
|
|
867
|
+
log('autostart: cron @reboot');
|
|
868
|
+
}
|
|
869
|
+
done = true;
|
|
870
|
+
}
|
|
871
|
+
if (!done) {
|
|
872
|
+
const prof = path.join(HOME, '.profile');
|
|
873
|
+
const txt = fs.existsSync(prof) ? fs.readFileSync(prof, 'utf8') : '';
|
|
874
|
+
if (!txt.includes('# kimi-bridge autostart')) {
|
|
875
|
+
const sh = path.join(APP_DIR, 'iniciar.sh');
|
|
876
|
+
const agFile = path.join(APP_DIR, 'antigravity.json');
|
|
877
|
+
const bootLog = path.join(LOG_DIR, 'boot.log');
|
|
878
|
+
fs.appendFileSync(
|
|
879
|
+
prof,
|
|
880
|
+
`\n# kimi-bridge autostart\nif ! curl -sf http://${CFG.host}:${CFG.port}/healthz >/dev/null 2>&1; then\n if [ -t 0 ] && [ ! -s "${agFile}" ]; then\n bash "${sh}"\n else\n nohup bash "${sh}" --background >> "${bootLog}" 2>&1 &\n fi\nfi\n`
|
|
881
|
+
);
|
|
882
|
+
log('autostart: login do shell (~/.profile)');
|
|
883
|
+
}
|
|
884
|
+
done = true;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
} catch (e) {
|
|
888
|
+
log('autostart nao instalado:', e.message);
|
|
889
|
+
}
|
|
890
|
+
try { fs.writeFileSync(marker, new Date().toISOString()); } catch {}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// ---------- estado do browser/captcha (pool paralelo + auto-hibernacao) ----------
|
|
894
|
+
// Em vez de 1 aba/profile compartilhado (que quebrava com SingletonLock e
|
|
895
|
+
// Execution context was destroyed quando varios subagentes chegavam juntos):
|
|
896
|
+
// - 1 processo leve (prefere chromium_headless_shell) com flags enxutas;
|
|
897
|
+
// - N contextos isolados (cada um com cookie jar/storage proprios);
|
|
898
|
+
// - M widgets paralelos por contexto, sobre HTML minimo interceptado na
|
|
899
|
+
// origem build.nvidia.com (sem carregar Next.js/React/imagens/fontes);
|
|
900
|
+
// - buffer de tokens frescos + fila com respeito a AbortSignal;
|
|
901
|
+
// - fecha o browser automaticamente apos browserIdleCloseMs sem uso NVIDIA
|
|
902
|
+
// (0 MB de RAM quando voce so esta usando Antigravity ou parado).
|
|
903
|
+
const CAPTCHA_WORKERS = Math.max(1, Math.min(8, Number(CFG.captchaWorkers) || 2));
|
|
904
|
+
const CAPTCHA_WIDGETS_PER_WORKER = Math.max(1, Math.min(4, Number(CFG.captchaWidgetsPerWorker) || 2));
|
|
905
|
+
const CAPTCHA_POOL_TARGET = Math.max(1, Math.min(12, Number(CFG.captchaPoolSize) || 4));
|
|
906
|
+
const CAPTCHA_TOKEN_TTL_MS = 65000;
|
|
907
|
+
const CAPTCHA_ROTATE_AFTER = 8; // gira o BrowserContext (cookies novos + libera RAM dos iframes) a cada 8 mints
|
|
908
|
+
const BROWSER_IDLE_CLOSE_MS = Math.max(30000, Number(CFG.browserIdleCloseMs) || 120000);
|
|
909
|
+
|
|
910
|
+
const state = {
|
|
911
|
+
browserObj: null,
|
|
912
|
+
workers: [], // { idx, ctx, page, active, uses, readyPromise, rotating, dead }
|
|
913
|
+
pool: [], // { token, at }
|
|
914
|
+
waiters: [], // { resolve, reject, forceFresh, signal, cleanup }
|
|
915
|
+
ready: false,
|
|
916
|
+
tokens: 0,
|
|
917
|
+
lastError: null,
|
|
918
|
+
browser: null,
|
|
919
|
+
launchPromise: null,
|
|
920
|
+
lastSse: null,
|
|
921
|
+
lastActivityAt: 0,
|
|
922
|
+
idleTimer: null,
|
|
923
|
+
refilling: 0,
|
|
924
|
+
};
|
|
925
|
+
|
|
926
|
+
function touchBrowserActivity() {
|
|
927
|
+
state.lastActivityAt = Date.now();
|
|
928
|
+
scheduleBrowserIdleCheck();
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
function scheduleBrowserIdleCheck() {
|
|
932
|
+
if (state.idleTimer) clearTimeout(state.idleTimer);
|
|
933
|
+
if (!state.browserObj) return;
|
|
934
|
+
state.idleTimer = setTimeout(async () => {
|
|
935
|
+
state.idleTimer = null;
|
|
936
|
+
if (!state.browserObj) return;
|
|
937
|
+
const busy = state.waiters.length > 0 || state.workers.some((w) => w.active > 0 || w.rotating);
|
|
938
|
+
if (busy || Date.now() - state.lastActivityAt < BROWSER_IDLE_CLOSE_MS - 1000) {
|
|
939
|
+
scheduleBrowserIdleCheck();
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
log(`browser ocioso ha ${Math.round((Date.now() - state.lastActivityAt) / 1000)}s; fechando para liberar RAM`);
|
|
943
|
+
await closeBrowser('ocioso');
|
|
944
|
+
}, BROWSER_IDLE_CLOSE_MS);
|
|
945
|
+
if (state.idleTimer.unref) state.idleTimer.unref();
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
function lightChromiumArgs(isShell) {
|
|
949
|
+
const args = [
|
|
950
|
+
'--no-sandbox',
|
|
951
|
+
'--disable-gpu',
|
|
952
|
+
'--disable-software-rasterizer',
|
|
953
|
+
'--disable-dev-shm-usage',
|
|
954
|
+
'--disable-extensions',
|
|
955
|
+
'--disable-sync',
|
|
956
|
+
'--disable-background-networking',
|
|
957
|
+
'--disable-component-update',
|
|
958
|
+
'--disable-default-apps',
|
|
959
|
+
'--disable-site-isolation-trials',
|
|
960
|
+
'--disable-features=Translate,MediaRouter,AudioServiceOutOfProcess,BackForwardCache,OptimizationHints,SitePerProcess,IsolateOrigins',
|
|
961
|
+
'--mute-audio',
|
|
962
|
+
'--no-first-run',
|
|
963
|
+
'--no-default-browser-check',
|
|
964
|
+
'--disable-blink-features=AutomationControlled',
|
|
965
|
+
'--renderer-process-limit=1',
|
|
966
|
+
'--js-flags=--max-old-space-size=128',
|
|
967
|
+
'--lang=en-US',
|
|
968
|
+
];
|
|
969
|
+
if (IS_WIN && !isShell && !CFG.headless) {
|
|
970
|
+
args.push('--window-position=-32000,-32000', '--window-size=480,360');
|
|
971
|
+
}
|
|
972
|
+
return args;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
async function setupLightCaptchaPage(page) {
|
|
976
|
+
const target = CFG.pageUrl;
|
|
977
|
+
await page.route('**/*', (route) => {
|
|
978
|
+
const reqUrl = route.request().url();
|
|
979
|
+
if (reqUrl === target || reqUrl === target + '/') {
|
|
980
|
+
return route.fulfill({
|
|
981
|
+
status: 200,
|
|
982
|
+
contentType: 'text/html; charset=utf-8',
|
|
983
|
+
body: '<!doctype html><html><head><script src="https://js.hcaptcha.com/1/api.js?render=explicit" async defer></script></head><body></body></html>',
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
const rt = route.request().resourceType();
|
|
987
|
+
if (rt === 'image' || rt === 'font' || rt === 'media' || rt === 'stylesheet') {
|
|
988
|
+
return route.abort();
|
|
989
|
+
}
|
|
990
|
+
return route.continue();
|
|
991
|
+
});
|
|
992
|
+
await page.goto(target, { waitUntil: 'domcontentloaded', timeout: 45000 });
|
|
993
|
+
await page.waitForFunction(() => !!window.hcaptcha, null, { timeout: 45000 });
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
async function createWorker(idx) {
|
|
997
|
+
const browser = state.browserObj;
|
|
998
|
+
if (!browser) throw new Error('browser fechado');
|
|
999
|
+
const ctx = await browser.newContext({
|
|
1000
|
+
viewport: { width: 420, height: 320 },
|
|
1001
|
+
locale: CFG.locale,
|
|
1002
|
+
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36',
|
|
1003
|
+
});
|
|
1004
|
+
try {
|
|
1005
|
+
const page = await ctx.newPage();
|
|
1006
|
+
await setupLightCaptchaPage(page);
|
|
1007
|
+
return { idx, ctx, page, active: 0, uses: 0, rotating: false, dead: false };
|
|
1008
|
+
} catch (e) {
|
|
1009
|
+
try { await ctx.close(); } catch {}
|
|
1010
|
+
throw e;
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
async function rotateWorker(w, reason = '') {
|
|
1015
|
+
if (!w || w.rotating) return;
|
|
1016
|
+
w.rotating = true;
|
|
1017
|
+
w.dead = true;
|
|
1018
|
+
const oldCtx = w.ctx;
|
|
1019
|
+
w.ctx = null;
|
|
1020
|
+
w.page = null;
|
|
1021
|
+
try { if (oldCtx) await oldCtx.close(); } catch {}
|
|
1022
|
+
if (!state.browserObj) {
|
|
1023
|
+
w.rotating = false;
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
try {
|
|
1027
|
+
const fresh = await createWorker(w.idx);
|
|
1028
|
+
w.ctx = fresh.ctx;
|
|
1029
|
+
w.page = fresh.page;
|
|
1030
|
+
w.uses = 0;
|
|
1031
|
+
w.dead = false;
|
|
1032
|
+
state.ready = true;
|
|
1033
|
+
state.lastError = null;
|
|
1034
|
+
if (reason) log(`captcha worker#${w.idx} reciclado (${reason})`);
|
|
1035
|
+
} catch (e) {
|
|
1036
|
+
state.lastError = e.message;
|
|
1037
|
+
log(`captcha worker#${w.idx} falhou ao reciclar:`, e.message.split('\n')[0]);
|
|
1038
|
+
} finally {
|
|
1039
|
+
w.rotating = false;
|
|
1040
|
+
pumpCaptchaWorkers();
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
async function closeBrowser(reason = '') {
|
|
1045
|
+
if (state.idleTimer) { clearTimeout(state.idleTimer); state.idleTimer = null; }
|
|
1046
|
+
const b = state.browserObj;
|
|
1047
|
+
const ws = state.workers.slice();
|
|
1048
|
+
state.browserObj = null;
|
|
1049
|
+
state.workers = [];
|
|
1050
|
+
state.pool = [];
|
|
1051
|
+
state.ready = false;
|
|
1052
|
+
for (const w of ws) {
|
|
1053
|
+
w.dead = true;
|
|
1054
|
+
try { if (w.ctx) await w.ctx.close(); } catch {}
|
|
1055
|
+
}
|
|
1056
|
+
if (b) {
|
|
1057
|
+
try { await b.close(); } catch {}
|
|
1058
|
+
log('browser fechado' + (reason ? ` (${reason})` : ''));
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
async function launchBrowserOnce(browserPath, headless) {
|
|
1063
|
+
const isShell = isHeadlessShellPath(browserPath);
|
|
1064
|
+
const useHeadless = isShell ? true : !!headless;
|
|
1065
|
+
if (!useHeadless) await ensureDisplay();
|
|
1066
|
+
log('abrindo browser leve:', browserPath, `headless=${useHeadless} workers=${CAPTCHA_WORKERS}x${CAPTCHA_WIDGETS_PER_WORKER}`);
|
|
1067
|
+
const browser = await chromium.launch({
|
|
1068
|
+
executablePath: browserPath,
|
|
1069
|
+
headless: useHeadless,
|
|
1070
|
+
args: lightChromiumArgs(isShell),
|
|
1071
|
+
});
|
|
1072
|
+
state.browserObj = browser;
|
|
1073
|
+
browser.on('disconnected', () => {
|
|
1074
|
+
if (state.browserObj === browser) {
|
|
1075
|
+
state.browserObj = null;
|
|
1076
|
+
state.workers = [];
|
|
1077
|
+
state.pool = [];
|
|
1078
|
+
state.ready = false;
|
|
1079
|
+
log('browser desconectou');
|
|
1080
|
+
}
|
|
1081
|
+
});
|
|
1082
|
+
const created = await Promise.all(
|
|
1083
|
+
Array.from({ length: CAPTCHA_WORKERS }, (_, i) => createWorker(i + 1))
|
|
1084
|
+
);
|
|
1085
|
+
state.workers = created;
|
|
1086
|
+
state.ready = true;
|
|
1087
|
+
state.lastError = null;
|
|
1088
|
+
touchBrowserActivity();
|
|
1089
|
+
log(`captcha pool pronto (${created.length} contextos isolados)`);
|
|
1090
|
+
return browser;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
async function launchBrowser() {
|
|
1094
|
+
if (state.browserObj && state.workers.some((w) => !w.dead && w.page)) {
|
|
1095
|
+
touchBrowserActivity();
|
|
1096
|
+
return state.browserObj;
|
|
1097
|
+
}
|
|
1098
|
+
if (state.launchPromise) return state.launchPromise;
|
|
1099
|
+
state.launchPromise = (async () => {
|
|
1100
|
+
try {
|
|
1101
|
+
const browserPath = await ensureBrowser();
|
|
1102
|
+
state.browser = browserPath;
|
|
1103
|
+
try {
|
|
1104
|
+
// Prefere headless (headless_shell sempre e headless; chrome normal
|
|
1105
|
+
// com pagina leve tambem roda bem em headless sem precisar de Xvfb).
|
|
1106
|
+
await launchBrowserOnce(browserPath, true);
|
|
1107
|
+
} catch (e) {
|
|
1108
|
+
log('launch headless falhou:', e.message.split('\n')[0], '-> tentando com display');
|
|
1109
|
+
await closeBrowser('fallback');
|
|
1110
|
+
await launchBrowserOnce(browserPath, false);
|
|
1111
|
+
}
|
|
1112
|
+
return state.browserObj;
|
|
1113
|
+
} catch (e2) {
|
|
1114
|
+
state.lastError = e2.message;
|
|
1115
|
+
await closeBrowser('erro');
|
|
1116
|
+
throw e2;
|
|
1117
|
+
} finally {
|
|
1118
|
+
state.launchPromise = null;
|
|
1119
|
+
}
|
|
1120
|
+
})();
|
|
1121
|
+
return state.launchPromise;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
// Compatibilidade com POST /admin/reload: recicla todos os contextos (cookies novos).
|
|
1125
|
+
async function openPage() {
|
|
1126
|
+
if (!state.browserObj) {
|
|
1127
|
+
await launchBrowser();
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
state.pool = [];
|
|
1131
|
+
await Promise.all(state.workers.map((w) => rotateWorker(w, 'reload manual')));
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
async function mintOnWorker(w, slotIdx) {
|
|
1135
|
+
if (!w || w.dead || !w.page) throw new Error('worker indisponivel');
|
|
1136
|
+
const token = await w.page.evaluate(async ({ sitekey, slotIdx }) => {
|
|
1137
|
+
const h = window.hcaptcha;
|
|
1138
|
+
if (!h) throw new Error('hcaptcha ausente');
|
|
1139
|
+
const box = document.createElement('div');
|
|
1140
|
+
box.style.cssText = `position:fixed;left:${slotIdx * 8}px;top:0;width:300px;height:80px;z-index:2147483000`;
|
|
1141
|
+
document.body.appendChild(box);
|
|
1142
|
+
let wid = null;
|
|
1143
|
+
try {
|
|
1144
|
+
return await new Promise((resolve, reject) => {
|
|
1145
|
+
const to = setTimeout(() => reject(new Error('timeout captcha')), 40000);
|
|
1146
|
+
wid = h.render(box, {
|
|
1147
|
+
sitekey,
|
|
1148
|
+
size: 'invisible',
|
|
1149
|
+
theme: 'dark',
|
|
1150
|
+
callback: (t) => { clearTimeout(to); resolve(t); },
|
|
1151
|
+
'error-callback': (e) => { clearTimeout(to); reject(new Error('captcha error: ' + e)); },
|
|
1152
|
+
});
|
|
1153
|
+
h.execute(wid);
|
|
1154
|
+
});
|
|
1155
|
+
} finally {
|
|
1156
|
+
try { if (wid !== null && typeof h.remove === 'function') h.remove(wid); } catch {}
|
|
1157
|
+
box.remove();
|
|
1158
|
+
}
|
|
1159
|
+
}, { sitekey: CFG.sitekey, slotIdx });
|
|
1160
|
+
state.tokens++;
|
|
1161
|
+
w.uses++;
|
|
1162
|
+
log(`token #${state.tokens} (w#${w.idx}) len ${token.length}`);
|
|
1163
|
+
return token;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
function pruneExpiredTokens() {
|
|
1167
|
+
const now = Date.now();
|
|
1168
|
+
while (state.pool.length && now - state.pool[0].at >= CAPTCHA_TOKEN_TTL_MS) {
|
|
1169
|
+
state.pool.shift();
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
function takeFreshFromPool() {
|
|
1174
|
+
pruneExpiredTokens();
|
|
1175
|
+
const item = state.pool.shift();
|
|
1176
|
+
return item ? item.token : null;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
function deliverToken(token) {
|
|
1180
|
+
// Prioriza quem esta esperando; so guarda no buffer se nao houver waiter.
|
|
1181
|
+
while (state.waiters.length) {
|
|
1182
|
+
const w = state.waiters.shift();
|
|
1183
|
+
w.cleanup();
|
|
1184
|
+
if (w.signal?.aborted) continue;
|
|
1185
|
+
w.resolve(token);
|
|
1186
|
+
return true;
|
|
1187
|
+
}
|
|
1188
|
+
pruneExpiredTokens();
|
|
1189
|
+
if (state.pool.length < CAPTCHA_POOL_TARGET) {
|
|
1190
|
+
state.pool.push({ token, at: Date.now() });
|
|
1191
|
+
}
|
|
1192
|
+
return false;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
function pickAvailableWorker() {
|
|
1196
|
+
let best = null;
|
|
1197
|
+
for (const w of state.workers) {
|
|
1198
|
+
if (w.dead || w.rotating || !w.page) continue;
|
|
1199
|
+
if (w.active >= CAPTCHA_WIDGETS_PER_WORKER) continue;
|
|
1200
|
+
if (!best || w.active < best.active) best = w;
|
|
1201
|
+
}
|
|
1202
|
+
return best;
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
function pumpCaptchaWorkers() {
|
|
1206
|
+
if (!state.browserObj) return;
|
|
1207
|
+
pruneExpiredTokens();
|
|
1208
|
+
|
|
1209
|
+
// Entrega tokens do buffer para waiters que aceitam buffer.
|
|
1210
|
+
for (let i = 0; i < state.waiters.length; ) {
|
|
1211
|
+
const w = state.waiters[i];
|
|
1212
|
+
if (w.signal?.aborted) {
|
|
1213
|
+
w.cleanup();
|
|
1214
|
+
state.waiters.splice(i, 1);
|
|
1215
|
+
continue;
|
|
1216
|
+
}
|
|
1217
|
+
if (!w.forceFresh && state.pool.length) {
|
|
1218
|
+
const tok = takeFreshFromPool();
|
|
1219
|
+
if (tok) {
|
|
1220
|
+
w.cleanup();
|
|
1221
|
+
state.waiters.splice(i, 1);
|
|
1222
|
+
w.resolve(tok);
|
|
1223
|
+
continue;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
i++;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
// Quantos mints em andamento precisamos?
|
|
1230
|
+
// Demanda = waiters pendentes + reposicao do buffer (somente se houve atividade recente).
|
|
1231
|
+
const activeMints = state.workers.reduce((s, w) => s + w.active, 0);
|
|
1232
|
+
const wantBuffer = state.lastActivityAt && (Date.now() - state.lastActivityAt < BROWSER_IDLE_CLOSE_MS)
|
|
1233
|
+
? Math.max(0, CAPTCHA_POOL_TARGET - state.pool.length)
|
|
1234
|
+
: 0;
|
|
1235
|
+
const need = state.waiters.length + wantBuffer;
|
|
1236
|
+
let toStart = need - activeMints;
|
|
1237
|
+
|
|
1238
|
+
while (toStart > 0) {
|
|
1239
|
+
const worker = pickAvailableWorker();
|
|
1240
|
+
if (!worker) break;
|
|
1241
|
+
toStart--;
|
|
1242
|
+
const slotIdx = worker.active++;
|
|
1243
|
+
(async () => {
|
|
1244
|
+
try {
|
|
1245
|
+
const token = await mintOnWorker(worker, slotIdx);
|
|
1246
|
+
touchBrowserActivity();
|
|
1247
|
+
deliverToken(token);
|
|
1248
|
+
} catch (err) {
|
|
1249
|
+
state.lastError = err.message;
|
|
1250
|
+
const msg = String(err.message || '').split('\n')[0];
|
|
1251
|
+
log(`mint w#${worker.idx} falhou:`, msg);
|
|
1252
|
+
// Se foi erro de pagina/challenge/rate-limit, marca para reciclar
|
|
1253
|
+
// com contexto/cookies novos assim que os slots desse worker zerarem.
|
|
1254
|
+
if (/challenge|rate-limit|timeout|closed|crashed|destroyed|ausente/i.test(msg)) {
|
|
1255
|
+
worker.dead = true;
|
|
1256
|
+
}
|
|
1257
|
+
} finally {
|
|
1258
|
+
worker.active = Math.max(0, worker.active - 1);
|
|
1259
|
+
if (worker.active === 0 && (worker.dead || worker.uses >= CAPTCHA_ROTATE_AFTER)) {
|
|
1260
|
+
const reason = worker.dead ? 'recuperacao' : `rotacao ${worker.uses} usos`;
|
|
1261
|
+
rotateWorker(worker, reason);
|
|
1262
|
+
} else {
|
|
1263
|
+
// Se o browser inteiro morreu e ainda ha waiters, relanca.
|
|
1264
|
+
if (!state.browserObj && state.waiters.length) {
|
|
1265
|
+
launchBrowser().then(() => pumpCaptchaWorkers()).catch(() => {});
|
|
1266
|
+
} else {
|
|
1267
|
+
pumpCaptchaWorkers();
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
})();
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
function prefetch() {
|
|
1276
|
+
// Nao sobe o browser so no boot se ninguem pediu NVIDIA ainda — economiza
|
|
1277
|
+
// 100% da RAM enquanto o usuario esta so no Antigravity. Se o browser ja
|
|
1278
|
+
// estiver aberto, apenas reabastece o buffer.
|
|
1279
|
+
if (state.browserObj) {
|
|
1280
|
+
touchBrowserActivity();
|
|
1281
|
+
pumpCaptchaWorkers();
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
async function getToken(forceFresh = false, signal = null) {
|
|
1286
|
+
if (signal?.aborted) throw new Error('cliente desconectou');
|
|
1287
|
+
touchBrowserActivity();
|
|
1288
|
+
if (!forceFresh) {
|
|
1289
|
+
const cached = takeFreshFromPool();
|
|
1290
|
+
if (cached) {
|
|
1291
|
+
pumpCaptchaWorkers();
|
|
1292
|
+
return cached;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
await launchBrowser();
|
|
1296
|
+
if (signal?.aborted) throw new Error('cliente desconectou');
|
|
1297
|
+
|
|
1298
|
+
// Re-checa buffer apos o launch caso outro mint ja tenha entregue.
|
|
1299
|
+
if (!forceFresh) {
|
|
1300
|
+
const cached = takeFreshFromPool();
|
|
1301
|
+
if (cached) {
|
|
1302
|
+
pumpCaptchaWorkers();
|
|
1303
|
+
return cached;
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
return await new Promise((resolve, reject) => {
|
|
1308
|
+
const timer = setTimeout(() => {
|
|
1309
|
+
cleanup();
|
|
1310
|
+
const idx = state.waiters.indexOf(entry);
|
|
1311
|
+
if (idx >= 0) state.waiters.splice(idx, 1);
|
|
1312
|
+
reject(new Error('sem token do captcha em 90s: ' + (state.lastError || 'fila ocupada')));
|
|
1313
|
+
}, 90000);
|
|
1314
|
+
const onAbort = () => {
|
|
1315
|
+
cleanup();
|
|
1316
|
+
const idx = state.waiters.indexOf(entry);
|
|
1317
|
+
if (idx >= 0) state.waiters.splice(idx, 1);
|
|
1318
|
+
reject(new Error('cliente desconectou'));
|
|
1319
|
+
};
|
|
1320
|
+
const cleanup = () => {
|
|
1321
|
+
clearTimeout(timer);
|
|
1322
|
+
signal?.removeEventListener('abort', onAbort);
|
|
1323
|
+
};
|
|
1324
|
+
const entry = { resolve, reject, forceFresh: !!forceFresh, signal, cleanup };
|
|
1325
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1326
|
+
state.waiters.push(entry);
|
|
1327
|
+
pumpCaptchaWorkers();
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
// ---------- payload ----------
|
|
1332
|
+
const REASONING_LEVELS = new Set(['low', 'medium', 'high', 'max']);
|
|
1333
|
+
|
|
1334
|
+
// Estimativa conservadora: o tokenizer real do Kimi nao esta disponivel
|
|
1335
|
+
// aqui, entao 3.2 caracteres por token faz o corte acontecer antes do
|
|
1336
|
+
// limite real, nunca depois.
|
|
1337
|
+
function estimateTokens(messages, tools) {
|
|
1338
|
+
let chars = 0;
|
|
1339
|
+
for (const m of messages) {
|
|
1340
|
+
if (!m) continue;
|
|
1341
|
+
chars += 8;
|
|
1342
|
+
if (typeof m.content === 'string') chars += m.content.length;
|
|
1343
|
+
else if (Array.isArray(m.content)) {
|
|
1344
|
+
for (const p of m.content) if (p && typeof p.text === 'string') chars += p.text.length;
|
|
1345
|
+
}
|
|
1346
|
+
if (m.tool_calls) chars += JSON.stringify(m.tool_calls).length;
|
|
1347
|
+
if (m.name) chars += m.name.length;
|
|
1348
|
+
}
|
|
1349
|
+
if (Array.isArray(tools)) chars += JSON.stringify(tools).length;
|
|
1350
|
+
return Math.ceil(chars / 3.2);
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
// Corta turnos inteiros, do mais antigo para o mais novo, preservando as
|
|
1354
|
+
// mensagens de sistema e o turno atual. Cortar mensagem solta quebraria o
|
|
1355
|
+
// par assistant/tool_calls + tool.
|
|
1356
|
+
function trimToContext(messages, budget, tools) {
|
|
1357
|
+
const before = estimateTokens(messages, tools);
|
|
1358
|
+
if (before <= budget) return { messages, before, after: before, dropped: 0 };
|
|
1359
|
+
const system = [];
|
|
1360
|
+
let i = 0;
|
|
1361
|
+
while (i < messages.length && messages[i] && (messages[i].role === 'system' || messages[i].role === 'developer')) {
|
|
1362
|
+
system.push(messages[i]);
|
|
1363
|
+
i++;
|
|
1364
|
+
}
|
|
1365
|
+
const turns = [];
|
|
1366
|
+
for (; i < messages.length; i++) {
|
|
1367
|
+
const m = messages[i];
|
|
1368
|
+
if (m && m.role === 'user') turns.push([m]);
|
|
1369
|
+
else if (turns.length) turns[turns.length - 1].push(m);
|
|
1370
|
+
else turns.push([m]);
|
|
1371
|
+
}
|
|
1372
|
+
let dropped = 0;
|
|
1373
|
+
while (turns.length > 1 && estimateTokens(system.concat(turns.flat()), tools) > budget) {
|
|
1374
|
+
dropped += turns.shift().length;
|
|
1375
|
+
}
|
|
1376
|
+
const rest = system.concat(turns.flat());
|
|
1377
|
+
return { messages: rest, before, after: estimateTokens(rest, tools), dropped };
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
const SUMMARY_RE = /\b(summar(?:y|ize|ise|ization)|resumo|resuma|resumir|context compaction|compact the (?:conversation|context)|conversation so far)\b/i;
|
|
1381
|
+
|
|
1382
|
+
function textoDeMensagem(m) {
|
|
1383
|
+
if (!m) return '';
|
|
1384
|
+
if (typeof m.content === 'string') return m.content;
|
|
1385
|
+
if (Array.isArray(m.content)) return m.content.map((p) => (p && typeof p.text === 'string' ? p.text : '')).join('\n');
|
|
1386
|
+
return '';
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
// Pedido de resumo/compactacao nao e resposta de persona: nao comeca com
|
|
1390
|
+
// o marcador e nao pode ser tratado como raciocinio pelo gate.
|
|
1391
|
+
function isSummaryRequest(messages) {
|
|
1392
|
+
if (!Array.isArray(messages)) return false;
|
|
1393
|
+
return messages.some((m) => m && (m.role === 'user' || m.role === 'system' || m.role === 'developer') && SUMMARY_RE.test(textoDeMensagem(m)));
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
function toUpstream(body, model = MODELS[0]) {
|
|
1397
|
+
const reasoning = REASONING_LEVELS.has(body.reasoning_effort) ? body.reasoning_effort : CFG.reasoning;
|
|
1398
|
+
let maxTokens = Math.min(Math.max(Number(body.max_tokens ?? body.max_completion_tokens) || CFG.maxTokens, 1), 65536);
|
|
1399
|
+
|
|
1400
|
+
const tools = Array.isArray(body.tools) && body.tools.length && body.tool_choice !== 'none' ? body.tools : null;
|
|
1401
|
+
const msgs = Array.isArray(body.messages) ? body.messages : [];
|
|
1402
|
+
const compact = isSummaryRequest(msgs);
|
|
1403
|
+
// Resumo de compactacao usa o limite cheio do modelo, mesmo que o
|
|
1404
|
+
// cliente peca menos: o resumo precisa caber no orcamento.
|
|
1405
|
+
if (compact) maxTokens = 65536;
|
|
1406
|
+
const context = Number(CFG.contextTokens) || 400000;
|
|
1407
|
+
const budget = Math.max(4096, context - maxTokens);
|
|
1408
|
+
const trim = trimToContext(msgs, budget, tools);
|
|
1409
|
+
|
|
1410
|
+
const out = {
|
|
1411
|
+
model: model.apiModel,
|
|
1412
|
+
messages: trim.messages,
|
|
1413
|
+
stream: body.stream !== false,
|
|
1414
|
+
seed: Number.isFinite(body.seed) ? body.seed : 0,
|
|
1415
|
+
max_tokens: maxTokens,
|
|
1416
|
+
};
|
|
1417
|
+
if (out.stream) out.stream_options = { include_usage: true };
|
|
1418
|
+
out.reasoning_effort = reasoning;
|
|
1419
|
+
if (tools) {
|
|
1420
|
+
out.tools = tools;
|
|
1421
|
+
if (body.tool_choice !== undefined) out.tool_choice = body.tool_choice;
|
|
1422
|
+
}
|
|
1423
|
+
if (typeof body.temperature === 'number') out.temperature = body.temperature;
|
|
1424
|
+
if (typeof body.top_p === 'number') out.top_p = body.top_p;
|
|
1425
|
+
if (body.stop !== undefined) out.stop = body.stop;
|
|
1426
|
+
if (body.response_format) out.response_format = body.response_format;
|
|
1427
|
+
return { payload: out, trim, compact };
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
// O fetch do Node roda sobre o undici, que corta o corpo da resposta depois
|
|
1431
|
+
// de 5 minutos (bodyTimeout padrao) e nao deixa ajustar isso sem depender de
|
|
1432
|
+
// pacote extra. Numa escrita longa era exatamente o que matava a resposta no
|
|
1433
|
+
// meio. Aqui a conexao com o upstream nao tem prazo de corpo: quem decide
|
|
1434
|
+
// desistir e o watchdog do proxy, com CFG.idleTimeoutMs (1 hora).
|
|
1435
|
+
const UPSTREAM_HTTPS_AGENT = new https.Agent({ keepAlive: true, maxSockets: 64, maxFreeSockets: 16 });
|
|
1436
|
+
const UPSTREAM_HTTP_AGENT = new http.Agent({ keepAlive: true, maxSockets: 64, maxFreeSockets: 16 });
|
|
1437
|
+
|
|
1438
|
+
function upstreamRequest(urlStr, headers, body, opts = {}) {
|
|
1439
|
+
const { signal = null, redirects = 0 } = opts;
|
|
1440
|
+
return new Promise((resolve, reject) => {
|
|
1441
|
+
if (signal?.aborted) return reject(new Error('cliente desconectou'));
|
|
1442
|
+
|
|
1443
|
+
const u = new URL(urlStr);
|
|
1444
|
+
const mod = u.protocol === 'https:' ? https : http;
|
|
1445
|
+
const agent = u.protocol === 'https:' ? UPSTREAM_HTTPS_AGENT : UPSTREAM_HTTP_AGENT;
|
|
1446
|
+
const payload = Buffer.isBuffer(body) ? body : Buffer.from(body || '');
|
|
1447
|
+
let req = null;
|
|
1448
|
+
const headerTimer = setTimeout(() => {
|
|
1449
|
+
try { req?.destroy(new Error('upstream nao respondeu em ' + Math.round(CFG.idleTimeoutMs / 1000) + 's')); } catch {}
|
|
1450
|
+
}, CFG.idleTimeoutMs);
|
|
1451
|
+
if (headerTimer.unref) headerTimer.unref();
|
|
1452
|
+
const onAbort = () => { try { req?.destroy(new Error('cliente desconectou')); } catch {} };
|
|
1453
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1454
|
+
const cleanup = () => {
|
|
1455
|
+
clearTimeout(headerTimer);
|
|
1456
|
+
signal?.removeEventListener('abort', onAbort);
|
|
1457
|
+
};
|
|
1458
|
+
|
|
1459
|
+
req = mod.request(u, {
|
|
1460
|
+
method: 'POST',
|
|
1461
|
+
agent,
|
|
1462
|
+
headers: { ...headers, 'content-length': payload.length },
|
|
1463
|
+
}, (res) => {
|
|
1464
|
+
clearTimeout(headerTimer);
|
|
1465
|
+
const status = res.statusCode || 0;
|
|
1466
|
+
if (res.headers.location && [301, 302, 303, 307, 308].includes(status) && redirects < 2) {
|
|
1467
|
+
res.resume();
|
|
1468
|
+
signal?.removeEventListener('abort', onAbort);
|
|
1469
|
+
const next = new URL(res.headers.location, urlStr).toString();
|
|
1470
|
+
return resolve(upstreamRequest(next, headers, payload, { signal, redirects: redirects + 1 }));
|
|
1471
|
+
}
|
|
1472
|
+
res.on('close', () => signal?.removeEventListener('abort', onAbort));
|
|
1473
|
+
|
|
1474
|
+
const it = res[Symbol.asyncIterator]();
|
|
1475
|
+
let closed = false;
|
|
1476
|
+
let cached = null;
|
|
1477
|
+
const stop = () => {
|
|
1478
|
+
closed = true;
|
|
1479
|
+
try { res.destroy(); } catch {}
|
|
1480
|
+
};
|
|
1481
|
+
const bodyObj = {
|
|
1482
|
+
getReader() {
|
|
1483
|
+
return {
|
|
1484
|
+
async read() {
|
|
1485
|
+
if (closed) return { done: true, value: undefined };
|
|
1486
|
+
const r = await it.next();
|
|
1487
|
+
if (r.done) closed = true;
|
|
1488
|
+
return { done: !!r.done, value: r.value };
|
|
1489
|
+
},
|
|
1490
|
+
cancel: async () => stop(),
|
|
1491
|
+
};
|
|
1492
|
+
},
|
|
1493
|
+
cancel: async () => stop(),
|
|
1494
|
+
};
|
|
1495
|
+
const text = async () => {
|
|
1496
|
+
if (cached !== null) return cached;
|
|
1497
|
+
if (closed) return '';
|
|
1498
|
+
const chunks = [];
|
|
1499
|
+
while (true) {
|
|
1500
|
+
const r = await it.next();
|
|
1501
|
+
if (r.done) break;
|
|
1502
|
+
chunks.push(r.value);
|
|
1503
|
+
}
|
|
1504
|
+
closed = true;
|
|
1505
|
+
cached = Buffer.concat(chunks).toString('utf8');
|
|
1506
|
+
return cached;
|
|
1507
|
+
};
|
|
1508
|
+
|
|
1509
|
+
resolve({
|
|
1510
|
+
status,
|
|
1511
|
+
ok: status >= 200 && status < 300,
|
|
1512
|
+
headers: {
|
|
1513
|
+
get(name) {
|
|
1514
|
+
const v = res.headers[String(name).toLowerCase()];
|
|
1515
|
+
if (v === undefined) return null;
|
|
1516
|
+
return Array.isArray(v) ? v.join(', ') : String(v);
|
|
1517
|
+
},
|
|
1518
|
+
},
|
|
1519
|
+
body: bodyObj,
|
|
1520
|
+
text,
|
|
1521
|
+
});
|
|
1522
|
+
});
|
|
1523
|
+
req.on('error', (e) => { cleanup(); reject(e); });
|
|
1524
|
+
// Keepalive de TCP: se o outro lado sumir de verdade (cabo, NAT, gateway
|
|
1525
|
+
// morto), o sistema percebe e a conexao cai. Servidor apenas lento,
|
|
1526
|
+
// que continua vivo, nao e afetado.
|
|
1527
|
+
req.on('socket', (socket) => { try { socket.setKeepAlive(true, 30000); } catch {} });
|
|
1528
|
+
// Sem timeout de socket: pausa longa do servidor nao derruba a conexao.
|
|
1529
|
+
req.setTimeout(0);
|
|
1530
|
+
req.end(payload);
|
|
1531
|
+
});
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
// ---------- espera entre tentativas ----------
|
|
1535
|
+
// O cliente oficial do playground (build.nvidia.com) usa
|
|
1536
|
+
// @microsoft/fetch-event-source para o SSE: reconecta a MESMA requisicao
|
|
1537
|
+
// sem limite de tentativas, com 1 s de intervalo por padrao, e o servidor
|
|
1538
|
+
// pode trocar esse intervalo pelo campo "retry:" do proprio SSE.
|
|
1539
|
+
//
|
|
1540
|
+
// A fila cheia do pool ("Pending acquire queue...") e o mesmo caso de
|
|
1541
|
+
// servidor ocupado: espera 1 s e tenta de novo, para sempre. A bridge nao
|
|
1542
|
+
// devolve erro de upstream para o cliente, nao conta tentativas e nao
|
|
1543
|
+
// aborta a requisicao do cliente por causa disso.
|
|
1544
|
+
const RETRY_MS = 1000; // mesmo intervalo do fetch-event-source oficial
|
|
1545
|
+
|
|
1546
|
+
function sleepAbortable(ms, signal) {
|
|
1547
|
+
return new Promise((resolve, reject) => {
|
|
1548
|
+
if (signal?.aborted) return reject(new Error('cliente desconectou'));
|
|
1549
|
+
let onAbort = null;
|
|
1550
|
+
const cleanup = () => signal?.removeEventListener('abort', onAbort);
|
|
1551
|
+
const t = setTimeout(() => { cleanup(); resolve(); }, ms);
|
|
1552
|
+
onAbort = () => { clearTimeout(t); cleanup(); reject(new Error('cliente desconectou')); };
|
|
1553
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1554
|
+
});
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
async function callUpstream(payload, model = MODELS[0], tries = null, signal = null) {
|
|
1558
|
+
const st = tries || { net: 0, token: 0, rate: 0, busy: 0 };
|
|
1559
|
+
if (signal?.aborted) throw new Error('cliente desconectou');
|
|
1560
|
+
|
|
1561
|
+
let token;
|
|
1562
|
+
try {
|
|
1563
|
+
token = await getToken(st.token > 0, signal);
|
|
1564
|
+
} catch (e) {
|
|
1565
|
+
if (signal?.aborted || e.message === 'cliente desconectou') throw new Error('cliente desconectou');
|
|
1566
|
+
st.net++;
|
|
1567
|
+
log(`token indisponivel (${e.message}); nova tentativa ${st.net} em ${RETRY_MS}ms`);
|
|
1568
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
1569
|
+
return callUpstream(payload, model, st, signal);
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
let res;
|
|
1573
|
+
try {
|
|
1574
|
+
res = await upstreamRequest(model.upstream, {
|
|
1575
|
+
'content-type': 'application/json',
|
|
1576
|
+
accept: 'text/event-stream',
|
|
1577
|
+
'nv-function-id': model.fnId,
|
|
1578
|
+
'nv-captcha-token': token,
|
|
1579
|
+
origin: 'https://build.nvidia.com',
|
|
1580
|
+
referer: 'https://build.nvidia.com/',
|
|
1581
|
+
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36',
|
|
1582
|
+
}, JSON.stringify(payload), { signal });
|
|
1583
|
+
} catch (e) {
|
|
1584
|
+
if (signal?.aborted) throw new Error('cliente desconectou');
|
|
1585
|
+
st.net++;
|
|
1586
|
+
log(`upstream rede falhou (${e.message}); nova tentativa ${st.net} em ${RETRY_MS}ms`);
|
|
1587
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
1588
|
+
return callUpstream(payload, model, st, signal);
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
if (res.status === 400) {
|
|
1592
|
+
const txt = await res.text().catch(() => '');
|
|
1593
|
+
if (/token is invalid|invalid.*token|captcha|kaizen/i.test(txt)) {
|
|
1594
|
+
st.token++;
|
|
1595
|
+
log(`upstream 400 (token invalido); novo token, tentativa ${st.token} em ${RETRY_MS}ms`);
|
|
1596
|
+
// Descarta buffer velho porque o token pode ter expirado/invalidado.
|
|
1597
|
+
state.pool = [];
|
|
1598
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
1599
|
+
return callUpstream(payload, model, st, signal);
|
|
1600
|
+
}
|
|
1601
|
+
log('upstream 400 (nao-token)', txt.slice(0, 300));
|
|
1602
|
+
return res;
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
if (res.status === 401 || res.status === 403) {
|
|
1606
|
+
st.token++;
|
|
1607
|
+
log(`upstream ${res.status}; novo token, tentativa ${st.token} em ${RETRY_MS}ms`);
|
|
1608
|
+
try { await res.body.cancel(); } catch {}
|
|
1609
|
+
state.pool = [];
|
|
1610
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
1611
|
+
return callUpstream(payload, model, st, signal);
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
if (res.status === 429 || res.status >= 500) {
|
|
1615
|
+
const txt = await res.text().catch(() => '');
|
|
1616
|
+
const n = res.status === 429 ? ++st.rate : ++st.busy;
|
|
1617
|
+
log(`upstream ${res.status} (${txt.slice(0, 160) || 'sem corpo'}); tentativa ${n} em ${RETRY_MS}ms`);
|
|
1618
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
1619
|
+
return callUpstream(payload, model, st, signal);
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
return res;
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
// ---------- SSE ----------
|
|
1626
|
+
// Dumps servem para diagnosticar, mas nao podem virar lixo acumulado:
|
|
1627
|
+
// guarda so os 20 mais recentes. O bridge.log ja gira sozinho no log().
|
|
1628
|
+
// A data do nome ordena os dumps sem depender de mtime: neste sistema de
|
|
1629
|
+
// arquivos o stat de um arquivo recem-escrito pode devolver horario velho,
|
|
1630
|
+
// e o prune acabava apagando o dump que tinha sido gravado segundos antes.
|
|
1631
|
+
function sseDumpTime(name) {
|
|
1632
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z/.exec(name);
|
|
1633
|
+
if (!m) return 0;
|
|
1634
|
+
return Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6], +m[7]);
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
function pruneSseDumps(maxFiles = 20, protect = null) {
|
|
1638
|
+
try {
|
|
1639
|
+
const files = fs.readdirSync(SSE_DIR)
|
|
1640
|
+
.filter((f) => f.endsWith('.log'))
|
|
1641
|
+
.map((name) => ({ name, p: path.join(SSE_DIR, name), t: sseDumpTime(name) }))
|
|
1642
|
+
.sort((a, b) => b.t - a.t);
|
|
1643
|
+
for (const old of files.slice(maxFiles)) {
|
|
1644
|
+
if (protect && old.p === protect) continue;
|
|
1645
|
+
if (Date.now() - old.t < 5 * 60 * 1000) continue;
|
|
1646
|
+
try { fs.unlinkSync(old.p); } catch {}
|
|
1647
|
+
}
|
|
1648
|
+
} catch {}
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
function sseDump(id, meta, raw) {
|
|
1652
|
+
try {
|
|
1653
|
+
fs.mkdirSync(SSE_DIR, { recursive: true });
|
|
1654
|
+
const file = path.join(SSE_DIR, `${new Date().toISOString().replace(/[:.]/g, '-')}-${id}.log`);
|
|
1655
|
+
fs.writeFileSync(file, JSON.stringify(meta) + '\n\n' + raw.slice(0, 8 * 1024 * 1024));
|
|
1656
|
+
log('sse dump:', file);
|
|
1657
|
+
pruneSseDumps(20, file);
|
|
1658
|
+
} catch (e) {
|
|
1659
|
+
log('sse dump falhou:', e.message);
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
pruneSseDumps();
|
|
1663
|
+
|
|
1664
|
+
// ---------- Antigravity (Google Cloud Code) ----------
|
|
1665
|
+
// Fluxo tirado do OmniRoute (release/v3.8.55): OAuth de conta Google,
|
|
1666
|
+
// loadCodeAssist/onboardUser para descobrir o projectId e envelope Cloud Code
|
|
1667
|
+
// em /v1internal:streamGenerateContent. O client e o do app desktop
|
|
1668
|
+
// Antigravity, que e publico por design (installed app).
|
|
1669
|
+
const AG = {
|
|
1670
|
+
clientId: '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com',
|
|
1671
|
+
clientSecret: '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',
|
|
1672
|
+
authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
|
|
1673
|
+
tokenUrl: 'https://oauth2.googleapis.com/token',
|
|
1674
|
+
userInfoUrl: 'https://www.googleapis.com/oauth2/v1/userinfo',
|
|
1675
|
+
scopes: [
|
|
1676
|
+
'https://www.googleapis.com/auth/cloud-platform',
|
|
1677
|
+
'https://www.googleapis.com/auth/userinfo.email',
|
|
1678
|
+
'https://www.googleapis.com/auth/userinfo.profile',
|
|
1679
|
+
'https://www.googleapis.com/auth/cclog',
|
|
1680
|
+
'https://www.googleapis.com/auth/experimentsandconfigs',
|
|
1681
|
+
],
|
|
1682
|
+
// Extraido do binario /root/.local/bin/agy (1.5.13):
|
|
1683
|
+
// - Endpoint do CLI consumer: daily-cloudcode-pa.googleapis.com
|
|
1684
|
+
// - User-Agent (codeassistclient.userAgent): inclui "aidev_client",
|
|
1685
|
+
// "os_type", "arch", "cl=1025641825" e "auth_method=consumer".
|
|
1686
|
+
// Sem o cl=1025641825 o servidor nao entrega Gemini 4 Neon/Hydrogen.
|
|
1687
|
+
apiBase: 'https://daily-cloudcode-pa.googleapis.com',
|
|
1688
|
+
bootstrapBase: 'https://daily-cloudcode-pa.googleapis.com',
|
|
1689
|
+
cliVersion: '1.5.13',
|
|
1690
|
+
cliCl: '1025641825',
|
|
1691
|
+
ua: '',
|
|
1692
|
+
ideNodeUa: '',
|
|
1693
|
+
tokenFile: path.join(APP_DIR, 'antigravity.json'),
|
|
1694
|
+
redirectPath: '/callback',
|
|
1695
|
+
};
|
|
1696
|
+
|
|
1697
|
+
function agUserAgent() {
|
|
1698
|
+
const osType = process.platform === 'win32' ? 'windows' : process.platform;
|
|
1699
|
+
const arch = process.arch === 'x64' ? 'amd64' : process.arch;
|
|
1700
|
+
return `antigravity/cli/${AG.cliVersion} (aidev_client; os_type=${osType}; arch=${arch}; cl=${AG.cliCl}; auth_method=consumer)`;
|
|
1701
|
+
}
|
|
1702
|
+
AG.ua = agUserAgent();
|
|
1703
|
+
AG.ideNodeUa = AG.ua;
|
|
1704
|
+
|
|
1705
|
+
// Armazenamento multi-conta (v2) em antigravity.json, com migracao automatica
|
|
1706
|
+
// do formato antigo (v1 de conta unica). Se uma conta esgotar a quota (5h ou
|
|
1707
|
+
// semanal), a bridge guarda o resetTime dela em cooldown e troca automaticamente
|
|
1708
|
+
// para outra conta com quota disponivel, voltando para a conta original quando
|
|
1709
|
+
// a quota dela retornar.
|
|
1710
|
+
let agStore = { version: 2, active: '', accounts: [] };
|
|
1711
|
+
const AG_RT = new Map(); // accountId -> { refreshing, lastDiscoverAt, quota, cooldowns }
|
|
1712
|
+
const AG_PENDING = new Map(); // state -> { expiresAt, status, account, error }
|
|
1713
|
+
|
|
1714
|
+
function agAccountId(acct) {
|
|
1715
|
+
return String((acct && (acct.id || acct.email || acct.projectId)) || 'default').trim().toLowerCase();
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
function agNormalizeAccount(raw) {
|
|
1719
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
1720
|
+
if (!raw.refreshToken && !raw.accessToken) return null;
|
|
1721
|
+
const acct = {
|
|
1722
|
+
id: '',
|
|
1723
|
+
email: String(raw.email || '').trim(),
|
|
1724
|
+
accessToken: String(raw.accessToken || ''),
|
|
1725
|
+
refreshToken: String(raw.refreshToken || ''),
|
|
1726
|
+
scope: String(raw.scope || AG.scopes.join(' ')),
|
|
1727
|
+
expiresAt: Number(raw.expiresAt) || 0,
|
|
1728
|
+
projectId: String(raw.projectId || '').trim(),
|
|
1729
|
+
tier: String(raw.tier || ''),
|
|
1730
|
+
paidTier: String(raw.paidTier || ''),
|
|
1731
|
+
paidTierName: String(raw.paidTierName || ''),
|
|
1732
|
+
credits: Array.isArray(raw.credits) ? raw.credits : [],
|
|
1733
|
+
createdAt: raw.createdAt || new Date().toISOString(),
|
|
1734
|
+
updatedAt: raw.updatedAt || new Date().toISOString(),
|
|
1735
|
+
};
|
|
1736
|
+
acct.id = agAccountId(raw.id ? { id: raw.id } : acct);
|
|
1737
|
+
return acct;
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
function agRuntime(acct) {
|
|
1741
|
+
const id = agAccountId(acct);
|
|
1742
|
+
let rt = AG_RT.get(id);
|
|
1743
|
+
if (!rt) {
|
|
1744
|
+
rt = {
|
|
1745
|
+
refreshing: null,
|
|
1746
|
+
lastDiscoverAt: 0,
|
|
1747
|
+
quota: { at: 0, models: {}, groups: [], description: null, defaultModel: null, error: null },
|
|
1748
|
+
cooldowns: new Map(), // bucket/wire -> { until, resetTime, reason }
|
|
1749
|
+
};
|
|
1750
|
+
AG_RT.set(id, rt);
|
|
1751
|
+
}
|
|
1752
|
+
return rt;
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
function agLoadTokens() {
|
|
1756
|
+
agStore = { version: 2, active: '', accounts: [] };
|
|
1757
|
+
try {
|
|
1758
|
+
const j = JSON.parse(fs.readFileSync(AG.tokenFile, 'utf8'));
|
|
1759
|
+
if (j && typeof j === 'object') {
|
|
1760
|
+
if (Array.isArray(j.accounts)) {
|
|
1761
|
+
const seen = new Set();
|
|
1762
|
+
for (const item of j.accounts) {
|
|
1763
|
+
const norm = agNormalizeAccount(item);
|
|
1764
|
+
if (!norm || seen.has(norm.id)) continue;
|
|
1765
|
+
seen.add(norm.id);
|
|
1766
|
+
agStore.accounts.push(norm);
|
|
1767
|
+
}
|
|
1768
|
+
agStore.active = String(j.active || '').trim().toLowerCase();
|
|
1769
|
+
} else {
|
|
1770
|
+
const single = agNormalizeAccount(j);
|
|
1771
|
+
if (single) {
|
|
1772
|
+
agStore.accounts.push(single);
|
|
1773
|
+
agStore.active = single.id;
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
} catch {}
|
|
1778
|
+
if (agStore.accounts.length && !agStore.accounts.some((a) => a.id === agStore.active)) {
|
|
1779
|
+
agStore.active = agStore.accounts[0].id;
|
|
1780
|
+
}
|
|
1781
|
+
return agActiveAccount();
|
|
1782
|
+
}
|
|
1783
|
+
agLoadTokens();
|
|
1784
|
+
|
|
1785
|
+
function agSaveTokens() {
|
|
1786
|
+
try {
|
|
1787
|
+
if (!agStore.accounts.length) {
|
|
1788
|
+
try { fs.unlinkSync(AG.tokenFile); } catch {}
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
if (!agStore.accounts.some((a) => a.id === agStore.active)) {
|
|
1792
|
+
agStore.active = agStore.accounts[0].id;
|
|
1793
|
+
}
|
|
1794
|
+
fs.writeFileSync(AG.tokenFile, JSON.stringify(agStore, null, 2) + '\n', { mode: 0o600 });
|
|
1795
|
+
try { fs.chmodSync(AG.tokenFile, 0o600); } catch {}
|
|
1796
|
+
} catch (e) {
|
|
1797
|
+
log('antigravity: nao consegui salvar o token:', e.message);
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
function agActiveAccount() {
|
|
1802
|
+
if (!agStore.accounts.length) return null;
|
|
1803
|
+
return agStore.accounts.find((a) => a.id === agStore.active) || agStore.accounts[0] || null;
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
function agFindAccount(hint) {
|
|
1807
|
+
const raw = String(hint || '').trim().replace(/^bearer\s+/i, '').replace(/^ag:/i, '').trim().toLowerCase();
|
|
1808
|
+
if (!raw) return null;
|
|
1809
|
+
return agStore.accounts.find((a) => a.id === raw || String(a.email || '').toLowerCase() === raw) || null;
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
function agUpsertAccount(acct) {
|
|
1813
|
+
const norm = agNormalizeAccount(acct);
|
|
1814
|
+
if (!norm) return null;
|
|
1815
|
+
const idx = agStore.accounts.findIndex((a) => a.id === norm.id);
|
|
1816
|
+
if (idx >= 0) {
|
|
1817
|
+
norm.createdAt = agStore.accounts[idx].createdAt || norm.createdAt;
|
|
1818
|
+
agStore.accounts[idx] = norm;
|
|
1819
|
+
} else {
|
|
1820
|
+
agStore.accounts.push(norm);
|
|
1821
|
+
}
|
|
1822
|
+
agStore.active = norm.id;
|
|
1823
|
+
agRuntime(norm).cooldowns.clear();
|
|
1824
|
+
agSaveTokens();
|
|
1825
|
+
return norm;
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
function agRemoveAccount(hint = '') {
|
|
1829
|
+
if (!hint) {
|
|
1830
|
+
agStore.accounts = [];
|
|
1831
|
+
agStore.active = '';
|
|
1832
|
+
AG_RT.clear();
|
|
1833
|
+
agSaveTokens();
|
|
1834
|
+
return { removed: 'all', remaining: 0 };
|
|
1835
|
+
}
|
|
1836
|
+
const target = agFindAccount(hint);
|
|
1837
|
+
if (!target) return { removed: null, remaining: agStore.accounts.length };
|
|
1838
|
+
agStore.accounts = agStore.accounts.filter((a) => a.id !== target.id);
|
|
1839
|
+
AG_RT.delete(target.id);
|
|
1840
|
+
if (agStore.active === target.id) {
|
|
1841
|
+
agStore.active = agStore.accounts[0]?.id || '';
|
|
1842
|
+
}
|
|
1843
|
+
agSaveTokens();
|
|
1844
|
+
return { removed: target.email || target.id, remaining: agStore.accounts.length };
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
function agLogged() {
|
|
1848
|
+
return agStore.accounts.some((a) => !!(a && (a.refreshToken || a.accessToken)));
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
function agTokenOk(acct = agActiveAccount()) {
|
|
1852
|
+
return !!(acct && acct.accessToken && Number(acct.expiresAt) > Date.now() + 120000);
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
function agPublicAccount(acct) {
|
|
1856
|
+
if (!acct) return null;
|
|
1857
|
+
const rt = agRuntime(acct);
|
|
1858
|
+
const now = Date.now();
|
|
1859
|
+
const cooldowns = {};
|
|
1860
|
+
for (const [k, v] of rt.cooldowns.entries()) {
|
|
1861
|
+
if (v.until <= now) { rt.cooldowns.delete(k); continue; }
|
|
1862
|
+
const sec = Math.max(0, Math.round((v.until - now) / 1000));
|
|
1863
|
+
cooldowns[k] = {
|
|
1864
|
+
until: new Date(v.until).toISOString(),
|
|
1865
|
+
resetInSeconds: sec,
|
|
1866
|
+
resetHuman: agFormatDuration(sec),
|
|
1867
|
+
reason: v.reason || 'quota',
|
|
1868
|
+
};
|
|
1869
|
+
}
|
|
1870
|
+
return {
|
|
1871
|
+
id: acct.id,
|
|
1872
|
+
email: acct.email || null,
|
|
1873
|
+
projectId: acct.projectId || null,
|
|
1874
|
+
tier: acct.tier || null,
|
|
1875
|
+
paidTier: acct.paidTier || null,
|
|
1876
|
+
paidTierName: acct.paidTierName || null,
|
|
1877
|
+
active: acct.id === agStore.active,
|
|
1878
|
+
expiresAt: acct.expiresAt || null,
|
|
1879
|
+
cooldowns,
|
|
1880
|
+
quota: agQuotaView(acct),
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
function agRedirectUri() {
|
|
1885
|
+
return `http://127.0.0.1:${CFG.port}${AG.redirectPath}`;
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
function agForm(obj) {
|
|
1889
|
+
const p = new URLSearchParams();
|
|
1890
|
+
for (const [k, v] of Object.entries(obj)) if (v !== undefined && v !== null && v !== '') p.set(k, String(v));
|
|
1891
|
+
return p.toString();
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
function agPostForm(url, obj, headers = {}) {
|
|
1895
|
+
return upstreamRequest(url, {
|
|
1896
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
1897
|
+
accept: 'application/json',
|
|
1898
|
+
'user-agent': AG.ideNodeUa,
|
|
1899
|
+
...headers,
|
|
1900
|
+
}, agForm(obj));
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
// Renova o access token de uma conta especifica. Chamadas concorrentes para a
|
|
1904
|
+
// mesma conta dividem a mesma renovacao.
|
|
1905
|
+
function agRefreshAccount(acct, force = false) {
|
|
1906
|
+
if (!acct) return Promise.reject(new Error('sem login do Antigravity; abra /antigravity/login'));
|
|
1907
|
+
if (!force && agTokenOk(acct)) return Promise.resolve(acct);
|
|
1908
|
+
const rt = agRuntime(acct);
|
|
1909
|
+
if (rt.refreshing) return rt.refreshing;
|
|
1910
|
+
rt.refreshing = (async () => {
|
|
1911
|
+
if (!acct.refreshToken) {
|
|
1912
|
+
throw new Error(`conta ${acct.email || acct.id} sem refreshToken; faca login de novo`);
|
|
1913
|
+
}
|
|
1914
|
+
const res = await agPostForm(AG.tokenUrl, {
|
|
1915
|
+
grant_type: 'refresh_token',
|
|
1916
|
+
client_id: AG.clientId,
|
|
1917
|
+
client_secret: AG.clientSecret,
|
|
1918
|
+
refresh_token: acct.refreshToken,
|
|
1919
|
+
});
|
|
1920
|
+
const txt = await res.text();
|
|
1921
|
+
if (!res.ok) throw new Error(`refresh ${res.status}: ${txt.slice(0, 300)}`);
|
|
1922
|
+
const j = JSON.parse(txt);
|
|
1923
|
+
if (!j.access_token) throw new Error('refresh sem access_token');
|
|
1924
|
+
acct.accessToken = j.access_token;
|
|
1925
|
+
if (j.refresh_token) acct.refreshToken = j.refresh_token;
|
|
1926
|
+
if (j.scope) acct.scope = j.scope;
|
|
1927
|
+
const ttl = Number(j.expires_in) > 0 ? Number(j.expires_in) : 3500;
|
|
1928
|
+
acct.expiresAt = Date.now() + (ttl - 60) * 1000;
|
|
1929
|
+
acct.updatedAt = new Date().toISOString();
|
|
1930
|
+
agSaveTokens();
|
|
1931
|
+
log(`antigravity[${acct.email || acct.id}]: token renovado (expira em ${ttl}s)`);
|
|
1932
|
+
return acct;
|
|
1933
|
+
})().finally(() => { rt.refreshing = null; });
|
|
1934
|
+
return rt.refreshing;
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
function agRefresh(force = false) {
|
|
1938
|
+
return agRefreshAccount(agActiveAccount(), force);
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
function agPlatformEnum() {
|
|
1942
|
+
const arch = process.arch;
|
|
1943
|
+
if (process.platform === 'darwin') return arch === 'arm64' ? 2 : 1;
|
|
1944
|
+
if (process.platform === 'linux') return arch === 'arm64' ? 4 : 3;
|
|
1945
|
+
if (process.platform === 'win32') return 5;
|
|
1946
|
+
return 0;
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
function agMetadata() {
|
|
1950
|
+
return { ideType: 9, platform: agPlatformEnum(), pluginType: 2 };
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
function agProjectOf(j) {
|
|
1954
|
+
const p = j && j.cloudaicompanionProject;
|
|
1955
|
+
if (typeof p === 'string') return p.trim();
|
|
1956
|
+
if (p && typeof p === 'object' && typeof p.id === 'string') return p.id.trim();
|
|
1957
|
+
return '';
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
function agBootstrapHeaders(accessToken) {
|
|
1961
|
+
return {
|
|
1962
|
+
authorization: `Bearer ${accessToken}`,
|
|
1963
|
+
'content-type': 'application/json',
|
|
1964
|
+
'user-agent': AG.ua,
|
|
1965
|
+
};
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
function agFormatDuration(sec) {
|
|
1969
|
+
if (sec === null || sec === undefined || !Number.isFinite(sec)) return null;
|
|
1970
|
+
if (sec <= 0) return 'agora';
|
|
1971
|
+
const d = Math.floor(sec / 86400);
|
|
1972
|
+
const h = Math.floor((sec % 86400) / 3600);
|
|
1973
|
+
const m = Math.floor((sec % 3600) / 60);
|
|
1974
|
+
const s = Math.floor(sec % 60);
|
|
1975
|
+
if (d > 0) return `${d}d ${h}h`;
|
|
1976
|
+
if (h > 0) return `${h}h ${m}m`;
|
|
1977
|
+
if (m > 0) return `${m}m ${s}s`;
|
|
1978
|
+
return `${s}s`;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
function agQuotaBucketKey(modelOrWire) {
|
|
1982
|
+
const w = typeof modelOrWire === 'string' ? modelOrWire : String(modelOrWire?.wire || modelOrWire?.id || '');
|
|
1983
|
+
if (/^claude/i.test(w)) return 'claude';
|
|
1984
|
+
if (/^gemini-4-(neon|hydrogen)/i.test(w)) return 'gemini';
|
|
1985
|
+
return w.toLowerCase() || 'default';
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
function agGroupMatchesBucket(groupName, bucketKey) {
|
|
1989
|
+
const g = String(groupName || '').toLowerCase();
|
|
1990
|
+
if (bucketKey === 'claude') return g.includes('claude');
|
|
1991
|
+
if (bucketKey === 'gemini') return g.includes('gemini') && !g.includes('argon');
|
|
1992
|
+
return false;
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
function agParseResetMs(text, retryAfterHeader) {
|
|
1996
|
+
const now = Date.now();
|
|
1997
|
+
if (retryAfterHeader) {
|
|
1998
|
+
const n = Number(retryAfterHeader);
|
|
1999
|
+
if (Number.isFinite(n) && n > 0) return now + n * 1000;
|
|
2000
|
+
const d = Date.parse(retryAfterHeader);
|
|
2001
|
+
if (Number.isFinite(d) && d > now) return d;
|
|
2002
|
+
}
|
|
2003
|
+
const s = String(text || '');
|
|
2004
|
+
const iso = s.match(/20\d{2}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z/);
|
|
2005
|
+
if (iso) {
|
|
2006
|
+
const d = Date.parse(iso[0]);
|
|
2007
|
+
if (Number.isFinite(d) && d > now) return d;
|
|
2008
|
+
}
|
|
2009
|
+
const rel = s.match(/resets?\s+in\s+((?:\d+\s*[dhms]\s*)+)/i);
|
|
2010
|
+
if (rel) {
|
|
2011
|
+
let sec = 0;
|
|
2012
|
+
for (const m of rel[1].matchAll(/(\d+)\s*([dhms])/gi)) {
|
|
2013
|
+
const v = Number(m[1]);
|
|
2014
|
+
const u = m[2].toLowerCase();
|
|
2015
|
+
if (u === 'd') sec += v * 86400;
|
|
2016
|
+
else if (u === 'h') sec += v * 3600;
|
|
2017
|
+
else if (u === 'm') sec += v * 60;
|
|
2018
|
+
else if (u === 's') sec += v;
|
|
2019
|
+
}
|
|
2020
|
+
if (sec > 0) return now + sec * 1000;
|
|
2021
|
+
}
|
|
2022
|
+
return null;
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
function agMarkCooldown(acct, model, wire, untilMs, reason = 'quota') {
|
|
2026
|
+
if (!acct) return;
|
|
2027
|
+
const rt = agRuntime(acct);
|
|
2028
|
+
const bucket = agQuotaBucketKey(model || wire);
|
|
2029
|
+
const until = Number(untilMs) > Date.now() ? Number(untilMs) : Date.now() + 5 * 60 * 1000;
|
|
2030
|
+
const entry = { until, resetTime: new Date(until).toISOString(), reason };
|
|
2031
|
+
const prevBucket = rt.cooldowns.get(bucket);
|
|
2032
|
+
if (!prevBucket || prevBucket.until < until) rt.cooldowns.set(bucket, entry);
|
|
2033
|
+
if (wire) {
|
|
2034
|
+
const prevWire = rt.cooldowns.get(wire);
|
|
2035
|
+
if (!prevWire || prevWire.until < until) rt.cooldowns.set(wire, entry);
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
function agAccountAvailability(acct, model, wire) {
|
|
2040
|
+
const now = Date.now();
|
|
2041
|
+
const rt = agRuntime(acct);
|
|
2042
|
+
const bucket = agQuotaBucketKey(model || wire);
|
|
2043
|
+
|
|
2044
|
+
// 1. Cooldown explicito (ex.: 429 recente ou cota 0 sincronizada)
|
|
2045
|
+
for (const key of [wire, bucket]) {
|
|
2046
|
+
if (!key) continue;
|
|
2047
|
+
const cd = rt.cooldowns.get(key);
|
|
2048
|
+
if (!cd) continue;
|
|
2049
|
+
if (cd.until <= now) {
|
|
2050
|
+
rt.cooldowns.delete(key);
|
|
2051
|
+
} else {
|
|
2052
|
+
return { exhausted: true, until: cd.until, resetTime: cd.resetTime, reason: cd.reason, remainingFraction: 0 };
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
// 2. Retrato de quota por modelo (fetchAvailableModels)
|
|
2057
|
+
const mq = wire ? rt.quota.models[wire] : null;
|
|
2058
|
+
if (mq) {
|
|
2059
|
+
if (mq.remainingFraction <= 0) {
|
|
2060
|
+
const resetMs = mq.resetTime ? Date.parse(mq.resetTime) : 0;
|
|
2061
|
+
if (resetMs > now) {
|
|
2062
|
+
return { exhausted: true, until: resetMs, resetTime: mq.resetTime, reason: 'quota_0', remainingFraction: 0 };
|
|
2063
|
+
}
|
|
2064
|
+
// Reset ja passou: dispara atualizacao em background e libera a conta!
|
|
2065
|
+
agDiscoverAccount(acct, true).catch(() => {});
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
// 3. Retrato de quota por grupo (retrieveUserQuotaSummary: 5h + weekly)
|
|
2070
|
+
for (const g of rt.quota.groups || []) {
|
|
2071
|
+
if (!agGroupMatchesBucket(g.displayName, bucket)) continue;
|
|
2072
|
+
for (const b of g.buckets || []) {
|
|
2073
|
+
const frac = typeof b.remainingFraction === 'number' ? b.remainingFraction : (b.resetTime ? 0 : null);
|
|
2074
|
+
if (frac !== null && frac <= 0) {
|
|
2075
|
+
const resetMs = b.resetTime ? Date.parse(b.resetTime) : 0;
|
|
2076
|
+
if (resetMs > now) {
|
|
2077
|
+
return { exhausted: true, until: resetMs, resetTime: b.resetTime, reason: `group_${b.window || 'quota'}_0`, remainingFraction: 0 };
|
|
2078
|
+
}
|
|
2079
|
+
agDiscoverAccount(acct, true).catch(() => {});
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
return {
|
|
2085
|
+
exhausted: false,
|
|
2086
|
+
until: 0,
|
|
2087
|
+
resetTime: mq?.resetTime || null,
|
|
2088
|
+
reason: null,
|
|
2089
|
+
remainingFraction: typeof mq?.remainingFraction === 'number' ? mq.remainingFraction : null,
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
|
|
2093
|
+
function agSelectAccounts(model, wire, preferredHint = '') {
|
|
2094
|
+
const preferred = agFindAccount(preferredHint) || agActiveAccount();
|
|
2095
|
+
const ordered = [];
|
|
2096
|
+
if (preferred) ordered.push(preferred);
|
|
2097
|
+
const others = agStore.accounts.filter((a) => !preferred || a.id !== preferred.id);
|
|
2098
|
+
// Entre contas alternativas, prioriza a que tem mais quota restante para este modelo.
|
|
2099
|
+
others.sort((a, b) => {
|
|
2100
|
+
const fa = agAccountAvailability(a, model, wire).remainingFraction;
|
|
2101
|
+
const fb = agAccountAvailability(b, model, wire).remainingFraction;
|
|
2102
|
+
const sa = fa === null ? 0.5 : fa;
|
|
2103
|
+
const sb = fb === null ? 0.5 : fb;
|
|
2104
|
+
return sb - sa;
|
|
2105
|
+
});
|
|
2106
|
+
ordered.push(...others);
|
|
2107
|
+
|
|
2108
|
+
const available = [];
|
|
2109
|
+
const exhausted = [];
|
|
2110
|
+
for (const acct of ordered) {
|
|
2111
|
+
const av = agAccountAvailability(acct, model, wire);
|
|
2112
|
+
if (av.exhausted) exhausted.push({ acct, ...av });
|
|
2113
|
+
else available.push(acct);
|
|
2114
|
+
}
|
|
2115
|
+
return { available, exhausted };
|
|
2116
|
+
}
|
|
2117
|
+
|
|
2118
|
+
const AG_USAGE = { since: new Date().toISOString(), models: {}, accounts: {} };
|
|
2119
|
+
const AG_USAGE_FILE = path.join(APP_DIR, 'antigravity-usage.json');
|
|
2120
|
+
|
|
2121
|
+
try {
|
|
2122
|
+
const j = JSON.parse(fs.readFileSync(AG_USAGE_FILE, 'utf8'));
|
|
2123
|
+
if (j && j.models) {
|
|
2124
|
+
AG_USAGE.since = j.since || AG_USAGE.since;
|
|
2125
|
+
AG_USAGE.models = j.models;
|
|
2126
|
+
if (j.accounts && typeof j.accounts === 'object') AG_USAGE.accounts = j.accounts;
|
|
2127
|
+
}
|
|
2128
|
+
} catch {}
|
|
2129
|
+
|
|
2130
|
+
let agUsageWrites = 0;
|
|
2131
|
+
function agSaveUsage() {
|
|
2132
|
+
if (++agUsageWrites % 5) return;
|
|
2133
|
+
try {
|
|
2134
|
+
fs.writeFileSync(AG_USAGE_FILE, JSON.stringify(AG_USAGE, null, 2) + '\n', { mode: 0o600 });
|
|
2135
|
+
} catch {}
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
function agTrackUsage(wire, usage, acct = null) {
|
|
2139
|
+
if (!wire || !usage) return;
|
|
2140
|
+
const bump = (bucket) => {
|
|
2141
|
+
bucket.requests++;
|
|
2142
|
+
bucket.prompt_tokens += Number(usage.prompt_tokens) || 0;
|
|
2143
|
+
const cached = usage.prompt_tokens_details && usage.prompt_tokens_details.cached_tokens;
|
|
2144
|
+
bucket.cached_tokens = (Number(bucket.cached_tokens) || 0) + (Number(cached) || 0);
|
|
2145
|
+
bucket.completion_tokens += Number(usage.completion_tokens) || 0;
|
|
2146
|
+
const reasoning = usage.completion_tokens_details && usage.completion_tokens_details.reasoning_tokens;
|
|
2147
|
+
bucket.reasoning_tokens += Number(reasoning) || 0;
|
|
2148
|
+
bucket.total_tokens += Number(usage.total_tokens) || 0;
|
|
2149
|
+
bucket.lastAt = new Date().toISOString();
|
|
2150
|
+
};
|
|
2151
|
+
const init = () => ({
|
|
2152
|
+
requests: 0, prompt_tokens: 0, cached_tokens: 0, completion_tokens: 0, reasoning_tokens: 0, total_tokens: 0,
|
|
2153
|
+
});
|
|
2154
|
+
const u = AG_USAGE.models[wire] || (AG_USAGE.models[wire] = init());
|
|
2155
|
+
bump(u);
|
|
2156
|
+
if (acct) {
|
|
2157
|
+
const ak = acct.email || acct.id;
|
|
2158
|
+
const au = AG_USAGE.accounts[ak] || (AG_USAGE.accounts[ak] = init());
|
|
2159
|
+
bump(au);
|
|
2160
|
+
}
|
|
2161
|
+
agSaveUsage();
|
|
2162
|
+
}
|
|
2163
|
+
|
|
2164
|
+
function agQuotaView(acct = agActiveAccount()) {
|
|
2165
|
+
const qState = acct ? agRuntime(acct).quota : { at: 0, models: {}, groups: [], description: null, defaultModel: null, error: null };
|
|
2166
|
+
const now = Date.now();
|
|
2167
|
+
const formatBucket = (b) => {
|
|
2168
|
+
const resetSec = b.resetTime ? Math.max(0, Math.round((Date.parse(b.resetTime) - now) / 1000)) : null;
|
|
2169
|
+
const frac = typeof b.remainingFraction === 'number' ? b.remainingFraction : (b.resetTime ? 0 : null);
|
|
2170
|
+
return {
|
|
2171
|
+
bucketId: b.bucketId || null,
|
|
2172
|
+
displayName: b.displayName || null,
|
|
2173
|
+
window: b.window || null,
|
|
2174
|
+
remainingFraction: frac,
|
|
2175
|
+
remainingPercent: frac !== null ? Math.round(frac * 1000) / 10 : null,
|
|
2176
|
+
resetTime: b.resetTime || null,
|
|
2177
|
+
resetInSeconds: resetSec,
|
|
2178
|
+
resetHuman: agFormatDuration(resetSec),
|
|
2179
|
+
description: b.description || null,
|
|
2180
|
+
};
|
|
2181
|
+
};
|
|
2182
|
+
const groups = (qState.groups || []).map((g) => ({
|
|
2183
|
+
displayName: g.displayName || null,
|
|
2184
|
+
description: g.description || null,
|
|
2185
|
+
buckets: Array.isArray(g.buckets) ? g.buckets.map(formatBucket) : [],
|
|
2186
|
+
}));
|
|
2187
|
+
const families = {};
|
|
2188
|
+
for (const m of MODELS.filter((x) => x.provider === 'antigravity')) {
|
|
2189
|
+
const served = (m.tiers || []).filter((t) => qState.models[`${m.wire}-${t}`]);
|
|
2190
|
+
const refId = served.length ? `${m.wire}-${served[served.length - 1]}` : null;
|
|
2191
|
+
const q = refId ? qState.models[refId] : null;
|
|
2192
|
+
const resetSec = q && q.resetTime ? Math.max(0, Math.round((Date.parse(q.resetTime) - now) / 1000)) : null;
|
|
2193
|
+
families[m.id] = {
|
|
2194
|
+
tiers: m.tiers || [],
|
|
2195
|
+
servedTiers: served,
|
|
2196
|
+
available: served.length > 0,
|
|
2197
|
+
remainingFraction: q ? q.remainingFraction : null,
|
|
2198
|
+
remainingPercent: q ? Math.round(q.remainingFraction * 1000) / 10 : null,
|
|
2199
|
+
resetTime: q ? q.resetTime : null,
|
|
2200
|
+
resetInSeconds: resetSec,
|
|
2201
|
+
resetHuman: agFormatDuration(resetSec),
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
const models = {};
|
|
2205
|
+
for (const [id, q] of Object.entries(qState.models)) {
|
|
2206
|
+
const resetSec = q.resetTime ? Math.max(0, Math.round((Date.parse(q.resetTime) - now) / 1000)) : null;
|
|
2207
|
+
models[id] = {
|
|
2208
|
+
remainingFraction: q.remainingFraction,
|
|
2209
|
+
remainingPercent: Math.round(q.remainingFraction * 1000) / 10,
|
|
2210
|
+
resetTime: q.resetTime,
|
|
2211
|
+
resetInSeconds: resetSec,
|
|
2212
|
+
resetHuman: agFormatDuration(resetSec),
|
|
2213
|
+
};
|
|
2214
|
+
}
|
|
2215
|
+
return {
|
|
2216
|
+
checkedAt: qState.at ? new Date(qState.at).toISOString() : null,
|
|
2217
|
+
error: qState.error,
|
|
2218
|
+
defaultModel: qState.defaultModel,
|
|
2219
|
+
description: qState.description,
|
|
2220
|
+
families,
|
|
2221
|
+
groups,
|
|
2222
|
+
models,
|
|
2223
|
+
};
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
const AG_TIER_ORDER = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
2227
|
+
function agTier(effort, tiers) {
|
|
2228
|
+
const list = Array.isArray(tiers) && tiers.length ? tiers : ['high'];
|
|
2229
|
+
if (list.includes(effort)) return effort;
|
|
2230
|
+
// max <-> xhigh: cada familia usa um nome para o topo. Se o topo pedido
|
|
2231
|
+
// nao existe, cai no mais alto que a familia serve.
|
|
2232
|
+
const top = list[list.length - 1];
|
|
2233
|
+
if (effort === 'max' || effort === 'xhigh') return top;
|
|
2234
|
+
return list.includes('high') ? 'high' : top;
|
|
2235
|
+
}
|
|
2236
|
+
|
|
2237
|
+
async function agRefreshPlanAccount(acct) {
|
|
2238
|
+
if (!acct || !acct.accessToken) return;
|
|
2239
|
+
try {
|
|
2240
|
+
const res = await upstreamRequest(
|
|
2241
|
+
`${AG.bootstrapBase}/v1internal:loadCodeAssist`,
|
|
2242
|
+
agBootstrapHeaders(acct.accessToken),
|
|
2243
|
+
JSON.stringify({ metadata: agMetadata() })
|
|
2244
|
+
);
|
|
2245
|
+
if (!res.ok) return;
|
|
2246
|
+
const j = JSON.parse(await res.text());
|
|
2247
|
+
const proj = agProjectOf(j);
|
|
2248
|
+
if (proj) acct.projectId = proj;
|
|
2249
|
+
if (j.currentTier) acct.tier = j.currentTier.id || j.currentTier.name || acct.tier;
|
|
2250
|
+
acct.paidTier = (j.paidTier && (j.paidTier.id || j.paidTier.name)) || '';
|
|
2251
|
+
acct.paidTierName = (j.paidTier && j.paidTier.name) || '';
|
|
2252
|
+
acct.credits = (j.paidTier && Array.isArray(j.paidTier.availableCredits)) ? j.paidTier.availableCredits : [];
|
|
2253
|
+
agSaveTokens();
|
|
2254
|
+
} catch {}
|
|
2255
|
+
}
|
|
2256
|
+
|
|
2257
|
+
async function agDiscoverAccount(acct, force = true) {
|
|
2258
|
+
if (!acct || (!acct.accessToken && !acct.refreshToken)) return;
|
|
2259
|
+
const rt = agRuntime(acct);
|
|
2260
|
+
if (!force && Date.now() - rt.lastDiscoverAt < 30000) return;
|
|
2261
|
+
rt.lastDiscoverAt = Date.now();
|
|
2262
|
+
const tag = acct.email || acct.id;
|
|
2263
|
+
let tok;
|
|
2264
|
+
try {
|
|
2265
|
+
tok = await agRefreshAccount(acct, false);
|
|
2266
|
+
} catch (e) {
|
|
2267
|
+
rt.quota.error = e.message;
|
|
2268
|
+
log(`antigravity[${tag}]: descoberta sem token:`, e.message);
|
|
2269
|
+
return;
|
|
2270
|
+
}
|
|
2271
|
+
if (!tok.projectId) await agRefreshPlanAccount(tok);
|
|
2272
|
+
if (!tok.projectId) return;
|
|
2273
|
+
|
|
2274
|
+
const headers = agBootstrapHeaders(tok.accessToken);
|
|
2275
|
+
const body = JSON.stringify({ project: tok.projectId });
|
|
2276
|
+
const [modelsRes, summaryRes] = await Promise.all([
|
|
2277
|
+
upstreamRequest(`${AG.apiBase}/v1internal:fetchAvailableModels`, headers, body).catch((e) => ({ ok: false, status: 0, err: e })),
|
|
2278
|
+
upstreamRequest(`${AG.apiBase}/v1internal:retrieveUserQuotaSummary`, headers, body).catch((e) => ({ ok: false, status: 0, err: e })),
|
|
2279
|
+
agRefreshPlanAccount(tok),
|
|
2280
|
+
]);
|
|
2281
|
+
|
|
2282
|
+
if (!modelsRes.ok) {
|
|
2283
|
+
rt.quota.error = modelsRes.err ? modelsRes.err.message : `fetchAvailableModels ${modelsRes.status}`;
|
|
2284
|
+
log(`antigravity[${tag}]: fetchAvailableModels falhou (${rt.quota.error})`);
|
|
2285
|
+
return;
|
|
2286
|
+
}
|
|
2287
|
+
const j = JSON.parse(await modelsRes.text());
|
|
2288
|
+
const all = j.models || {};
|
|
2289
|
+
rt.quota.at = Date.now();
|
|
2290
|
+
rt.quota.error = null;
|
|
2291
|
+
rt.quota.defaultModel = j.defaultAgentModelId || null;
|
|
2292
|
+
rt.quota.models = {};
|
|
2293
|
+
const now = Date.now();
|
|
2294
|
+
for (const [id, v] of Object.entries(all)) {
|
|
2295
|
+
const q = v && v.quotaInfo;
|
|
2296
|
+
if (!q) continue;
|
|
2297
|
+
// Em proto3 JSON, remainingFraction == 0 (cota zerada) e omitido e o objeto
|
|
2298
|
+
// vem apenas com {"resetTime": "..."}.
|
|
2299
|
+
const frac = typeof q.remainingFraction === 'number' ? q.remainingFraction : (q.resetTime ? 0 : null);
|
|
2300
|
+
if (frac === null) continue;
|
|
2301
|
+
rt.quota.models[id] = { remainingFraction: frac, resetTime: q.resetTime || null };
|
|
2302
|
+
const bucket = agQuotaBucketKey(id);
|
|
2303
|
+
if (frac <= 0 && q.resetTime) {
|
|
2304
|
+
const resetMs = Date.parse(q.resetTime);
|
|
2305
|
+
if (resetMs > now) agMarkCooldown(acct, null, id, resetMs, 'quota_0');
|
|
2306
|
+
} else if (frac > 0) {
|
|
2307
|
+
// Cota voltou: limpa cooldowns antigos de quota_0 para este modelo/bucket.
|
|
2308
|
+
const prevW = rt.cooldowns.get(id);
|
|
2309
|
+
if (prevW && prevW.reason !== 'soft_429') rt.cooldowns.delete(id);
|
|
2310
|
+
const prevB = rt.cooldowns.get(bucket);
|
|
2311
|
+
if (prevB && prevB.reason !== 'soft_429') rt.cooldowns.delete(bucket);
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
|
|
2315
|
+
if (summaryRes.ok) {
|
|
2316
|
+
try {
|
|
2317
|
+
const qs = JSON.parse(await summaryRes.text());
|
|
2318
|
+
rt.quota.groups = Array.isArray(qs.groups) ? qs.groups : [];
|
|
2319
|
+
rt.quota.description = qs.description || null;
|
|
2320
|
+
} catch {}
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
for (const m of MODELS.filter((x) => x.provider === 'antigravity')) {
|
|
2324
|
+
const served = (m.tiers || []).filter((t) => rt.quota.models[`${m.wire}-${t}`]);
|
|
2325
|
+
if (served.length) {
|
|
2326
|
+
const prev = Array.isArray(m.served) ? m.served : [];
|
|
2327
|
+
m.served = [...new Set([...prev, ...served])];
|
|
2328
|
+
}
|
|
2329
|
+
if (!served.length) {
|
|
2330
|
+
log(`antigravity[${tag}]: ${m.id} indisponivel no catalogo da conta agora`);
|
|
2331
|
+
continue;
|
|
2332
|
+
}
|
|
2333
|
+
const q = rt.quota.models[`${m.wire}-${served[served.length - 1]}`];
|
|
2334
|
+
const pct = Math.round(q.remainingFraction * 1000) / 10;
|
|
2335
|
+
const reset = q.resetTime ? new Date(q.resetTime).toISOString() : 'sem reset';
|
|
2336
|
+
log(`antigravity[${tag}]: quota ${m.id} [${served.join(',')}] ${pct}% restante (volta em ${reset})`);
|
|
2337
|
+
}
|
|
2338
|
+
for (const g of rt.quota.groups) {
|
|
2339
|
+
const parts = (g.buckets || []).map((b) => {
|
|
2340
|
+
const pct = typeof b.remainingFraction === 'number' ? `${Math.round(b.remainingFraction * 1000) / 10}%` : (b.resetTime ? '0%' : '?');
|
|
2341
|
+
return `${b.window || b.bucketId}=${pct} (reset ${b.resetTime || '-'})`;
|
|
2342
|
+
});
|
|
2343
|
+
if (parts.length) log(`antigravity[${tag}]: grupo "${g.displayName}": ${parts.join(' | ')}`);
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
async function agDiscover(force = true) {
|
|
2348
|
+
await Promise.all(agStore.accounts.map((a) => agDiscoverAccount(a, force)));
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
// Descobre o projectId do Cloud Code. Sem ele o upstream devolve 404 em tudo.
|
|
2352
|
+
// Mesmo caminho do OmniRoute: loadCodeAssist, onboardUser se nao houver
|
|
2353
|
+
// projeto, e loadCodeAssist de novo depois do onboarding.
|
|
2354
|
+
async function agBootstrapProject(accessToken) {
|
|
2355
|
+
const headers = agBootstrapHeaders(accessToken);
|
|
2356
|
+
const meta = agMetadata();
|
|
2357
|
+
let project = '';
|
|
2358
|
+
let tier = 'legacy-tier';
|
|
2359
|
+
let paidTier = '';
|
|
2360
|
+
let paidTierName = '';
|
|
2361
|
+
let credits = [];
|
|
2362
|
+
|
|
2363
|
+
const readTiers = (j) => {
|
|
2364
|
+
tier = (j.currentTier && (j.currentTier.id || j.currentTier.name)) || tier;
|
|
2365
|
+
paidTier = (j.paidTier && (j.paidTier.id || j.paidTier.name)) || paidTier;
|
|
2366
|
+
paidTierName = (j.paidTier && j.paidTier.name) || paidTierName;
|
|
2367
|
+
if (j.paidTier && Array.isArray(j.paidTier.availableCredits)) credits = j.paidTier.availableCredits;
|
|
2368
|
+
};
|
|
2369
|
+
|
|
2370
|
+
for (let i = 0; i < 3 && !project; i++) {
|
|
2371
|
+
try {
|
|
2372
|
+
const res = await upstreamRequest(`${AG.bootstrapBase}/v1internal:loadCodeAssist`, headers, JSON.stringify({ metadata: meta }));
|
|
2373
|
+
const txt = await res.text();
|
|
2374
|
+
if (res.ok) {
|
|
2375
|
+
const j = JSON.parse(txt);
|
|
2376
|
+
project = agProjectOf(j);
|
|
2377
|
+
readTiers(j);
|
|
2378
|
+
log(`antigravity: loadCodeAssist project=${project || '-'} tier=${tier} paidTier=${paidTier || '-'}`);
|
|
2379
|
+
} else {
|
|
2380
|
+
log(`antigravity: loadCodeAssist ${res.status}`, txt.slice(0, 200));
|
|
2381
|
+
}
|
|
2382
|
+
} catch (e) {
|
|
2383
|
+
log('antigravity: loadCodeAssist falhou:', e.message);
|
|
2384
|
+
}
|
|
2385
|
+
if (!project) await sleep(1500);
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
if (!project) {
|
|
2389
|
+
for (let i = 0; i < 3 && !project; i++) {
|
|
2390
|
+
try {
|
|
2391
|
+
const res = await upstreamRequest(`${AG.bootstrapBase}/v1internal:onboardUser`, headers, JSON.stringify({ tier_id: tier, metadata: meta }));
|
|
2392
|
+
const txt = await res.text();
|
|
2393
|
+
log(`antigravity: onboardUser ${res.status}`, txt.slice(0, 160));
|
|
2394
|
+
if (res.ok) {
|
|
2395
|
+
try { project = agProjectOf(JSON.parse(txt)); } catch {}
|
|
2396
|
+
await sleep(1200);
|
|
2397
|
+
const r2 = await upstreamRequest(`${AG.bootstrapBase}/v1internal:loadCodeAssist`, headers, JSON.stringify({ metadata: meta }));
|
|
2398
|
+
if (r2.ok) {
|
|
2399
|
+
const j2 = JSON.parse(await r2.text());
|
|
2400
|
+
project = agProjectOf(j2) || project;
|
|
2401
|
+
readTiers(j2);
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
} catch (e) {
|
|
2405
|
+
log('antigravity: onboardUser falhou:', e.message);
|
|
2406
|
+
}
|
|
2407
|
+
if (!project) await sleep(1500);
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2411
|
+
return { project, tier, paidTier, paidTierName, credits };
|
|
2412
|
+
}
|
|
2413
|
+
|
|
2414
|
+
function agNewState() {
|
|
2415
|
+
const now = Date.now();
|
|
2416
|
+
for (const [s, entry] of AG_PENDING) {
|
|
2417
|
+
if (!entry || entry.expiresAt < now) AG_PENDING.delete(s);
|
|
2418
|
+
}
|
|
2419
|
+
const state = crypto.randomBytes(8).toString('hex');
|
|
2420
|
+
AG_PENDING.set(state, {
|
|
2421
|
+
expiresAt: now + 30 * 60 * 1000,
|
|
2422
|
+
status: 'pending',
|
|
2423
|
+
account: null,
|
|
2424
|
+
error: null,
|
|
2425
|
+
});
|
|
2426
|
+
return state;
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
function agShortLoginUrl(state) {
|
|
2430
|
+
return `http://127.0.0.1:${CFG.port}/antigravity/go/${state}`;
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
function agLoginUrl(state = agNewState()) {
|
|
2434
|
+
const p = new URLSearchParams({
|
|
2435
|
+
client_id: AG.clientId,
|
|
2436
|
+
response_type: 'code',
|
|
2437
|
+
redirect_uri: agRedirectUri(),
|
|
2438
|
+
scope: AG.scopes.join(' '),
|
|
2439
|
+
state,
|
|
2440
|
+
access_type: 'offline',
|
|
2441
|
+
prompt: 'select_account consent',
|
|
2442
|
+
});
|
|
2443
|
+
return `${AG.authorizeUrl}?${p.toString()}`;
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
async function agUserInfo(accessToken) {
|
|
2447
|
+
try {
|
|
2448
|
+
const res = await fetch(`${AG.userInfoUrl}?alt=json`, {
|
|
2449
|
+
headers: { authorization: `Bearer ${accessToken}` },
|
|
2450
|
+
signal: AbortSignal.timeout(15000),
|
|
2451
|
+
});
|
|
2452
|
+
if (!res.ok) return {};
|
|
2453
|
+
return await res.json();
|
|
2454
|
+
} catch {
|
|
2455
|
+
return {};
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
async function agFinishLogin(code, state) {
|
|
2460
|
+
const entry = AG_PENDING.get(state);
|
|
2461
|
+
if (!entry || entry.expiresAt < Date.now()) {
|
|
2462
|
+
throw new Error('state de login invalido ou expirado; abra /antigravity/login de novo');
|
|
2463
|
+
}
|
|
2464
|
+
if (entry.status === 'complete' && entry.account) {
|
|
2465
|
+
return agFindAccount(entry.account.email || entry.account.id) || entry.account;
|
|
2466
|
+
}
|
|
2467
|
+
|
|
2468
|
+
try {
|
|
2469
|
+
const res = await agPostForm(AG.tokenUrl, {
|
|
2470
|
+
grant_type: 'authorization_code',
|
|
2471
|
+
client_id: AG.clientId,
|
|
2472
|
+
client_secret: AG.clientSecret,
|
|
2473
|
+
code,
|
|
2474
|
+
redirect_uri: agRedirectUri(),
|
|
2475
|
+
});
|
|
2476
|
+
const txt = await res.text();
|
|
2477
|
+
if (!res.ok) throw new Error(`troca do code falhou (${res.status}): ${txt.slice(0, 300)}`);
|
|
2478
|
+
const j = JSON.parse(txt);
|
|
2479
|
+
if (!j.access_token) throw new Error('troca do code sem access_token');
|
|
2480
|
+
|
|
2481
|
+
const ttl = Number(j.expires_in) > 0 ? Number(j.expires_in) : 3500;
|
|
2482
|
+
const rawAcct = {
|
|
2483
|
+
accessToken: j.access_token,
|
|
2484
|
+
refreshToken: j.refresh_token || '',
|
|
2485
|
+
scope: j.scope || AG.scopes.join(' '),
|
|
2486
|
+
expiresAt: Date.now() + (ttl - 60) * 1000,
|
|
2487
|
+
createdAt: new Date().toISOString(),
|
|
2488
|
+
email: '',
|
|
2489
|
+
projectId: '',
|
|
2490
|
+
tier: '',
|
|
2491
|
+
paidTier: '',
|
|
2492
|
+
paidTierName: '',
|
|
2493
|
+
credits: [],
|
|
2494
|
+
};
|
|
2495
|
+
|
|
2496
|
+
const info = await agUserInfo(j.access_token);
|
|
2497
|
+
if (info && info.email) rawAcct.email = info.email;
|
|
2498
|
+
|
|
2499
|
+
const boot = await agBootstrapProject(j.access_token);
|
|
2500
|
+
rawAcct.projectId = boot.project;
|
|
2501
|
+
rawAcct.tier = boot.tier;
|
|
2502
|
+
rawAcct.paidTier = boot.paidTier;
|
|
2503
|
+
rawAcct.paidTierName = boot.paidTierName;
|
|
2504
|
+
rawAcct.credits = boot.credits;
|
|
2505
|
+
rawAcct.updatedAt = new Date().toISOString();
|
|
2506
|
+
|
|
2507
|
+
const saved = agUpsertAccount(rawAcct);
|
|
2508
|
+
entry.status = 'complete';
|
|
2509
|
+
entry.account = agPublicAccount(saved);
|
|
2510
|
+
entry.expiresAt = Date.now() + 10 * 60 * 1000;
|
|
2511
|
+
log(`antigravity: login ok ${saved.email || '(sem email)'} project=${saved.projectId || '-'} tier=${saved.tier || '-'} paidTier=${saved.paidTier || '-'} (total contas=${agStore.accounts.length})`);
|
|
2512
|
+
agDiscoverAccount(saved, true).catch(() => {});
|
|
2513
|
+
if (!saved.projectId) {
|
|
2514
|
+
log('antigravity: conta sem projectId do Cloud Code; os pedidos vao falhar ate o projeto existir. Rode o login do CLI oficial (agy login) nessa conta e tente de novo.');
|
|
2515
|
+
}
|
|
2516
|
+
return saved;
|
|
2517
|
+
} catch (err) {
|
|
2518
|
+
entry.status = 'failed';
|
|
2519
|
+
entry.error = err.message;
|
|
2520
|
+
entry.expiresAt = Date.now() + 10 * 60 * 1000;
|
|
2521
|
+
throw err;
|
|
2522
|
+
}
|
|
2523
|
+
}
|
|
2524
|
+
|
|
2525
|
+
// Gera UUID deterministico para a sessao/conversa (prompt_cache_key do OpenCode
|
|
2526
|
+
// ou hash do inicio da conversa). Manter sessionId e trajectory_id estaveis
|
|
2527
|
+
// entre turnos maximiza o prompt cache implicito no Cloud Code.
|
|
2528
|
+
function agUuidFromSeed(seed) {
|
|
2529
|
+
const b = crypto.createHash('sha256').update(String(seed || 'antigravity')).digest();
|
|
2530
|
+
b[6] = (b[6] & 0x0f) | 0x40;
|
|
2531
|
+
b[8] = (b[8] & 0x3f) | 0x80;
|
|
2532
|
+
const hex = b.subarray(0, 16).toString('hex');
|
|
2533
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
2534
|
+
}
|
|
2535
|
+
|
|
2536
|
+
function agConversationIds(body, system, contents, acct = agActiveAccount()) {
|
|
2537
|
+
const acctKey = (acct && (acct.email || acct.projectId || acct.id)) || 'antigravity';
|
|
2538
|
+
const cacheKey = (typeof body.prompt_cache_key === 'string' && body.prompt_cache_key.trim())
|
|
2539
|
+
|| (typeof body.session_id === 'string' && body.session_id.trim())
|
|
2540
|
+
|| (typeof body.user === 'string' && body.user.trim())
|
|
2541
|
+
|| '';
|
|
2542
|
+
if (cacheKey) {
|
|
2543
|
+
const id = agUuidFromSeed(`${acctKey}:key:${cacheKey}`);
|
|
2544
|
+
return { sessionId: id, trajectoryId: id };
|
|
2545
|
+
}
|
|
2546
|
+
const firstUser = contents.find((c) => c && c.role === 'user');
|
|
2547
|
+
const firstText = firstUser && Array.isArray(firstUser.parts)
|
|
2548
|
+
? firstUser.parts.map((p) => (p && typeof p.text === 'string' ? p.text : '')).join('\n').slice(0, 512)
|
|
2549
|
+
: '';
|
|
2550
|
+
const id = agUuidFromSeed(`${acctKey}:conv:${String(system || '').slice(0, 512)}:${firstText}`);
|
|
2551
|
+
return { sessionId: id, trajectoryId: id };
|
|
2552
|
+
}
|
|
2553
|
+
|
|
2554
|
+
function agTextOf(content) {
|
|
2555
|
+
if (typeof content === 'string') return content;
|
|
2556
|
+
if (Array.isArray(content)) {
|
|
2557
|
+
return content
|
|
2558
|
+
.map((p) => (p && typeof p.text === 'string' ? p.text : ''))
|
|
2559
|
+
.filter(Boolean)
|
|
2560
|
+
.join('\n');
|
|
2561
|
+
}
|
|
2562
|
+
return '';
|
|
2563
|
+
}
|
|
2564
|
+
|
|
2565
|
+
// Schema de ferramenta no formato que o Cloud Code aceita: sem meta-chaves de
|
|
2566
|
+
// JSON Schema 2020-12, tipo em minuscula, required preservado.
|
|
2567
|
+
function agCleanSchema(schema) {
|
|
2568
|
+
if (!schema || typeof schema !== 'object') return schema;
|
|
2569
|
+
if (Array.isArray(schema)) return schema.map(agCleanSchema);
|
|
2570
|
+
const drop = new Set([
|
|
2571
|
+
'$schema', '$defs', 'definitions', '$ref', '$comment', 'const',
|
|
2572
|
+
'additionalProperties', 'propertyNames', 'patternProperties',
|
|
2573
|
+
'title', 'strict', 'examples', 'default', 'exclusiveMinimum',
|
|
2574
|
+
'exclusiveMaximum', 'contentMediaType', 'contentEncoding', 'deprecated',
|
|
2575
|
+
]);
|
|
2576
|
+
const out = {};
|
|
2577
|
+
for (const [k, v] of Object.entries(schema)) {
|
|
2578
|
+
if (drop.has(k) || k.startsWith('x-')) continue;
|
|
2579
|
+
if (k === 'properties' && v && typeof v === 'object' && !Array.isArray(v)) {
|
|
2580
|
+
const props = {};
|
|
2581
|
+
for (const [name, sub] of Object.entries(v)) props[name] = agCleanSchema(sub);
|
|
2582
|
+
out.properties = props;
|
|
2583
|
+
} else if (k === 'required' && Array.isArray(v)) {
|
|
2584
|
+
out.required = v.filter((x) => typeof x === 'string');
|
|
2585
|
+
} else if (k === 'type' && Array.isArray(v)) {
|
|
2586
|
+
const first = v.find((t) => t !== 'null') || 'string';
|
|
2587
|
+
out.type = String(first).toLowerCase();
|
|
2588
|
+
if (v.includes('null')) out.nullable = true;
|
|
2589
|
+
} else if (k === 'type' && typeof v === 'string') {
|
|
2590
|
+
out.type = v.toLowerCase();
|
|
2591
|
+
} else {
|
|
2592
|
+
out[k] = agCleanSchema(v);
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
if (out.type === 'object' && !out.properties) out.properties = {};
|
|
2596
|
+
if (out.required && (!out.required.length || !out.properties)) delete out.required;
|
|
2597
|
+
return out;
|
|
2598
|
+
}
|
|
2599
|
+
|
|
2600
|
+
const AG_AUDIO_MIME = {
|
|
2601
|
+
wav: 'audio/wav',
|
|
2602
|
+
wave: 'audio/wav',
|
|
2603
|
+
mp3: 'audio/mpeg',
|
|
2604
|
+
mpeg: 'audio/mpeg',
|
|
2605
|
+
ogg: 'audio/ogg',
|
|
2606
|
+
opus: 'audio/opus',
|
|
2607
|
+
flac: 'audio/flac',
|
|
2608
|
+
m4a: 'audio/m4a',
|
|
2609
|
+
mp4: 'audio/mp4',
|
|
2610
|
+
aac: 'audio/aac',
|
|
2611
|
+
amr: 'audio/amr',
|
|
2612
|
+
webm: 'audio/webm',
|
|
2613
|
+
aiff: 'audio/aiff',
|
|
2614
|
+
};
|
|
2615
|
+
|
|
2616
|
+
function agMimeFromName(filename, fallback = 'application/octet-stream') {
|
|
2617
|
+
const ext = String(filename || '').toLowerCase().split('.').pop();
|
|
2618
|
+
const map = {
|
|
2619
|
+
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', heic: 'image/heic', heif: 'image/heif',
|
|
2620
|
+
mp4: 'video/mp4', webm: 'video/webm', mov: 'video/mp4',
|
|
2621
|
+
pdf: 'application/pdf', txt: 'text/plain', md: 'text/markdown', csv: 'text/csv', json: 'application/json',
|
|
2622
|
+
...AG_AUDIO_MIME,
|
|
2623
|
+
};
|
|
2624
|
+
return map[ext] || fallback;
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
async function agMediaPart(url, defaultMime = 'image/png') {
|
|
2628
|
+
if (!url || typeof url !== 'string') return null;
|
|
2629
|
+
const m = /^data:([^;,]+)?(?:;[^;,]*)*?(;base64)?,(.*)$/s.exec(url);
|
|
2630
|
+
if (m) {
|
|
2631
|
+
const mimeType = m[1] || defaultMime;
|
|
2632
|
+
if (m[2]) return { inlineData: { mimeType, data: m[3] } };
|
|
2633
|
+
return { inlineData: { mimeType, data: Buffer.from(decodeURIComponent(m[3])).toString('base64') } };
|
|
2634
|
+
}
|
|
2635
|
+
if (/^https?:\/\//i.test(url)) {
|
|
2636
|
+
try {
|
|
2637
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(30000) });
|
|
2638
|
+
if (!res.ok) return null;
|
|
2639
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
2640
|
+
if (buf.length > 50 * 1024 * 1024) return null;
|
|
2641
|
+
const mimeType = (res.headers.get('content-type') || defaultMime).split(';')[0].trim();
|
|
2642
|
+
return { inlineData: { mimeType, data: buf.toString('base64') } };
|
|
2643
|
+
} catch {
|
|
2644
|
+
return null;
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
return null;
|
|
2648
|
+
}
|
|
2649
|
+
|
|
2650
|
+
async function agParts(content) {
|
|
2651
|
+
if (content === null || content === undefined) return [];
|
|
2652
|
+
if (typeof content === 'string') return content ? [{ text: content }] : [];
|
|
2653
|
+
if (!Array.isArray(content)) return [];
|
|
2654
|
+
const parts = [];
|
|
2655
|
+
for (const p of content) {
|
|
2656
|
+
if (!p) continue;
|
|
2657
|
+
if (typeof p === 'string') { if (p) parts.push({ text: p }); continue; }
|
|
2658
|
+
if (typeof p.text === 'string') { if (p.text) parts.push({ text: p.text }); continue; }
|
|
2659
|
+
// Imagem: OpenAI chat (image_url) e responses (input_image)
|
|
2660
|
+
if ((p.type === 'image_url' || p.type === 'input_image') && p.image_url) {
|
|
2661
|
+
const u = typeof p.image_url === 'string' ? p.image_url : p.image_url.url;
|
|
2662
|
+
const part = await agMediaPart(u, 'image/png');
|
|
2663
|
+
if (part) parts.push(part);
|
|
2664
|
+
continue;
|
|
2665
|
+
}
|
|
2666
|
+
// Audio: OpenAI input_audio ({ data, format }) ou audio_url
|
|
2667
|
+
if (p.type === 'input_audio' && p.input_audio && p.input_audio.data) {
|
|
2668
|
+
const fmt = String(p.input_audio.format || 'wav').toLowerCase().replace(/^audio\//, '');
|
|
2669
|
+
const mimeType = AG_AUDIO_MIME[fmt] || `audio/${fmt}`;
|
|
2670
|
+
const raw = String(p.input_audio.data);
|
|
2671
|
+
const part = raw.startsWith('data:') ? await agMediaPart(raw, mimeType) : { inlineData: { mimeType, data: raw } };
|
|
2672
|
+
if (part) parts.push(part);
|
|
2673
|
+
continue;
|
|
2674
|
+
}
|
|
2675
|
+
if ((p.type === 'audio_url' || p.type === 'input_audio_url') && p.audio_url) {
|
|
2676
|
+
const u = typeof p.audio_url === 'string' ? p.audio_url : p.audio_url.url;
|
|
2677
|
+
const part = await agMediaPart(u, 'audio/mpeg');
|
|
2678
|
+
if (part) parts.push(part);
|
|
2679
|
+
continue;
|
|
2680
|
+
}
|
|
2681
|
+
// Video: video_url / input_video
|
|
2682
|
+
if ((p.type === 'video_url' || p.type === 'input_video') && p.video_url) {
|
|
2683
|
+
const u = typeof p.video_url === 'string' ? p.video_url : p.video_url.url;
|
|
2684
|
+
const part = await agMediaPart(u, 'video/mp4');
|
|
2685
|
+
if (part) parts.push(part);
|
|
2686
|
+
continue;
|
|
2687
|
+
}
|
|
2688
|
+
// Arquivos / PDF / midias genericas enviadas pelo OpenCode (type: "file" ou "input_file")
|
|
2689
|
+
if (p.type === 'file' && p.file) {
|
|
2690
|
+
const src = p.file.file_data || p.file.file_url || p.file.data || '';
|
|
2691
|
+
const defMime = p.file.mime_type || agMimeFromName(p.file.filename, 'application/pdf');
|
|
2692
|
+
const part = src.startsWith('data:') || /^https?:\/\//i.test(src)
|
|
2693
|
+
? await agMediaPart(src, defMime)
|
|
2694
|
+
: (src ? { inlineData: { mimeType: defMime, data: src } } : null);
|
|
2695
|
+
if (part) parts.push(part);
|
|
2696
|
+
continue;
|
|
2697
|
+
}
|
|
2698
|
+
if (p.type === 'input_file') {
|
|
2699
|
+
const src = p.file_data || p.file_url || '';
|
|
2700
|
+
const defMime = p.mime_type || agMimeFromName(p.filename, 'application/pdf');
|
|
2701
|
+
const part = src.startsWith('data:') || /^https?:\/\//i.test(src)
|
|
2702
|
+
? await agMediaPart(src, defMime)
|
|
2703
|
+
: (src ? { inlineData: { mimeType: defMime, data: src } } : null);
|
|
2704
|
+
if (part) parts.push(part);
|
|
2705
|
+
continue;
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
return parts;
|
|
2709
|
+
}
|
|
2710
|
+
|
|
2711
|
+
function agTools(tools) {
|
|
2712
|
+
if (!Array.isArray(tools) || !tools.length) return null;
|
|
2713
|
+
const decls = [];
|
|
2714
|
+
for (const t of tools) {
|
|
2715
|
+
const fn = t && (t.function || (t.type === 'function' ? t : null));
|
|
2716
|
+
if (!fn || !fn.name) continue;
|
|
2717
|
+
const d = { name: fn.name };
|
|
2718
|
+
if (fn.description) d.description = String(fn.description).slice(0, 4000);
|
|
2719
|
+
d.parameters = agCleanSchema(fn.parameters || { type: 'object', properties: {} });
|
|
2720
|
+
decls.push(d);
|
|
2721
|
+
}
|
|
2722
|
+
return decls.length ? [{ functionDeclarations: decls }] : null;
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
function agFinish(reason, hasTools) {
|
|
2726
|
+
if (!reason) return hasTools ? 'tool_calls' : 'stop';
|
|
2727
|
+
const r = String(reason).toUpperCase();
|
|
2728
|
+
if (r === 'MAX_TOKENS') return 'length';
|
|
2729
|
+
if (r === 'SAFETY' || r === 'RECITATION' || r === 'BLOCKLIST' || r === 'PROHIBITED_CONTENT') return 'content_filter';
|
|
2730
|
+
if (r === 'MALFORMED_FUNCTION_CALL') return 'tool_calls';
|
|
2731
|
+
return hasTools ? 'tool_calls' : 'stop';
|
|
2732
|
+
}
|
|
2733
|
+
|
|
2734
|
+
function agUsage(um) {
|
|
2735
|
+
if (!um) return null;
|
|
2736
|
+
const prompt = Number(um.promptTokenCount) || 0;
|
|
2737
|
+
const cached = Number(um.cachedContentTokenCount) || 0;
|
|
2738
|
+
const thoughts = Number(um.thoughtsTokenCount) || 0;
|
|
2739
|
+
const candidates = Number(um.candidatesTokenCount) || 0;
|
|
2740
|
+
const total = Number(um.totalTokenCount) || (prompt + candidates + thoughts);
|
|
2741
|
+
const out = {
|
|
2742
|
+
prompt_tokens: prompt,
|
|
2743
|
+
completion_tokens: candidates + thoughts,
|
|
2744
|
+
total_tokens: total,
|
|
2745
|
+
};
|
|
2746
|
+
if (cached > 0) out.prompt_tokens_details = { cached_tokens: cached };
|
|
2747
|
+
if (thoughts > 0) out.completion_tokens_details = { reasoning_tokens: thoughts };
|
|
2748
|
+
return out;
|
|
2749
|
+
}
|
|
2750
|
+
|
|
2751
|
+
function agResolveWire(body, model) {
|
|
2752
|
+
const fromName = extractTierFromModelName(body.model, model);
|
|
2753
|
+
const rawEffort = String(body.reasoning_effort || fromName || '').toLowerCase();
|
|
2754
|
+
const effort = AG_TIER_ORDER.includes(rawEffort) ? rawEffort : String(CFG.reasoning || 'high').toLowerCase();
|
|
2755
|
+
const tier = agTier(effort, model.tiers);
|
|
2756
|
+
return { tier, wire: `${model.wire}-${tier}` };
|
|
2757
|
+
}
|
|
2758
|
+
|
|
2759
|
+
// OpenAI (chat.completions) -> envelope Cloud Code.
|
|
2760
|
+
async function agEnvelope(body, model, acct = agActiveAccount()) {
|
|
2761
|
+
if (!acct || (!acct.accessToken && !acct.refreshToken)) throw new Error('sem login do Antigravity');
|
|
2762
|
+
if (!acct.projectId) throw new Error(`conta ${acct.email || acct.id} sem projectId do Cloud Code; rode /antigravity/login e, se persistir, o login do CLI oficial uma vez`);
|
|
2763
|
+
|
|
2764
|
+
const rawMsgs = Array.isArray(body.messages) ? body.messages : [];
|
|
2765
|
+
// O OpenCode compacta no limite de model.context (400k). Aqui no bridge so
|
|
2766
|
+
// cortamos se passar do teto REAL do modelo na API (wireContext: 1M / 1.048M),
|
|
2767
|
+
// porque cortar turnos do inicio perto de 400k (estimativa chars/3.2) quebra
|
|
2768
|
+
// o prefixo do prompt cache e manda ~300k tokens frios de uma vez (429).
|
|
2769
|
+
const ctxLimit = Number(model.wireContext) || Number(model.context) || Number(CFG.contextTokens) || 400000;
|
|
2770
|
+
const budget = Math.max(4096, ctxLimit - 8192);
|
|
2771
|
+
const trim = trimToContext(rawMsgs, budget, body.tools);
|
|
2772
|
+
const msgs = trim.messages;
|
|
2773
|
+
if (trim.dropped) {
|
|
2774
|
+
log(`antigravity: trimToContext cortou ${trim.dropped} msgs (${trim.before}->${trim.after} tokens estimados, limite=${ctxLimit})`);
|
|
2775
|
+
}
|
|
2776
|
+
let system = '';
|
|
2777
|
+
const contents = [];
|
|
2778
|
+
const names = new Map();
|
|
2779
|
+
const push = (role, parts) => {
|
|
2780
|
+
if (!parts.length) return;
|
|
2781
|
+
const last = contents[contents.length - 1];
|
|
2782
|
+
if (last && last.role === role) last.parts.push(...parts);
|
|
2783
|
+
else contents.push({ role, parts });
|
|
2784
|
+
};
|
|
2785
|
+
|
|
2786
|
+
for (const msg of msgs) {
|
|
2787
|
+
if (!msg) continue;
|
|
2788
|
+
if (msg.role === 'system' || msg.role === 'developer') {
|
|
2789
|
+
const t = agTextOf(msg.content);
|
|
2790
|
+
if (t) system = system ? system + '\n\n' + t : t;
|
|
2791
|
+
continue;
|
|
2792
|
+
}
|
|
2793
|
+
if (msg.role === 'user') {
|
|
2794
|
+
push('user', await agParts(msg.content));
|
|
2795
|
+
continue;
|
|
2796
|
+
}
|
|
2797
|
+
if (msg.role === 'assistant') {
|
|
2798
|
+
const parts = await agParts(msg.content);
|
|
2799
|
+
if (Array.isArray(msg.tool_calls)) {
|
|
2800
|
+
for (const tc of msg.tool_calls) {
|
|
2801
|
+
const fn = tc && tc.function;
|
|
2802
|
+
if (!fn || !fn.name) continue;
|
|
2803
|
+
const id = tc.id || `call_${rid()}`;
|
|
2804
|
+
names.set(id, fn.name);
|
|
2805
|
+
let args = {};
|
|
2806
|
+
try { args = typeof fn.arguments === 'string' ? JSON.parse(fn.arguments || '{}') : (fn.arguments || {}); } catch { args = {}; }
|
|
2807
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) args = {};
|
|
2808
|
+
parts.push({
|
|
2809
|
+
thoughtSignature: 'skip_thought_signature_validator',
|
|
2810
|
+
functionCall: { id, name: fn.name, args },
|
|
2811
|
+
});
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
push('model', parts);
|
|
2815
|
+
continue;
|
|
2816
|
+
}
|
|
2817
|
+
if (msg.role === 'tool' || msg.role === 'function') {
|
|
2818
|
+
const id = msg.tool_call_id || msg.name || `call_${rid()}`;
|
|
2819
|
+
const name = msg.name || names.get(msg.tool_call_id) || names.get(id) || 'unknown';
|
|
2820
|
+
// Sempre envia o retorno da tool como string em response.result (sem JSON.parse).
|
|
2821
|
+
// No Gemini/Cloud Code, objetos {"$ref": "..."} dentro de functionResponse.response
|
|
2822
|
+
// sao interpretados como referencia multimodal para functionResponse.parts[].display_name,
|
|
2823
|
+
// causando 400 INVALID_ARGUMENT quando a tool retorna JSON/OpenAPI com "$ref".
|
|
2824
|
+
const text = agTextOf(msg.content);
|
|
2825
|
+
push('user', [{
|
|
2826
|
+
functionResponse: {
|
|
2827
|
+
id: msg.tool_call_id || id,
|
|
2828
|
+
name,
|
|
2829
|
+
response: { result: text },
|
|
2830
|
+
},
|
|
2831
|
+
}]);
|
|
2832
|
+
continue;
|
|
2833
|
+
}
|
|
2834
|
+
}
|
|
2835
|
+
|
|
2836
|
+
while (contents.length > 1 && contents[contents.length - 1].role === 'model') contents.pop();
|
|
2837
|
+
if (!contents.length) contents.push({ role: 'user', parts: [{ text: ' ' }] });
|
|
2838
|
+
if (contents[contents.length - 1].role === 'model') contents.push({ role: 'user', parts: [{ text: ' ' }] });
|
|
2839
|
+
|
|
2840
|
+
const maxOut = Math.min(
|
|
2841
|
+
Math.max(Number(body.max_tokens ?? body.max_completion_tokens) || 8192, 1),
|
|
2842
|
+
Number(model.maxOut) || 65536
|
|
2843
|
+
);
|
|
2844
|
+
|
|
2845
|
+
const conv = agConversationIds(body, system, contents, acct);
|
|
2846
|
+
const request = {
|
|
2847
|
+
contents,
|
|
2848
|
+
sessionId: conv.sessionId,
|
|
2849
|
+
};
|
|
2850
|
+
if (system) request.systemInstruction = { role: 'system', parts: [{ text: system }] };
|
|
2851
|
+
|
|
2852
|
+
const tools = agTools(body.tools);
|
|
2853
|
+
if (tools) {
|
|
2854
|
+
request.tools = tools;
|
|
2855
|
+
request.toolConfig = { functionCallingConfig: { mode: 'VALIDATED' } };
|
|
2856
|
+
}
|
|
2857
|
+
|
|
2858
|
+
// O tier desta familia mais proximo do esforco pedido (Neon/Hydrogen -> ate xhigh; Claude 5.5 -> ate high).
|
|
2859
|
+
const { tier, wire } = agResolveWire(body, model);
|
|
2860
|
+
|
|
2861
|
+
const gen = { maxOutputTokens: maxOut };
|
|
2862
|
+
if (typeof body.temperature === 'number') gen.temperature = body.temperature;
|
|
2863
|
+
if (typeof body.top_p === 'number') gen.topP = body.top_p;
|
|
2864
|
+
if (typeof body.top_k === 'number') gen.topK = body.top_k;
|
|
2865
|
+
if (body.stop !== undefined) {
|
|
2866
|
+
gen.stopSequences = Array.isArray(body.stop) ? body.stop.slice(0, 5) : [String(body.stop)];
|
|
2867
|
+
}
|
|
2868
|
+
const isClaude = /^claude/i.test(model.wire || '');
|
|
2869
|
+
// Extraido de codeassistclient.marshalCCPARequest no binario agy:
|
|
2870
|
+
// LOW=1, MEDIUM=2, HIGH=3 (strings), EXTRA_HIGH=5 / MAX=6 (enviados como
|
|
2871
|
+
// numero de enum no JSON para valores GOOGLE_INTERNAL).
|
|
2872
|
+
const AG_THINKING_WIRE = { low: 'LOW', medium: 'MEDIUM', high: 'HIGH', xhigh: 5, max: 6 };
|
|
2873
|
+
if (!isClaude && model.reasoning) {
|
|
2874
|
+
gen.thinkingConfig = { includeThoughts: true, thinkingLevel: AG_THINKING_WIRE[tier] ?? 'HIGH' };
|
|
2875
|
+
}
|
|
2876
|
+
request.generationConfig = gen;
|
|
2877
|
+
|
|
2878
|
+
const agentId = crypto.randomUUID();
|
|
2879
|
+
const trajectoryId = conv.trajectoryId;
|
|
2880
|
+
const labels = {
|
|
2881
|
+
last_step_index: String(contents.length),
|
|
2882
|
+
trajectory_id: trajectoryId,
|
|
2883
|
+
used_claude: String(isClaude),
|
|
2884
|
+
used_claude_conservative: String(isClaude),
|
|
2885
|
+
};
|
|
2886
|
+
request.labels = labels;
|
|
2887
|
+
|
|
2888
|
+
return {
|
|
2889
|
+
project: acct.projectId,
|
|
2890
|
+
requestId: `agent/${agentId}/${Date.now()}/${trajectoryId}/2`,
|
|
2891
|
+
request,
|
|
2892
|
+
model: wire,
|
|
2893
|
+
userAgent: 'antigravity',
|
|
2894
|
+
requestType: 'agent',
|
|
2895
|
+
};
|
|
2896
|
+
}
|
|
2897
|
+
|
|
2898
|
+
function agRequest(acct, envelope, signal) {
|
|
2899
|
+
return upstreamRequest(`${AG.apiBase}/v1internal:streamGenerateContent?alt=sse`, {
|
|
2900
|
+
authorization: `Bearer ${acct.accessToken}`,
|
|
2901
|
+
'content-type': 'application/json',
|
|
2902
|
+
accept: 'text/event-stream',
|
|
2903
|
+
'user-agent': AG.ua,
|
|
2904
|
+
}, JSON.stringify(envelope), { signal });
|
|
2905
|
+
}
|
|
2906
|
+
|
|
2907
|
+
// Chama o upstream usando uma conta especifica. Quando ha outra conta disponivel
|
|
2908
|
+
// (hasMoreAccounts=true), qualquer esgotamento de quota (429) ou credencial
|
|
2909
|
+
// revogada devolve `{ ok: false, failover: true }` para o roteador trocar de
|
|
2910
|
+
// conta imediatamente na mesma requisicao.
|
|
2911
|
+
async function agCallForAccount(acct, model, envelope, signal, hasMoreAccounts = false) {
|
|
2912
|
+
const tag = acct.email || acct.id;
|
|
2913
|
+
const rt = agRuntime(acct);
|
|
2914
|
+
let n = 0;
|
|
2915
|
+
let authFails = 0;
|
|
2916
|
+
for (;;) {
|
|
2917
|
+
if (signal?.aborted) throw new Error('cliente desconectou');
|
|
2918
|
+
try {
|
|
2919
|
+
await agRefreshAccount(acct, false);
|
|
2920
|
+
} catch (e) {
|
|
2921
|
+
if (signal?.aborted) throw e;
|
|
2922
|
+
if (hasMoreAccounts && ++authFails >= 2) {
|
|
2923
|
+
log(`antigravity[${tag}]: refresh falhou (${e.message}); trocando de conta`);
|
|
2924
|
+
return { ok: false, status: 401, failover: true, errorText: e.message };
|
|
2925
|
+
}
|
|
2926
|
+
log(`antigravity[${tag}]: ${e.message}; tentativa ${++n} em ${RETRY_MS}ms`);
|
|
2927
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
2928
|
+
continue;
|
|
2929
|
+
}
|
|
2930
|
+
let res;
|
|
2931
|
+
try {
|
|
2932
|
+
res = await agRequest(acct, envelope, signal);
|
|
2933
|
+
} catch (e) {
|
|
2934
|
+
if (signal?.aborted) throw e;
|
|
2935
|
+
log(`antigravity[${tag}]: rede falhou (${e.message}); tentativa ${++n} em ${RETRY_MS}ms`);
|
|
2936
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
2937
|
+
continue;
|
|
2938
|
+
}
|
|
2939
|
+
if (res.status === 401 || res.status === 403) {
|
|
2940
|
+
const t = await res.text().catch(() => '');
|
|
2941
|
+
log(`antigravity[${tag}]: upstream ${res.status} (${t.slice(0, 160)}); renovando token`);
|
|
2942
|
+
try {
|
|
2943
|
+
await agRefreshAccount(acct, true);
|
|
2944
|
+
} catch (e) {
|
|
2945
|
+
log(`antigravity[${tag}]: refresh falhou:`, e.message);
|
|
2946
|
+
if (hasMoreAccounts) return { ok: false, status: res.status, failover: true, errorText: t || e.message };
|
|
2947
|
+
}
|
|
2948
|
+
if (hasMoreAccounts && ++authFails >= 2) {
|
|
2949
|
+
return { ok: false, status: res.status, failover: true, errorText: t || `HTTP ${res.status}` };
|
|
2950
|
+
}
|
|
2951
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
2952
|
+
continue;
|
|
2953
|
+
}
|
|
2954
|
+
if (res.status === 429) {
|
|
2955
|
+
const t = await res.text().catch(() => '');
|
|
2956
|
+
const ra = res.headers.get('retry-after');
|
|
2957
|
+
rt.quota.error = `upstream 429 em ${new Date().toISOString()}${ra ? `; retry-after=${ra}s` : ''}`;
|
|
2958
|
+
const hardQuota = /individual quota|quota reached|QUOTA_EXHAUSTED|resets in/i.test(t) && !/MODEL_CAPACITY_EXHAUSTED|capacity/i.test(t);
|
|
2959
|
+
const parsedReset = agParseResetMs(t, ra);
|
|
2960
|
+
const maxRetries = hasMoreAccounts ? 1 : 4;
|
|
2961
|
+
if (hardQuota || n >= maxRetries) {
|
|
2962
|
+
const until = parsedReset || (hardQuota ? Date.now() + 10 * 60 * 1000 : Date.now() + 60 * 1000);
|
|
2963
|
+
agMarkCooldown(acct, model, envelope.model, until, hardQuota ? 'hard_429' : 'soft_429');
|
|
2964
|
+
agDiscoverAccount(acct, true).catch(() => {});
|
|
2965
|
+
log(`antigravity[${tag}]: 429 para ${envelope.model} (hardQuota=${hardQuota}, tentativas=${n}, failover=${hasMoreAccounts}): ${t.slice(0, 200)}`);
|
|
2966
|
+
return { ok: false, status: 429, failover: hasMoreAccounts, resetUntil: until, errorText: t || 'Quota exhausted (429)' };
|
|
2967
|
+
}
|
|
2968
|
+
const backoff = RETRY_MS * Math.pow(2, n);
|
|
2969
|
+
const waitMs = Math.min(15000, Math.max(backoff, (Number(ra) || 0) * 1000));
|
|
2970
|
+
log(`antigravity[${tag}]: upstream 429 transitorio${ra ? ` retry-after=${ra}s` : ''} (${t.slice(0, 160)}); tentativa ${++n}/${maxRetries} em ${waitMs}ms`);
|
|
2971
|
+
await sleepAbortable(waitMs, signal);
|
|
2972
|
+
continue;
|
|
2973
|
+
}
|
|
2974
|
+
if (res.status >= 500) {
|
|
2975
|
+
const t = await res.text().catch(() => '');
|
|
2976
|
+
if (hasMoreAccounts && n >= 2) {
|
|
2977
|
+
log(`antigravity[${tag}]: upstream ${res.status} apos ${n} tentativas; tentando outra conta`);
|
|
2978
|
+
return { ok: false, status: res.status, failover: true, errorText: t };
|
|
2979
|
+
}
|
|
2980
|
+
log(`antigravity[${tag}]: upstream ${res.status} (${t.slice(0, 160)}); tentativa ${++n} em ${RETRY_MS}ms`);
|
|
2981
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
2982
|
+
continue;
|
|
2983
|
+
}
|
|
2984
|
+
if (res.status === 400 || res.status === 404 || res.status === 422) {
|
|
2985
|
+
const t = await res.text().catch(() => '');
|
|
2986
|
+
if (/token|credential|unauthenticated|invalid auth|oauth/i.test(t)) {
|
|
2987
|
+
log(`antigravity[${tag}]: ${res.status} de credencial (${t.slice(0, 120)}); renovando e repetindo`);
|
|
2988
|
+
try { await agRefreshAccount(acct, true); } catch {}
|
|
2989
|
+
if (hasMoreAccounts && ++authFails >= 2) {
|
|
2990
|
+
return { ok: false, status: res.status, failover: true, errorText: t };
|
|
2991
|
+
}
|
|
2992
|
+
await sleepAbortable(RETRY_MS, signal);
|
|
2993
|
+
continue;
|
|
2994
|
+
}
|
|
2995
|
+
log(`antigravity[${tag}]: upstream ${res.status}`, t.slice(0, 300));
|
|
2996
|
+
return { ok: false, status: res.status, failover: false, errorText: t };
|
|
2997
|
+
}
|
|
2998
|
+
return res;
|
|
2999
|
+
}
|
|
3000
|
+
}
|
|
3001
|
+
|
|
3002
|
+
function agLinePayload(line) {
|
|
3003
|
+
const s = line.endsWith('\r') ? line.slice(0, -1) : line;
|
|
3004
|
+
if (!s.startsWith('data:')) return null;
|
|
3005
|
+
const payload = s.slice(5).trim();
|
|
3006
|
+
if (!payload || payload === '[DONE]') return null;
|
|
3007
|
+
try { return JSON.parse(payload); } catch { return null; }
|
|
3008
|
+
}
|
|
3009
|
+
|
|
3010
|
+
function agPiece(j) {
|
|
3011
|
+
const r = j && j.response ? j.response : j;
|
|
3012
|
+
if (!r || !Array.isArray(r.candidates) || !r.candidates.length) {
|
|
3013
|
+
return { parts: [], finish: null, usage: r && r.usageMetadata };
|
|
3014
|
+
}
|
|
3015
|
+
const c = r.candidates[0] || {};
|
|
3016
|
+
const parts = (c.content && Array.isArray(c.content.parts)) ? c.content.parts : [];
|
|
3017
|
+
return { parts, finish: c.finishReason || null, usage: r.usageMetadata || null };
|
|
3018
|
+
}
|
|
3019
|
+
|
|
3020
|
+
async function agProxyStream(up, res, info) {
|
|
3021
|
+
const t0 = Date.now();
|
|
3022
|
+
const outModel = info.model.id;
|
|
3023
|
+
const streamId = 'chatcmpl-' + info.id;
|
|
3024
|
+
res.writeHead(200, {
|
|
3025
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
3026
|
+
'cache-control': 'no-cache, no-transform',
|
|
3027
|
+
connection: 'keep-alive',
|
|
3028
|
+
'x-accel-buffering': 'no',
|
|
3029
|
+
...CORS,
|
|
3030
|
+
});
|
|
3031
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
3032
|
+
|
|
3033
|
+
const write = (s) => { if (!res.writableEnded && !res.destroyed) res.write(s); };
|
|
3034
|
+
const emit = (delta, finish = null) => {
|
|
3035
|
+
write('data: ' + JSON.stringify({
|
|
3036
|
+
id: streamId,
|
|
3037
|
+
object: 'chat.completion.chunk',
|
|
3038
|
+
created: Math.floor(Date.now() / 1000),
|
|
3039
|
+
model: outModel,
|
|
3040
|
+
choices: [{ index: 0, delta, finish_reason: finish }],
|
|
3041
|
+
}) + '\n\n');
|
|
3042
|
+
};
|
|
3043
|
+
|
|
3044
|
+
emit({ role: 'assistant' });
|
|
3045
|
+
|
|
3046
|
+
const reader = up.body.getReader();
|
|
3047
|
+
const dec = new TextDecoder('utf-8');
|
|
3048
|
+
let buf = '';
|
|
3049
|
+
let bytes = 0;
|
|
3050
|
+
let events = 0;
|
|
3051
|
+
let contentChars = 0;
|
|
3052
|
+
let reasoningChars = 0;
|
|
3053
|
+
let toolCalls = 0;
|
|
3054
|
+
let finish = null;
|
|
3055
|
+
let lastUsage = null;
|
|
3056
|
+
let lastByte = Date.now();
|
|
3057
|
+
let aborted = false;
|
|
3058
|
+
|
|
3059
|
+
const watchdog = setInterval(() => {
|
|
3060
|
+
if (Date.now() - lastByte > CFG.idleTimeoutMs) {
|
|
3061
|
+
aborted = true;
|
|
3062
|
+
try { up.body.cancel(); } catch {}
|
|
3063
|
+
}
|
|
3064
|
+
}, 30000);
|
|
3065
|
+
if (watchdog.unref) watchdog.unref();
|
|
3066
|
+
res.on('close', () => {
|
|
3067
|
+
if (!res.writableEnded) {
|
|
3068
|
+
aborted = true;
|
|
3069
|
+
try { up.body.cancel(); } catch {}
|
|
3070
|
+
}
|
|
3071
|
+
});
|
|
3072
|
+
|
|
3073
|
+
try {
|
|
3074
|
+
while (!aborted) {
|
|
3075
|
+
const r = await reader.read();
|
|
3076
|
+
if (r.done) break;
|
|
3077
|
+
const chunk = r.value;
|
|
3078
|
+
if (!chunk) continue;
|
|
3079
|
+
bytes += chunk.length;
|
|
3080
|
+
lastByte = Date.now();
|
|
3081
|
+
buf += dec.decode(chunk, { stream: true });
|
|
3082
|
+
let idx;
|
|
3083
|
+
while ((idx = buf.indexOf('\n')) >= 0) {
|
|
3084
|
+
const line = buf.slice(0, idx);
|
|
3085
|
+
buf = buf.slice(idx + 1);
|
|
3086
|
+
const j = agLinePayload(line);
|
|
3087
|
+
if (!j) continue;
|
|
3088
|
+
events++;
|
|
3089
|
+
const piece = agPiece(j);
|
|
3090
|
+
for (const part of piece.parts) {
|
|
3091
|
+
if (!part) continue;
|
|
3092
|
+
if (part.thought === true && typeof part.text === 'string') {
|
|
3093
|
+
if (part.text) { reasoningChars += part.text.length; emit({ reasoning_content: part.text }); }
|
|
3094
|
+
continue;
|
|
3095
|
+
}
|
|
3096
|
+
if (typeof part.text === 'string') {
|
|
3097
|
+
if (part.text) { contentChars += part.text.length; emit({ content: part.text }); }
|
|
3098
|
+
continue;
|
|
3099
|
+
}
|
|
3100
|
+
if (part.functionCall && part.functionCall.name) {
|
|
3101
|
+
const n = toolCalls++;
|
|
3102
|
+
const callId = part.functionCall.id || `${info.id}-${n}`;
|
|
3103
|
+
const args = part.functionCall.args && typeof part.functionCall.args === 'object'
|
|
3104
|
+
? JSON.stringify(part.functionCall.args)
|
|
3105
|
+
: String(part.functionCall.args || '{}');
|
|
3106
|
+
emit({
|
|
3107
|
+
tool_calls: [{
|
|
3108
|
+
index: n,
|
|
3109
|
+
id: String(callId),
|
|
3110
|
+
type: 'function',
|
|
3111
|
+
function: { name: part.functionCall.name, arguments: args },
|
|
3112
|
+
}],
|
|
3113
|
+
});
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
if (piece.finish && !finish) finish = piece.finish;
|
|
3117
|
+
const usage = agUsage(piece.usage);
|
|
3118
|
+
if (usage) lastUsage = usage;
|
|
3119
|
+
}
|
|
3120
|
+
}
|
|
3121
|
+
} catch (e) {
|
|
3122
|
+
if (!aborted) log(`antigravity: stream falhou (${e.message})`);
|
|
3123
|
+
} finally {
|
|
3124
|
+
clearInterval(watchdog);
|
|
3125
|
+
}
|
|
3126
|
+
|
|
3127
|
+
if (lastUsage) agTrackUsage(info.wire, lastUsage, info.account);
|
|
3128
|
+
|
|
3129
|
+
if (!res.writableEnded && !res.destroyed) {
|
|
3130
|
+
const reason = agFinish(finish, toolCalls > 0);
|
|
3131
|
+
emit({}, reason);
|
|
3132
|
+
if (lastUsage) {
|
|
3133
|
+
write('data: ' + JSON.stringify({
|
|
3134
|
+
id: streamId,
|
|
3135
|
+
object: 'chat.completion.chunk',
|
|
3136
|
+
created: Math.floor(Date.now() / 1000),
|
|
3137
|
+
model: outModel,
|
|
3138
|
+
choices: [],
|
|
3139
|
+
usage: lastUsage,
|
|
3140
|
+
}) + '\n\n');
|
|
3141
|
+
}
|
|
3142
|
+
write('data: [DONE]\n\n');
|
|
3143
|
+
try { res.end(); } catch {}
|
|
3144
|
+
}
|
|
3145
|
+
|
|
3146
|
+
const dur = Date.now() - t0;
|
|
3147
|
+
const cachedTok = lastUsage?.prompt_tokens_details?.cached_tokens || 0;
|
|
3148
|
+
log(
|
|
3149
|
+
`ag ${info.id}: ${dur}ms bytes=${bytes} eventos=${events}` +
|
|
3150
|
+
` content=${contentChars} reasoning=${reasoningChars} toolCalls=${toolCalls}` +
|
|
3151
|
+
(cachedTok ? ` cached=${cachedTok}` : '') +
|
|
3152
|
+
` finish=${finish || 'null'} cancelado=${aborted}`
|
|
3153
|
+
);
|
|
3154
|
+
}
|
|
3155
|
+
|
|
3156
|
+
function agCollect(text, modelId, wire, acct = null) {
|
|
3157
|
+
const out = {
|
|
3158
|
+
id: 'chatcmpl-' + rid(),
|
|
3159
|
+
object: 'chat.completion',
|
|
3160
|
+
created: Math.floor(Date.now() / 1000),
|
|
3161
|
+
model: modelId,
|
|
3162
|
+
choices: [{ index: 0, message: { role: 'assistant', content: '' }, finish_reason: null }],
|
|
3163
|
+
usage: null,
|
|
3164
|
+
};
|
|
3165
|
+
let src = String(text || '');
|
|
3166
|
+
const whole = src.trim();
|
|
3167
|
+
if (whole.startsWith('{')) {
|
|
3168
|
+
try {
|
|
3169
|
+
const j = JSON.parse(whole);
|
|
3170
|
+
if (j && (j.response || j.candidates)) src = 'data: ' + whole + '\n';
|
|
3171
|
+
} catch {}
|
|
3172
|
+
}
|
|
3173
|
+
let content = '';
|
|
3174
|
+
let reasoning = '';
|
|
3175
|
+
let finish = null;
|
|
3176
|
+
let usage = null;
|
|
3177
|
+
const calls = [];
|
|
3178
|
+
for (const line of src.split('\n')) {
|
|
3179
|
+
const j = agLinePayload(line);
|
|
3180
|
+
if (!j) continue;
|
|
3181
|
+
const piece = agPiece(j);
|
|
3182
|
+
for (const part of piece.parts) {
|
|
3183
|
+
if (!part) continue;
|
|
3184
|
+
if (part.thought === true && typeof part.text === 'string') { reasoning += part.text; continue; }
|
|
3185
|
+
if (typeof part.text === 'string') { content += part.text; continue; }
|
|
3186
|
+
if (part.functionCall && part.functionCall.name) {
|
|
3187
|
+
const n = calls.length;
|
|
3188
|
+
const args = part.functionCall.args && typeof part.functionCall.args === 'object'
|
|
3189
|
+
? JSON.stringify(part.functionCall.args)
|
|
3190
|
+
: String(part.functionCall.args || '{}');
|
|
3191
|
+
calls.push({
|
|
3192
|
+
id: String(part.functionCall.id || `call_${n}`),
|
|
3193
|
+
type: 'function',
|
|
3194
|
+
function: { name: part.functionCall.name, arguments: args },
|
|
3195
|
+
});
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
if (piece.finish) finish = piece.finish;
|
|
3199
|
+
const u = agUsage(piece.usage);
|
|
3200
|
+
if (u) usage = u;
|
|
3201
|
+
}
|
|
3202
|
+
const msg = { role: 'assistant', content };
|
|
3203
|
+
if (reasoning) msg.reasoning_content = reasoning;
|
|
3204
|
+
if (calls.length) msg.tool_calls = calls;
|
|
3205
|
+
out.choices[0].message = msg;
|
|
3206
|
+
out.choices[0].finish_reason = agFinish(finish, calls.length > 0);
|
|
3207
|
+
if (usage) {
|
|
3208
|
+
out.usage = usage;
|
|
3209
|
+
agTrackUsage(wire, usage, acct);
|
|
3210
|
+
}
|
|
3211
|
+
return out;
|
|
3212
|
+
}
|
|
3213
|
+
|
|
3214
|
+
async function handleAntigravityChat(body, model, res, reqAbort, preferredHint = '') {
|
|
3215
|
+
const sendJson = (code, obj) => {
|
|
3216
|
+
if (res.writableEnded) return;
|
|
3217
|
+
res.writeHead(code, { 'content-type': 'application/json', ...CORS });
|
|
3218
|
+
res.end(JSON.stringify(obj));
|
|
3219
|
+
};
|
|
3220
|
+
if (!agLogged()) {
|
|
3221
|
+
return sendJson(401, {
|
|
3222
|
+
error: {
|
|
3223
|
+
message: `antigravity: sem login. Use /connect no OpenCode (Kimi Bridge) ou abra http://127.0.0.1:${CFG.port}/antigravity/login.`,
|
|
3224
|
+
type: 'antigravity_login_required',
|
|
3225
|
+
},
|
|
3226
|
+
});
|
|
3227
|
+
}
|
|
3228
|
+
|
|
3229
|
+
const { wire } = agResolveWire(body, model);
|
|
3230
|
+
let { available, exhausted } = agSelectAccounts(model, wire, preferredHint);
|
|
3231
|
+
|
|
3232
|
+
// Se todas as contas constam sem quota, reconsulta uma vez o upstream caso
|
|
3233
|
+
// alguma ja tenha voltado antes do esperado.
|
|
3234
|
+
if (!available.length && exhausted.length) {
|
|
3235
|
+
await agDiscover(true).catch(() => {});
|
|
3236
|
+
({ available, exhausted } = agSelectAccounts(model, wire, preferredHint));
|
|
3237
|
+
}
|
|
3238
|
+
|
|
3239
|
+
if (!available.length) {
|
|
3240
|
+
exhausted.sort((a, b) => (a.until || Infinity) - (b.until || Infinity));
|
|
3241
|
+
const earliest = exhausted[0];
|
|
3242
|
+
const sec = earliest && earliest.until ? Math.max(0, Math.round((earliest.until - Date.now()) / 1000)) : null;
|
|
3243
|
+
const when = earliest && earliest.until
|
|
3244
|
+
? `${earliest.acct.email || earliest.acct.id} em ${agFormatDuration(sec)} (${new Date(earliest.until).toISOString()})`
|
|
3245
|
+
: 'aguarde o reset da janela';
|
|
3246
|
+
const msg = `Todas as ${agStore.accounts.length} conta(s) Antigravity estao sem quota para ${wire}. Proximo reset: ${when}.`;
|
|
3247
|
+
log(`antigravity: ${msg}`);
|
|
3248
|
+
return sendJson(429, { error: { message: msg, type: 'antigravity_quota_exhausted', code: 429 } });
|
|
3249
|
+
}
|
|
3250
|
+
|
|
3251
|
+
const id = rid();
|
|
3252
|
+
const t0 = Date.now();
|
|
3253
|
+
const stream = body.stream !== false;
|
|
3254
|
+
let lastErr = null;
|
|
3255
|
+
|
|
3256
|
+
for (let i = 0; i < available.length; i++) {
|
|
3257
|
+
if (reqAbort.signal.aborted) return;
|
|
3258
|
+
const acct = available[i];
|
|
3259
|
+
const tag = acct.email || acct.id;
|
|
3260
|
+
const hasMore = i + 1 < available.length;
|
|
3261
|
+
|
|
3262
|
+
try {
|
|
3263
|
+
await agRefreshAccount(acct, false);
|
|
3264
|
+
if (!acct.projectId) await agRefreshPlanAccount(acct);
|
|
3265
|
+
} catch (e) {
|
|
3266
|
+
log(`req ${id}: conta ${tag} falhou no refresh (${e.message})${hasMore ? '; tentando proxima conta' : ''}`);
|
|
3267
|
+
lastErr = { status: 401, errorText: e.message };
|
|
3268
|
+
if (hasMore) continue;
|
|
3269
|
+
return sendJson(401, { error: { message: e.message, type: 'antigravity_auth_error', code: 401 } });
|
|
3270
|
+
}
|
|
3271
|
+
|
|
3272
|
+
let envelope;
|
|
3273
|
+
try {
|
|
3274
|
+
envelope = await agEnvelope(body, model, acct);
|
|
3275
|
+
} catch (e) {
|
|
3276
|
+
if (hasMore && /projectId|sem login/i.test(e.message)) {
|
|
3277
|
+
log(`req ${id}: conta ${tag} indisponivel (${e.message}); tentando proxima conta`);
|
|
3278
|
+
lastErr = { status: 400, errorText: e.message };
|
|
3279
|
+
continue;
|
|
3280
|
+
}
|
|
3281
|
+
return sendJson(400, { error: { message: e.message, type: 'antigravity_request' } });
|
|
3282
|
+
}
|
|
3283
|
+
|
|
3284
|
+
log(
|
|
3285
|
+
`req ${id}: model=${model.id} wire=${envelope.model} provider=antigravity acct=${tag}` +
|
|
3286
|
+
(agStore.accounts.length > 1 ? ` (${i + 1}/${available.length})` : '') +
|
|
3287
|
+
` stream=${stream} contents=${envelope.request.contents.length}` +
|
|
3288
|
+
` tools=${envelope.request.tools ? envelope.request.tools[0].functionDeclarations.length : 0}` +
|
|
3289
|
+
` max_tokens=${envelope.request.generationConfig.maxOutputTokens}`
|
|
3290
|
+
);
|
|
3291
|
+
|
|
3292
|
+
let up;
|
|
3293
|
+
try {
|
|
3294
|
+
up = await agCallForAccount(acct, model, envelope, reqAbort.signal, hasMore);
|
|
3295
|
+
} catch (e) {
|
|
3296
|
+
if (reqAbort.signal.aborted) return;
|
|
3297
|
+
log(`req ${id}: antigravity[${tag}] falhou:`, e.message);
|
|
3298
|
+
if (hasMore) { lastErr = { status: 502, errorText: e.message }; continue; }
|
|
3299
|
+
return sendJson(502, { error: { message: e.message, type: 'antigravity_error' } });
|
|
3300
|
+
}
|
|
3301
|
+
|
|
3302
|
+
if (reqAbort.signal.aborted) {
|
|
3303
|
+
try { await up.body?.cancel(); } catch {}
|
|
3304
|
+
return;
|
|
3305
|
+
}
|
|
3306
|
+
|
|
3307
|
+
if (!up.ok) {
|
|
3308
|
+
lastErr = up;
|
|
3309
|
+
if (up.failover && hasMore) {
|
|
3310
|
+
const nextTag = available[i + 1].email || available[i + 1].id;
|
|
3311
|
+
const waitStr = up.resetUntil ? agFormatDuration(Math.max(0, Math.round((up.resetUntil - Date.now()) / 1000))) : null;
|
|
3312
|
+
log(`req ${id}: conta ${tag} indisponivel/sem quota${waitStr ? ` (volta em ~${waitStr})` : ''}; trocando automaticamente para ${nextTag}`);
|
|
3313
|
+
continue;
|
|
3314
|
+
}
|
|
3315
|
+
log(`req ${id}: erro upstream`, String(up.errorText || '').slice(0, 400));
|
|
3316
|
+
return sendJson(up.status || 400, {
|
|
3317
|
+
error: { message: String(up.errorText || 'upstream error').slice(0, 1200), type: 'upstream_error', code: up.status || 400 },
|
|
3318
|
+
});
|
|
3319
|
+
}
|
|
3320
|
+
|
|
3321
|
+
log(`req ${id}: upstream ${up.status} (${tag}) ${up.headers.get('content-type') || ''} em ${Date.now() - t0}ms`);
|
|
3322
|
+
if (!stream) {
|
|
3323
|
+
const text = await up.text();
|
|
3324
|
+
return sendJson(200, agCollect(text, model.id, envelope.model, acct));
|
|
3325
|
+
}
|
|
3326
|
+
return agProxyStream(up, res, { id, model, wire: envelope.model, account: acct });
|
|
3327
|
+
}
|
|
3328
|
+
|
|
3329
|
+
return sendJson(lastErr?.status || 429, {
|
|
3330
|
+
error: {
|
|
3331
|
+
message: String(lastErr?.errorText || `Todas as contas Antigravity falharam para ${wire}`).slice(0, 1200),
|
|
3332
|
+
type: 'antigravity_failover_exhausted',
|
|
3333
|
+
code: lastErr?.status || 429,
|
|
3334
|
+
},
|
|
3335
|
+
});
|
|
3336
|
+
}
|
|
3337
|
+
|
|
3338
|
+
async function proxyStream(upstream, res, info) {
|
|
3339
|
+
const t0 = Date.now();
|
|
3340
|
+
const tag = info.part ? `${info.id}/c${info.part}` : info.id;
|
|
3341
|
+
// O id que o cliente pediu volta em cada chunk; o apiModel so vai para
|
|
3342
|
+
// o upstream no payload.
|
|
3343
|
+
const outModel = info.model?.id || CFG.model;
|
|
3344
|
+
if (!info.skipHead) {
|
|
3345
|
+
res.writeHead(200, {
|
|
3346
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
3347
|
+
'cache-control': 'no-cache, no-transform',
|
|
3348
|
+
connection: 'keep-alive',
|
|
3349
|
+
'x-accel-buffering': 'no',
|
|
3350
|
+
...CORS,
|
|
3351
|
+
});
|
|
3352
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
3353
|
+
}
|
|
3354
|
+
|
|
3355
|
+
const dec = new TextDecoder('utf-8');
|
|
3356
|
+
const rawChunks = [];
|
|
3357
|
+
let rawSize = 0;
|
|
3358
|
+
let buf = '';
|
|
3359
|
+
let bytes = 0;
|
|
3360
|
+
let events = 0;
|
|
3361
|
+
let contentChars = 0;
|
|
3362
|
+
let contentText = '';
|
|
3363
|
+
let reasoningChars = 0;
|
|
3364
|
+
let toolDeltas = 0;
|
|
3365
|
+
let role = null;
|
|
3366
|
+
let finish = null;
|
|
3367
|
+
let finishAt = 0;
|
|
3368
|
+
let streamId = 'chatcmpl-' + info.id;
|
|
3369
|
+
let syntheticFinish = false;
|
|
3370
|
+
let lastPingAt = Date.now();
|
|
3371
|
+
let upstreamDone = false;
|
|
3372
|
+
let sentDone = false;
|
|
3373
|
+
let lastAt = Date.now();
|
|
3374
|
+
let maxGap = 0;
|
|
3375
|
+
let gaps60 = 0;
|
|
3376
|
+
let firstContentMs = null;
|
|
3377
|
+
let firstReasoningMs = null;
|
|
3378
|
+
let error = null;
|
|
3379
|
+
let clientGone = false;
|
|
3380
|
+
let activeReader = null;
|
|
3381
|
+
let abortResolve = null;
|
|
3382
|
+
let watchdogFired = false;
|
|
3383
|
+
let suppressReasoning = false;
|
|
3384
|
+
let continued = false;
|
|
3385
|
+
let roleSent = false;
|
|
3386
|
+
let reclassChars = 0;
|
|
3387
|
+
let dupContent = false;
|
|
3388
|
+
let lastContentOut = '';
|
|
3389
|
+
|
|
3390
|
+
// Marcador que o prompt exige na primeira linha da resposta. So liga o
|
|
3391
|
+
// gate quando o inicio do prompt (system/developer) traz o marcador; num
|
|
3392
|
+
// pedido comum a bridge se comporta como um proxy normal.
|
|
3393
|
+
const MARKER = String(CFG.answerMarker || '').trim();
|
|
3394
|
+
const textoDe = (c) => {
|
|
3395
|
+
if (typeof c === 'string') return c;
|
|
3396
|
+
if (Array.isArray(c)) return c.map((p) => (p && typeof p.text === 'string' ? p.text : '')).join('\n');
|
|
3397
|
+
return '';
|
|
3398
|
+
};
|
|
3399
|
+
const CORE = MARKER.replace(/\*/g, '').trim();
|
|
3400
|
+
const summaryReq = isSummaryRequest(info.payload?.messages);
|
|
3401
|
+
const primeira = Array.isArray(info.payload?.messages) ? info.payload.messages[0] : null;
|
|
3402
|
+
const gateEnabled = !summaryReq && !!CORE && !!primeira && textoDe(primeira.content).includes(CORE);
|
|
3403
|
+
let answerStarted = !gateEnabled;
|
|
3404
|
+
let gateHold = '';
|
|
3405
|
+
let holdAtLineStart = true;
|
|
3406
|
+
|
|
3407
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
3408
|
+
const markerRe = CORE ? new RegExp('\\*{0,2}' + escapeRe(CORE) + '\\*{0,2}', 'g') : null;
|
|
3409
|
+
|
|
3410
|
+
const findMarker = (s, startOk) => {
|
|
3411
|
+
if (!markerRe) return -1;
|
|
3412
|
+
markerRe.lastIndex = 0;
|
|
3413
|
+
let m;
|
|
3414
|
+
while ((m = markerRe.exec(s))) {
|
|
3415
|
+
const i = m.index;
|
|
3416
|
+
if ((i === 0 && startOk) || (i > 0 && s[i - 1] === '\n')) return i;
|
|
3417
|
+
}
|
|
3418
|
+
return -1;
|
|
3419
|
+
};
|
|
3420
|
+
|
|
3421
|
+
// Antes do marcador o texto e raciocinio, mesmo que o upstream tenha
|
|
3422
|
+
// mandado no campo content. O que sobra depois do marcador e resposta.
|
|
3423
|
+
// O final do buffer fica retido por alguns caracteres para o marcador
|
|
3424
|
+
// que chega picado entre deltas.
|
|
3425
|
+
const HOLD = 16;
|
|
3426
|
+
const classifyContent = (text) => {
|
|
3427
|
+
const buf = gateHold + text;
|
|
3428
|
+
const startOk = holdAtLineStart;
|
|
3429
|
+
gateHold = '';
|
|
3430
|
+
holdAtLineStart = false;
|
|
3431
|
+
const idx = findMarker(buf, startOk);
|
|
3432
|
+
if (idx >= 0) {
|
|
3433
|
+
answerStarted = true;
|
|
3434
|
+
return { reason: buf.slice(0, idx), content: buf.slice(idx) };
|
|
3435
|
+
}
|
|
3436
|
+
if (buf.length > HOLD) {
|
|
3437
|
+
const cut = buf.length - HOLD;
|
|
3438
|
+
gateHold = buf.slice(cut);
|
|
3439
|
+
holdAtLineStart = buf[cut - 1] === '\n';
|
|
3440
|
+
return { reason: buf.slice(0, cut) };
|
|
3441
|
+
}
|
|
3442
|
+
gateHold = buf;
|
|
3443
|
+
holdAtLineStart = startOk;
|
|
3444
|
+
return { reason: '' };
|
|
3445
|
+
};
|
|
3446
|
+
|
|
3447
|
+
const write = (s) => {
|
|
3448
|
+
if (clientGone || res.writableEnded) return;
|
|
3449
|
+
try { res.write(s); } catch { clientGone = true; }
|
|
3450
|
+
};
|
|
3451
|
+
|
|
3452
|
+
// Todo chunk que sai da bridge e remontado aqui. O cliente recebe
|
|
3453
|
+
// exatamente o formato OpenAI, sem campo desconhecido do upstream.
|
|
3454
|
+
const emitDelta = (delta) => {
|
|
3455
|
+
const chunk = {
|
|
3456
|
+
id: streamId,
|
|
3457
|
+
object: 'chat.completion.chunk',
|
|
3458
|
+
created: Math.floor(Date.now() / 1000),
|
|
3459
|
+
model: outModel,
|
|
3460
|
+
choices: [{ index: 0, delta, finish_reason: null }],
|
|
3461
|
+
};
|
|
3462
|
+
write('data: ' + JSON.stringify(chunk) + '\n\n');
|
|
3463
|
+
};
|
|
3464
|
+
|
|
3465
|
+
res.on('close', () => {
|
|
3466
|
+
if (!res.writableEnded) {
|
|
3467
|
+
clientGone = true;
|
|
3468
|
+
log(`sse ${tag}: cliente fechou a conexao`);
|
|
3469
|
+
try { abortResolve?.(); } catch {}
|
|
3470
|
+
try { activeReader?.cancel(); } catch {}
|
|
3471
|
+
}
|
|
3472
|
+
});
|
|
3473
|
+
|
|
3474
|
+
const handleLine = (line) => {
|
|
3475
|
+
if (!line.startsWith('data:')) return;
|
|
3476
|
+
let payload = line.slice(5).trim();
|
|
3477
|
+
if (!payload) return;
|
|
3478
|
+
if (payload === '[DONE]') {
|
|
3479
|
+
// Nao repassa na hora: se o stream fechou com finish=length e sem
|
|
3480
|
+
// conteudo, ainda da para pedir a resposta antes de encerrar. O
|
|
3481
|
+
// [DONE] definitivo sai no fechamento.
|
|
3482
|
+
upstreamDone = true;
|
|
3483
|
+
return;
|
|
3484
|
+
}
|
|
3485
|
+
if (upstreamDone) return;
|
|
3486
|
+
events++;
|
|
3487
|
+
const now = Date.now();
|
|
3488
|
+
if (events > 1) {
|
|
3489
|
+
const gap = now - lastAt;
|
|
3490
|
+
if (gap > maxGap) maxGap = gap;
|
|
3491
|
+
if (gap > 60000) gaps60++;
|
|
3492
|
+
}
|
|
3493
|
+
lastAt = now;
|
|
3494
|
+
if (finishAt) finishAt = now;
|
|
3495
|
+
|
|
3496
|
+
let j = null;
|
|
3497
|
+
try { j = JSON.parse(payload); } catch {}
|
|
3498
|
+
if (j?.id) streamId = j.id;
|
|
3499
|
+
const ch = j?.choices?.[0];
|
|
3500
|
+
const d = ch?.delta || {};
|
|
3501
|
+
|
|
3502
|
+
// O raciocinio do upstream vem em "reasoning_content". Nao repetimos o
|
|
3503
|
+
// mesmo texto em "reasoning": cliente que reconhece os dois campos
|
|
3504
|
+
// renderiza o pensamento duas vezes.
|
|
3505
|
+
const reasoningIn = typeof d.reasoning_content === 'string' ? d.reasoning_content : '';
|
|
3506
|
+
let reasonOut = suppressReasoning ? '' : reasoningIn;
|
|
3507
|
+
let contentOut = typeof d.content === 'string' ? d.content : '';
|
|
3508
|
+
|
|
3509
|
+
// Gate do content: enquanto o marcador da resposta nao aparece, o texto
|
|
3510
|
+
// e raciocinio. Conserta o upstream que manda o pensamento no content.
|
|
3511
|
+
let gateReason = '';
|
|
3512
|
+
if (contentOut && gateEnabled && !answerStarted) {
|
|
3513
|
+
const cls = classifyContent(contentOut);
|
|
3514
|
+
contentOut = cls.content || '';
|
|
3515
|
+
gateReason = cls.reason || '';
|
|
3516
|
+
}
|
|
3517
|
+
if (suppressReasoning) gateReason = '';
|
|
3518
|
+
|
|
3519
|
+
// O finish_reason do upstream nunca vai direto para o cliente. Se a
|
|
3520
|
+
// bridge for continuar, o cliente ja teria visto um fim e o conteudo
|
|
3521
|
+
// seguinte apareceria como uma segunda resposta (a duplicata). Guarda o
|
|
3522
|
+
// motivo e emite um unico finish no fechamento.
|
|
3523
|
+
if (ch?.finish_reason) {
|
|
3524
|
+
finish = ch.finish_reason;
|
|
3525
|
+
if (!finishAt) finishAt = Date.now();
|
|
3526
|
+
}
|
|
3527
|
+
|
|
3528
|
+
if (d.role) role = d.role;
|
|
3529
|
+
if (reasonOut) {
|
|
3530
|
+
reasoningChars += reasonOut.length;
|
|
3531
|
+
if (firstReasoningMs === null) firstReasoningMs = now - t0;
|
|
3532
|
+
}
|
|
3533
|
+
if (gateReason) {
|
|
3534
|
+
reclassChars += gateReason.length;
|
|
3535
|
+
reasoningChars += gateReason.length;
|
|
3536
|
+
if (firstReasoningMs === null) firstReasoningMs = now - t0;
|
|
3537
|
+
}
|
|
3538
|
+
if (contentOut) {
|
|
3539
|
+
contentChars += contentOut.length;
|
|
3540
|
+
contentText += contentOut;
|
|
3541
|
+
if (firstContentMs === null) firstContentMs = now - t0;
|
|
3542
|
+
}
|
|
3543
|
+
if (Array.isArray(d.tool_calls)) toolDeltas += d.tool_calls.length;
|
|
3544
|
+
|
|
3545
|
+
const temDelta = !!(gateReason || reasonOut || contentOut || (Array.isArray(d.tool_calls) && d.tool_calls.length));
|
|
3546
|
+
if (temDelta && !roleSent) { emitDelta({ role: role || 'assistant' }); roleSent = true; }
|
|
3547
|
+
if (gateReason) emitDelta({ reasoning_content: gateReason });
|
|
3548
|
+
if (reasonOut) emitDelta({ reasoning_content: reasonOut });
|
|
3549
|
+
if (contentOut) emitDelta({ content: contentOut });
|
|
3550
|
+
if (Array.isArray(d.tool_calls) && d.tool_calls.length) emitDelta({ tool_calls: d.tool_calls });
|
|
3551
|
+
if (j?.usage) {
|
|
3552
|
+
write('data: ' + JSON.stringify({
|
|
3553
|
+
id: streamId,
|
|
3554
|
+
object: 'chat.completion.chunk',
|
|
3555
|
+
created: Math.floor(Date.now() / 1000),
|
|
3556
|
+
model: outModel,
|
|
3557
|
+
choices: [],
|
|
3558
|
+
usage: j.usage,
|
|
3559
|
+
}) + '\n\n');
|
|
3560
|
+
}
|
|
3561
|
+
};
|
|
3562
|
+
|
|
3563
|
+
const watchdog = setInterval(() => {
|
|
3564
|
+
if (clientGone || sentDone || upstreamDone || watchdogFired) return;
|
|
3565
|
+
const now = Date.now();
|
|
3566
|
+
if (finishAt && now - finishAt > 15000) {
|
|
3567
|
+
watchdogFired = true;
|
|
3568
|
+
log(`sse ${tag}: finish_reason sem [DONE] ha ${now - finishAt}ms -> encerrando`);
|
|
3569
|
+
try { abortResolve?.(); } catch {}
|
|
3570
|
+
try { activeReader?.cancel(); } catch {}
|
|
3571
|
+
return;
|
|
3572
|
+
}
|
|
3573
|
+
if (now - lastAt > CFG.idleTimeoutMs) {
|
|
3574
|
+
watchdogFired = true;
|
|
3575
|
+
log(`sse ${tag}: sem eventos ha ${now - lastAt}ms (limite ${CFG.idleTimeoutMs}ms) -> encerrando`);
|
|
3576
|
+
try { abortResolve?.(); } catch {}
|
|
3577
|
+
try { activeReader?.cancel(); } catch {}
|
|
3578
|
+
return;
|
|
3579
|
+
}
|
|
3580
|
+
if (now - lastAt > 8000 && now - lastPingAt > 8000) {
|
|
3581
|
+
lastPingAt = now;
|
|
3582
|
+
write(': ping\n\n');
|
|
3583
|
+
}
|
|
3584
|
+
}, 1000);
|
|
3585
|
+
|
|
3586
|
+
const pump = async (up) => {
|
|
3587
|
+
buf = '';
|
|
3588
|
+
watchdogFired = false;
|
|
3589
|
+
const abortPromise = new Promise((resolve) => { abortResolve = () => resolve({ done: true }); });
|
|
3590
|
+
activeReader = up.body.getReader();
|
|
3591
|
+
try {
|
|
3592
|
+
while (true) {
|
|
3593
|
+
const { done, value } = await Promise.race([activeReader.read(), abortPromise]);
|
|
3594
|
+
if (done) break;
|
|
3595
|
+
if (clientGone) break;
|
|
3596
|
+
bytes += value.byteLength;
|
|
3597
|
+
// Qualquer byte prova atividade: o upstream pode mandar heartbeat
|
|
3598
|
+
// em comentario SSE (": keep-alive") durante pausas longas. Contar
|
|
3599
|
+
// so eventos data: fazia o watchdog matar stream vivo.
|
|
3600
|
+
lastAt = Date.now();
|
|
3601
|
+
if (rawSize < 8 * 1024 * 1024) {
|
|
3602
|
+
rawChunks.push(Buffer.from(value));
|
|
3603
|
+
rawSize += value.byteLength;
|
|
3604
|
+
}
|
|
3605
|
+
buf += dec.decode(value, { stream: true });
|
|
3606
|
+
let nl;
|
|
3607
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
3608
|
+
let line = buf.slice(0, nl);
|
|
3609
|
+
buf = buf.slice(nl + 1);
|
|
3610
|
+
if (line.endsWith('\r')) line = line.slice(0, -1);
|
|
3611
|
+
try { handleLine(line); } catch (e) { error = e.message; }
|
|
3612
|
+
}
|
|
3613
|
+
if (upstreamDone) {
|
|
3614
|
+
try { await activeReader.cancel(); } catch {}
|
|
3615
|
+
break;
|
|
3616
|
+
}
|
|
3617
|
+
}
|
|
3618
|
+
if (buf.trim()) {
|
|
3619
|
+
let line = buf.trim();
|
|
3620
|
+
if (line.endsWith('\r')) line = line.slice(0, -1);
|
|
3621
|
+
try { handleLine(line); } catch (e) { error = e.message; }
|
|
3622
|
+
}
|
|
3623
|
+
} catch (e) {
|
|
3624
|
+
if (!clientGone) error = e.message;
|
|
3625
|
+
log(`sse ${info.id}: erro de leitura:`, e.message, `(ultimo byte ha ${Date.now() - lastAt}ms)`);
|
|
3626
|
+
}
|
|
3627
|
+
};
|
|
3628
|
+
|
|
3629
|
+
await pump(upstream);
|
|
3630
|
+
|
|
3631
|
+
// O que ficou retido no gate nao chegou a virar resposta: era raciocinio
|
|
3632
|
+
// ou um marcador incompleto. Sai como raciocinio.
|
|
3633
|
+
if (gateHold && !suppressReasoning) {
|
|
3634
|
+
reclassChars += gateHold.length;
|
|
3635
|
+
reasoningChars += gateHold.length;
|
|
3636
|
+
emitDelta({ reasoning_content: gateHold });
|
|
3637
|
+
}
|
|
3638
|
+
gateHold = '';
|
|
3639
|
+
|
|
3640
|
+
// O modelo as vezes gasta todo o max_tokens no raciocinio e fecha com
|
|
3641
|
+
// finish=length sem nenhum content. O primeiro stream ja entregou o
|
|
3642
|
+
// pensamento; o segundo pede a resposta com mais espaco e com o
|
|
3643
|
+
// raciocinio suprimido para nao duplicar.
|
|
3644
|
+
// Continuar quando o stream nao entregou NENHUMA resposta: o modelo
|
|
3645
|
+
// gastou o orcamento no raciocinio, ou o upstream rotulou o pensamento
|
|
3646
|
+
// como content e o gate devolveu tudo para o canal de raciocinio. Se ja
|
|
3647
|
+
// saiu content ou tool call, repetir a chamada duplicava a resposta.
|
|
3648
|
+
if (!clientGone && !continued && info.payload && contentChars === 0 && toolDeltas === 0 && reasoningChars > 0 && (finish === 'length' || finish === 'stop' || !finish)) {
|
|
3649
|
+
continued = true;
|
|
3650
|
+
log(`sse ${tag}: finish=${finish || 'null'} content=${contentChars} -> continuando`);
|
|
3651
|
+
suppressReasoning = true;
|
|
3652
|
+
finish = null;
|
|
3653
|
+
finishAt = 0;
|
|
3654
|
+
upstreamDone = false;
|
|
3655
|
+
sentDone = false;
|
|
3656
|
+
lastAt = Date.now();
|
|
3657
|
+
try {
|
|
3658
|
+
const msgs = [...(info.payload.messages || [])];
|
|
3659
|
+
if (contentText.trim()) {
|
|
3660
|
+
msgs.push({ role: 'assistant', content: contentText });
|
|
3661
|
+
msgs.push({ role: 'user', content: 'Continue exatamente de onde parou, sem repetir o que ja foi escrito. Se precisar de uma ferramenta, chame agora.' });
|
|
3662
|
+
}
|
|
3663
|
+
const base = { ...info.payload, messages: msgs, max_tokens: 65536 };
|
|
3664
|
+
if (Array.isArray(base.tools) && base.tools.length) base.tool_choice = 'required';
|
|
3665
|
+
let up2 = await callUpstream({ ...base, reasoning_effort: 'low' }, info.model);
|
|
3666
|
+
if (!up2.ok && (up2.status === 400 || up2.status >= 500)) {
|
|
3667
|
+
const t = await up2.text().catch(() => '');
|
|
3668
|
+
log(`sse ${tag}: continuacao low falhou ${up2.status}`, t.slice(0, 200));
|
|
3669
|
+
up2 = await callUpstream({ ...base, reasoning_effort: 'medium' }, info.model);
|
|
3670
|
+
}
|
|
3671
|
+
if (up2.ok && (up2.headers.get('content-type') || '').includes('text/event-stream')) {
|
|
3672
|
+
await pump(up2);
|
|
3673
|
+
} else {
|
|
3674
|
+
const errText = await up2.text().catch(() => '');
|
|
3675
|
+
log(`sse ${tag}: continuacao falhou status=${up2.status}`, errText.slice(0, 300));
|
|
3676
|
+
}
|
|
3677
|
+
} catch (e) {
|
|
3678
|
+
log(`sse ${tag}: continuacao erro:`, e.message);
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
|
|
3682
|
+
clearInterval(watchdog);
|
|
3683
|
+
const hadUpstreamDone = upstreamDone;
|
|
3684
|
+
if (!clientGone) {
|
|
3685
|
+
// Se o upstream cortou antes do finish_reason, fecha o stream com um
|
|
3686
|
+
// chunk de finish + [DONE]. Sem isso o cliente acha que a resposta
|
|
3687
|
+
// foi interrompida e repete a chamada (a duplicata).
|
|
3688
|
+
// O finish do upstream foi retido; aqui sai o unico finish que o
|
|
3689
|
+
// cliente ve. Se o upstream nao mandou nenhum, sintetiza.
|
|
3690
|
+
const synthetic = finish || (toolDeltas > 0 ? 'tool_calls' : (contentChars > 0 ? 'stop' : (reasoningChars > 0 ? 'length' : 'stop')));
|
|
3691
|
+
const fin = {
|
|
3692
|
+
id: streamId,
|
|
3693
|
+
object: 'chat.completion.chunk',
|
|
3694
|
+
created: Math.floor(Date.now() / 1000),
|
|
3695
|
+
model: outModel,
|
|
3696
|
+
choices: [{ index: 0, delta: {}, finish_reason: synthetic }],
|
|
3697
|
+
};
|
|
3698
|
+
write('data: ' + JSON.stringify(fin) + '\n\n');
|
|
3699
|
+
if (!finish) {
|
|
3700
|
+
finish = synthetic;
|
|
3701
|
+
syntheticFinish = true;
|
|
3702
|
+
}
|
|
3703
|
+
if (!sentDone) {
|
|
3704
|
+
sentDone = true;
|
|
3705
|
+
write('data: [DONE]\n\n');
|
|
3706
|
+
}
|
|
3707
|
+
try { res.end(); } catch {}
|
|
3708
|
+
}
|
|
3709
|
+
|
|
3710
|
+
const dur = Date.now() - t0;
|
|
3711
|
+
// Duplicata de conteudo no que saiu para o cliente: bloco de 120
|
|
3712
|
+
// caracteres que reaparece mais adiante. Prova se a bridge (ou o
|
|
3713
|
+
// upstream) repetiu a resposta.
|
|
3714
|
+
if (contentText.length >= 240) {
|
|
3715
|
+
const bloco = contentText.slice(0, 120);
|
|
3716
|
+
if (contentText.indexOf(bloco, 120) >= 0) dupContent = true;
|
|
3717
|
+
}
|
|
3718
|
+
const anomaly = !hadUpstreamDone || !finish || finish === 'length' || reclassChars > 0 || dupContent || !!error || clientGone || maxGap > 60000;
|
|
3719
|
+
const meta = {
|
|
3720
|
+
id: info.id,
|
|
3721
|
+
ms: dur,
|
|
3722
|
+
bytes,
|
|
3723
|
+
events,
|
|
3724
|
+
contentChars,
|
|
3725
|
+
reasoningChars,
|
|
3726
|
+
toolDeltas,
|
|
3727
|
+
role,
|
|
3728
|
+
finish,
|
|
3729
|
+
syntheticFinish,
|
|
3730
|
+
upstreamDone: hadUpstreamDone,
|
|
3731
|
+
sentDone,
|
|
3732
|
+
maxGapMs: maxGap,
|
|
3733
|
+
gapsOver60s: gaps60,
|
|
3734
|
+
reclassChars,
|
|
3735
|
+
dupContent,
|
|
3736
|
+
firstContentMs,
|
|
3737
|
+
firstReasoningMs,
|
|
3738
|
+
error,
|
|
3739
|
+
clientGone,
|
|
3740
|
+
req: info.req,
|
|
3741
|
+
};
|
|
3742
|
+
state.lastSse = meta;
|
|
3743
|
+
log(
|
|
3744
|
+
`sse ${info.id}: ${dur}ms bytes=${bytes} eventos=${events}` +
|
|
3745
|
+
` content=${contentChars} reasoning=${reasoningChars} toolDeltas=${toolDeltas}` +
|
|
3746
|
+
` finish=${finish || 'null'}${syntheticFinish ? '(sintetizado)' : ''} done=${hadUpstreamDone ? 'sim' : 'nao->sintetizado'}` +
|
|
3747
|
+
` maxGap=${maxGap}ms reclass=${reclassChars} dupContent=${dupContent}` +
|
|
3748
|
+
` primeiroContent=${firstContentMs ?? '-'}ms primeiroReasoning=${firstReasoningMs ?? '-'}ms` +
|
|
3749
|
+
(error ? ` erro=${error}` : '') +
|
|
3750
|
+
(clientGone ? ' clienteSaiu' : '')
|
|
3751
|
+
);
|
|
3752
|
+
if (anomaly) sseDump(info.id, meta, Buffer.concat(rawChunks).toString('utf8'));
|
|
3753
|
+
}
|
|
3754
|
+
|
|
3755
|
+
function collectSse(text, modelId = CFG.model) {
|
|
3756
|
+
const out = {
|
|
3757
|
+
id: 'chatcmpl-' + rid(),
|
|
3758
|
+
object: 'chat.completion',
|
|
3759
|
+
created: Math.floor(Date.now() / 1000),
|
|
3760
|
+
model: modelId,
|
|
3761
|
+
choices: [{ index: 0, message: { role: 'assistant', content: '' }, finish_reason: null }],
|
|
3762
|
+
usage: null,
|
|
3763
|
+
};
|
|
3764
|
+
const texto = (v) => {
|
|
3765
|
+
if (typeof v === 'string') return v;
|
|
3766
|
+
if (Array.isArray(v)) return v.map((p) => (p && typeof p.text === 'string' ? p.text : '')).join('');
|
|
3767
|
+
return '';
|
|
3768
|
+
};
|
|
3769
|
+
// Alguns modelos respondem JSON puro mesmo com "stream": false, as vezes
|
|
3770
|
+
// declarando content-type de SSE. Nesse caso o corpo inteiro ja e a
|
|
3771
|
+
// resposta pronta: nao ha evento para acumular.
|
|
3772
|
+
const whole = text.trim();
|
|
3773
|
+
if (whole.startsWith('{')) {
|
|
3774
|
+
let j = null;
|
|
3775
|
+
try { j = JSON.parse(whole); } catch {}
|
|
3776
|
+
const ch = j && Array.isArray(j.choices) ? j.choices[0] : null;
|
|
3777
|
+
if (ch && (ch.message || ch.delta)) {
|
|
3778
|
+
const m = ch.message || ch.delta || {};
|
|
3779
|
+
const msg = { role: m.role || 'assistant', content: texto(m.content) };
|
|
3780
|
+
if (m.reasoning_content) msg.reasoning_content = m.reasoning_content;
|
|
3781
|
+
else if (m.reasoning) msg.reasoning_content = m.reasoning;
|
|
3782
|
+
if (Array.isArray(m.tool_calls) && m.tool_calls.length) msg.tool_calls = m.tool_calls;
|
|
3783
|
+
out.choices[0] = { index: 0, message: msg, finish_reason: ch.finish_reason || 'stop' };
|
|
3784
|
+
if (j.usage) out.usage = j.usage;
|
|
3785
|
+
return out;
|
|
3786
|
+
}
|
|
3787
|
+
}
|
|
3788
|
+
let content = '';
|
|
3789
|
+
let reasoning = '';
|
|
3790
|
+
let finish = null;
|
|
3791
|
+
const tools = new Map();
|
|
3792
|
+
for (const rawLine of text.split('\n')) {
|
|
3793
|
+
const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
|
|
3794
|
+
if (!line.startsWith('data:')) continue;
|
|
3795
|
+
const payload = line.slice(5).trim();
|
|
3796
|
+
if (!payload || payload === '[DONE]') continue;
|
|
3797
|
+
let j;
|
|
3798
|
+
try { j = JSON.parse(payload); } catch { continue; }
|
|
3799
|
+
const ch = j?.choices?.[0];
|
|
3800
|
+
if (ch) {
|
|
3801
|
+
const d = ch.delta || {};
|
|
3802
|
+
if (d.content) content += d.content;
|
|
3803
|
+
if (d.reasoning_content) reasoning += d.reasoning_content;
|
|
3804
|
+
if (Array.isArray(d.tool_calls)) {
|
|
3805
|
+
for (const tc of d.tool_calls) {
|
|
3806
|
+
const idx = Number.isInteger(tc.index) ? tc.index : 0;
|
|
3807
|
+
const cur = tools.get(idx) || { id: '', type: 'function', function: { name: '', arguments: '' } };
|
|
3808
|
+
if (tc.id) cur.id = tc.id;
|
|
3809
|
+
if (tc.type) cur.type = tc.type;
|
|
3810
|
+
if (tc.function?.name) cur.function.name += tc.function.name;
|
|
3811
|
+
if (tc.function?.arguments) cur.function.arguments += tc.function.arguments;
|
|
3812
|
+
tools.set(idx, cur);
|
|
3813
|
+
}
|
|
3814
|
+
}
|
|
3815
|
+
if (ch.finish_reason) finish = ch.finish_reason;
|
|
3816
|
+
}
|
|
3817
|
+
if (j.usage) out.usage = j.usage;
|
|
3818
|
+
}
|
|
3819
|
+
const msg = { role: 'assistant', content };
|
|
3820
|
+
if (reasoning) msg.reasoning_content = reasoning;
|
|
3821
|
+
if (tools.size) msg.tool_calls = [...tools.entries()].sort((a, b) => a[0] - b[0]).map(([, v]) => v);
|
|
3822
|
+
out.choices[0].message = msg;
|
|
3823
|
+
out.choices[0].finish_reason = finish || 'stop';
|
|
3824
|
+
return out;
|
|
3825
|
+
}
|
|
3826
|
+
|
|
3827
|
+
// ---------- servidor ----------
|
|
3828
|
+
function readBody(req) {
|
|
3829
|
+
return new Promise((resolve, reject) => {
|
|
3830
|
+
const chunks = [];
|
|
3831
|
+
let size = 0;
|
|
3832
|
+
req.on('data', (c) => {
|
|
3833
|
+
size += c.length;
|
|
3834
|
+
if (size > 64 * 1024 * 1024) { reject(new Error('body grande demais')); req.destroy(); return; }
|
|
3835
|
+
chunks.push(c);
|
|
3836
|
+
});
|
|
3837
|
+
req.on('end', () => {
|
|
3838
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
3839
|
+
if (!raw) return resolve({});
|
|
3840
|
+
try { resolve(JSON.parse(raw)); } catch (e) { reject(e); }
|
|
3841
|
+
});
|
|
3842
|
+
req.on('error', reject);
|
|
3843
|
+
});
|
|
3844
|
+
}
|
|
3845
|
+
|
|
3846
|
+
const CORS = {
|
|
3847
|
+
'access-control-allow-origin': '*',
|
|
3848
|
+
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
|
3849
|
+
'access-control-allow-headers': 'content-type, authorization, x-api-key',
|
|
3850
|
+
};
|
|
3851
|
+
|
|
3852
|
+
const server = http.createServer(async (req, res) => {
|
|
3853
|
+
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
|
3854
|
+
const json = (code, obj) => {
|
|
3855
|
+
if (res.writableEnded) return;
|
|
3856
|
+
res.writeHead(code, { 'content-type': 'application/json', ...CORS });
|
|
3857
|
+
res.end(JSON.stringify(obj));
|
|
3858
|
+
};
|
|
3859
|
+
const html = (code, s) => {
|
|
3860
|
+
if (res.writableEnded) return;
|
|
3861
|
+
res.writeHead(code, { 'content-type': 'text/html; charset=utf-8', ...CORS });
|
|
3862
|
+
res.end(s);
|
|
3863
|
+
};
|
|
3864
|
+
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
3865
|
+
// Se o cliente desiste (opencode cancelou, aba fechou), a requisicao que
|
|
3866
|
+
// ainda esta na fila do upstream tem que morrer junto. Sem isso o bridge
|
|
3867
|
+
// continuava retentando sozinho e enchendo a fila do playground.
|
|
3868
|
+
const reqAbort = new AbortController();
|
|
3869
|
+
let clientAborted = false;
|
|
3870
|
+
res.on('close', () => {
|
|
3871
|
+
if (!res.writableEnded) {
|
|
3872
|
+
clientAborted = true;
|
|
3873
|
+
try { reqAbort.abort(); } catch {}
|
|
3874
|
+
}
|
|
3875
|
+
});
|
|
3876
|
+
try {
|
|
3877
|
+
if (req.method === 'OPTIONS') {
|
|
3878
|
+
res.writeHead(204, CORS);
|
|
3879
|
+
return res.end();
|
|
3880
|
+
}
|
|
3881
|
+
if (req.method === 'GET' && (url.pathname === AG.redirectPath || url.pathname === '/antigravity/callback')) {
|
|
3882
|
+
const err = url.searchParams.get('error');
|
|
3883
|
+
const st = url.searchParams.get('state') || '';
|
|
3884
|
+
if (err) {
|
|
3885
|
+
const desc = url.searchParams.get('error_description') || err;
|
|
3886
|
+
const entry = AG_PENDING.get(st);
|
|
3887
|
+
if (entry) { entry.status = 'failed'; entry.error = desc; }
|
|
3888
|
+
log('antigravity: login cancelado pelo Google:', desc);
|
|
3889
|
+
return html(400, `<h2>Login cancelado</h2><p>${esc(desc)}</p>`);
|
|
3890
|
+
}
|
|
3891
|
+
const code = url.searchParams.get('code');
|
|
3892
|
+
if (!code) return html(400, '<h2>Sem code na URL</h2><p>Abra /antigravity/login de novo.</p>');
|
|
3893
|
+
try {
|
|
3894
|
+
const t = await agFinishLogin(code, st);
|
|
3895
|
+
return html(200,
|
|
3896
|
+
'<h2>Antigravity conectado</h2>' +
|
|
3897
|
+
`<p>${esc(t.email || '(conta sem email)')} · project <code>${esc(t.projectId || '(nenhum)')}</code></p>` +
|
|
3898
|
+
`<p>Total de contas conectadas: <strong>${agStore.accounts.length}</strong> (troca automatica de quota ativa).</p>` +
|
|
3899
|
+
'<p>Pode fechar esta aba e voltar para o opencode.</p>');
|
|
3900
|
+
} catch (e) {
|
|
3901
|
+
log('antigravity: login falhou:', e.message);
|
|
3902
|
+
return html(400, `<h2>Falhou</h2><p>${esc(e.message)}</p>`);
|
|
3903
|
+
}
|
|
3904
|
+
}
|
|
3905
|
+
if (req.method === 'GET' && url.pathname.startsWith('/antigravity/go/')) {
|
|
3906
|
+
const st = decodeURIComponent(url.pathname.slice('/antigravity/go/'.length)).trim();
|
|
3907
|
+
const entry = AG_PENDING.get(st);
|
|
3908
|
+
if (!entry || entry.expiresAt < Date.now()) {
|
|
3909
|
+
return html(400, '<h2>Link expirado</h2><p>Volte no OpenCode e rode <code>/connect</code> de novo, ou abra <a href="/antigravity/login">/antigravity/login</a>.</p>');
|
|
3910
|
+
}
|
|
3911
|
+
res.writeHead(302, { location: agLoginUrl(st), ...CORS });
|
|
3912
|
+
return res.end();
|
|
3913
|
+
}
|
|
3914
|
+
if (req.method === 'POST' && url.pathname === '/antigravity/login/start') {
|
|
3915
|
+
const st = agNewState();
|
|
3916
|
+
const link = agLoginUrl(st);
|
|
3917
|
+
const shortUrl = agShortLoginUrl(st);
|
|
3918
|
+
const entry = AG_PENDING.get(st);
|
|
3919
|
+
log(`antigravity: sessao de login iniciada via /connect (redirect ${agRedirectUri()})`);
|
|
3920
|
+
return json(200, { state: st, url: link, shortUrl, redirect_uri: agRedirectUri(), expiresAt: entry?.expiresAt || null });
|
|
3921
|
+
}
|
|
3922
|
+
if (req.method === 'GET' && url.pathname === '/antigravity/login/status') {
|
|
3923
|
+
const st = url.searchParams.get('state') || '';
|
|
3924
|
+
const entry = AG_PENDING.get(st);
|
|
3925
|
+
if (!entry) return json(200, { status: 'expired', error: 'state desconhecido ou expirado' });
|
|
3926
|
+
if (entry.status === 'pending' && entry.expiresAt < Date.now()) {
|
|
3927
|
+
AG_PENDING.delete(st);
|
|
3928
|
+
return json(200, { status: 'expired', error: 'link de login expirado' });
|
|
3929
|
+
}
|
|
3930
|
+
return json(200, { status: entry.status, account: entry.account || null, error: entry.error || null });
|
|
3931
|
+
}
|
|
3932
|
+
if (req.method === 'POST' && url.pathname === '/antigravity/login/complete') {
|
|
3933
|
+
const body = await readBody(req);
|
|
3934
|
+
const expectedState = String(body.state || '').trim();
|
|
3935
|
+
const rawInput = String(body.input || body.url || body.code || '').trim();
|
|
3936
|
+
if (!rawInput) return json(400, { ok: false, error: 'Cole a URL completa de retorno (com ?state=...&code=...).' });
|
|
3937
|
+
let code = '';
|
|
3938
|
+
let st = expectedState;
|
|
3939
|
+
if (/^https?:\/\//i.test(rawInput) || rawInput.includes('code=')) {
|
|
3940
|
+
try {
|
|
3941
|
+
const parsed = new URL(/^https?:\/\//i.test(rawInput) ? rawInput : `http://127.0.0.1${rawInput.startsWith('/') ? '' : '/callback?'}${rawInput}`);
|
|
3942
|
+
const err = parsed.searchParams.get('error_description') || parsed.searchParams.get('error');
|
|
3943
|
+
if (err) return json(400, { ok: false, error: err });
|
|
3944
|
+
code = parsed.searchParams.get('code') || '';
|
|
3945
|
+
const urlState = parsed.searchParams.get('state') || '';
|
|
3946
|
+
if (expectedState && urlState && urlState !== expectedState) {
|
|
3947
|
+
return json(400, { ok: false, error: 'Essa URL pertence a outra tentativa de login.' });
|
|
3948
|
+
}
|
|
3949
|
+
if (urlState) st = urlState;
|
|
3950
|
+
} catch {
|
|
3951
|
+
return json(400, { ok: false, error: 'URL invalida. Cole a URL inteira da barra do navegador.' });
|
|
3952
|
+
}
|
|
3953
|
+
} else {
|
|
3954
|
+
code = rawInput;
|
|
3955
|
+
}
|
|
3956
|
+
if (!code || !st) return json(400, { ok: false, error: 'Nao encontrei code/state na URL colada.' });
|
|
3957
|
+
try {
|
|
3958
|
+
const saved = await agFinishLogin(code, st);
|
|
3959
|
+
return json(200, { ok: true, account: agPublicAccount(saved), accountsCount: agStore.accounts.length });
|
|
3960
|
+
} catch (e) {
|
|
3961
|
+
return json(400, { ok: false, error: e.message });
|
|
3962
|
+
}
|
|
3963
|
+
}
|
|
3964
|
+
if (req.method === 'GET' && url.pathname === '/antigravity/login') {
|
|
3965
|
+
const st = agNewState();
|
|
3966
|
+
const link = agLoginUrl(st);
|
|
3967
|
+
log(`antigravity: link de login gerado (redirect ${agRedirectUri()})`);
|
|
3968
|
+
if (url.searchParams.get('link') === '1' || String(req.headers.accept || '').includes('application/json')) {
|
|
3969
|
+
return json(200, { state: st, url: link, redirect_uri: agRedirectUri() });
|
|
3970
|
+
}
|
|
3971
|
+
res.writeHead(302, { location: link, ...CORS });
|
|
3972
|
+
return res.end();
|
|
3973
|
+
}
|
|
3974
|
+
if (req.method === 'GET' && url.pathname === '/antigravity/accounts') {
|
|
3975
|
+
return json(200, {
|
|
3976
|
+
active: agStore.active || null,
|
|
3977
|
+
total: agStore.accounts.length,
|
|
3978
|
+
accounts: agStore.accounts.map(agPublicAccount),
|
|
3979
|
+
});
|
|
3980
|
+
}
|
|
3981
|
+
if (req.method === 'POST' && url.pathname === '/antigravity/accounts/active') {
|
|
3982
|
+
const body = await readBody(req);
|
|
3983
|
+
const hint = String(body.email || body.id || '').trim();
|
|
3984
|
+
const found = agFindAccount(hint);
|
|
3985
|
+
if (!found) return json(404, { ok: false, error: `conta nao encontrada: ${hint}` });
|
|
3986
|
+
agStore.active = found.id;
|
|
3987
|
+
agSaveTokens();
|
|
3988
|
+
log(`antigravity: conta preferencial alterada para ${found.email || found.id}`);
|
|
3989
|
+
return json(200, { ok: true, active: found.id, account: agPublicAccount(found) });
|
|
3990
|
+
}
|
|
3991
|
+
if (req.method === 'GET' && url.pathname === '/antigravity/status') {
|
|
3992
|
+
const logged = agLogged();
|
|
3993
|
+
const active = agActiveAccount();
|
|
3994
|
+
return json(200, {
|
|
3995
|
+
loggedIn: logged,
|
|
3996
|
+
email: (active && active.email) || null,
|
|
3997
|
+
projectId: (active && active.projectId) || null,
|
|
3998
|
+
tier: (active && active.tier) || null,
|
|
3999
|
+
paidTier: (active && active.paidTier) || null,
|
|
4000
|
+
paidTierName: (active && active.paidTierName) || null,
|
|
4001
|
+
credits: (active && active.credits) || [],
|
|
4002
|
+
expiresAt: (active && active.expiresAt) || null,
|
|
4003
|
+
accountsCount: agStore.accounts.length,
|
|
4004
|
+
accounts: agStore.accounts.map(agPublicAccount),
|
|
4005
|
+
loginUrl: logged ? null : `http://127.0.0.1:${CFG.port}/antigravity/login`,
|
|
4006
|
+
models: MODELS.filter((m) => m.provider === 'antigravity').map((m) => ({
|
|
4007
|
+
id: m.id,
|
|
4008
|
+
tiers: m.tiers,
|
|
4009
|
+
servedTiers: m.served || null,
|
|
4010
|
+
context: m.context,
|
|
4011
|
+
maxOut: m.maxOut,
|
|
4012
|
+
})),
|
|
4013
|
+
quota: agQuotaView(active),
|
|
4014
|
+
usage: AG_USAGE,
|
|
4015
|
+
});
|
|
4016
|
+
}
|
|
4017
|
+
// Retrato da cota: remainingFraction/resetTime por modelo e por conta.
|
|
4018
|
+
if (req.method === 'GET' && url.pathname === '/antigravity/quota') {
|
|
4019
|
+
if (agLogged()) await agDiscover(true);
|
|
4020
|
+
const active = agActiveAccount();
|
|
4021
|
+
return json(200, {
|
|
4022
|
+
quota: agQuotaView(active),
|
|
4023
|
+
accountsCount: agStore.accounts.length,
|
|
4024
|
+
accounts: agStore.accounts.map(agPublicAccount),
|
|
4025
|
+
usage: AG_USAGE,
|
|
4026
|
+
});
|
|
4027
|
+
}
|
|
4028
|
+
if (req.method === 'POST' && url.pathname === '/antigravity/logout') {
|
|
4029
|
+
const body = await readBody(req).catch(() => ({}));
|
|
4030
|
+
const hint = String(body.email || body.id || url.searchParams.get('email') || '').trim();
|
|
4031
|
+
const r = agRemoveAccount(hint);
|
|
4032
|
+
log(`antigravity: logout (${r.removed || 'nenhuma removida'}; restantes=${r.remaining})`);
|
|
4033
|
+
return json(200, { ok: true, ...r });
|
|
4034
|
+
}
|
|
4035
|
+
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/healthz')) {
|
|
4036
|
+
const active = agActiveAccount();
|
|
4037
|
+
pruneExpiredTokens();
|
|
4038
|
+
return json(200, {
|
|
4039
|
+
ok: true,
|
|
4040
|
+
ready: state.ready,
|
|
4041
|
+
tokens: state.tokens,
|
|
4042
|
+
lastError: state.lastError,
|
|
4043
|
+
model: MODELS[0].apiModel,
|
|
4044
|
+
models: MODELS.map((m) => m.id),
|
|
4045
|
+
captcha: {
|
|
4046
|
+
browserOpen: !!state.browserObj,
|
|
4047
|
+
workers: state.workers.map((w) => ({ idx: w.idx, active: w.active, uses: w.uses, rotating: w.rotating, dead: w.dead })),
|
|
4048
|
+
pool: state.pool.length,
|
|
4049
|
+
waiters: state.waiters.length,
|
|
4050
|
+
idleCloseMs: BROWSER_IDLE_CLOSE_MS,
|
|
4051
|
+
},
|
|
4052
|
+
antigravity: {
|
|
4053
|
+
loggedIn: agLogged(),
|
|
4054
|
+
email: (active && active.email) || null,
|
|
4055
|
+
projectId: (active && active.projectId) || null,
|
|
4056
|
+
accountsCount: agStore.accounts.length,
|
|
4057
|
+
accounts: agStore.accounts.map((a) => ({ id: a.id, email: a.email, active: a.id === agStore.active })),
|
|
4058
|
+
quota: agQuotaView(active),
|
|
4059
|
+
usage: AG_USAGE,
|
|
4060
|
+
},
|
|
4061
|
+
browser: state.browser,
|
|
4062
|
+
profile: CFG.profileDir,
|
|
4063
|
+
uptime: Math.round(process.uptime()),
|
|
4064
|
+
lastSse: state.lastSse,
|
|
4065
|
+
});
|
|
4066
|
+
}
|
|
4067
|
+
if (req.method === 'GET' && url.pathname === '/v1/models') {
|
|
4068
|
+
const created = Math.floor(Date.now() / 1000);
|
|
4069
|
+
const data = [];
|
|
4070
|
+
const seen = new Set();
|
|
4071
|
+
for (const m of MODELS) {
|
|
4072
|
+
for (const id of [m.id, m.apiModel]) {
|
|
4073
|
+
if (!id || seen.has(id)) continue;
|
|
4074
|
+
seen.add(id);
|
|
4075
|
+
data.push({
|
|
4076
|
+
id,
|
|
4077
|
+
object: 'model',
|
|
4078
|
+
created,
|
|
4079
|
+
owned_by: m.provider === 'antigravity' ? 'google-antigravity' : 'nvidia-buildapi',
|
|
4080
|
+
context_length: Number(m.context) || CFG.contextTokens,
|
|
4081
|
+
});
|
|
4082
|
+
}
|
|
4083
|
+
}
|
|
4084
|
+
return json(200, { object: 'list', data });
|
|
4085
|
+
}
|
|
4086
|
+
if (req.method === 'POST' && url.pathname === '/admin/reload') {
|
|
4087
|
+
await openPage();
|
|
4088
|
+
return json(200, { ok: true });
|
|
4089
|
+
}
|
|
4090
|
+
if (req.method === 'POST' && url.pathname === '/v1/chat/completions') {
|
|
4091
|
+
const body = await readBody(req);
|
|
4092
|
+
const model = resolveModel(body.model);
|
|
4093
|
+
if (model.provider === 'antigravity') {
|
|
4094
|
+
const authHdr = String(req.headers.authorization || '').trim();
|
|
4095
|
+
const acctHdr = String(req.headers['x-antigravity-account'] || '').trim();
|
|
4096
|
+
const preferredHint = acctHdr || (/^bearer\s+ag:/i.test(authHdr) ? authHdr : '');
|
|
4097
|
+
return await handleAntigravityChat(body, model, res, reqAbort, preferredHint);
|
|
4098
|
+
}
|
|
4099
|
+
const { payload, trim, compact } = toUpstream(body, model);
|
|
4100
|
+
const id = rid();
|
|
4101
|
+
const t0 = Date.now();
|
|
4102
|
+
log(
|
|
4103
|
+
`req ${id}: model=${model.id} stream=${payload.stream} msgs=${payload.messages.length}` +
|
|
4104
|
+
` tools=${Array.isArray(payload.tools) ? payload.tools.length : 0}` +
|
|
4105
|
+
` max_tokens=${payload.max_tokens} reasoning=${payload.reasoning_effort}` +
|
|
4106
|
+
(compact ? ' compact=sim' : '') +
|
|
4107
|
+
(trim.dropped ? ` contexto=${trim.before}->${trim.after}tokens cortou=${trim.dropped}msgs` : '')
|
|
4108
|
+
);
|
|
4109
|
+
// Para stream=true, se o captcha/upstream demorar mais de ~2s (ex.: boot
|
|
4110
|
+
// frio do headless_shell ou rajada de 20 subagentes), envia headers SSE
|
|
4111
|
+
// antecipados + comentarios keepalive a cada 10s para evitar o erro
|
|
4112
|
+
// "Timed out waiting for response headers" no OpenCode/fetch.
|
|
4113
|
+
let earlyHeadSent = false;
|
|
4114
|
+
let earlyHeadTimer = null;
|
|
4115
|
+
let earlyKeepaliveTimer = null;
|
|
4116
|
+
const stopEarlyKeepalive = () => {
|
|
4117
|
+
if (earlyHeadTimer) { clearTimeout(earlyHeadTimer); earlyHeadTimer = null; }
|
|
4118
|
+
if (earlyKeepaliveTimer) { clearInterval(earlyKeepaliveTimer); earlyKeepaliveTimer = null; }
|
|
4119
|
+
};
|
|
4120
|
+
const sendEarlyHead = () => {
|
|
4121
|
+
if (earlyHeadSent || clientAborted || res.headersSent || res.writableEnded) return;
|
|
4122
|
+
earlyHeadSent = true;
|
|
4123
|
+
res.writeHead(200, {
|
|
4124
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
4125
|
+
'cache-control': 'no-cache, no-transform',
|
|
4126
|
+
connection: 'keep-alive',
|
|
4127
|
+
'x-accel-buffering': 'no',
|
|
4128
|
+
...CORS,
|
|
4129
|
+
});
|
|
4130
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
4131
|
+
try { res.write(': waiting-upstream\n\n'); } catch {}
|
|
4132
|
+
earlyKeepaliveTimer = setInterval(() => {
|
|
4133
|
+
if (clientAborted || res.writableEnded) { stopEarlyKeepalive(); return; }
|
|
4134
|
+
try { res.write(': keepalive\n\n'); } catch { stopEarlyKeepalive(); }
|
|
4135
|
+
}, 10000);
|
|
4136
|
+
if (earlyKeepaliveTimer.unref) earlyKeepaliveTimer.unref();
|
|
4137
|
+
};
|
|
4138
|
+
if (payload.stream) {
|
|
4139
|
+
earlyHeadTimer = setTimeout(sendEarlyHead, 2000);
|
|
4140
|
+
if (earlyHeadTimer.unref) earlyHeadTimer.unref();
|
|
4141
|
+
}
|
|
4142
|
+
|
|
4143
|
+
let upstream;
|
|
4144
|
+
try {
|
|
4145
|
+
upstream = await callUpstream(payload, model, null, reqAbort.signal);
|
|
4146
|
+
} finally {
|
|
4147
|
+
stopEarlyKeepalive();
|
|
4148
|
+
}
|
|
4149
|
+
if (clientAborted) {
|
|
4150
|
+
// A resposta chegou depois que o cliente desistiu: fecha o corpo para
|
|
4151
|
+
// devolver a vaga do upstream.
|
|
4152
|
+
try { await upstream.body.cancel(); } catch {}
|
|
4153
|
+
return;
|
|
4154
|
+
}
|
|
4155
|
+
log(`req ${id}: upstream ${upstream.status} ${upstream.headers.get('content-type')} em ${Date.now() - t0}ms`);
|
|
4156
|
+
if (!upstream.ok) {
|
|
4157
|
+
const text = await upstream.text().catch(() => '');
|
|
4158
|
+
log(`req ${id}: erro upstream`, text.slice(0, 500));
|
|
4159
|
+
if (earlyHeadSent || res.headersSent) {
|
|
4160
|
+
try {
|
|
4161
|
+
res.write(`data: ${JSON.stringify({ error: { message: text.slice(0, 1200) || 'upstream error', type: 'upstream_error', code: upstream.status } })}\n\n`);
|
|
4162
|
+
res.write('data: [DONE]\n\n');
|
|
4163
|
+
res.end();
|
|
4164
|
+
} catch {}
|
|
4165
|
+
return;
|
|
4166
|
+
}
|
|
4167
|
+
return json(upstream.status, {
|
|
4168
|
+
error: { message: text.slice(0, 1200) || 'upstream error', type: 'upstream_error', code: upstream.status },
|
|
4169
|
+
});
|
|
4170
|
+
}
|
|
4171
|
+
const ct = upstream.headers.get('content-type') || '';
|
|
4172
|
+
if (ct.includes('text/event-stream') && payload.stream) {
|
|
4173
|
+
return proxyStream(upstream, res, {
|
|
4174
|
+
id,
|
|
4175
|
+
payload,
|
|
4176
|
+
model,
|
|
4177
|
+
skipHead: earlyHeadSent,
|
|
4178
|
+
req: { msgs: payload.messages.length, tools: payload.tools?.length || 0 },
|
|
4179
|
+
});
|
|
4180
|
+
}
|
|
4181
|
+
const text = await upstream.text();
|
|
4182
|
+
if (earlyHeadSent || res.headersSent) {
|
|
4183
|
+
// Cliente pediu stream=true e ja recebeu headers SSE antecipados, mas
|
|
4184
|
+
// o upstream respondeu JSON pronto: converte para chunks SSE validos.
|
|
4185
|
+
const parsed = collectSse(text, model.id);
|
|
4186
|
+
const choice = parsed?.choices?.[0];
|
|
4187
|
+
const msg = choice?.message || {};
|
|
4188
|
+
const created = Math.floor(Date.now() / 1000);
|
|
4189
|
+
const sid = 'chatcmpl-' + id;
|
|
4190
|
+
const delta = { role: 'assistant' };
|
|
4191
|
+
if (msg.reasoning_content) delta.reasoning_content = msg.reasoning_content;
|
|
4192
|
+
if (msg.content) delta.content = msg.content;
|
|
4193
|
+
if (Array.isArray(msg.tool_calls) && msg.tool_calls.length) delta.tool_calls = msg.tool_calls;
|
|
4194
|
+
try {
|
|
4195
|
+
res.write(`data: ${JSON.stringify({ id: sid, object: 'chat.completion.chunk', created, model: model.id, choices: [{ index: 0, delta, finish_reason: null }] })}\n\n`);
|
|
4196
|
+
res.write(`data: ${JSON.stringify({ id: sid, object: 'chat.completion.chunk', created, model: model.id, choices: [{ index: 0, delta: {}, finish_reason: choice?.finish_reason || 'stop' }], ...(parsed?.usage ? { usage: parsed.usage } : {}) })}\n\n`);
|
|
4197
|
+
res.write('data: [DONE]\n\n');
|
|
4198
|
+
res.end();
|
|
4199
|
+
} catch {}
|
|
4200
|
+
return;
|
|
4201
|
+
}
|
|
4202
|
+
if (ct.includes('text/event-stream')) {
|
|
4203
|
+
return json(200, collectSse(text, model.id));
|
|
4204
|
+
}
|
|
4205
|
+
if (ct.includes('json')) {
|
|
4206
|
+
try {
|
|
4207
|
+
const j = JSON.parse(text);
|
|
4208
|
+
if (j && Array.isArray(j.choices) && j.choices.length) {
|
|
4209
|
+
return json(200, collectSse(text, model.id));
|
|
4210
|
+
}
|
|
4211
|
+
} catch {}
|
|
4212
|
+
}
|
|
4213
|
+
res.writeHead(200, { 'content-type': ct || 'application/json', ...CORS });
|
|
4214
|
+
return res.end(text);
|
|
4215
|
+
}
|
|
4216
|
+
json(404, { error: { message: 'not found', type: 'invalid_request_error' } });
|
|
4217
|
+
} catch (err) {
|
|
4218
|
+
if (clientAborted || err.message === 'cliente desconectou') {
|
|
4219
|
+
log('req: cliente saiu antes da resposta');
|
|
4220
|
+
return;
|
|
4221
|
+
}
|
|
4222
|
+
log('erro:', err.message);
|
|
4223
|
+
if (!res.headersSent) json(500, { error: { message: err.message, type: 'bridge_error' } });
|
|
4224
|
+
else { try { res.end(); } catch {} }
|
|
4225
|
+
}
|
|
4226
|
+
});
|
|
4227
|
+
|
|
4228
|
+
server.on('error', (e) => {
|
|
4229
|
+
log('server erro:', e.message);
|
|
4230
|
+
if (e.code === 'EADDRINUSE') log('porta', CFG.port, 'em uso; feche o outro processo ou mude a porta no config.json');
|
|
4231
|
+
});
|
|
4232
|
+
|
|
4233
|
+
// Node 18+ corta requisicoes pelo requestTimeout padrao (5 min). Num stream
|
|
4234
|
+
// longo isso virava 408 no meio do texto. No loopback nao ha por que manter
|
|
4235
|
+
// esse teto: quem limita e o watchdog de CFG.idleTimeoutMs.
|
|
4236
|
+
server.requestTimeout = 0;
|
|
4237
|
+
server.headersTimeout = 60000;
|
|
4238
|
+
server.keepAliveTimeout = 65000;
|
|
4239
|
+
server.timeout = 0;
|
|
4240
|
+
|
|
4241
|
+
if (process.argv.includes('--setup-opencode')) {
|
|
4242
|
+
await setupOpencode();
|
|
4243
|
+
process.exit(0);
|
|
4244
|
+
}
|
|
4245
|
+
|
|
4246
|
+
server.listen(CFG.port, CFG.host, async () => {
|
|
4247
|
+
log(`bridge em http://${CFG.host}:${CFG.port} -> ${MODELS.map((m) => m.id).join(', ')} (reasoning=${CFG.reasoning})`);
|
|
4248
|
+
log(`timeout de ocioso: ${CFG.idleTimeoutMs}ms; corpo do upstream sem prazo`);
|
|
4249
|
+
if (agLogged()) {
|
|
4250
|
+
const active = agActiveAccount();
|
|
4251
|
+
const list = agStore.accounts.map((a) => a.email || a.id).join(', ');
|
|
4252
|
+
log(`antigravity: ${agStore.accounts.length} conta(s) conectada(s) [${list}] | ativa=${active?.email || active?.id || '-'} project=${active?.projectId || '-'} paidTier=${active?.paidTier || '-'}`);
|
|
4253
|
+
agDiscover(true).catch((e) => log('antigravity: descoberta no boot falhou:', e.message));
|
|
4254
|
+
} else {
|
|
4255
|
+
log(`antigravity: sem login; abra http://127.0.0.1:${CFG.port}/antigravity/login (ou /antigravity/login?link=1 para so pegar o link)`);
|
|
4256
|
+
}
|
|
4257
|
+
if (process.env.KIMI_SUPERVISADO !== '1') {
|
|
4258
|
+
await setupOpencode();
|
|
4259
|
+
await installAutostart();
|
|
4260
|
+
} else {
|
|
4261
|
+
log('modo supervisionado pelo nyxo (setupOpencode/installAutostart gerenciados pelo painel)');
|
|
4262
|
+
}
|
|
4263
|
+
// O navegador leve (headless_shell) sobe sob demanda na primeira chamada
|
|
4264
|
+
// NVIDIA e hiberna automaticamente apos browserIdleCloseMs sem uso (0 MB RAM
|
|
4265
|
+
// enquanto voce usa so Antigravity ou a bridge fica ociosa).
|
|
4266
|
+
const detectedBrowser = findBrowser();
|
|
4267
|
+
if (detectedBrowser) {
|
|
4268
|
+
state.browser = detectedBrowser;
|
|
4269
|
+
log(`browser NVIDIA pronto (sob demanda): ${detectedBrowser} | pool=${CAPTCHA_WORKERS}x${CAPTCHA_WIDGETS_PER_WORKER} idleClose=${Math.round(BROWSER_IDLE_CLOSE_MS / 1000)}s`);
|
|
4270
|
+
} else {
|
|
4271
|
+
log('browser NVIDIA ainda nao encontrado; sera instalado automaticamente na primeira chamada NVIDIA');
|
|
4272
|
+
}
|
|
4273
|
+
});
|
|
4274
|
+
|
|
4275
|
+
for (const sig of ['SIGINT', 'SIGTERM']) {
|
|
4276
|
+
process.on(sig, async () => {
|
|
4277
|
+
try { await closeBrowser('shutdown'); } catch {}
|
|
4278
|
+
process.exit(0);
|
|
4279
|
+
});
|
|
4280
|
+
}
|