Repository navigation
Expand file tree
/
Copy pathcloudflare-worker.mjs
More file actions
2187 lines (1925 loc) · 65.4 KB
/
Copy pathcloudflare-worker.mjs
File metadata and controls
2187 lines (1925 loc) · 65.4 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
import { BUILD_ID } from "./worker/build-id.mjs";
import { admitContainerDelegation } from "./worker/peer-controls.mjs";
import { dispatchFailure } from "./worker/provider-dispatch.mjs";
import { KEY_CONTROLS } from "./worker/key-controls-capability.mjs";
import { nativeGenerationFetch, withForwardedCorrelation, withNativeMetrics, nativeCacheHeader, nativeGenerationSetup, generationErrorResponse, forwardedGenerationHeaders, runScheduledMaintenance, scheduledMaintenanceEnabled, handleRoleplayContextPageRequest, handleRealtimeRequest } from "./worker/gateway-extensions.mjs";
import { batchesEnabled, runScheduledBatches } from "./worker/batch-jobs.mjs";
import { tickNativeRevisionSync } from "./worker/native-config-sync.mjs";
import { firewallFetch } from "./worker/secret-firewall.mjs";
import { Container, ContainerProxy, getContainer } from "@cloudflare/containers";
import { collectContainerEnv } from "./worker/container-env.mjs";
import { d1Readiness } from "./worker/d1-schema.mjs";
import { handleIntelligenceOutbound } from "./worker/intelligence-outbound.mjs";
import { handleKnowledgeOutbound } from "./worker/knowledge-outbound.mjs";
import { handleAiOutbound } from "./worker/ai-outbound.mjs";
import { handleMediaOutbound } from "./worker/media-outbound.mjs";
import { serveSignedMediaFile, signedMediaFileId } from "./worker/media-files.mjs";
import { MediaJobWorkflow } from "./worker/media-workflow.mjs";
import { AdmissionCoordinator } from "./worker/admission-do.mjs";
import { handleKnowledgeEdgeRequest, isKnowledgeEdgePath } from "./worker/knowledge-edge.mjs";
import { withAccessIdentity } from "./worker/access-sso.mjs";
import { runScheduledShadowEval } from "./worker/shadow-eval-schedule.mjs";
import { fetchIfRunning, runScheduledHealth } from "./worker/health-schedule.mjs";
import { STATUS_PATHS, handleStatusRequest, handleStatusPrometheusRequest, prometheusEnabled } from "./worker/status-page.mjs";
export { ContainerProxy };
import { isApiRequestPath } from "./worker/api-paths.mjs";
import { buildRootFallbackResponse } from "./worker/fallback-page.mjs";
import { CLIENT_HEADER_NAMES, OPENCODE_CLIENT_HEADER_NAMES, withClientDefaults, withOpencodeSession } from "./worker/client-headers.mjs";
import { withOpencodeRequestSession } from "./worker/opencode-session.mjs";
import { withOpencodeGlmReasoning } from "./worker/opencode/reasoning-request.mjs";
import {
RoleplaySession,
handleRoleplayEdgeRequest,
isRoleplayPath,
} from "./worker/roleplay/endpoint.mjs";
import {
normalizeOpencodeChatResponse,
resolveOpencodeChatMetadata,
} from "./worker/opencode/reasoning-response.mjs";
import {
GPTImageModerationError,
withDefaultGptImageModeration,
} from "./worker/gpt-image-moderation.mjs";
import {
resolveSseHeartbeatMs,
withSseHeartbeat,
} from "./worker/sse-heartbeat.mjs";
import { withJanitorGlmReasoningNormalization } from "./worker/janitor-reasoning-response.mjs";
export { RoleplaySession };
export { AdmissionCoordinator };
export { MediaJobWorkflow };
import { CORS_ALLOWED_METHODS, CORS_DEFAULT_HEADERS, CORS_EXPOSE_HEADERS } from "./worker/cors-policy.mjs";
const LINKAPI_DEFAULT_BASE_URL = "https://api.linkapi.ai";
const CODEX_EASY_BASE_URL = "https://codex-easy.ai";
const CODEX_EASY_ROUTE_PREFIX = "/codex-easy";
const KIMI_CODE_ROUTE_PREFIX = "/kimi-code";
const CONTAINER_PACKAGE_STARTUP_ERROR_PREFIXES = new Map([
[500, "Failed to start container:"],
[503, "There is no Container instance available at this time."],
]);
const LINKAPI_ALLOWED_HOSTNAMES = new Set([
"linkapi.ai",
"api.linkapi.ai",
"hk.linkapi.ai",
"jp.linkapi.ai",
"linkapi.cc",
"linkapi.pro",
]);
const OPENCODE_DEFAULT_BASE_URL = "https://opencode.ai/zen/go/v1";
const OPENCODE_ROUTE_PREFIX = "/opencode";
const OPENCODE_REQUEST_HEADER_WHITELIST = new Set([
...CLIENT_HEADER_NAMES,
...OPENCODE_CLIENT_HEADER_NAMES,
"accept",
"accept-language",
"anthropic-beta",
"anthropic-dangerous-direct-browser-access",
"anthropic-version",
"content-type",
"idempotency-key",
"openai-beta",
"openai-organization",
"openai-project",
"user-agent",
"x-client-request-id",
"x-request-id",
"x-stainless-arch",
"x-stainless-async",
"x-stainless-lang",
"x-stainless-os",
"x-stainless-package-version",
"x-stainless-retry-count",
"x-stainless-runtime",
"x-stainless-runtime-version",
"x-stainless-timeout",
]);
const LINKAPI_REQUEST_HEADER_WHITELIST = new Set([
...CLIENT_HEADER_NAMES,
"accept",
"accept-language",
"anthropic-beta",
"anthropic-dangerous-direct-browser-access",
"anthropic-version",
"content-type",
"idempotency-key",
"openai-beta",
"openai-organization",
"openai-project",
"user-agent",
"x-client-request-id",
"x-goog-api-client",
"x-goog-user-project",
"x-request-id",
"x-stainless-arch",
"x-stainless-async",
"x-stainless-lang",
"x-stainless-os",
"x-stainless-package-version",
"x-stainless-retry-count",
"x-stainless-runtime",
"x-stainless-runtime-version",
"x-stainless-timeout",
]);
const LINKAPI_OPENAI_REQUEST_HEADER_WHITELIST = new Set(["x-grok-conv-id"]);
const LINKAPI_RESPONSE_HEADER_WHITELIST = new Set([
"cache-control",
"content-disposition",
"content-type",
"date",
"etag",
"expires",
"last-modified",
"openai-processing-ms",
"openai-version",
"request-id",
"retry-after",
"vary",
"x-request-id",
"x-should-retry",
"x-multillm-secret-scan",
]);
const LINKAPI_RESPONSE_HEADER_PREFIXES = [
"anthropic-ratelimit-",
"ratelimit-",
"x-ratelimit-",
];
const CODEX_EASY_REQUEST_HEADER_WHITELIST = new Set([
...CLIENT_HEADER_NAMES,
"accept",
"content-type",
"idempotency-key",
"openai-beta",
"openai-organization",
"openai-project",
"x-client-request-id",
"x-grok-conv-id",
]);
const CODEX_EASY_RESPONSE_HEADER_WHITELIST = new Set([
"accept-ranges",
"cache-control",
"content-disposition",
"content-language",
"content-range",
"content-type",
"etag",
"expires",
"last-modified",
"openai-processing-ms",
"openai-version",
"pragma",
"request-id",
"retry-after",
"vary",
"x-request-id",
"x-should-retry",
"x-multillm-secret-scan",
]);
const CODEX_EASY_RESPONSE_HEADER_PREFIXES = ["ratelimit-", "x-ratelimit-"];
// The Container would decode `/%69nternal/` or merge `//internal/`, so check the decoded path.
function isInternalPath(pathname) {
try {
return /^\/+internal(?:\/|$)/i.test(decodeURIComponent(pathname));
} catch {
return true;
}
}
function isDirectHealthPath(pathname) {
return pathname === "/health";
}
function isDirectOpencodePath(pathname) {
return pathname === "/opencode" || pathname.startsWith("/opencode/");
}
function isDirectLinkApiPath(pathname) {
return pathname === "/linkapi" || pathname.startsWith("/linkapi/");
}
function isCodexEasyNamespacePath(pathname) {
let candidate = pathname.toLowerCase();
for (let decodeCount = 0; decodeCount < 4; decodeCount += 1) {
if (
candidate === CODEX_EASY_ROUTE_PREFIX ||
candidate.startsWith(`${CODEX_EASY_ROUTE_PREFIX}/`) ||
candidate.startsWith(`${CODEX_EASY_ROUTE_PREFIX}\\`) ||
candidate.startsWith(`${CODEX_EASY_ROUTE_PREFIX}%`)
) {
return true;
}
if (!candidate.includes("%")) {
return false;
}
try {
const decodedCandidate = decodeURIComponent(candidate);
if (decodedCandidate === candidate) {
return false;
}
candidate = decodedCandidate;
} catch {
return false;
}
}
return false;
}
function isKimiCodeNamespacePath(pathname) {
let candidate = pathname.toLowerCase();
for (let decodeCount = 0; decodeCount < 4; decodeCount += 1) {
if (
candidate === KIMI_CODE_ROUTE_PREFIX ||
candidate.startsWith(`${KIMI_CODE_ROUTE_PREFIX}/`) ||
candidate.startsWith(`${KIMI_CODE_ROUTE_PREFIX}\\`) ||
candidate.startsWith(`${KIMI_CODE_ROUTE_PREFIX}%`)
) {
return true;
}
if (!candidate.includes("%")) {
return false;
}
try {
const decodedCandidate = decodeURIComponent(candidate);
if (decodedCandidate === candidate) {
return false;
}
candidate = decodedCandidate;
} catch {
return false;
}
}
return false;
}
function extractBearerToken(request) {
const authHeader = request.headers.get("Authorization") ?? "";
if (!authHeader.startsWith("Bearer ")) {
return "";
}
return authHeader.slice("Bearer ".length).trim();
}
function jsonResponse(body, init = {}) {
const headers = new Headers(init.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
return new Response(JSON.stringify(body), {
...init,
headers,
});
}
function buildFallbackHealthResponse() {
return jsonResponse({
status: "healthy", key_controls: KEY_CONTROLS,
mode: "worker-fallback",
});
}
function buildContainerNotReadyApiResponse() {
return jsonResponse(
{
error: "Proxy unavailable",
message: "The proxy container is not ready to handle requests.",
},
{
status: 503,
headers: { "Retry-After": "5" },
},
);
}
function buildContainerNotReadyTextResponse() {
return new Response("Proxy unavailable", {
status: 503,
headers: {
"Content-Type": "text/plain; charset=UTF-8",
"Retry-After": "5",
},
});
}
function buildUnauthorizedResponse() {
return jsonResponse(
{
error: "Authentication required",
message: "Please provide a valid admin API key in the Authorization header.",
},
{ status: 401 },
);
}
function buildMissingUpstreamKeyResponse() {
return jsonResponse(
{
error: "Server configuration error",
message:
"OPENCODE_GO_API_KEY (or OPENCODE_API_KEY) is not configured on the worker.",
},
{ status: 500 },
);
}
function buildLinkApiUnauthorizedResponse() {
return jsonResponse(
{
error: "Authentication required",
message: "Please provide a valid admin API key.",
},
{ status: 401 },
);
}
function buildMissingLinkApiKeyResponse() {
return jsonResponse(
{
error: "Server configuration error",
message: "The requested provider is not configured on the worker.",
},
{ status: 500 },
);
}
function buildCodexEasyUnsupportedPathResponse() {
return jsonResponse(
{
error: "Not found",
message: "The requested provider path is not supported.",
},
{ status: 404 },
);
}
function buildMissingCodexEasyKeyResponse() {
return jsonResponse(
{
error: "Server configuration error",
message: "The requested provider is not configured on the worker.",
},
{ status: 500 },
);
}
function buildKimiCodeUnsupportedPathResponse() {
return jsonResponse(
{
error: "Not found",
message: "The requested provider path is not supported.",
},
{ status: 404 },
);
}
function buildMissingKimiCodeKeyResponse() {
return jsonResponse(
{
error: "Server configuration error",
message: "The requested provider is not configured on the worker.",
},
{ status: 500 },
);
}
function logStructuredError(event, error) {
const candidateName = error instanceof Error ? error.name : "UnknownError";
const errorName = /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(candidateName)
? candidateName
: "Error";
console.error({ event, errorName });
}
function extractLinkApiCallerToken(request, requestUrl) {
const authorization = request.headers.get("Authorization") ?? "";
const bearerMatch = authorization.match(/^Bearer\s+(.+)$/i);
const candidates = [
bearerMatch?.[1],
request.headers.get("x-api-key"),
request.headers.get("x-goog-api-key"),
...requestUrl.searchParams.getAll("key"),
];
for (const candidate of candidates) {
if (typeof candidate === "string" && candidate.trim()) {
return candidate.trim();
}
}
return "";
}
async function timingSafeTokenMatch(providedToken, expectedToken) {
const encoder = new TextEncoder();
const [providedDigest, expectedDigest] = await Promise.all([
crypto.subtle.digest("SHA-256", encoder.encode(String(providedToken ?? ""))),
crypto.subtle.digest("SHA-256", encoder.encode(String(expectedToken ?? ""))),
]);
const providedBytes = new Uint8Array(providedDigest);
const expectedBytes = new Uint8Array(expectedDigest);
if (typeof crypto.subtle.timingSafeEqual === "function") {
return (
Boolean(providedToken) &&
Boolean(expectedToken) &&
crypto.subtle.timingSafeEqual(providedBytes, expectedBytes)
);
}
// Node's Web Crypto test harness lacks Workers' timingSafeEqual extension.
let mismatch = providedBytes.byteLength ^ expectedBytes.byteLength;
for (let index = 0; index < providedBytes.byteLength; index += 1) {
mismatch |= providedBytes[index] ^ expectedBytes[index];
}
return Boolean(providedToken) && Boolean(expectedToken) && mismatch === 0;
}
function getTrustedLinkApiBaseUrl(configuredBaseUrl) {
if (typeof configuredBaseUrl !== "string" || !configuredBaseUrl.trim()) {
return new URL(LINKAPI_DEFAULT_BASE_URL);
}
try {
const candidate = new URL(configuredBaseUrl.trim());
const hasUnsupportedParts =
candidate.protocol !== "https:" ||
Boolean(candidate.username) ||
Boolean(candidate.password) ||
Boolean(candidate.search) ||
Boolean(candidate.hash) ||
Boolean(candidate.port) ||
!LINKAPI_ALLOWED_HOSTNAMES.has(candidate.hostname) ||
(candidate.pathname !== "/" && candidate.pathname !== "");
if (hasUnsupportedParts) {
return new URL(LINKAPI_DEFAULT_BASE_URL);
}
return new URL(candidate.origin);
} catch {
return new URL(LINKAPI_DEFAULT_BASE_URL);
}
}
function getLinkApiProtocol(pathname) {
if (pathname === "/v1/messages" || pathname.startsWith("/v1/messages/")) {
return "claude";
}
if (pathname === "/v1beta" || pathname.startsWith("/v1beta/")) {
return "gemini";
}
return "openai";
}
function buildLinkApiUpstreamUrl(requestUrl, env) {
const upstreamUrl = getTrustedLinkApiBaseUrl(env.LINKAPI_BASE_URL);
const suffix = requestUrl.pathname.slice("/linkapi".length) || "/";
upstreamUrl.pathname = suffix;
for (const [name, value] of requestUrl.searchParams.entries()) {
if (name.toLowerCase() !== "key") {
upstreamUrl.searchParams.append(name, value);
}
}
return upstreamUrl;
}
function buildLinkApiUpstreamHeaders(request, protocol, upstreamPathname, upstreamToken) {
const headers = new Headers();
for (const [header, value] of request.headers.entries()) {
const normalized = header.toLowerCase();
if (
LINKAPI_REQUEST_HEADER_WHITELIST.has(normalized) ||
(protocol === "openai" &&
upstreamPathname === "/v1/chat/completions" &&
LINKAPI_OPENAI_REQUEST_HEADER_WHITELIST.has(normalized))
) {
headers.set(header, value);
}
}
if (request.method !== "GET" && request.method !== "HEAD" && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
if (!headers.has("Accept")) {
headers.set("Accept", "application/json");
}
if (protocol === "claude") {
headers.set("x-api-key", upstreamToken);
if (!headers.has("anthropic-version")) {
headers.set("anthropic-version", "2023-06-01");
}
} else if (protocol === "gemini") {
headers.set("x-goog-api-key", upstreamToken);
} else if (protocol === "openai") {
headers.set("Authorization", `Bearer ${upstreamToken}`);
}
return headers;
}
function copyLinkApiResponseHeaders(headers, env) {
const responseHeaders = new Headers();
for (const [header, value] of headers.entries()) {
const normalized = header.toLowerCase();
if (
nativeCacheHeader(normalized, headers, env) || LINKAPI_RESPONSE_HEADER_WHITELIST.has(normalized) ||
LINKAPI_RESPONSE_HEADER_PREFIXES.some((prefix) => normalized.startsWith(prefix))
) {
responseHeaders.set(header, value);
}
}
return responseHeaders;
}
function getCodexEasyUpstreamPath(pathname) {
if (
!pathname.startsWith(`${CODEX_EASY_ROUTE_PREFIX}/`) ||
pathname.includes("%") ||
pathname.includes("\\")
) {
return null;
}
const suffix = pathname.slice(CODEX_EASY_ROUTE_PREFIX.length);
if (
suffix === "/v1/models" ||
suffix === "/v1/responses" ||
suffix === "/v1/chat/completions" ||
suffix === "/v1/images"
) {
return suffix;
}
if (!suffix.startsWith("/v1/images/")) {
return null;
}
const imagePathSegments = suffix.slice("/v1/images/".length).split("/");
if (
imagePathSegments.some(
(segment) =>
!segment ||
segment === "." ||
segment === ".." ||
!/^[A-Za-z0-9._~!$&'()*+,;=:@-]+$/.test(segment),
)
) {
return null;
}
return suffix;
}
function buildCodexEasyUpstreamUrl(requestUrl, upstreamPath) {
const upstreamUrl = new URL(CODEX_EASY_BASE_URL);
upstreamUrl.pathname = upstreamPath;
for (const [name, value] of requestUrl.searchParams.entries()) {
if (name.toLowerCase() !== "key") {
upstreamUrl.searchParams.append(name, value);
}
}
return upstreamUrl;
}
function buildCodexEasyUpstreamHeaders(request, upstreamToken) {
const headers = new Headers();
for (const [header, value] of request.headers.entries()) {
const normalized = header.toLowerCase();
if (
CODEX_EASY_REQUEST_HEADER_WHITELIST.has(normalized) ||
normalized.startsWith("x-stainless-")
) {
headers.set(header, value);
}
}
if (!headers.has("Accept")) {
headers.set("Accept", "application/json");
}
headers.set("Authorization", `Bearer ${upstreamToken}`);
return headers;
}
function copyCodexEasyResponseHeaders(headers, env) {
const responseHeaders = new Headers();
for (const [header, value] of headers.entries()) {
const normalized = header.toLowerCase();
if (
nativeCacheHeader(normalized, headers, env) || CODEX_EASY_RESPONSE_HEADER_WHITELIST.has(normalized) ||
CODEX_EASY_RESPONSE_HEADER_PREFIXES.some((prefix) => normalized.startsWith(prefix))
) {
responseHeaders.set(header, value);
}
}
return responseHeaders;
}
function getKimiCodeUpstreamPath(pathname) {
if (
!pathname.startsWith(`${KIMI_CODE_ROUTE_PREFIX}/`) ||
pathname.includes("%") ||
pathname.includes("\\")
) {
return null;
}
const suffix = pathname.slice(KIMI_CODE_ROUTE_PREFIX.length);
if (suffix === "/v1/models") {
return "/models";
}
if (suffix === "/v1/chat/completions") {
return "/chat/completions";
}
return null;
}
function isKimiCodeMethodAllowed(upstreamPath, method) {
return (
(upstreamPath === "/models" && method === "GET") ||
(upstreamPath === "/chat/completions" && method === "POST")
);
}
function getOpencodeUpstreamPath(pathname) {
if (
pathname !== OPENCODE_ROUTE_PREFIX &&
!pathname.startsWith(`${OPENCODE_ROUTE_PREFIX}/`)
) {
return null;
}
const suffix = pathname.slice(OPENCODE_ROUTE_PREFIX.length).replace(/^\/+/, "");
if (!suffix || suffix.toLowerCase() === "v1") {
return "/v1";
}
if (suffix.toLowerCase().startsWith("v1/")) {
return `/${suffix}`;
}
return `/v1/${suffix}`;
}
function isOpencodeNativeRequest(pathname, method) {
const upstreamPath = getOpencodeUpstreamPath(pathname)?.toLowerCase();
const documented =
(upstreamPath === "/v1/chat/completions" && method === "POST") ||
(upstreamPath === "/v1/messages" && method === "POST") ||
(upstreamPath === "/v1/responses" && method === "POST") ||
(upstreamPath === "/v1/models" && method === "GET");
return documented && pathname.toLowerCase() !== "/opencode/chat/completions";
}
function getOpencodeBaseUrl(env) {
const configuredBaseUrl =
env.OPENCODE_GO_BASE_URL ||
env.OPENCODE_BASE_URL ||
OPENCODE_DEFAULT_BASE_URL;
try {
const candidate = new URL(configuredBaseUrl);
if (
candidate.protocol !== "https:" ||
candidate.username ||
candidate.password ||
candidate.search ||
candidate.hash
) {
return new URL(OPENCODE_DEFAULT_BASE_URL);
}
return candidate;
} catch {
return new URL(OPENCODE_DEFAULT_BASE_URL);
}
}
function buildOpencodeUpstreamUrl(requestUrl, env, upstreamPath) {
const upstreamUrl = getOpencodeBaseUrl(env);
const normalizedBasePath = upstreamUrl.pathname.replace(/\/+$/, "");
let suffix = upstreamPath;
if (normalizedBasePath.toLowerCase().endsWith("/v1")) {
if (upstreamPath.toLowerCase() === "/v1") {
suffix = "";
} else if (upstreamPath.toLowerCase().startsWith("/v1/")) {
suffix = upstreamPath.slice("/v1".length);
}
}
upstreamUrl.pathname = `${normalizedBasePath}${suffix}`;
upstreamUrl.search = requestUrl.search;
return upstreamUrl;
}
function extractOpencodeCallerToken(request) {
const proxyToken = request.headers.get("x-multillm-api-key")?.trim();
if (proxyToken) {
return proxyToken;
}
const bearerToken = extractBearerToken(request);
if (bearerToken) {
return bearerToken;
}
return request.headers.get("x-api-key")?.trim() ?? "";
}
function opencodeCallerUpstreamAuth(request) {
if (!request.headers.get("x-multillm-api-key")?.trim()) {
return {};
}
const authorization = request.headers.get("Authorization") ?? "";
const bearerMatch = authorization.match(/^Bearer\s+(.+)$/i);
const apiKey = request.headers.get("x-api-key")?.trim();
return {
...(bearerMatch?.[1]?.trim()
? { authorization: `Bearer ${bearerMatch[1].trim()}` }
: {}),
...(apiKey ? { apiKey } : {}),
};
}
function buildOpencodeUpstreamHeaders(
request,
upstreamPath,
upstreamToken,
callerAuth,
) {
let headers = new Headers();
for (const [header, value] of request.headers.entries()) {
if (OPENCODE_REQUEST_HEADER_WHITELIST.has(header.toLowerCase())) {
headers.set(header, value);
}
}
headers = withOpencodeSession(headers);
if (
request.method !== "GET" &&
request.method !== "HEAD" &&
!headers.has("Content-Type")
) {
headers.set("Content-Type", "application/json");
}
if (!headers.has("Accept")) {
headers.set("Accept", "application/json");
}
if (callerAuth.authorization) {
headers.set("Authorization", callerAuth.authorization);
}
if (callerAuth.apiKey) {
headers.set("X-Api-Key", callerAuth.apiKey);
}
if (!callerAuth.authorization && !callerAuth.apiKey) {
if (upstreamPath.toLowerCase() === "/v1/messages") {
headers.set("X-Api-Key", upstreamToken);
} else {
headers.set("Authorization", `Bearer ${upstreamToken}`);
}
}
if (
upstreamPath.toLowerCase() === "/v1/messages" &&
!headers.has("Anthropic-Version")
) {
headers.set("Anthropic-Version", "2023-06-01");
}
return headers;
}
function copyProxyResponseHeaders(headers) {
const responseHeaders = new Headers();
for (const [header, value] of headers.entries()) {
const normalized = header.toLowerCase();
if (normalized === "content-length" || normalized === "content-encoding" || normalized === "transfer-encoding") {
continue;
}
responseHeaders.set(header, value);
}
return responseHeaders;
}
async function responseStartsWithAsciiPrefix(response, prefix) {
let reader;
try {
const probeBody = response.clone().body;
if (!probeBody) {
return false;
}
reader = probeBody.getReader();
const expectedBytes = new TextEncoder().encode(prefix);
let matchedBytes = 0;
while (matchedBytes < expectedBytes.byteLength) {
const { value, done } = await reader.read();
if (done || !value) {
return false;
}
const chunk = value instanceof Uint8Array ? value : new Uint8Array(value);
for (const byte of chunk) {
if (byte !== expectedBytes[matchedBytes]) {
return false;
}
matchedBytes += 1;
if (matchedBytes === expectedBytes.byteLength) {
return true;
}
}
}
} catch {
return false;
} finally {
if (reader) {
void reader.cancel().catch(() => {});
}
}
return false;
}
async function isContainerPackageStartupFailure(response) {
const expectedPrefix = CONTAINER_PACKAGE_STARTUP_ERROR_PREFIXES.get(response.status);
if (!expectedPrefix) {
return false;
}
const mediaType = (response.headers.get("content-type") ?? "")
.split(";", 1)[0]
.trim()
.toLowerCase();
if (mediaType !== "text/plain") {
return false;
}
return responseStartsWithAsciiPrefix(response, expectedPrefix);
}
function looksLikeMeaningfulStreamText(text) {
if (!text) {
return false;
}
let alnumChars = 0;
let asciiWordChars = 0;
for (const char of text) {
if (/[0-9A-Za-z]/.test(char)) {
asciiWordChars += 1;
}
if (/\p{L}|\p{N}/u.test(char)) {
alnumChars += 1;
}
}
return alnumChars > 0 && asciiWordChars >= 4;
}
function stripThinkBlocks(value, { trimEdges = true } = {}) {
if (typeof value !== "string") {
return "";
}
let remaining = value;
let stripped = "";
while (remaining) {
const lowerRemaining = remaining.toLowerCase();
const openingIndex = lowerRemaining.indexOf("<think>");
const closingIndex = lowerRemaining.indexOf("</think>");
if (openingIndex === -1) {
stripped += remaining.replace(/<\/think>/gi, "");
break;
}
if (closingIndex !== -1 && closingIndex < openingIndex) {
stripped += remaining.slice(0, closingIndex);
remaining = remaining.slice(closingIndex + "</think>".length);
continue;
}
stripped += remaining.slice(0, openingIndex);
remaining = remaining.slice(openingIndex + "<think>".length);
const innerClosingIndex = remaining.toLowerCase().indexOf("</think>");
if (innerClosingIndex === -1) {
break;
}
remaining = remaining.slice(innerClosingIndex + "</think>".length);
}
return trimEdges ? stripped.trim() : stripped;
}
function sanitizeReasoningCandidate(value, { trimEdges = false } = {}) {
if (typeof value !== "string") {
return "";
}
let sanitized = value.replace(/<\/?think>/gi, "");
const strippedEmbeddedPayload = stripEmbeddedStreamChunkPayload(sanitized);
if (strippedEmbeddedPayload !== null) {
sanitized = strippedEmbeddedPayload;
}
return trimEdges ? sanitized.trim() : sanitized;
}
function extractReasoningPreview(source, { trimEdges = true } = {}) {
if (!source || typeof source !== "object") {
return "";
}
const parts = [];
const seen = new Set();
const maybePush = (value) => {
const sanitized = sanitizeReasoningCandidate(value, { trimEdges });
if (!sanitized || seen.has(sanitized)) {
return;
}
seen.add(sanitized);
parts.push(sanitized);
};
maybePush(source.reasoning_content);
maybePush(source.reasoning);
if (Array.isArray(source.reasoning_details)) {
for (const detail of source.reasoning_details) {
if (typeof detail === "string") {
maybePush(detail);
continue;
}
if (detail && typeof detail === "object") {
maybePush(detail.text);
maybePush(detail.reasoning);
maybePush(detail.reasoning_content);
}
}
}
return parts.join("");
}
function formatVisibleThinkBlock(reasoningPreview, content = "") {
const normalizedPreview = sanitizeReasoningCandidate(reasoningPreview, { trimEdges: true });
const normalizedContent = stripThinkBlocks(content);
if (!normalizedPreview) {
return normalizedContent;
}
return `<think>${normalizedPreview}</think>${normalizedContent ? `\n\n${normalizedContent}` : ""}`;
}
function flushVisibleThinkingBuffer(state) {