-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker-kiro.js
More file actions
2201 lines (1866 loc) · 72.9 KB
/
Copy pathworker-kiro.js
File metadata and controls
2201 lines (1866 loc) · 72.9 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
// Cloudflare Workers AI API 代理 - Kiro 增强版
// 支持 OpenAI, Anthropic, Google Gemini, Amazon Q (Kiro)
// ============ Kiro 格式转换模块 ============
// ProfileArn 配置
const KIRO_BUILDER_ID_PROFILE_ARN = 'arn:aws:codewhisperer:us-east-1:638616132270:profile/AAAACCCCXXXX';
const KIRO_SOCIAL_PROFILE_ARN = 'arn:aws:codewhisperer:us-east-1:699475941385:profile/EHGA3GRVQMUK';
// 根据账号类型解析 profileArn
function resolveProfileArn(account) {
// 如果账号有自己的 profileArn,使用它
if (account.profileArn) {
return account.profileArn;
}
// 根据认证方式判断
const authMethod = account.authMethod || 'oidc';
// 社交登录(GitHub/Google)
if (authMethod === 'social') {
return KIRO_SOCIAL_PROFILE_ARN;
}
// Builder ID 或 IdC
return KIRO_BUILDER_ID_PROFILE_ARN;
}
// 生成 Kiro User-Agent
function getKiroUserAgent() {
return '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';
}
// 生成 Kiro AMZ User-Agent
function getKiroAmzUserAgent() {
return 'aws-sdk-js/3.698.0 KiroIDE-1.0.0';
}
// 模型 ID 映射
const MODEL_ID_MAP = {
// Claude 4.5 系列
'claude-sonnet-4-5': 'claude-sonnet-4.5',
'claude-sonnet-4.5': 'claude-sonnet-4.5',
'claude-haiku-4-5': 'claude-haiku-4.5',
'claude-haiku-4.5': 'claude-haiku-4.5',
// Claude 4 系列
'claude-sonnet-4': 'claude-sonnet-4',
'claude-sonnet-4-20250514': 'claude-sonnet-4',
// Claude 3.5 系列(映射到 Sonnet 4.5)
'claude-3-5-sonnet': 'claude-sonnet-4.5',
'claude-3-5-sonnet-20241022': 'claude-sonnet-4.5',
'claude-3-opus': 'claude-sonnet-4.5',
'claude-3-sonnet': 'claude-sonnet-4',
'claude-3-haiku': 'claude-haiku-4.5',
// Anthropic 格式
'anthropic.claude-3-5-sonnet-20241022-v2:0': 'claude-sonnet-4.5',
'anthropic.claude-3-sonnet-20240229-v1:0': 'claude-sonnet-4',
'anthropic.claude-3-haiku-20240307-v1:0': 'claude-haiku-4.5',
// GPT 系列(映射到 Claude)
'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'
};
// 映射模型 ID
function mapModelId(model) {
if (!model || typeof model !== 'string') {
return MODEL_ID_MAP.default;
}
const modelId = model.trim().toLowerCase();
// 精确匹配
if (MODEL_ID_MAP[modelId]) {
return MODEL_ID_MAP[modelId];
}
// 模糊匹配
for (const [key, value] of Object.entries(MODEL_ID_MAP)) {
if (modelId.includes(key) || key.includes(modelId)) {
return value;
}
}
// 兜底
return MODEL_ID_MAP.default;
}
// OpenAI 格式 → Kiro 格式
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();
if (systemPrompt) {
systemPrompt = `[Context: Current time is ${timestamp}]\n\n${systemPrompt}`;
}
// 构建历史消息(符合 Kiro 规范)
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) {
currentUserMessage = `${systemPrompt}\n\n${currentUserMessage}`;
}
// 构建 Kiro payload(符合 AWS CodeWhisperer 规范)
const payload = {
conversationState: {
agentContinuationId: generateUUID(),
agentTaskType: 'vibe',
chatTriggerType: 'MANUAL',
conversationId: generateUUID(),
currentMessage: {
userInputMessage: {
content: currentUserMessage,
origin: 'AI_EDITOR',
modelId: modelId
}
},
history: history.length > 0 ? history : undefined
}
};
// 添加 profileArn(如果有)
if (profileArn) {
payload.profileArn = profileArn;
}
return payload;
}
// 生成 UUID
function generateUUID() {
return crypto.randomUUID();
}
// ============ 原有代码继续 ============
// 账号类型定义 (注释形式)
// KiroAccount {
// id: string;
// email: string;
// provider: 'kiro';
//
// // Kiro 特有字段
// ssoToken?: string; // SSO Token(AWS IAM Identity Center)
// accessToken?: string; // Bearer Token
// refreshToken?: string; // 用于刷新
//
// // OIDC 认证(Builder ID / GitHub / Google)
// clientId?: string;
// clientSecret?: string;
// idToken?: string;
//
// // 账号信息
// region?: string; // AWS 区域,默认 us-east-1
// expiresAt?: number;
// enabled: boolean;
// lastUsed?: number;
// createdAt: number;
//
// // 使用统计
// usage?: {
// currentMonth: number; // 当前月使用量
// limit: number; // 配额限制
// resetAt: number; // 重置时间
// };
// }
// Kiro API 端点配置(正确的 AWS CodeWhisperer 端点)
const KIRO_ENDPOINTS = [
{
url: 'https://codewhisperer.us-east-1.amazonaws.com/generateAssistantResponse',
origin: 'AI_EDITOR',
amzTarget: 'AmazonCodeWhispererStreamingService.GenerateAssistantResponse',
name: 'CodeWhisperer'
},
{
url: 'https://q.us-east-1.amazonaws.com/generateAssistantResponse',
origin: 'AI_EDITOR',
amzTarget: 'AmazonCodeWhispererStreamingService.GenerateAssistantResponse',
name: 'AmazonQ'
}
];
// 静态网页文件(Base64 编码)
const STATIC_FILES = {
'/': 'index.html',
'/index.html': 'index.html',
'/docs.html': 'docs.html',
};
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const path = url.pathname;
// CORS 预检
if (request.method === 'OPTIONS') {
return corsResponse();
}
// 静态网页文件
if (STATIC_FILES[path]) {
return serveStaticFile(path);
}
// 管理接口
if (path.startsWith('/admin')) {
return handleAdminRequest(request, env, path);
}
// Kiro 专用端点
if (path.startsWith('/kiro')) {
return handleKiroRequest(request, env, path, url);
}
// 健康检查
if (path === '/health') {
return jsonResponse({
status: 'ok',
timestamp: new Date().toISOString(),
version: '2.0.0-kiro',
supported: ['openai', 'anthropic', 'gemini', 'kiro']
});
}
// 调试端点:测试 Kiro API 原始响应
if (path === '/debug/kiro') {
return handleKiroDebug(request, env);
}
// API 信息(用于 API 工具调用)
if (path === '/api-info') {
return jsonResponse({
name: 'AI API Proxy (Kiro Enhanced)',
version: '2.0.0',
features: [
'Multi-account management',
'Auto token refresh',
'Load balancing',
'Kiro (Amazon Q) support'
],
endpoints: {
openai: '/v1/*',
anthropic: '/anthropic/*',
gemini: '/gemini/*',
kiro: '/kiro/api/v1/* (Amazon Q)',
health: '/health',
admin: '/admin/* (requires auth)'
}
});
}
// 拒绝未认证的请求
return jsonResponse({
error: 'Invalid endpoint',
message: 'Please check the API documentation'
}, 404);
}
};
// 提供静态文件
function serveStaticFile(path) {
// 重定向根路径到 index.html
const fileName = path === '/' ? '/index.html' : path;
// 这里返回简单的重定向,实际文件通过外部托管
// 或者你可以把 HTML 内容内嵌到这里
if (fileName === '/index.html') {
return new Response(INDEX_HTML, {
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'public, max-age=300'
}
});
}
if (fileName === '/docs.html') {
return new Response(DOCS_HTML, {
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'public, max-age=300'
}
});
}
return new Response('Not Found', { status: 404 });
}
// 首页 HTML(简化版,指向外部文件)
const INDEX_HTML = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI API 代理服务</title>
<meta http-equiv="refresh" content="0; url=https://github.com/WHUT666/ai-api-proxy">
</head>
<body>
<p>正在跳转到项目主页...</p>
<p>如果没有自动跳转,请访问:<a href="https://github.com/WHUT666/ai-api-proxy">https://github.com/WHUT666/ai-api-proxy</a></p>
</body>
</html>`;
const DOCS_HTML = INDEX_HTML;
// 处理 Kiro 请求
async function handleKiroRequest(request, env, path, url) {
// 检查是否是 OpenAI 兼容的聊天接口
if (path === '/kiro/v1/chat/completions') {
return handleKiroChatCompletion(request, env);
}
// 检查是否是 Responses 兼容接口
if (path === '/kiro/v1/responses' || path === '/kiro/responses') {
return handleKiroResponses(request, env);
}
// 获取可用账号
const account = await getAvailableAccount(env, 'kiro');
if (!account) {
return jsonResponse({
error: 'No available Kiro accounts',
message: 'Please add Kiro accounts in admin panel'
}, 503);
}
// 检查 Token 是否过期
if (account.expiresAt && account.expiresAt < Date.now() + 300000) {
await refreshKiroToken(env, account.id);
const refreshedAccount = await getAccount(env, account.id);
if (refreshedAccount) {
Object.assign(account, refreshedAccount);
}
}
// 确定正确的 Kiro API 端点
const region = account.region || 'us-east-1';
// 使用正确的 generateAssistantResponse 端点
const kiroUrl = `https://codewhisperer.${region}.amazonaws.com/generateAssistantResponse`;
// 解析请求体
let requestBody;
try {
requestBody = await request.json();
} catch (e) {
return jsonResponse({
error: 'Invalid JSON',
message: 'Request body must be valid JSON'
}, 400);
}
// 确保请求体包含必要的 conversationState 结构
if (!requestBody.conversationState) {
return jsonResponse({
error: 'Invalid request',
message: 'Missing conversationState in request body'
}, 400);
}
// 添加 profileArn
const profileArn = resolveProfileArn(account);
requestBody.profileArn = profileArn;
// 构建正确的请求头
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${account.accessToken || account.ssoToken}`,
'x-amzn-kiro-agent-mode': 'spec',
'x-amz-user-agent': getKiroAmzUserAgent(),
'user-agent': getKiroUserAgent(),
'amz-sdk-invocation-id': generateUUID(),
'amz-sdk-request': 'attempt=1; max=3'
};
try {
const response = await fetch(kiroUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(requestBody)
});
const statusCode = response.status;
// 记录请求结果
await recordRequest(env, account.id, response.ok, null, statusCode);
// 检查认证错误
if (statusCode === 401 || statusCode === 403) {
const excludeIds = new Set([account.id]);
const nextAccount = await getAvailableAccount(env, 'kiro', excludeIds);
if (nextAccount && nextAccount.id !== account.id) {
console.log(`[Kiro] Auth failed for ${account.email || account.id}, retrying with ${nextAccount.email || nextAccount.id}`);
const retryHeaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${nextAccount.accessToken || nextAccount.ssoToken}`,
'x-amzn-kiro-agent-mode': 'spec',
'x-amz-user-agent': getKiroAmzUserAgent(),
'user-agent': getKiroUserAgent(),
'amz-sdk-invocation-id': generateUUID(),
'amz-sdk-request': 'attempt=2; max=3'
};
const retryResponse = await fetch(kiroUrl, {
method: 'POST',
headers: retryHeaders,
body: JSON.stringify(requestBody)
});
await recordRequest(env, nextAccount.id, retryResponse.ok, null, retryResponse.status);
if (retryResponse.ok) {
await updateAccountLastUsed(env, nextAccount.id);
const proxyResponse = new Response(retryResponse.body, retryResponse);
proxyResponse.headers.set('Access-Control-Allow-Origin', '*');
proxyResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
proxyResponse.headers.set('Access-Control-Allow-Headers', '*');
proxyResponse.headers.set('Content-Type', 'text/event-stream');
return proxyResponse;
}
}
const errorText = await response.text();
return jsonResponse({
error: 'Authentication failed',
message: 'Token expired or invalid for all available accounts',
accountId: account.id,
details: errorText
}, 401);
}
// 检查其他可恢复错误(配额/限流)
if (statusCode === 402 || statusCode === 429) {
const excludeIds = new Set([account.id]);
const nextAccount = await getAvailableAccount(env, 'kiro', excludeIds);
if (nextAccount && nextAccount.id !== account.id) {
console.log(`[Kiro] Quota/Rate limit for ${account.email || account.id}, retrying with ${nextAccount.email || nextAccount.id}`);
const retryHeaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${nextAccount.accessToken || nextAccount.ssoToken}`,
'x-amzn-kiro-agent-mode': 'spec',
'x-amz-user-agent': getKiroAmzUserAgent(),
'user-agent': getKiroUserAgent(),
'amz-sdk-invocation-id': generateUUID(),
'amz-sdk-request': 'attempt=2; max=3'
};
const retryResponse = await fetch(kiroUrl, {
method: 'POST',
headers: retryHeaders,
body: JSON.stringify(requestBody)
});
await recordRequest(env, nextAccount.id, retryResponse.ok, null, retryResponse.status);
if (retryResponse.ok) {
await updateAccountLastUsed(env, nextAccount.id);
const proxyResponse = new Response(retryResponse.body, retryResponse);
proxyResponse.headers.set('Access-Control-Allow-Origin', '*');
proxyResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
proxyResponse.headers.set('Access-Control-Allow-Headers', '*');
proxyResponse.headers.set('Content-Type', 'text/event-stream');
return proxyResponse;
}
}
}
// 记录成功的请求
if (response.ok) {
await updateAccountLastUsed(env, account.id);
await updateKiroUsage(env, account.id);
}
// 返回代理响应
const proxyResponse = new Response(response.body, response);
proxyResponse.headers.set('Access-Control-Allow-Origin', '*');
proxyResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
proxyResponse.headers.set('Access-Control-Allow-Headers', '*');
proxyResponse.headers.set('Content-Type', 'text/event-stream');
return proxyResponse;
} catch (error) {
await recordRequest(env, account.id, false, error.message, 500);
return jsonResponse({
error: 'Proxy error',
message: error.message
}, 500);
}
}
// 将 Kiro 的 AWS Event Stream 二进制原始字节流转换为标准 OpenAI 兼容的 SSE Stream 响应
function handleKiroStreamResponse(kiroResponse, openaiRequest) {
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();
const encoder = new TextEncoder();
const requestId = `chatcmpl-${generateUUID()}`;
(async () => {
let buffer = new Uint8Array(0);
const reader = kiroResponse.body.getReader();
const textDecoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const newBuffer = new Uint8Array(buffer.length + value.length);
newBuffer.set(buffer);
newBuffer.set(value, buffer.length);
buffer = newBuffer;
while (buffer.length >= 16) {
const totalLength = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
if (buffer.length < totalLength) break;
const headersLength = (buffer[4] << 24) | (buffer[5] << 16) | (buffer[6] << 8) | buffer[7];
const headersBuffer = buffer.subarray(12, 12 + headersLength);
let eventType = '';
let offset = 0;
while (offset < headersBuffer.length) {
const nameLen = headersBuffer[offset];
offset++;
if (offset + nameLen > headersBuffer.length) break;
const name = 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 = textDecoder.decode(headersBuffer.slice(offset, offset + valueLen));
offset += valueLen;
if (name === ':event-type') {
eventType = value;
break;
}
} else {
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;
}
}
}
const payloadStart = 12 + headersLength;
const payloadEnd = totalLength - 4;
if (payloadStart < payloadEnd) {
const payloadBytes = buffer.subarray(payloadStart, payloadEnd);
try {
const payloadText = 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: openaiRequest.model || 'gpt-4o',
choices: [{ index: 0, delta: { content }, finish_reason: null }]
};
await writer.write(encoder.encode(`data: ${JSON.stringify(streamChunk)}\n\n`));
}
} catch (e) {}
}
buffer = buffer.subarray(totalLength);
}
}
const finalChunk = {
id: requestId,
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: openaiRequest.model || 'gpt-4o',
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }]
};
await writer.write(encoder.encode(`data: ${JSON.stringify(finalChunk)}\n\n`));
await writer.write(encoder.encode('data: [DONE]\n\n'));
} catch (err) {
console.error('[Stream error]', err);
} finally {
try {
await writer.close();
} catch (e) {}
}
})();
return new Response(readable, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
}
});
}
// 处理 OpenAI 格式的 Kiro 聊天请求
async function handleKiroChatCompletion(request, env) {
try {
console.log('[handleKiroChatCompletion] Starting...');
// 获取可用的 Kiro 账号
const account = await getAvailableAccount(env, 'kiro');
console.log(`[handleKiroChatCompletion] Account: ${account ? (account.email || account.id) : 'NULL'}`);
if (!account) {
return jsonResponse({
error: 'No available Kiro accounts',
message: 'Please add Kiro accounts in admin panel'
}, 503);
}
console.log(`[handleKiroChatCompletion] Has accessToken: ${!!account.accessToken}, Has ssoToken: ${!!account.ssoToken}`);
// 检查账号是否有 accessToken
if (!account.accessToken && !account.ssoToken) {
console.log('[handleKiroChatCompletion] No token, attempting refresh...');
// 尝试刷新 Token
const refreshResult = await refreshKiroToken(env, account.id);
if (refreshResult.success) {
// 重新获取账号
const refreshedAccount = await getAccount(env, account.id);
if (refreshedAccount && refreshedAccount.accessToken) {
Object.assign(account, refreshedAccount);
console.log('[handleKiroChatCompletion] Token refreshed successfully');
} else {
return jsonResponse({
error: 'Token refresh succeeded but account still has no accessToken',
message: 'Please check KV storage configuration',
accountId: account.id
}, 500);
}
} else {
return jsonResponse({
error: 'Account missing token and refresh failed',
message: refreshResult.error,
accountId: account.id
}, 500);
}
}
// 检查 Token 是否过期
if (account.expiresAt && account.expiresAt < Date.now() + 300000) {
console.log('[handleKiroChatCompletion] Token expiring soon, refreshing...');
await refreshKiroToken(env, account.id);
const refreshedAccount = await getAccount(env, account.id);
if (refreshedAccount) {
Object.assign(account, refreshedAccount);
}
}
// 解析 OpenAI 格式的请求
const openaiRequest = await request.json();
console.log(`[handleKiroChatCompletion] Request model: ${openaiRequest.model}, messages: ${openaiRequest.messages?.length}`);
// 解析 profileArn
const profileArn = resolveProfileArn(account);
// 转换为 Kiro 格式
const kiroPayload = openaiToKiro(openaiRequest, profileArn);
console.log(`[handleKiroChatCompletion] Kiro payload conversationId: ${kiroPayload.conversationState?.conversationId}`);
// 构建 Kiro API 请求
const region = account.region || 'us-east-1';
const kiroUrl = `https://codewhisperer.${region}.amazonaws.com/generateAssistantResponse`;
console.log(`[handleKiroChatCompletion] Calling Kiro API: ${kiroUrl}`);
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${account.accessToken || account.ssoToken}`,
'x-amzn-kiro-agent-mode': 'spec',
'x-amz-user-agent': getKiroAmzUserAgent(),
'user-agent': getKiroUserAgent(),
'amz-sdk-invocation-id': generateUUID(),
'amz-sdk-request': 'attempt=1; max=3'
};
// 发送请求到 Kiro
const kiroResponse = await fetch(kiroUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(kiroPayload)
});
console.log(`[handleKiroChatCompletion] Kiro API response status: ${kiroResponse.status}`);
console.log(`[handleKiroChatCompletion] Response Content-Type: ${kiroResponse.headers.get('content-type')}`);
// 记录请求结果
const statusCode = kiroResponse.status;
await recordRequest(env, account.id, kiroResponse.ok, null, statusCode);
// 检查认证错误
if (statusCode === 401 || statusCode === 403) {
// 尝试切换到下一个账号
const excludeIds = new Set([account.id]);
const nextAccount = await getAvailableAccount(env, 'kiro', excludeIds);
if (nextAccount && nextAccount.id !== account.id) {
console.log(`[Kiro] Auth failed for ${account.email || account.id}, retrying with ${nextAccount.email || nextAccount.id}`);
// 使用新账号重试
const retryHeaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${nextAccount.accessToken || nextAccount.ssoToken}`,
'x-amzn-kiro-agent-mode': 'spec',
'x-amz-user-agent': getKiroAmzUserAgent(),
'user-agent': getKiroUserAgent(),
'amz-sdk-invocation-id': generateUUID(),
'amz-sdk-request': 'attempt=2; max=3'
};
const retryPayload = openaiToKiro(openaiRequest, resolveProfileArn(nextAccount));
const retryResponse = await fetch(kiroUrl, {
method: 'POST',
headers: retryHeaders,
body: JSON.stringify(retryPayload)
});
await recordRequest(env, nextAccount.id, retryResponse.ok, null, retryResponse.status);
if (retryResponse.ok) {
await updateAccountLastUsed(env, nextAccount.id);
// 处理流式响应
if (openaiRequest.stream) {
return handleKiroStreamResponse(retryResponse, openaiRequest);
} else {
// 重新解析响应(复制主流程的逻辑)
const arrayBuffer = await retryResponse.arrayBuffer();
const buffer = new Uint8Array(arrayBuffer);
let content = '';
let offset = 0;
while (offset < buffer.length) {
if (offset + 16 > buffer.length) break;
const totalLength = (buffer[offset] << 24) | (buffer[offset + 1] << 16) |
(buffer[offset + 2] << 8) | buffer[offset + 3];
if (totalLength === 0 || totalLength > 1000000 || offset + totalLength > buffer.length) break;
const headersLength = (buffer[offset + 4] << 24) | (buffer[offset + 5] << 16) |
(buffer[offset + 6] << 8) | buffer[offset + 7];
const payloadStart = offset + 12 + headersLength;
const payloadEnd = offset + totalLength - 4;
if (payloadStart < payloadEnd) {
const payloadBytes = buffer.slice(payloadStart, payloadEnd);
const payloadText = new TextDecoder().decode(payloadBytes);
try {
const event = JSON.parse(payloadText);
if (event.content && typeof event.content === 'string') {
content += event.content;
}
if (event.assistantResponseEvent && event.assistantResponseEvent.content) {
content += event.assistantResponseEvent.content;
}
if (event.codeEvent && event.codeEvent.content) {
content += event.codeEvent.content;
}
} catch (e) {
// 忽略解析错误
}
}
offset += totalLength;
}
const openaiResponse = {
id: `chatcmpl-${generateUUID()}`,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: openaiRequest.model || 'claude-sonnet-4.5',
choices: [{
index: 0,
message: {
role: 'assistant',
content: content
},
finish_reason: 'stop'
}],
usage: {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0
}
};
return jsonResponse(openaiResponse);
}
}
}
// 无可用账号或重试失败
const errorText = await kiroResponse.text();
return jsonResponse({
error: 'Authentication failed',
message: 'Token expired or invalid',
kiroError: errorText,
accountId: account.id,
tokenLength: account.accessToken ? account.accessToken.length : 0
}, 401);
}
if (!kiroResponse.ok) {
const errorText = await kiroResponse.text();
return jsonResponse({
error: 'Kiro API error',
message: errorText,
status: kiroResponse.status
}, kiroResponse.status);
}
// 解析 Kiro 响应(AWS Event Stream 格式)
// Kiro API 返回的是二进制事件流,需要解析每个事件
if (openaiRequest.stream) {
return handleKiroStreamResponse(kiroResponse, openaiRequest);
}
const arrayBuffer = await kiroResponse.arrayBuffer();
const buffer = new Uint8Array(arrayBuffer);
console.log(`[Debug] Kiro response size: ${buffer.length} bytes`);
// 显示前64字节的hex dump
if (buffer.length > 0) {
const hex = Array.from(buffer.slice(0, Math.min(64, buffer.length)))
.map(b => b.toString(16).padStart(2, '0'))
.join(' ');
console.log(`[Debug] First 64 bytes (hex): ${hex}`);
// 也显示为文本(如果可读)
const text = new TextDecoder().decode(buffer.slice(0, Math.min(200, buffer.length)));
console.log(`[Debug] First 200 chars as text: ${text.replace(/\n/g, '\\n')}`);
}
let content = '';
let offset = 0;
let eventCount = 0;
// 解析 AWS Event Stream 格式
// 每个消息格式:[4字节总长度][4字节头长度][4字节CRC][头部][payload][4字节CRC]
while (offset < buffer.length) {
// 至少需要 16 字节(prelude)
if (offset + 16 > buffer.length) {
console.log(`[Debug] Incomplete message at offset ${offset}, remaining ${buffer.length - offset} bytes`);
break;
}
// 读取总长度(big-endian uint32)
const totalLength = (buffer[offset] << 24) | (buffer[offset + 1] << 16) |
(buffer[offset + 2] << 8) | buffer[offset + 3];
console.log(`[Debug] Message at offset ${offset}: totalLength=${totalLength}`);
// 检查是否有完整消息
if (totalLength === 0 || totalLength > 1000000) {
console.log(`[Debug] Invalid totalLength: ${totalLength}, stopping parse`);
break;
}
if (offset + totalLength > buffer.length) {
console.log(`[Debug] Incomplete message: need ${totalLength}, have ${buffer.length - offset}`);
break;
}
// 读取头部长度
const headersLength = (buffer[offset + 4] << 24) | (buffer[offset + 5] << 16) |
(buffer[offset + 6] << 8) | buffer[offset + 7];
console.log(`[Debug] headersLength=${headersLength}`);
// 提取 payload(跳过 prelude(12字节) + headers)
const payloadStart = offset + 12 + headersLength;
const payloadEnd = offset + totalLength - 4; // 减去最后的 CRC
if (payloadStart < payloadEnd) {
const payloadBytes = buffer.slice(payloadStart, payloadEnd);
const payloadText = new TextDecoder().decode(payloadBytes);
console.log(`[Debug] Payload length: ${payloadBytes.length}, text length: ${payloadText.length}`);
console.log(`[Debug] Payload preview: ${payloadText.substring(0, 100)}`);
try {
const event = JSON.parse(payloadText);
eventCount++;
console.log(`[Debug] Event ${eventCount} keys:`, Object.keys(event).join(', '));
// 多层级提取内容
// 1. 检查直接的 content 字段
if (event.content && typeof event.content === 'string') {
content += event.content;
console.log(`[Debug] Added direct content: ${event.content.length} chars, total: ${content.length}`);
}
// 2. 检查 assistantResponseEvent.content
if (event.assistantResponseEvent && event.assistantResponseEvent.content) {
content += event.assistantResponseEvent.content;
console.log(`[Debug] Added assistantResponseEvent.content: ${event.assistantResponseEvent.content.length} chars`);
}
// 3. 检查 codeEvent.content
if (event.codeEvent && event.codeEvent.content) {
content += event.codeEvent.content;
console.log(`[Debug] Added codeEvent.content: ${event.codeEvent.content.length} chars`);
}
// 4. 检查 supplementaryWebLinksEvent
if (event.supplementaryWebLinksEvent && event.supplementaryWebLinksEvent.supplementaryWebLinks) {