-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkiro-proxy.js
More file actions
1270 lines (1111 loc) · 41.3 KB
/
Copy pathkiro-proxy.js
File metadata and controls
1270 lines (1111 loc) · 41.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
996
997
998
999
1000
const express = require('express');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const router = express.Router();
const adminRouter = express.Router();
const ADMIN_KEY = process.env.ADMIN_KEY || 'kiro-admin-2024';
const ACCOUNTS_FILE = path.join(__dirname, 'accounts_active.json');
const INITIAL_ACCOUNTS_FILE = path.join(__dirname, 'accounts_part7.json');
// Kiro 默认配置
const KIRO_SOCIAL_PROFILE_ARN = 'arn:aws:codewhisperer:us-east-1:699475941385:profile/EHGA3GRVQMUK';
const KIRO_BUILDER_ID_PROFILE_ARN = 'arn:aws:codewhisperer:us-east-1:638616132270:profile/AAAACCCCXXXX';
// 账号故障处理 & 退避机制配置
const COOLDOWN_CONFIG = {
baseCooldownMs: 60000, // 60秒 基础冷却
maxBackoffMultiplier: 1440, // 最大退避 1440倍 (24小时)
quotaResetMs: 3600000 // 配额重置 1小时
};
const ErrorType = {
FATAL: 'fatal',
RECOVERABLE: 'recoverable'
};
// 1. ==================== 账号存储 & 管理 ====================
class LocalAccountPool {
constructor() {
this.accounts = [];
this.loadAccounts();
}
loadAccounts() {
try {
if (fs.existsSync(ACCOUNTS_FILE)) {
const data = fs.readFileSync(ACCOUNTS_FILE, 'utf8');
this.accounts = JSON.parse(data);
console.log(`[LocalAccountPool] Loaded ${this.accounts.length} active accounts from disk.`);
} else if (fs.existsSync(INITIAL_ACCOUNTS_FILE)) {
console.log(`[LocalAccountPool] active file not found. Loading from part7 initial file.`);
const data = fs.readFileSync(INITIAL_ACCOUNTS_FILE, 'utf8');
const rawAccounts = JSON.parse(data);
this.accounts = rawAccounts.map(account => ({
id: account.id || crypto.randomBytes(16).toString('hex'),
email: account.email,
clientId: account.clientId,
clientSecret: account.clientSecret,
refreshToken: account.refreshToken,
region: account.region || 'us-east-1',
provider: 'kiro',
authMethod: account.authMethod || 'oidc',
profileArn: account.profileArn || KIRO_BUILDER_ID_PROFILE_ARN,
enabled: true,
errorCount: 0,
createdAt: Date.now()
}));
this.saveAccounts();
} else {
console.log('[LocalAccountPool] No account files found. Starting with empty pool.');
this.accounts = [];
}
} catch (e) {
console.error('[LocalAccountPool] Failed to load accounts:', e);
this.accounts = [];
}
}
saveAccounts() {
try {
fs.writeFileSync(ACCOUNTS_FILE, JSON.stringify(this.accounts, null, 2), 'utf8');
} catch (e) {
console.error('[LocalAccountPool] Failed to save accounts:', e);
}
}
getAccounts() {
return this.accounts;
}
getAccount(id) {
return this.accounts.find(a => a.id === id);
}
addAccount(accountData) {
const id = crypto.randomBytes(16).toString('hex');
const newAccount = {
id,
email: accountData.email,
clientId: accountData.clientId,
clientSecret: accountData.clientSecret,
refreshToken: accountData.refreshToken,
region: accountData.region || 'us-east-1',
provider: 'kiro',
authMethod: accountData.authMethod || 'oidc',
profileArn: accountData.profileArn || KIRO_BUILDER_ID_PROFILE_ARN,
enabled: true,
errorCount: 0,
createdAt: Date.now()
};
this.accounts.push(newAccount);
this.saveAccounts();
return newAccount;
}
updateAccount(id, updates) {
const account = this.getAccount(id);
if (account) {
Object.assign(account, updates);
this.saveAccounts();
return true;
}
return false;
}
deleteAccount(id) {
const index = this.accounts.findIndex(a => a.id === id);
if (index !== -1) {
this.accounts.splice(index, 1);
this.saveAccounts();
return true;
}
return false;
}
classifyError(statusCode, errorMsg) {
const msg = (errorMsg || '').toLowerCase();
if (statusCode === 400) return ErrorType.FATAL;
if (
statusCode === 401 ||
statusCode === 403 ||
statusCode === 402 ||
statusCode === 429 ||
statusCode >= 500 ||
msg.includes('fetch') ||
msg.includes('timeout') ||
msg.includes('network')
) {
return ErrorType.RECOVERABLE;
}
return ErrorType.FATAL;
}
getAvailableAccount(excludeIds = new Set()) {
const now = Date.now();
const candidates = [];
for (const account of this.accounts) {
if (excludeIds.has(account.id)) continue;
if (account.suspendedAt) continue;
if (account.enabled === false) continue;
if (account.quotaExhaustedAt) {
if (now < account.quotaExhaustedAt + COOLDOWN_CONFIG.quotaResetMs) {
continue;
} else {
account.quotaExhaustedAt = undefined;
}
}
if (account.errorCount > 0 && account.lastUsed) {
const backoffMultiplier = Math.min(
Math.pow(2, account.errorCount - 1),
COOLDOWN_CONFIG.maxBackoffMultiplier
);
const cooldownDuration = COOLDOWN_CONFIG.baseCooldownMs * backoffMultiplier;
if (now < account.lastUsed + cooldownDuration) {
continue;
}
}
const hasValidToken = !!(account.accessToken || account.ssoToken || account.refreshToken);
if (!hasValidToken) continue;
const priority = (account.expiresAt && account.expiresAt > now) ? 1 : 2;
candidates.push({ ...account, priority });
}
if (candidates.length === 0) return null;
candidates.sort((a, b) => {
if (a.priority !== b.priority) return a.priority - b.priority;
return (a.lastUsed || 0) - (b.lastUsed || 0);
});
return this.getAccount(candidates[0].id);
}
async recordRequest(accountId, success, errorMsg = null, statusCode = null) {
const account = this.getAccount(accountId);
if (!account) return;
const now = Date.now();
if (!account.stats) {
account.stats = { total: 0, success: 0, failed: 0 };
}
account.stats.total++;
if (success) {
account.stats.success++;
account.errorCount = 0;
account.lastUsed = now;
account.enabled = true;
if (account.quotaExhaustedAt) {
account.quotaExhaustedAt = undefined;
}
} else {
account.stats.failed++;
const errorType = this.classifyError(statusCode, errorMsg);
if (errorType === ErrorType.RECOVERABLE) {
account.errorCount = (account.errorCount || 0) + 1;
account.lastUsed = now;
if (statusCode === 402 || statusCode === 429) {
account.quotaExhaustedAt = now;
}
if (account.errorCount >= 5 && (statusCode === 403 || statusCode === 401)) {
account.suspendedAt = now;
account.suspendReason = 'MULTIPLE_AUTH_FAILURES';
account.suspendMessage = `Suspended after ${account.errorCount} consecutive auth failures`;
account.enabled = false;
console.warn(`[LocalAccountPool] Account ${account.email || account.id} SUSPENDED.`);
}
}
}
this.saveAccounts();
}
}
const pool = new LocalAccountPool();
// 2. ==================== Token 刷新逻辑 ====================
async function refreshKiroToken(accountId) {
const account = pool.getAccount(accountId);
if (!account) return { success: false, error: 'Account not found' };
try {
const region = account.region || 'us-east-1';
const authMethod = account.authMethod || 'oidc';
if (authMethod === 'social' && account.refreshToken) {
const tokenUrl = 'https://prod.us-east-1.auth.desktop.kiro.dev/refreshToken';
const response = await fetch(tokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'AWS-Toolkit-For-VSCode/3.148.0'
},
body: JSON.stringify({ refreshToken: account.refreshToken })
});
if (!response.ok) {
const errText = await response.text();
throw new Error(`Social refresh failed: ${response.status} - ${errText}`);
}
const data = await response.json();
pool.updateAccount(accountId, {
accessToken: data.accessToken,
refreshToken: data.refreshToken || account.refreshToken,
expiresAt: Date.now() + (data.expiresIn || 3600) * 1000,
enabled: true
});
return { success: true, accessToken: data.accessToken };
}
if (account.clientId && account.clientSecret && account.refreshToken) {
const tokenUrl = `https://oidc.${region}.amazonaws.com/token`;
const response = await fetch(tokenUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: account.clientId,
clientSecret: account.clientSecret,
refreshToken: account.refreshToken,
grantType: 'refresh_token'
})
});
if (!response.ok) {
const errText = await response.text();
throw new Error(`OIDC refresh failed: ${response.status} - ${errText}`);
}
const data = await response.json();
pool.updateAccount(accountId, {
accessToken: data.accessToken,
refreshToken: data.refreshToken || account.refreshToken,
idToken: data.idToken,
expiresAt: Date.now() + (data.expiresIn || 3600) * 1000,
enabled: true
});
return { success: true, accessToken: data.accessToken };
}
return { success: false, error: 'No refresh credentials available' };
} catch (error) {
console.error(`[TokenRefresh] Failed for ${account.email || accountId}:`, error.message);
pool.updateAccount(accountId, { enabled: false });
return { success: false, error: error.message };
}
}
// 3. ==================== 格式映射与翻译器 ====================
const MODEL_ID_MAP = {
'claude-3-5-sonnet': 'claude-sonnet-4.5',
'claude-3-opus': 'claude-sonnet-4.5',
'claude-3-sonnet': 'claude-sonnet-4',
'claude-3-haiku': 'claude-haiku-4.5',
'gpt-4': 'claude-sonnet-4.5',
'gpt-4o': 'claude-sonnet-4.5',
'gpt-4-turbo': 'claude-sonnet-4.5',
'gpt-3.5-turbo': 'claude-sonnet-4.5',
'default': 'claude-sonnet-4.5'
};
function mapModelId(model) {
if (!model || typeof model !== 'string') return MODEL_ID_MAP.default;
const m = model.trim().toLowerCase();
if (MODEL_ID_MAP[m]) return MODEL_ID_MAP[m];
for (const [k, v] of Object.entries(MODEL_ID_MAP)) {
if (m.includes(k) || k.includes(m)) return v;
}
return MODEL_ID_MAP.default;
}
function resolveProfileArn(account) {
if (account.profileArn) return account.profileArn;
if (account.authMethod === 'social') return KIRO_SOCIAL_PROFILE_ARN;
return KIRO_BUILDER_ID_PROFILE_ARN;
}
// OpenAI 格式转 Kiro Payload
function openaiToKiro(request, profileArn) {
const modelId = mapModelId(request.model);
let systemPrompt = '';
const nonSystemMessages = [];
for (const msg of request.messages || []) {
if (msg.role === 'system') {
if (typeof msg.content === 'string') {
systemPrompt += (systemPrompt ? '\n' : '') + msg.content;
}
} else {
nonSystemMessages.push(msg);
}
}
const timestamp = new Date().toISOString();
systemPrompt = `[Context: Current time is ${timestamp}]\n\n${systemPrompt}`;
const history = [];
for (let i = 0; i < nonSystemMessages.length - 1; i++) {
const msg = nonSystemMessages[i];
if (msg.role === 'user') {
history.push({
userInputMessage: {
content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
origin: 'AI_EDITOR',
modelId: modelId
}
});
} else if (msg.role === 'assistant') {
history.push({
assistantResponseMessage: {
content: msg.content || ''
}
});
}
}
const lastMessage = nonSystemMessages[nonSystemMessages.length - 1];
let currentUserMessage = 'Hello';
if (lastMessage && lastMessage.role === 'user') {
currentUserMessage = typeof lastMessage.content === 'string'
? lastMessage.content
: JSON.stringify(lastMessage.content);
}
if (systemPrompt.trim()) {
currentUserMessage = `${systemPrompt}\n\n${currentUserMessage}`;
}
const payload = {
conversationState: {
agentContinuationId: crypto.randomUUID(),
agentTaskType: 'vibe',
chatTriggerType: 'MANUAL',
conversationId: crypto.randomUUID(),
currentMessage: {
userInputMessage: {
content: currentUserMessage,
origin: 'AI_EDITOR',
modelId: modelId
}
},
history: history.length > 0 ? history : undefined
}
};
if (profileArn) {
payload.profileArn = profileArn;
}
return payload;
}
// Anthropic/Claude 格式转 Kiro Payload
function claudeToKiro(request, profileArn) {
const modelId = mapModelId(request.model);
let systemPrompt = '';
if (typeof request.system === 'string') {
systemPrompt = request.system;
} else if (Array.isArray(request.system)) {
systemPrompt = request.system.map(s => s.text || '').join('\n');
}
const timestamp = new Date().toISOString();
systemPrompt = `[Context: Current time is ${timestamp}]\n\n${systemPrompt}`;
const history = [];
const nonSystemMessages = request.messages || [];
for (let i = 0; i < nonSystemMessages.length - 1; i++) {
const msg = nonSystemMessages[i];
let msgContent = '';
if (typeof msg.content === 'string') {
msgContent = msg.content;
} else if (Array.isArray(msg.content)) {
msgContent = msg.content.map(block => block.text || '').join('\n');
}
if (msg.role === 'user') {
history.push({
userInputMessage: {
content: msgContent,
origin: 'AI_EDITOR',
modelId: modelId
}
});
} else if (msg.role === 'assistant') {
history.push({
assistantResponseMessage: {
content: msgContent
}
});
}
}
const lastMessage = nonSystemMessages[nonSystemMessages.length - 1];
let currentUserMessage = 'Hello';
if (lastMessage) {
if (typeof lastMessage.content === 'string') {
currentUserMessage = lastMessage.content;
} else if (Array.isArray(lastMessage.content)) {
currentUserMessage = lastMessage.content.map(block => block.text || '').join('\n');
}
}
if (systemPrompt.trim()) {
currentUserMessage = `${systemPrompt}\n\n${currentUserMessage}`;
}
const payload = {
conversationState: {
agentContinuationId: crypto.randomUUID(),
agentTaskType: 'vibe',
chatTriggerType: 'MANUAL',
conversationId: crypto.randomUUID(),
currentMessage: {
userInputMessage: {
content: currentUserMessage,
origin: 'AI_EDITOR',
modelId: modelId
}
},
history: history.length > 0 ? history : undefined
}
};
if (profileArn) {
payload.profileArn = profileArn;
}
return payload;
}
// Responses 格式转 OpenAI 格式
function responsesToOpenAIChat(request) {
const messages = [];
if (request.instructions) {
messages.push({ role: 'system', content: request.instructions });
}
if (typeof request.input === 'string') {
messages.push({ role: 'user', content: request.input });
} else if (Array.isArray(request.input)) {
for (const item of request.input) {
if (item.type === 'message') {
messages.push({
role: item.role === 'assistant' ? 'assistant' : 'user',
content: typeof item.content === 'string' ? item.content : JSON.stringify(item.content)
});
}
}
}
const chatReq = {
model: request.model || 'gpt-4o',
messages,
stream: request.stream === true
};
if (request.temperature !== undefined) chatReq.temperature = request.temperature;
if (request.max_output_tokens !== undefined) chatReq.max_tokens = request.max_output_tokens;
return chatReq;
}
// OpenAI 响应转 Responses 响应
function openAIChatToResponsesResponse(response) {
const choice = response.choices[0];
const output = [{
type: 'message',
id: `msg_${crypto.randomUUID()}`,
role: 'assistant',
content: [{ type: 'output_text', text: choice.message.content || '' }]
}];
return {
id: `resp_${crypto.randomUUID()}`,
object: 'response',
created_at: response.created,
model: response.model,
output,
usage: {
input_tokens: response.usage.prompt_tokens,
output_tokens: response.usage.completion_tokens,
total_tokens: response.usage.total_tokens
}
};
}
// 4. ==================== AWS Event Stream 二进制流式解析器 ====================
function extractEventType(headersBuffer) {
let offset = 0;
while (offset < headersBuffer.length) {
if (offset >= headersBuffer.length) break;
const nameLen = headersBuffer[offset];
offset++;
if (offset + nameLen > headersBuffer.length) break;
const name = new TextDecoder().decode(headersBuffer.slice(offset, offset + nameLen));
offset += nameLen;
if (offset >= headersBuffer.length) break;
const valueType = headersBuffer[offset];
offset++;
if (valueType === 7) {
if (offset + 2 > headersBuffer.length) break;
const valueLen = (headersBuffer[offset] << 8) | headersBuffer[offset + 1];
offset += 2;
if (offset + valueLen > headersBuffer.length) break;
const value = new TextDecoder().decode(headersBuffer.slice(offset, offset + valueLen));
offset += valueLen;
if (name === ':event-type') {
return value;
}
continue;
}
const skipSizes = { 0: 0, 1: 0, 2: 1, 3: 2, 4: 4, 5: 8, 8: 8, 9: 16 };
if (valueType === 6) {
if (offset + 2 > headersBuffer.length) break;
const len = (headersBuffer[offset] << 8) | headersBuffer[offset + 1];
offset += 2 + len;
} else if (skipSizes[valueType] !== undefined) {
offset += skipSizes[valueType];
} else {
break;
}
}
return '';
}
// 4.1 OpenAI 流式输出解析
async function parseEventStreamToClient(res, responseBody, model, requestId) {
let buffer = Buffer.alloc(0);
for await (const chunk of responseBody) {
buffer = Buffer.concat([buffer, chunk]);
while (buffer.length >= 16) {
const totalLength = buffer.readUInt32BE(0);
if (buffer.length < totalLength) break;
const headersLength = buffer.readUInt32BE(4);
const eventType = extractEventType(buffer.subarray(12, 12 + headersLength));
const payloadStart = 12 + headersLength;
const payloadEnd = totalLength - 4;
if (payloadStart < payloadEnd) {
const payloadBytes = buffer.subarray(payloadStart, payloadEnd);
try {
const payloadText = new TextDecoder().decode(payloadBytes);
const event = JSON.parse(payloadText);
let content = '';
if (eventType === 'assistantResponseEvent' || event.assistantResponseEvent) {
const assistantResp = event.assistantResponseEvent || event;
if (assistantResp.content) content = assistantResp.content;
} else if (eventType === 'codeEvent' || event.codeEvent) {
const codeResp = event.codeEvent || event;
if (codeResp.content) content = codeResp.content;
}
if (content) {
const streamChunk = {
id: requestId,
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: model,
choices: [{
index: 0,
delta: { content },
finish_reason: null
}]
};
res.write(`data: ${JSON.stringify(streamChunk)}\n\n`);
}
if (eventType === 'toolUseEvent' || event.toolUseEvent) {
const toolUse = event.toolUseEvent || event;
const toolChunk = {
id: requestId,
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: model,
choices: [{
index: 0,
delta: {
tool_calls: [{
index: 0,
id: toolUse.toolUseId,
type: 'function',
function: {
name: toolUse.name,
arguments: typeof toolUse.input === 'string' ? toolUse.input : JSON.stringify(toolUse.input)
}
}]
},
finish_reason: toolUse.stop ? 'tool_calls' : null
}]
};
res.write(`data: ${JSON.stringify(toolChunk)}\n\n`);
}
} catch (e) {}
}
buffer = buffer.subarray(totalLength);
}
}
const finalChunk = {
id: requestId,
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: model,
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }]
};
res.write(`data: ${JSON.stringify(finalChunk)}\n\n`);
res.write('data: [DONE]\n\n');
res.end();
}
// 4.2 Anthropic/Claude 流式输出解析
async function parseEventStreamToClaudeClient(res, responseBody, model, requestId) {
let buffer = Buffer.alloc(0);
let hasSentStart = false;
let textBlockStarted = false;
// 1. 发送 message_start 事件
const messageStart = {
type: 'message_start',
message: {
id: requestId,
type: 'message',
role: 'assistant',
model: model,
content: [],
stop_reason: null,
stop_sequence: null,
usage: { input_tokens: 0, output_tokens: 0 }
}
};
res.write(`event: message_start\ndata: ${JSON.stringify(messageStart)}\n\n`);
hasSentStart = true;
for await (const chunk of responseBody) {
buffer = Buffer.concat([buffer, chunk]);
while (buffer.length >= 16) {
const totalLength = buffer.readUInt32BE(0);
if (buffer.length < totalLength) break;
const headersLength = buffer.readUInt32BE(4);
const eventType = extractEventType(buffer.subarray(12, 12 + headersLength));
const payloadStart = 12 + headersLength;
const payloadEnd = totalLength - 4;
if (payloadStart < payloadEnd) {
const payloadBytes = buffer.subarray(payloadStart, payloadEnd);
try {
const payloadText = new TextDecoder().decode(payloadBytes);
const event = JSON.parse(payloadText);
let content = '';
if (eventType === 'assistantResponseEvent' || event.assistantResponseEvent) {
const assistantResp = event.assistantResponseEvent || event;
if (assistantResp.content) content = assistantResp.content;
} else if (eventType === 'codeEvent' || event.codeEvent) {
const codeResp = event.codeEvent || event;
if (codeResp.content) content = codeResp.content;
}
if (content) {
// 如果还没触发 content_block_start,先发送
if (!textBlockStarted) {
const blockStart = {
type: 'content_block_start',
index: 0,
content_block: { type: 'text', text: '' }
};
res.write(`event: content_block_start\ndata: ${JSON.stringify(blockStart)}\n\n`);
textBlockStarted = true;
}
const blockDelta = {
type: 'content_block_delta',
index: 0,
delta: { type: 'text_delta', text: content }
};
res.write(`event: content_block_delta\ndata: ${JSON.stringify(blockDelta)}\n\n`);
}
// 对 tool_useEvent 暂时按 Anthropic content_block 流化推送
if (eventType === 'toolUseEvent' || event.toolUseEvent) {
const toolUse = event.toolUseEvent || event;
const toolBlockStart = {
type: 'content_block_start',
index: 1,
content_block: { type: 'tool_use', id: toolUse.toolUseId, name: toolUse.name, input: {} }
};
res.write(`event: content_block_start\ndata: ${JSON.stringify(toolBlockStart)}\n\n`);
const toolDelta = {
type: 'content_block_delta',
index: 1,
delta: { type: 'input_json_delta', partial_json: typeof toolUse.input === 'string' ? toolUse.input : JSON.stringify(toolUse.input) }
};
res.write(`event: content_block_delta\ndata: ${JSON.stringify(toolDelta)}\n\n`);
if (toolUse.stop) {
const toolBlockStop = { type: 'content_block_stop', index: 1 };
res.write(`event: content_block_stop\ndata: ${JSON.stringify(toolBlockStop)}\n\n`);
}
}
} catch (e) {}
}
buffer = buffer.subarray(totalLength);
}
}
// 终结内容块并发送 message_stop
if (textBlockStarted) {
const blockStop = { type: 'content_block_stop', index: 0 };
res.write(`event: content_block_stop\ndata: ${JSON.stringify(blockStop)}\n\n`);
}
const messageDelta = {
type: 'message_delta',
delta: { stop_reason: 'end_turn', stop_sequence: null },
usage: { output_tokens: 0 }
};
res.write(`event: message_delta\ndata: ${JSON.stringify(messageDelta)}\n\n`);
const messageStop = { type: 'message_stop' };
res.write(`event: message_stop\ndata: ${JSON.stringify(messageStop)}\n\n`);
res.end();
}
// 解析完整的非流式二进制 AWS Event Stream
async function parseEventStreamToText(responseBody) {
let buffer = Buffer.alloc(0);
let content = '';
for await (const chunk of responseBody) {
buffer = Buffer.concat([buffer, chunk]);
while (buffer.length >= 16) {
const totalLength = buffer.readUInt32BE(0);
if (buffer.length < totalLength) break;
const headersLength = buffer.readUInt32BE(4);
const eventType = extractEventType(buffer.subarray(12, 12 + headersLength));
const payloadStart = 12 + headersLength;
const payloadEnd = totalLength - 4;
if (payloadStart < payloadEnd) {
const payloadBytes = buffer.subarray(payloadStart, payloadEnd);
try {
const payloadText = new TextDecoder().decode(payloadBytes);
const event = JSON.parse(payloadText);
if (eventType === 'assistantResponseEvent' || event.assistantResponseEvent) {
const assistantResp = event.assistantResponseEvent || event;
if (assistantResp.content) content += assistantResp.content;
} else if (eventType === 'codeEvent' || event.codeEvent) {
const codeResp = event.codeEvent || event;
if (codeResp.content) content += codeResp.content;
}
} catch (e) {}
}
buffer = buffer.subarray(totalLength);
}
}
return content;
}
// 5. ==================== API 核心端点路由 ====================
// OpenAI 兼容的模型列表
router.get('/v1/models', (req, res) => {
res.json({
object: 'list',
data: [
{ id: 'gpt-4', object: 'model', created: 1686935002, owned_by: 'kiro' },
{ id: 'gpt-4o', object: 'model', created: 1686935002, owned_by: 'kiro' },
{ id: 'claude-3-5-sonnet', object: 'model', created: 1686935002, owned_by: 'kiro' },
{ id: 'claude-sonnet-4.5', object: 'model', created: 1686935002, owned_by: 'kiro' }
]
});
});
// 5.1 OpenAI 兼容聊天接口
router.post('/v1/chat/completions', async (req, res) => {
const excludeIds = new Set();
let retryCount = 0;
const maxRetries = 3;
const requestBody = req.body;
const stream = requestBody.stream === true;
const model = requestBody.model || 'gpt-4o';
const requestId = `chatcmpl-${crypto.randomUUID()}`;
while (retryCount < maxRetries) {
const account = pool.getAvailableAccount(excludeIds);
if (!account) {
return res.status(503).json({
error: 'No available Kiro accounts',
message: 'No active accounts found in the local pool, or all accounts are in cooldown/quota-limit.'
});
}
if (account.expiresAt && account.expiresAt < Date.now() + 300000) {
await refreshKiroToken(account.id);
}
const region = account.region || 'us-east-1';
const kiroUrl = `https://codewhisperer.${region}.amazonaws.com/generateAssistantResponse`;
const profileArn = resolveProfileArn(account);
const kiroPayload = openaiToKiro(requestBody, profileArn);
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${account.accessToken || account.ssoToken}`,
'x-amzn-kiro-agent-mode': 'spec',
'x-amz-user-agent': 'aws-sdk-js/3.698.0 KiroIDE-1.0.0',
'user-agent': 'aws-sdk-js/3.698.0 ua/2.1 os/linux lang/js md/nodejs#20.0.0 api/codewhispererstreaming#2024-11-20 m/E KiroIDE-1.0.0',
'amz-sdk-invocation-id': crypto.randomUUID(),
'amz-sdk-request': `attempt=${retryCount + 1}; max=3`
};
try {
console.log(`[KiroProxy][OpenAI] Forwarding to ${kiroUrl} using: ${account.email}`);
const response = await fetch(kiroUrl, {
method: 'POST',
headers,
body: JSON.stringify(kiroPayload)
});
const statusCode = response.status;
if (statusCode === 401 || statusCode === 403) {
const refreshResult = await refreshKiroToken(account.id);
if (refreshResult.success) {
headers['Authorization'] = `Bearer ${refreshResult.accessToken}`;
const retryResponse = await fetch(kiroUrl, {
method: 'POST',
headers,
body: JSON.stringify(kiroPayload)
});
if (retryResponse.ok) {
pool.recordRequest(account.id, true);
if (stream) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
await parseEventStreamToClient(res, retryResponse.body, model, requestId);
} else {
const content = await parseEventStreamToText(retryResponse.body);
res.json({
id: requestId,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model,
choices: [{
index: 0,
message: { role: 'assistant', content },
finish_reason: 'stop'
}],
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
});
}
return;
}
}
pool.recordRequest(account.id, false, 'Auth error', statusCode);
excludeIds.add(account.id);
retryCount++;
continue;
}
if (statusCode === 402 || statusCode === 429) {
pool.recordRequest(account.id, false, 'Quota or rate limit', statusCode);
excludeIds.add(account.id);
retryCount++;
continue;
}
if (!response.ok) {
const errorText = await response.text();
pool.recordRequest(account.id, false, errorText, statusCode);
excludeIds.add(account.id);
retryCount++;
continue;
}
pool.recordRequest(account.id, true);
if (stream) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
await parseEventStreamToClient(res, response.body, model, requestId);
} else {
const content = await parseEventStreamToText(response.body);
res.json({
id: requestId,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model,
choices: [{
index: 0,
message: { role: 'assistant', content },
finish_reason: 'stop'
}],
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
});
}
return;
} catch (err) {
console.error(`[KiroProxy] OpenAI error:`, err.message);
pool.recordRequest(account.id, false, err.message, 500);
excludeIds.add(account.id);
retryCount++;
}
}
res.status(500).json({ error: 'Proxy Error', message: 'Failed after retrying all available accounts.' });
});
// 5.2 Anthropic/Claude 兼容消息端点
const handleClaudeRoute = async (req, res) => {
const excludeIds = new Set();
let retryCount = 0;
const maxRetries = 3;
const requestBody = req.body;
const stream = requestBody.stream === true;