forked from kevinnft/agy-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
995 lines (901 loc) · 39.3 KB
/
Copy pathserver.js
File metadata and controls
995 lines (901 loc) · 39.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
'use strict';
// Antigravity (agy) -> OpenAI / Anthropic / Gemini compatible proxy
// Port default 8081. Multi-akun round-robin + egress proxy round-robin.
//
// Endpoint:
// GET /v1/models (OpenAI)
// POST /v1/chat/completions (OpenAI, stream + non-stream)
// POST /v1/messages (Anthropic, stream + non-stream)
// POST /v1beta/models/{m}:streamGenerateContent (Gemini native)
// GET /v1beta/models (Gemini)
// GET /healthz
// ADMIN (loopback only, tanpa auth):
// GET /admin/state /admin/accounts /admin/egress /admin/quota
// POST /admin/accounts/{disable,enable,reset} /admin/egress/{load,config,reset,check}
// GET /admin/ui (dashboard web)
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const agy = require('./agy_cli.js');
const accounts = require('./accounts.js');
const proxies = require('./proxies.js');
const auth = require('./auth.js');
const quotaMod = require('./quota.js');
const usage = require('./usage.js');
const DIR = __dirname;
const PORT = parseInt(process.env.AGY_PROXY_PORT || '8081', 10);
const CONFIG_FILE = path.join(DIR, 'config.json');
let config = {
apiKey: 'change-me',
rotation: 'rotate',
maxAccountRetries: 4,
cooldownMs: 60000,
defaultModel: 'gemini-3.7-flash-low',
adminAuth: false,
listenHost: '127.0.0.1',
maxInflight: 8,
permissionMode: 'skip',
egress: { enabled: false, mode: 'rotate', failThreshold: 3 },
};
if (fs.existsSync(CONFIG_FILE)) {
try { config = Object.assign({}, config, JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'))); }
catch (e) { console.error('[config] parse gagal, pakai default:', e.message); }
}
const HOST = process.env.AGY_PROXY_HOST || config.listenHost || '127.0.0.1';
const BIND_PUBLIC = HOST === '0.0.0.0' || HOST === '::';
proxies.setConfig(config.egress || {});
proxies.load();
let MODEL_CACHE = agy.listModels();
// ---------------- util ----------------
function sendJson(res, code, obj, extraHeaders) {
const body = JSON.stringify(obj);
res.writeHead(code, Object.assign({
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
'Access-Control-Allow-Origin': '*',
'Access-Control-Expose-Headers': 'X-Agy-Account,X-Agy-Egress',
}, extraHeaders || {}));
res.end(body);
}
function readBody(req, limitBytes = 12 * 1024 * 1024) {
return new Promise((resolve, reject) => {
let size = 0; const chunks = [];
req.on('data', c => {
size += c.length;
if (size > limitBytes) { reject(new Error('body terlalu besar')); req.destroy(); return; }
chunks.push(c);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function newId(p) { return (p || 'chatcmpl-') + crypto.randomBytes(12).toString('hex'); }
function nowSec() { return Math.floor(Date.now() / 1000); }
function isLoopback(ip) {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1' || ip === 'localhost';
}
function clientIp(req) {
return (req.socket.remoteAddress || '').replace('::ffff:', '');
}
// Autentikasi klien untuk /v1/*
function authorized(req, url) {
if (!config.apiKey) return true;
const h = req.headers['authorization'] || '';
const bearer = h.startsWith('Bearer ') ? h.slice(7).trim() : '';
const xkey = req.headers['x-api-key'] || '';
let keyParam = '';
try { keyParam = url.searchParams.get('key') || ''; } catch (e) { keyParam = ''; }
return bearer === config.apiKey || xkey === config.apiKey || keyParam === config.apiKey;
}
// ---------------- konversi format ----------------
// OpenAI messages -> satu prompt teks bergaya percakapan.
function openaiMessagesToPrompt(messages) {
const parts = [];
if (Array.isArray(messages)) {
for (const m of messages) {
const role = (m.role || 'user');
let content = m.content;
if (Array.isArray(content)) {
content = content.map(c => (c && (c.text || c.content)) || '').filter(Boolean).join('\n');
}
content = content || '';
let assistantExtra = '';
if (m.reasoning_content) {
assistantExtra += `<thought>\n${m.reasoning_content}\n</thought>\n`;
}
if (Array.isArray(m.tool_calls) && m.tool_calls.length) {
for (const tc of m.tool_calls) {
const fn = tc.function || {};
assistantExtra += `\n[Tool Call: ${fn.name || 'tool'}(${fn.arguments || ''})]\n`;
}
}
if (role === 'system') parts.push('[SYSTEM]\n' + content);
else if (role === 'assistant') parts.push('[ASSISTANT]\n' + (assistantExtra ? assistantExtra + content : content));
else if (role === 'tool') parts.push(`[TOOL RESULT: ${m.name || m.tool_call_id || 'tool'}]\n` + content);
else parts.push('[USER]\n' + content);
}
}
return parts.join('\n\n') || '';
}
// Anthropic messages -> prompt (system terpisah).
function anthropicToPrompt(body) {
const sys = typeof body.system === 'string' ? body.system
: Array.isArray(body.system) ? body.system.map(s => s && s.text || '').join('\n') : '';
const parts = [];
if (sys) parts.push('[SYSTEM]\n' + sys);
for (const m of body.messages || []) {
let content = m.content;
if (Array.isArray(content)) content = content.map(c => (c && (c.text || c.content)) || '').filter(Boolean).join('\n');
parts.push((m.role === 'assistant' ? '[ASSISTANT]\n' : '[USER]\n') + content);
}
return parts.join('\n\n');
}
function usageFromAgy(u, model) {
const inp = (u && u.input_tokens) || 0;
const out = (u && u.output_tokens) || 0;
const reason = (u && (u.thinking_tokens || u.thoughts_token_count || u.reasoning_tokens)) || 0;
return {
prompt_tokens: inp,
completion_tokens: out,
total_tokens: inp + out,
prompt_tokens_details: { cached_tokens: (u && u.cache_read_tokens) || 0 },
completion_tokens_details: { reasoning_tokens: reason },
};
}
// ---------------- inti: jalankan ke agy dengan rotasi akun ----------------
const recentReqs = [];
function logReq(entry) {
recentReqs.unshift(entry);
if (recentReqs.length > 80) recentReqs.length = 80;
usage.append(entry);
}
let inflight = 0;
const MAX_INFLIGHT = parseInt(process.env.AGY_MAX_INFLIGHT || String(config.maxInflight || 32), 10);
const waitQueue = [];
let quotaCache = { at: 0, data: null };
const QUOTA_TTL_MS = 60 * 1000;
async function withSlot(fn) {
while (inflight >= MAX_INFLIGHT) {
await new Promise(r => waitQueue.push(r));
}
inflight++;
try { return await fn(); }
finally {
inflight--;
const n = waitQueue.shift();
if (n) n();
}
}
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
async function acquireAccount(mode, timeoutMs) {
const t0 = Date.now();
while (Date.now() - t0 < timeoutMs) {
const acct = accounts.acquireNext(mode === 'lru' ? 'lru' : 'rotate');
if (acct) return acct;
await sleep(40);
}
return null;
}
const SERIAL_CRED = process.env.AGY_SERIAL_CRED
? process.env.AGY_SERIAL_CRED !== '0'
: process.platform === 'win32';
async function runAgyForAccount(acct, prompt, opts, egress) {
const run = () => agy.runOnce(prompt, {
model: opts.model,
cwd: acct.geminiDir || process.cwd(),
home: acct.geminiDir || undefined,
proxyUrl: egress ? egress.url : undefined,
timeoutSec: opts.timeoutSec || 300,
effort: opts.effort,
permissionMode: opts.permissionMode || config.permissionMode,
});
if (!SERIAL_CRED) return run();
return auth.withCredLock(async () => {
await auth.activateAccountToken(acct);
return run();
});
}
function runAgyStreamForAccount(acct, prompt, opts, egress, onEvent) {
let abortChild = null;
const start = () => {
const handle = agy.runStream(prompt, {
model: opts.model,
cwd: acct.geminiDir || process.cwd(),
home: acct.geminiDir || undefined,
proxyUrl: egress ? egress.url : undefined,
timeoutSec: opts.timeoutSec || 300,
effort: opts.effort,
permissionMode: opts.permissionMode || config.permissionMode,
}, onEvent);
abortChild = handle.abort;
return handle.promise;
};
if (!SERIAL_CRED) {
const p = start();
return { promise: p, abort: () => { if (abortChild) abortChild(); } };
}
const promise = auth.withCredLock(async () => {
await auth.activateAccountToken(acct);
return start();
});
return {
promise,
abort: () => {
if (abortChild) abortChild();
},
};
}
async function runWithRotation(prompt, opts) {
return runStreamWithRotation(prompt, opts);
}
async function runStreamWithRotation(prompt, opts, callbacks = {}) {
return withSlot(() => runStreamWithRotationInner(prompt, opts, callbacks));
}
async function runStreamWithRotationInner(prompt, opts, callbacks = {}) {
const maxTries = config.maxAccountRetries || 4;
const waitAcctMs = opts.waitAcctMs || 180000;
const mode = config.rotation === 'lru' ? 'lru' : 'rotate';
let lastErr = null;
const tried = [];
for (let attempt = 0; attempt < maxTries; attempt++) {
const acct = await acquireAccount(mode, waitAcctMs);
if (!acct) {
return { ok: false, status: 503, error: 'tidak ada akun (semua sibuk/cooldown/disabled)', tried };
}
const egress = proxies.pick(acct.label);
tried.push({ label: acct.label, egress: egress ? egress.host : 'direct' });
const t0 = Date.now();
let firstDataEmitted = false;
const pendingEvents = [];
const handleEvent = (ev) => {
if (ev.type === 'thought' || ev.type === 'text') {
if (!firstDataEmitted) {
firstDataEmitted = true;
if (callbacks.onFirstData) {
callbacks.onFirstData({ account: acct.label, egress: egress ? egress.host : 'direct', usage: ev.usage });
}
for (const pe of pendingEvents) {
if (callbacks.onEvent) callbacks.onEvent(pe);
}
pendingEvents.length = 0;
}
if (callbacks.onEvent) callbacks.onEvent(ev);
} else if (!firstDataEmitted) {
pendingEvents.push(ev);
} else {
if (callbacks.onEvent) callbacks.onEvent(ev);
}
};
let streamHandle;
try {
streamHandle = runAgyStreamForAccount(acct, prompt, opts, egress, handleEvent);
if (callbacks.onStreamStart) {
callbacks.onStreamStart({ account: acct.label, egress: egress ? egress.host : 'direct' }, streamHandle.abort);
}
} catch (e) {
accounts.release(acct);
accounts.markError(acct, e.message, config.cooldownMs);
lastErr = e.message;
logReq({ t: Date.now(), ok: false, account: acct.label, egress: egress ? egress.host : 'direct', model: opts.model, ms: Date.now() - t0, err: String(e.message).slice(0, 180), proto: opts.proto || '-' });
continue;
}
let r;
try {
r = await streamHandle.promise;
} catch (e) {
r = { ok: false, raw: { err: e.message } };
} finally {
accounts.release(acct);
}
if (r.ok && ((r.text && r.text.trim()) || (r.thoughtText && r.thoughtText.trim()))) {
accounts.markOk(acct, r.usage, { durationMs: r.durationMs });
if (egress) proxies.reportOk(egress, r.durationMs);
logReq({ t: Date.now(), ok: true, account: acct.label, egress: egress ? egress.host : 'direct', model: opts.model, ms: r.durationMs, tokens_in: (r.usage && r.usage.input_tokens) || 0, tokens_out: (r.usage && r.usage.output_tokens) || 0, proto: opts.proto || '-' });
return { ok: true, text: r.text, thoughtText: r.thoughtText, account: acct.label, egress: egress ? egress.host : 'direct', usage: r.usage, durationMs: r.durationMs, tried };
}
const msg = (r.raw && (r.raw.err || r.raw.stderr)) || r.text || 'respon kosong';
accounts.markError(acct, msg, accounts.isQuotaError(msg) ? config.cooldownMs : 0);
if (egress) proxies.reportFail(egress, msg);
lastErr = msg;
logReq({ t: Date.now(), ok: false, account: acct.label, egress: egress ? egress.host : 'direct', model: opts.model, ms: Date.now() - t0, err: String(msg).slice(0, 180), proto: opts.proto || '-' });
if (accounts.isAuthError(msg)) accounts.setDisabled(acct.label, true);
if (firstDataEmitted && callbacks.onFirstData) {
return { ok: false, status: 502, error: msg, tried };
}
}
const status = accounts.isQuotaError(lastErr) ? 429 : 502;
return { ok: false, status, error: String(lastErr || 'gagal').slice(0, 500), tried };
}
// ---------------- handler OpenAI ----------------
async function handleOpenAIChat(req, res, body) {
let payload;
try { payload = JSON.parse(body); }
catch (e) { return sendJson(res, 400, { error: { message: 'JSON tidak valid', type: 'invalid_request_error' } }); }
const model = payload.model || config.defaultModel;
const effort = payload.reasoning_effort || payload.effort || (payload.thinking && payload.thinking.effort) || undefined;
const prompt = openaiMessagesToPrompt(payload.messages);
if (!prompt) return sendJson(res, 400, { error: { message: 'messages kosong', type: 'invalid_request_error' } });
const wantStream = !!payload.stream;
const maxTokens = payload.max_tokens || payload.max_completion_tokens;
if (!wantStream) {
const r = await runWithRotation(prompt, { model, effort, timeoutSec: 300, proto: 'openai' });
const hdr = { 'X-Agy-Account': r.account || '-', 'X-Agy-Egress': r.egress || '-' };
if (!r.ok) {
return sendJson(res, r.status, { error: { message: r.error, type: 'upstream_error', tried: r.tried } }, hdr);
}
const id = newId('chatcmpl-');
const usage = usageFromAgy(r.usage, model);
const msg = { role: 'assistant', content: r.text || '' };
if (r.thoughtText) {
msg.reasoning_content = r.thoughtText;
msg.reasoning = r.thoughtText;
}
const resp = {
id, object: 'chat.completion', created: nowSec(), model,
choices: [{ index: 0, message: msg, finish_reason: 'stop', logprobs: null }],
usage,
system_fingerprint: 'agy-' + (r.account || 'na'),
};
if (maxTokens) resp.usage.completion_tokens = Math.min(resp.usage.completion_tokens, maxTokens);
return sendJson(res, 200, resp, hdr);
}
// True streaming mode:
const id = newId('chatcmpl-');
const created = nowSec();
let headersSent = false;
let sentRole = false;
let activeAbort = null;
const onAbort = () => {
if (activeAbort) activeAbort();
};
req.on('close', onAbort);
const r = await runStreamWithRotation(prompt, { model, effort, timeoutSec: 300, proto: 'openai' }, {
onStreamStart: (streamInfo, abortFn) => {
activeAbort = abortFn;
},
onFirstData: (info) => {
headersSent = true;
const hdr = {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no',
'X-Agy-Account': info.account || '-',
'X-Agy-Egress': info.egress || '-',
};
res.writeHead(200, hdr);
},
onEvent: (ev) => {
const delta = {};
if (!sentRole) {
delta.role = 'assistant';
sentRole = true;
}
if (ev.type === 'thought') {
delta.reasoning_content = ev.delta;
delta.reasoning = ev.delta;
delta.content = '';
} else if (ev.type === 'text') {
delta.content = ev.delta;
}
const chunk = {
id, object: 'chat.completion.chunk', created, model,
choices: [{ index: 0, delta, finish_reason: null }],
};
res.write('data: ' + JSON.stringify(chunk) + '\n\n');
},
});
req.off('close', onAbort);
if (!headersSent) {
const hdr = { 'X-Agy-Account': r.account || '-', 'X-Agy-Egress': r.egress || '-' };
return sendJson(res, r.status || 502, { error: { message: r.error, type: 'upstream_error', tried: r.tried } }, hdr);
}
const usage = usageFromAgy(r.usage, model);
const fin = {
id, object: 'chat.completion.chunk', created, model,
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
usage,
};
res.write('data: ' + JSON.stringify(fin) + '\n\n');
res.write('data: [DONE]\n\n');
return res.end();
}
// ---------------- handler Anthropic ----------------
async function handleAnthropicMessages(req, res, body) {
let payload;
try { payload = JSON.parse(body); }
catch (e) { return sendJson(res, 400, { type: 'error', error: { type: 'invalid_request_error', message: 'JSON tidak valid' } }); }
const model = payload.model || config.defaultModel;
const effort = payload.effort || (payload.thinking && payload.thinking.type === 'enabled' ? ((payload.thinking.budget_tokens && payload.thinking.budget_tokens <= 2048) ? 'low' : 'high') : undefined);
const prompt = anthropicToPrompt(payload);
if (!prompt) return sendJson(res, 400, { type: 'error', error: { type: 'invalid_request_error', message: 'messages kosong' } });
const wantStream = !!payload.stream;
if (!wantStream) {
const r = await runWithRotation(prompt, { model, effort, timeoutSec: 300, proto: 'anthropic' });
const hdr = { 'X-Agy-Account': r.account || '-', 'X-Agy-Egress': r.egress || '-' };
if (!r.ok) return sendJson(res, r.status, { type: 'error', error: { type: 'upstream_error', message: r.error, tried: r.tried } }, hdr);
const id = newId('msg_');
const inp = (r.usage && r.usage.input_tokens) || 0;
const out = (r.usage && r.usage.output_tokens) || 0;
const content = [];
if (r.thoughtText) {
content.push({ type: 'thinking', thinking: r.thoughtText });
}
content.push({ type: 'text', text: r.text || '' });
return sendJson(res, 200, {
id, type: 'message', role: 'assistant', model,
content,
stop_reason: 'end_turn', stop_sequence: null,
usage: { input_tokens: inp, output_tokens: out },
}, hdr);
}
// True streaming mode for Anthropic:
const id = newId('msg_');
let headersSent = false;
let activeAbort = null;
let currentBlockType = null; // 'thinking' | 'text' | null
let blockIndex = 0;
const onAbort = () => { if (activeAbort) activeAbort(); };
req.on('close', onAbort);
const send = (ev, data) => res.write('event: ' + ev + '\ndata: ' + JSON.stringify(data) + '\n\n');
const r = await runStreamWithRotation(prompt, { model, effort, timeoutSec: 300, proto: 'anthropic' }, {
onStreamStart: (streamInfo, abortFn) => {
activeAbort = abortFn;
},
onFirstData: (info) => {
headersSent = true;
const hdr = {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no',
'X-Agy-Account': info.account || '-',
'X-Agy-Egress': info.egress || '-',
};
res.writeHead(200, hdr);
const inp = (info.usage && info.usage.input_tokens) || 0;
send('message_start', {
type: 'message_start',
message: { id, type: 'message', role: 'assistant', model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: inp, output_tokens: 1 } },
});
},
onEvent: (ev) => {
if (ev.type === 'thought') {
if (currentBlockType !== 'thinking') {
if (currentBlockType === 'text') {
send('content_block_stop', { type: 'content_block_stop', index: blockIndex });
blockIndex++;
}
currentBlockType = 'thinking';
send('content_block_start', {
type: 'content_block_start',
index: blockIndex,
content_block: { type: 'thinking', thinking: '' },
});
}
send('content_block_delta', {
type: 'content_block_delta',
index: blockIndex,
delta: { type: 'thinking_delta', thinking: ev.delta },
});
} else if (ev.type === 'text') {
if (currentBlockType !== 'text') {
if (currentBlockType === 'thinking') {
send('content_block_stop', { type: 'content_block_stop', index: blockIndex });
blockIndex++;
}
currentBlockType = 'text';
send('content_block_start', {
type: 'content_block_start',
index: blockIndex,
content_block: { type: 'text', text: '' },
});
}
send('content_block_delta', {
type: 'content_block_delta',
index: blockIndex,
delta: { type: 'text_delta', text: ev.delta },
});
}
},
});
req.off('close', onAbort);
if (!headersSent) {
const hdr = { 'X-Agy-Account': r.account || '-', 'X-Agy-Egress': r.egress || '-' };
return sendJson(res, r.status || 502, { type: 'error', error: { type: 'upstream_error', message: r.error, tried: r.tried } }, hdr);
}
if (currentBlockType !== null) {
send('content_block_stop', { type: 'content_block_stop', index: blockIndex });
}
const out = (r.usage && r.usage.output_tokens) || 0;
send('message_delta', { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: out } });
send('message_stop', { type: 'message_stop' });
return res.end();
}
// ---------------- handler Gemini native ----------------
async function handleGeminiGenerate(req, res, body, stream) {
let payload;
try { payload = JSON.parse(body); }
catch (e) { return sendJson(res, 400, { error: { code: 400, message: 'JSON tidak valid', status: 'INVALID_ARGUMENT' } }); }
const model = req.url.includes('/models/') ? decodeURIComponent(req.url.split('/models/')[1].split(':')[0]) : config.defaultModel;
const effort = payload.effort || (payload.generationConfig && payload.generationConfig.thinkingConfig ? 'high' : undefined);
const parts = [];
for (const c of (payload.contents || [])) {
const t = (c.parts || []).map(p => p.text || '').join('');
if (t) parts.push((c.role === 'model' ? '[ASSISTANT]\n' : '[USER]\n') + t);
}
if (payload.systemInstruction) {
const si = (payload.systemInstruction.parts || []).map(p => p.text || '').join('');
if (si) parts.unshift('[SYSTEM]\n' + si);
}
const prompt = parts.join('\n\n');
if (!prompt) return sendJson(res, 400, { error: { code: 400, message: 'contents kosong', status: 'INVALID_ARGUMENT' } });
if (!stream) {
const r = await runWithRotation(prompt, { model, effort, timeoutSec: 300, proto: 'gemini' });
const hdr = { 'X-Agy-Account': r.account || '-', 'X-Agy-Egress': r.egress || '-' };
if (!r.ok) return sendJson(res, r.status, { error: { code: r.status, message: r.error, status: 'UNAVAILABLE', tried: r.tried } }, hdr);
const outParts = [];
if (r.thoughtText) {
outParts.push({ text: r.thoughtText, thought: true });
}
outParts.push({ text: r.text || '' });
const usage = r.usage || {};
const out = {
candidates: [{ content: { role: 'model', parts: outParts }, finishReason: 'STOP', index: 0 }],
usageMetadata: {
promptTokenCount: usage.input_tokens || 0,
candidatesTokenCount: usage.output_tokens || 0,
totalTokenCount: (usage.input_tokens || 0) + (usage.output_tokens || 0),
},
modelVersion: model,
};
return sendJson(res, 200, out, hdr);
}
// True streaming mode for Gemini:
let headersSent = false;
let activeAbort = null;
const onAbort = () => { if (activeAbort) activeAbort(); };
req.on('close', onAbort);
const r = await runStreamWithRotation(prompt, { model, effort, timeoutSec: 300, proto: 'gemini' }, {
onStreamStart: (streamInfo, abortFn) => {
activeAbort = abortFn;
},
onFirstData: (info) => {
headersSent = true;
const hdr = {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
'X-Accel-Buffering': 'no',
'X-Agy-Account': info.account || '-',
'X-Agy-Egress': info.egress || '-',
};
res.writeHead(200, hdr);
},
onEvent: (ev) => {
if (ev.type === 'thought') {
res.write('data: ' + JSON.stringify({
candidates: [{ content: { role: 'model', parts: [{ text: ev.delta, thought: true }] }, index: 0 }],
modelVersion: model,
}) + '\n\n');
} else if (ev.type === 'text') {
res.write('data: ' + JSON.stringify({
candidates: [{ content: { role: 'model', parts: [{ text: ev.delta }] }, index: 0 }],
modelVersion: model,
}) + '\n\n');
}
},
});
req.off('close', onAbort);
if (!headersSent) {
const hdr = { 'X-Agy-Account': r.account || '-', 'X-Agy-Egress': r.egress || '-' };
return sendJson(res, r.status || 502, { error: { code: r.status, message: r.error, status: 'UNAVAILABLE', tried: r.tried } }, hdr);
}
const usage = r.usage || {};
res.write('data: ' + JSON.stringify({
candidates: [{ content: { role: 'model', parts: [{ text: '' }] }, finishReason: 'STOP', index: 0 }],
usageMetadata: {
promptTokenCount: usage.input_tokens || 0,
candidatesTokenCount: usage.output_tokens || 0,
totalTokenCount: (usage.input_tokens || 0) + (usage.output_tokens || 0),
},
modelVersion: model,
}) + '\n\n');
return res.end();
}
// ---------------- admin ----------------
function handleAdmin(req, res, urlPath, urlObj) {
const ip = clientIp(req);
const local = isLoopback(ip);
if (!local) {
if (!authorized(req, urlObj || new URL('http://x'))) {
return sendJson(res, 401, { error: 'admin butuh API key (Authorization: Bearer …)' });
}
}
if (urlPath === '/admin/ui') {
const p = path.join(DIR, 'dashboard.html');
if (!fs.existsSync(p)) return sendJson(res, 404, { error: 'dashboard.html tidak ada' });
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end(fs.readFileSync(p));
}
if (urlPath === '/admin/state' && req.method === 'GET') {
return sendJson(res, 200, {
port: PORT, version: '1.1.1', agy: agy.AGY,
config: { rotation: config.rotation, defaultModel: config.defaultModel, permissionMode: config.permissionMode || 'skip', cooldownMs: config.cooldownMs, maxAccountRetries: config.maxAccountRetries, apiKeySet: !!config.apiKey, listenHost: HOST, maxInflight: MAX_INFLIGHT },
accounts: { summary: accounts.summary(), items: accounts.stats(), busy: accounts.busyCount() },
egress: proxies.stats(),
models: MODEL_CACHE,
uptimeSec: Math.floor(process.uptime()),
inflight, maxInflight: MAX_INFLIGHT, queued: waitQueue.length,
recent: recentReqs.slice(0, 40),
usage: usage.summarize(),
});
}
if (urlPath === '/admin/accounts' && req.method === 'GET') {
return sendJson(res, 200, { summary: accounts.summary(), items: accounts.stats() });
}
if (urlPath === '/admin/egress' && req.method === 'GET') {
return sendJson(res, 200, proxies.stats());
}
if (urlPath === '/admin/quota' && req.method === 'GET') {
return (async () => {
const force = (new URL(req.url, 'http://x')).searchParams.get('force') === '1';
const list = accounts.all();
if (!force && quotaCache.data && quotaCache.data.items
&& quotaCache.data.items.length === list.length
&& (Date.now() - quotaCache.at) < QUOTA_TTL_MS) {
return sendJson(res, 200, Object.assign({ cached: true, ageMs: Date.now() - quotaCache.at }, quotaCache.data));
}
const fetched = await quotaMod.fetchAll(list);
const data = { items: fetched.items, total: fetched.items.length };
quotaCache = { at: Date.now(), data };
sendJson(res, 200, Object.assign({ cached: false, ageMs: 0, ok: true }, data));
})();
}
if (urlPath === '/admin/recent' && req.method === 'GET') {
return sendJson(res, 200, { items: recentReqs.slice(0, 50) });
}
if (urlPath === '/admin/config' && req.method === 'POST') {
return readBody(req).then(b => {
let o = {};
try { o = JSON.parse(b || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
if (o.rotation === 'lru' || o.rotation === 'rotate') config.rotation = o.rotation;
if (typeof o.defaultModel === 'string' && o.defaultModel) config.defaultModel = o.defaultModel;
if (['skip', 'accept-edits', 'plan'].includes(o.permissionMode)) config.permissionMode = o.permissionMode;
if (typeof o.cooldownMs === 'number' && o.cooldownMs >= 0) config.cooldownMs = o.cooldownMs;
if (typeof o.maxAccountRetries === 'number' && o.maxAccountRetries >= 1) config.maxAccountRetries = o.maxAccountRetries;
if (typeof o.listenHost === 'string' && o.listenHost) config.listenHost = o.listenHost;
try { fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2)); } catch (e) {}
return sendJson(res, 200, { ok: true, config: { rotation: config.rotation, defaultModel: config.defaultModel, permissionMode: config.permissionMode, cooldownMs: config.cooldownMs, maxAccountRetries: config.maxAccountRetries } });
});
}
if (urlPath === '/admin/playground' && req.method === 'POST') {
return (async () => {
let o = {};
try { o = JSON.parse(await readBody(req) || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
const prompt = String(o.prompt || '').trim();
if (!prompt) return sendJson(res, 400, { error: 'prompt wajib diisi' });
const model = o.model || config.defaultModel;
const r = await runWithRotation(prompt, { model, timeoutSec: 180, proto: 'ui' });
return sendJson(res, r.ok ? 200 : (r.status || 502), r);
})();
}
// ---- tambah / hapus akun ----
if (urlPath === '/admin/accounts/add' && req.method === 'POST') {
return readBody(req).then(b => {
let o = {};
try { o = JSON.parse(b || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
const r = accounts.addAccount(o);
return sendJson(res, r.ok ? 200 : 400, r);
});
}
if (urlPath === '/admin/accounts/login/start' && req.method === 'POST') {
return readBody(req).then(b => {
let o = {};
try { o = JSON.parse(b || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
const label = String(o.label || '').trim();
if (!label) return sendJson(res, 400, { error: 'label wajib diisi' });
let acc = accounts.find(label);
if (!acc) {
const created = accounts.addAccount({ label, geminiDir: o.geminiDir, credTarget: o.credTarget });
if (!created.ok) return sendJson(res, 400, created);
acc = created.account;
}
const r = auth.startLogin({ label, home: acc.geminiDir });
return Promise.resolve(r).then(out => sendJson(res, out.ok ? 200 : 400, out));
});
}
if (urlPath === '/admin/accounts/login/complete' && req.method === 'POST') {
return (async () => {
let o = {};
try { o = JSON.parse(await readBody(req) || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
const label = String(o.label || '').trim();
if (!label) return sendJson(res, 400, { error: 'label wajib diisi' });
const acc = accounts.find(label);
const r = await auth.completeLogin({ label, code: o.code || o.url || o.redirect, home: acc && acc.geminiDir });
if (r.ok && r.email) accounts.setEmail(label, r.email);
if (r.ok && acc) accounts.setDisabled(label, false);
return sendJson(res, r.ok ? 200 : 400, r);
})();
}
if (urlPath === '/admin/accounts/remove' && req.method === 'POST') {
return readBody(req).then(b => {
let o = {};
try { o = JSON.parse(b || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
const r = accounts.removeAccount(o.label);
return sendJson(res, r.ok ? 200 : 404, r);
});
}
if (urlPath === '/admin/accounts/reset' && req.method === 'POST') {
const n = accounts.resetCooldowns();
return sendJson(res, 200, { ok: true, reset: n });
}
if (urlPath === '/admin/accounts/reload' && req.method === 'POST') {
accounts.load(); proxies.load();
return sendJson(res, 200, { ok: true, accounts: accounts.all().length, proxies: proxies.stats().total });
}
if (urlPath === '/admin/accounts/probe' && req.method === 'POST') {
return (async () => {
const r = await accounts.probe({ concurrency: 3 });
sendJson(res, 200, { ok: true, results: r });
})();
}
if (urlPath === '/admin/egress/load' && req.method === 'POST') {
proxies.load();
return sendJson(res, 200, { ok: true, total: proxies.stats().total });
}
if (urlPath === '/admin/egress/reset' && req.method === 'POST') {
return sendJson(res, 200, { ok: true, reset: proxies.reset() });
}
if (urlPath === '/admin/egress/check' && req.method === 'POST') {
return (async () => {
try {
const r = await proxies.checkAll();
if (r && r.error) return sendJson(res, 500, { ok: false, error: r.error, ...r, stats: proxies.stats() });
sendJson(res, 200, { ok: true, ...r, stats: proxies.stats() });
} catch (e) {
console.error('[admin] egress/check:', e);
sendJson(res, 500, { ok: false, error: String(e && e.message || e) });
}
})();
}
// ---- tambah / hapus proxy ----
if (urlPath === '/admin/egress/add' && req.method === 'POST') {
return readBody(req).then(b => {
let o;
try { o = JSON.parse(b || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
// terima {line:"host:port:user:pass"} atau {host,port,user,pass}
const input = o.line ? o.line : o;
const r = proxies.addProxy(input);
return sendJson(res, r.ok ? 200 : 400, r);
});
}
if (urlPath === '/admin/egress/add-bulk' && req.method === 'POST') {
return readBody(req).then(b => {
let o = {};
try { o = JSON.parse(b || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
const text = o.text || o.lines || o.list || '';
const r = proxies.addMany(text);
return sendJson(res, r.ok ? 200 : 400, r);
});
}
if (urlPath === '/admin/egress/clear' && req.method === 'POST') {
return sendJson(res, 200, proxies.clearAll());
}
if (urlPath === '/admin/egress/remove' && req.method === 'POST') {
return readBody(req).then(b => {
let o = {};
try { o = JSON.parse(b || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
const target = (o.id !== undefined && o.id !== null && o.id !== '') ? o.id : o.host;
if (target === undefined) return sendJson(res, 400, { error: 'id atau host wajib diisi' });
const r = proxies.removeProxy(target);
return sendJson(res, r.ok ? 200 : 404, r);
});
}
if (urlPath === '/admin/egress/config' && req.method === 'POST') {
return readBody(req).then(b => {
let cfg = {};
try { cfg = JSON.parse(b || '{}'); } catch (e) { return sendJson(res, 400, { error: 'JSON tidak valid' }); }
proxies.setConfig(cfg);
config.egress = proxies.getConfig();
try { fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2)); } catch (e) {}
return sendJson(res, 200, { ok: true, egress: proxies.getConfig() });
});
}
// disable/enable akun: /admin/accounts/{label}/disable
let m = urlPath.match(/^\/admin\/accounts\/([^\/]+)\/(disable|enable)$/);
if (m && req.method === 'POST') {
const label = decodeURIComponent(m[1]);
const okk = accounts.setDisabled(label, m[2] === 'disable');
return sendJson(res, okk ? 200 : 404, okk ? { ok: true, label, disabled: m[2] === 'disable' } : { error: 'akun tidak ditemukan' });
}
return sendJson(res, 404, { error: 'admin endpoint tidak dikenal', path: urlPath });
}
// ---------------- router ----------------
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://' + (req.headers.host || 'localhost'));
const p = u.pathname;
// CORS preflight
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
'Access-Control-Allow-Headers': 'Authorization,Content-Type,x-api-key,anthropic-version',
});
return res.end();
}
try {
if (p === '/healthz') {
return sendJson(res, 200, {
ok: true, port: PORT, version: '1.1.1',
accounts: accounts.summary(),
egress: proxies.stats().alive + '/' + proxies.stats().total,
inflight, queued: waitQueue.length, busy: accounts.busyCount(),
});
}
if (p.startsWith('/admin')) return handleAdmin(req, res, p, u);
// endpoint API butuh kunci
if (!authorized(req, u)) {
return sendJson(res, 401, { error: { message: 'api key tidak valid (Authorization: Bearer <kunci> atau x-api-key)' } });
}
if (p === '/v1/models' && req.method === 'GET') {
return sendJson(res, 200, {
object: 'list',
data: MODEL_CACHE.map(m => ({ id: m.id, object: 'model', created: nowSec(), owned_by: 'antigravity' })),
});
}
if (p === '/v1/chat/completions' && req.method === 'POST') {
const body = await readBody(req);
return await handleOpenAIChat(req, res, body);
}
if ((p === '/v1/messages' || p === '/v1/messages/count_tokens') && req.method === 'POST') {
const body = await readBody(req);
return await handleAnthropicMessages(req, res, body);
}
if (p === '/v1beta/models' && req.method === 'GET') {
return sendJson(res, 200, {
models: MODEL_CACHE.map(m => ({ name: 'models/' + m.id, displayName: m.label, supportedGenerationMethods: ['generateContent', 'streamGenerateContent'] })),
});
}
if (/\/v1beta\/models\/[^/]+:(streamGenerateContent|generateContent)$/.test(p) && req.method === 'POST') {
const body = await readBody(req);
return await handleGeminiGenerate(req, res, body, p.includes('streamGenerateContent'));
}
return sendJson(res, 404, { error: { message: 'endpoint tidak dikenal: ' + p } });
} catch (e) {
console.error('[server] error:', e);
return sendJson(res, 500, { error: { message: String(e && e.message || e) } });
}
});
// ---------------- boot ----------------
accounts.load();
if (!accounts.all().length) {
// Akun default: pakai kredensial yang sedang login di Windows Credential Manager.
accounts.all().push({
label: 'primary',
credTarget: 'gemini:antigravity',
geminiDir: process.env.HOME || process.env.USERPROFILE || process.cwd(),
disabled: false, cooldown_until: 0,
requests: 0, errors: 0, tokens_in: 0, tokens_out: 0, last_used: 0,
last_error: null, ok_count: 0, last_ms: 0,
});
accounts.save();
console.log('[boot] accounts.json kosong -> dibuat akun default "primary"');
}
agy.fetchModels().then(list => { if (list && list.length) { MODEL_CACHE = list; console.log('[boot] model dimuat dari CLI:', list.length); } }).catch(() => {});
server.listen(PORT, HOST, () => {
console.log('==================================================');
console.log(' Antigravity proxy aktif http://' + HOST + ':' + PORT);
console.log(' API key : ' + (config.apiKey || '(tanpa kunci)'));
console.log(' Akun : ' + accounts.summary().usable + '/' + accounts.summary().total + ' siap');
console.log(' Egress : ' + proxies.stats().alive + '/' + proxies.stats().total + ' proxy (mode ' + proxies.getConfig().mode + ', enabled=' + proxies.getConfig().enabled + ')');
console.log(' Dashboard : http://' + (BIND_PUBLIC ? '<host>' : '127.0.0.1') + ':' + PORT + '/admin/ui');
console.log(' Cred lock : ' + (SERIAL_CRED ? 'SERIAL (wincred aman)' : 'off (HOME isolasi / Linux)'));
if (BIND_PUBLIC) console.log(' BIND : 0.0.0.0 (VPS) — /admin remote butuh API key');
console.log('==================================================');
});
server.on('error', (e) => {
if (e.code === 'EADDRINUSE') console.error('PORT ' + PORT + ' sudah dipakai. Matikan proses lain atau set AGY_PROXY_PORT.');
else console.error('[server]', e);
process.exit(1);
});