-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.test.js
More file actions
1688 lines (1457 loc) · 53.4 KB
/
index.test.js
File metadata and controls
1688 lines (1457 loc) · 53.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 test, { describe, it } from "node:test"
import assert from "node:assert/strict"
import {
createProxyFetchHandler,
createSseQueue,
toTextContent,
normalizeMessages,
normalizeResponseInput,
buildSystemPrompt,
buildPrompt,
extractAssistantText,
mapFinishReason,
resolveModel,
normalizeAnthropicMessages,
mapFinishReasonToAnthropic,
normalizeGeminiContents,
extractGeminiSystemInstruction,
mapFinishReasonToGemini,
} from "./index.js"
// ---------------------------------------------------------------------------
// Integration: createProxyFetchHandler
// ---------------------------------------------------------------------------
function createClient() {
return {
app: {
log: async () => {},
},
config: {
providers: async () => ({
data: {
providers: [],
},
}),
},
}
}
function createStreamingClient(chunks) {
async function* makeStream() {
for (const chunk of chunks) {
yield chunk
}
}
return {
app: { log: async () => {} },
tool: { ids: async () => ({ data: [] }) },
config: {
providers: async () => ({
data: {
providers: [
{
id: "openai",
models: { "gpt-4o": { id: "gpt-4o", name: "GPT-4o" } },
},
],
},
}),
},
session: {
create: async () => ({ data: { id: "sess-123" } }),
promptAsync: async () => {},
messages: async () => ({
data: [
{
role: "assistant",
tokens: { input: 10, output: 5, reasoning: 0, cache: { read: 0, write: 0 } },
finish: "end_turn",
},
],
}),
},
event: {
subscribe: async () => ({ stream: makeStream() }),
},
}
}
test("OPTIONS preflight returns CORS headers", async () => {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/v1/models", {
method: "OPTIONS",
headers: {
Origin: "https://app.example.com",
"Access-Control-Request-Method": "POST",
"Access-Control-Request-Headers": "authorization, content-type, x-opencode-provider",
"Access-Control-Request-Private-Network": "true",
},
})
const response = await handler(request)
assert.equal(response.status, 204)
assert.equal(response.headers.get("access-control-allow-origin"), "*")
assert.equal(response.headers.get("access-control-allow-methods"), "POST")
assert.equal(
response.headers.get("access-control-allow-headers"),
"authorization, content-type, x-opencode-provider",
)
assert.equal(response.headers.get("access-control-allow-private-network"), "true")
assert.equal(response.headers.get("access-control-max-age"), "86400")
})
test("health response includes CORS headers", async () => {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/health", {
headers: {
Origin: "https://app.example.com",
},
})
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 200)
assert.equal(response.headers.get("access-control-allow-origin"), "*")
assert.deepEqual(body, { healthy: true, service: "opencode-openai-proxy" })
})
test("configured origin is returned for normal requests", async () => {
process.env.OPENCODE_LLM_PROXY_CORS_ORIGIN = "https://console.example.com"
try {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/health", {
headers: {
Origin: "https://app.example.com",
},
})
const response = await handler(request)
assert.equal(response.headers.get("access-control-allow-origin"), "https://console.example.com")
} finally {
delete process.env.OPENCODE_LLM_PROXY_CORS_ORIGIN
}
})
test("disallowed origin does not receive its own origin back", async () => {
process.env.OPENCODE_LLM_PROXY_CORS_ORIGIN = "https://allowed.example.com"
try {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/health", {
headers: { Origin: "https://evil.example.com" },
})
const response = await handler(request)
// The header must be the configured origin, not the request's origin
assert.equal(response.headers.get("access-control-allow-origin"), "https://allowed.example.com")
assert.notEqual(response.headers.get("access-control-allow-origin"), "https://evil.example.com")
} finally {
delete process.env.OPENCODE_LLM_PROXY_CORS_ORIGIN
}
})
test("request with no Origin header is handled gracefully", async () => {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/health")
const response = await handler(request)
assert.equal(response.status, 200)
// CORS header is still present (wildcard default) even without an Origin
assert.equal(response.headers.get("access-control-allow-origin"), "*")
})
test("OPTIONS preflight for disallowed origin returns configured origin, not request origin", async () => {
process.env.OPENCODE_LLM_PROXY_CORS_ORIGIN = "https://allowed.example.com"
try {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/v1/chat/completions", {
method: "OPTIONS",
headers: {
Origin: "https://evil.example.com",
"Access-Control-Request-Method": "POST",
},
})
const response = await handler(request)
assert.equal(response.status, 204)
assert.equal(response.headers.get("access-control-allow-origin"), "https://allowed.example.com")
assert.notEqual(response.headers.get("access-control-allow-origin"), "https://evil.example.com")
} finally {
delete process.env.OPENCODE_LLM_PROXY_CORS_ORIGIN
}
})
// ---------------------------------------------------------------------------
// Integration: authentication
// ---------------------------------------------------------------------------
test("missing token returns 401 when token is configured", async () => {
process.env.OPENCODE_LLM_PROXY_TOKEN = "secret-token"
try {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/health")
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 401)
assert.equal(body.error.type, "invalid_request_error")
assert.ok(response.headers.get("www-authenticate")?.includes("Bearer"))
} finally {
delete process.env.OPENCODE_LLM_PROXY_TOKEN
}
})
test("wrong token returns 401", async () => {
process.env.OPENCODE_LLM_PROXY_TOKEN = "secret-token"
try {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/health", {
headers: { Authorization: "Bearer wrong-token" },
})
const response = await handler(request)
assert.equal(response.status, 401)
} finally {
delete process.env.OPENCODE_LLM_PROXY_TOKEN
}
})
test("correct token passes through", async () => {
process.env.OPENCODE_LLM_PROXY_TOKEN = "secret-token"
try {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/health", {
headers: { Authorization: "Bearer secret-token" },
})
const response = await handler(request)
assert.equal(response.status, 200)
} finally {
delete process.env.OPENCODE_LLM_PROXY_TOKEN
}
})
test("no token configured allows all requests through", async () => {
delete process.env.OPENCODE_LLM_PROXY_TOKEN
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/health")
const response = await handler(request)
assert.equal(response.status, 200)
})
// ---------------------------------------------------------------------------
// Integration: /v1/chat/completions error handling
// ---------------------------------------------------------------------------
test("malformed JSON body returns 400", async () => {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{ not valid json",
})
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 400)
assert.equal(body.error.type, "invalid_request_error")
})
test("missing model field returns 400", async () => {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }),
})
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 400)
assert.ok(body.error.message.includes("model"))
})
test("missing messages field returns 400", async () => {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ model: "gpt-4o" }),
})
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 400)
assert.ok(body.error.message.includes("messages"))
})
test("stream: true returns SSE response", async () => {
const events = [
{
type: "message.part.updated",
properties: {
part: { sessionID: "sess-123", type: "text" },
delta: "Hello",
},
},
{
type: "message.part.updated",
properties: {
part: { sessionID: "sess-123", type: "text" },
delta: " world",
},
},
{ type: "session.idle", properties: { sessionID: "sess-123" } },
]
const handler = createProxyFetchHandler(createStreamingClient(events))
const request = new Request("http://127.0.0.1:4010/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: "gpt-4o",
stream: true,
messages: [{ role: "user", content: "hi" }],
}),
})
const response = await handler(request)
assert.equal(response.status, 200)
assert.ok(response.headers.get("content-type")?.includes("text/event-stream"))
const text = await response.text()
assert.ok(text.includes("chat.completion.chunk"))
assert.ok(text.includes("Hello"))
assert.ok(text.includes(" world"))
assert.ok(text.includes("[DONE]"))
})
test("stream: true with unknown model returns 502", async () => {
const handler = createProxyFetchHandler(createClient()) // no providers
const request = new Request("http://127.0.0.1:4010/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: "nonexistent-model",
stream: true,
messages: [{ role: "user", content: "hi" }],
}),
})
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 502)
assert.ok(body.error.message.includes("nonexistent-model"))
})
test("stream: true propagates session.error into the SSE stream", async () => {
const events = [
{
type: "session.error",
properties: {
sessionID: "sess-123",
error: { message: "Model overloaded" },
},
},
{ type: "session.idle", properties: { sessionID: "sess-123" } },
]
const handler = createProxyFetchHandler(createStreamingClient(events))
const request = new Request("http://127.0.0.1:4010/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: "gpt-4o",
stream: true,
messages: [{ role: "user", content: "hi" }],
}),
})
const response = await handler(request)
assert.equal(response.status, 200)
assert.ok(response.headers.get("content-type")?.includes("text/event-stream"))
const text = await response.text()
assert.ok(text.includes("server_error") || text.includes("Model overloaded"))
assert.ok(text.includes("[DONE]"))
})
test("unknown model returns 502", async () => {
const handler = createProxyFetchHandler(createClient()) // client returns no providers
const request = new Request("http://127.0.0.1:4010/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: "nonexistent-model",
messages: [{ role: "user", content: "hi" }],
}),
})
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 502)
assert.ok(body.error.message.includes("nonexistent-model"))
})
test("unknown route returns 404", async () => {
const handler = createProxyFetchHandler(createClient())
const request = new Request("http://127.0.0.1:4010/unknown-path")
const response = await handler(request)
assert.equal(response.status, 404)
})
// ---------------------------------------------------------------------------
describe("toTextContent", () => {
it("returns a string unchanged", () => {
assert.equal(toTextContent("hello"), "hello")
})
it("returns empty string for non-string non-array", () => {
assert.equal(toTextContent(null), "")
assert.equal(toTextContent(42), "")
assert.equal(toTextContent({}), "")
})
it("joins text parts from an array", () => {
const parts = [
{ type: "text", text: "hello" },
{ type: "text", text: "world" },
]
assert.equal(toTextContent(parts), "hello\n\nworld")
})
it("ignores non-text parts", () => {
const parts = [
{ type: "image", url: "http://example.com/img.png" },
{ type: "text", text: "only this" },
]
assert.equal(toTextContent(parts), "only this")
})
it("filters out empty text parts", () => {
const parts = [
{ type: "text", text: "" },
{ type: "text", text: " " },
{ type: "text", text: "kept" },
]
assert.equal(toTextContent(parts), "kept")
})
it("returns empty string for an empty array", () => {
assert.equal(toTextContent([]), "")
})
})
// ---------------------------------------------------------------------------
// Unit: normalizeMessages
// ---------------------------------------------------------------------------
describe("normalizeMessages", () => {
it("passes through simple user messages", () => {
const input = [{ role: "user", content: "hello" }]
assert.deepEqual(normalizeMessages(input), [{ role: "user", content: "hello" }])
})
it("trims whitespace from content", () => {
const input = [{ role: "user", content: " hi " }]
assert.deepEqual(normalizeMessages(input), [{ role: "user", content: "hi" }])
})
it("drops messages with empty content", () => {
const input = [
{ role: "user", content: "" },
{ role: "assistant", content: "response" },
]
assert.deepEqual(normalizeMessages(input), [{ role: "assistant", content: "response" }])
})
it("converts array content to text", () => {
const input = [
{ role: "user", content: [{ type: "text", text: "question" }] },
]
assert.deepEqual(normalizeMessages(input), [{ role: "user", content: "question" }])
})
})
// ---------------------------------------------------------------------------
// Unit: normalizeResponseInput
// ---------------------------------------------------------------------------
describe("normalizeResponseInput", () => {
it("wraps a plain string in a user message", () => {
assert.deepEqual(normalizeResponseInput("hi"), [{ role: "user", content: "hi" }])
})
it("returns empty array for empty string", () => {
assert.deepEqual(normalizeResponseInput(" "), [])
})
it("returns empty array for non-array non-string input", () => {
assert.deepEqual(normalizeResponseInput(null), [])
assert.deepEqual(normalizeResponseInput(42), [])
})
it("handles array of objects with string content", () => {
const input = [{ role: "user", content: "hello" }]
assert.deepEqual(normalizeResponseInput(input), [{ role: "user", content: "hello" }])
})
it("handles array content with text parts", () => {
const input = [
{ role: "user", content: [{ type: "text", text: "from parts" }] },
]
assert.deepEqual(normalizeResponseInput(input), [{ role: "user", content: "from parts" }])
})
it("handles input array with text parts", () => {
const input = [
{ role: "user", input: [{ text: "from input array" }] },
]
assert.deepEqual(normalizeResponseInput(input), [{ role: "user", content: "from input array" }])
})
it("falls back to type field for role", () => {
const input = [{ type: "user", content: "hello" }]
assert.deepEqual(normalizeResponseInput(input), [{ role: "user", content: "hello" }])
})
it("drops items with empty content", () => {
const input = [
{ role: "user", content: "" },
{ role: "assistant", content: "kept" },
]
assert.deepEqual(normalizeResponseInput(input), [{ role: "assistant", content: "kept" }])
})
})
// ---------------------------------------------------------------------------
// Unit: buildSystemPrompt
// ---------------------------------------------------------------------------
describe("buildSystemPrompt", () => {
it("includes system message content", () => {
const messages = [{ role: "system", content: "Be concise." }]
const result = buildSystemPrompt(messages, {})
assert.ok(result.includes("Be concise."))
})
it("includes developer message content", () => {
const messages = [{ role: "developer", content: "Dev instructions." }]
const result = buildSystemPrompt(messages, {})
assert.ok(result.includes("Dev instructions."))
})
it("always includes the proxy hint lines", () => {
const result = buildSystemPrompt([], {})
assert.ok(result.includes("proxy backed by OpenCode"))
assert.ok(result.includes("Return only the assistant"))
})
it("appends temperature hint when provided", () => {
const result = buildSystemPrompt([], { temperature: 0.7 })
assert.ok(result.includes("0.7"))
})
it("appends max_completion_tokens hint when provided", () => {
const result = buildSystemPrompt([], { max_completion_tokens: 512 })
assert.ok(result.includes("512"))
})
it("appends max_tokens hint when provided", () => {
const result = buildSystemPrompt([], { max_tokens: 256 })
assert.ok(result.includes("256"))
})
it("ignores non-system roles", () => {
const messages = [
{ role: "user", content: "user message" },
{ role: "assistant", content: "assistant message" },
]
const result = buildSystemPrompt(messages, {})
assert.ok(!result.includes("user message"))
assert.ok(!result.includes("assistant message"))
})
})
// ---------------------------------------------------------------------------
// Unit: buildPrompt
// ---------------------------------------------------------------------------
describe("buildPrompt", () => {
it("returns fallback for empty messages", () => {
assert.equal(buildPrompt([]), "Say hello.")
})
it("returns bare content for single user message", () => {
const messages = [{ role: "user", content: "What is 2+2?" }]
assert.equal(buildPrompt(messages), "What is 2+2?")
})
it("builds a transcript for multi-turn conversations", () => {
const messages = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
{ role: "user", content: "How are you?" },
]
const result = buildPrompt(messages)
assert.ok(result.includes("USER:\nHello"))
assert.ok(result.includes("ASSISTANT:\nHi there"))
assert.ok(result.includes("USER:\nHow are you?"))
assert.ok(result.includes("Continue the conversation"))
})
it("excludes system messages from the transcript", () => {
const messages = [
{ role: "system", content: "System instruction" },
{ role: "user", content: "User question" },
]
const result = buildPrompt(messages)
assert.ok(!result.includes("System instruction"))
assert.equal(result, "User question")
})
})
// ---------------------------------------------------------------------------
// Unit: extractAssistantText
// ---------------------------------------------------------------------------
describe("extractAssistantText", () => {
it("joins text parts", () => {
const parts = [
{ type: "text", text: "Hello " },
{ type: "text", text: "world" },
]
assert.equal(extractAssistantText(parts), "Hello world")
})
it("ignores non-text parts", () => {
const parts = [
{ type: "tool_use", id: "1" },
{ type: "text", text: "answer" },
]
assert.equal(extractAssistantText(parts), "answer")
})
it("returns empty string for empty array", () => {
assert.equal(extractAssistantText([]), "")
})
it("trims surrounding whitespace", () => {
const parts = [{ type: "text", text: " trimmed " }]
assert.equal(extractAssistantText(parts), "trimmed")
})
})
// ---------------------------------------------------------------------------
// Unit: mapFinishReason
// ---------------------------------------------------------------------------
describe("mapFinishReason", () => {
it("returns 'stop' for undefined", () => {
assert.equal(mapFinishReason(undefined), "stop")
})
it("returns 'stop' for null", () => {
assert.equal(mapFinishReason(null), "stop")
})
it("returns 'length' when finish includes 'length'", () => {
assert.equal(mapFinishReason("max_length"), "length")
assert.equal(mapFinishReason("length"), "length")
})
it("returns 'tool_calls' when finish includes 'tool'", () => {
assert.equal(mapFinishReason("tool_use"), "tool_calls")
assert.equal(mapFinishReason("tool"), "tool_calls")
})
it("returns 'stop' for unrecognised values", () => {
assert.equal(mapFinishReason("end_turn"), "stop")
assert.equal(mapFinishReason("stop"), "stop")
})
})
// ---------------------------------------------------------------------------
// Unit: resolveModel
// ---------------------------------------------------------------------------
describe("resolveModel", () => {
function makeClient(providers) {
return {
config: {
providers: async () => ({ data: { providers } }),
},
}
}
const providers = [
{
id: "openai",
models: {
"gpt-4o": { id: "gpt-4o", name: "GPT-4o" },
"gpt-4o-mini": { id: "gpt-4o-mini", name: "GPT-4o Mini" },
},
},
{
id: "anthropic",
models: {
"claude-3-5-sonnet": { id: "claude-3-5-sonnet", name: "Claude 3.5 Sonnet" },
},
},
]
it("resolves a fully-qualified provider/model ID", async () => {
const client = makeClient(providers)
const model = await resolveModel(client, "openai/gpt-4o")
assert.equal(model.providerID, "openai")
assert.equal(model.modelID, "gpt-4o")
})
it("resolves an unambiguous bare model ID", async () => {
const client = makeClient(providers)
const model = await resolveModel(client, "claude-3-5-sonnet")
assert.equal(model.providerID, "anthropic")
assert.equal(model.modelID, "claude-3-5-sonnet")
})
it("throws for an unknown model", async () => {
const client = makeClient(providers)
await assert.rejects(
() => resolveModel(client, "unknown-model"),
/Unknown model/,
)
})
it("throws for an ambiguous bare model ID present in multiple providers", async () => {
const ambiguousProviders = [
{ id: "providerA", models: { shared: { id: "shared" } } },
{ id: "providerB", models: { shared: { id: "shared" } } },
]
const client = makeClient(ambiguousProviders)
await assert.rejects(
() => resolveModel(client, "shared"),
/ambiguous/,
)
})
it("resolves with providerOverride when bare model matches", async () => {
const client = makeClient(providers)
const model = await resolveModel(client, "gpt-4o", "openai")
assert.equal(model.providerID, "openai")
assert.equal(model.modelID, "gpt-4o")
})
it("resolves fully-qualified ID with a matching providerOverride", async () => {
const client = makeClient(providers)
const model = await resolveModel(client, "openai/gpt-4o-mini", "openai")
assert.equal(model.providerID, "openai")
assert.equal(model.modelID, "gpt-4o-mini")
})
})
// ---------------------------------------------------------------------------
// Unit: createSseQueue
// ---------------------------------------------------------------------------
describe("createSseQueue", () => {
it("enqueue followed by generateChunks yields the value", async () => {
const queue = createSseQueue()
queue.enqueue("hello")
queue.finish()
const results = []
for await (const chunk of queue.generateChunks()) {
results.push(chunk)
}
assert.deepEqual(results, ["hello"])
})
it("multiple enqueues before finish yields all values in order", async () => {
const queue = createSseQueue()
queue.enqueue("a")
queue.enqueue("b")
queue.enqueue("c")
queue.finish()
const results = []
for await (const chunk of queue.generateChunks()) {
results.push(chunk)
}
assert.deepEqual(results, ["a", "b", "c"])
})
it("finish with no enqueues yields nothing", async () => {
const queue = createSseQueue()
queue.finish()
const results = []
for await (const chunk of queue.generateChunks()) {
results.push(chunk)
}
assert.deepEqual(results, [])
})
it("enqueue after generateChunks starts still yields the value", async () => {
const queue = createSseQueue()
// Start consuming before anything is enqueued
const generatorPromise = (async () => {
const results = []
for await (const chunk of queue.generateChunks()) {
results.push(chunk)
}
return results
})()
// Enqueue asynchronously
await Promise.resolve()
queue.enqueue("late")
queue.finish()
const results = await generatorPromise
assert.deepEqual(results, ["late"])
})
})
// ---------------------------------------------------------------------------
// Integration: GET /v1/models
// ---------------------------------------------------------------------------
function createModelsClient(providers = []) {
return {
app: { log: async () => {} },
config: {
providers: async () => ({ data: { providers } }),
},
}
}
test("GET /v1/models returns model list", async () => {
const client = createModelsClient([
{
id: "openai",
models: {
"gpt-4o": { id: "gpt-4o", name: "GPT-4o" },
"gpt-4o-mini": { id: "gpt-4o-mini", name: "GPT-4o Mini" },
},
},
{
id: "anthropic",
models: {
"claude-3-5-sonnet": { id: "claude-3-5-sonnet", name: "Claude 3.5 Sonnet" },
},
},
])
const handler = createProxyFetchHandler(client)
const request = new Request("http://127.0.0.1:4010/v1/models")
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 200)
assert.equal(body.object, "list")
assert.ok(Array.isArray(body.data))
assert.equal(body.data.length, 3)
const ids = body.data.map((m) => m.id)
assert.ok(ids.includes("openai/gpt-4o"))
assert.ok(ids.includes("openai/gpt-4o-mini"))
assert.ok(ids.includes("anthropic/claude-3-5-sonnet"))
const first = body.data[0]
assert.equal(first.object, "model")
assert.ok("owned_by" in first)
assert.ok("created" in first)
})
test("GET /v1/models returns empty list when no providers configured", async () => {
const handler = createProxyFetchHandler(createModelsClient([]))
const request = new Request("http://127.0.0.1:4010/v1/models")
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 200)
assert.deepEqual(body, { object: "list", data: [] })
})
test("GET /v1/models returns 500 when providers call throws", async () => {
const client = {
app: { log: async () => {} },
config: {
providers: async () => {
throw new Error("upstream failure")
},
},
}
const handler = createProxyFetchHandler(client)
const request = new Request("http://127.0.0.1:4010/v1/models")
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 500)
assert.equal(body.error.type, "server_error")
})
// ---------------------------------------------------------------------------
// Integration: POST /v1/responses
// ---------------------------------------------------------------------------
function createResponsesClient(responseContent = "The answer is 42.") {
return {
app: { log: async () => {} },
tool: { ids: async () => ({ data: [] }) },
config: {
providers: async () => ({
data: {
providers: [
{
id: "anthropic",
models: { "claude-3-5-sonnet": { id: "claude-3-5-sonnet", name: "Claude 3.5 Sonnet" } },
},
],
},
}),
},
session: {
create: async () => ({ data: { id: "sess-resp-1" } }),
prompt: async () => ({
data: {
parts: [{ type: "text", text: responseContent }],
info: { tokens: { input: 20, output: 8, reasoning: 0, cache: { read: 0, write: 0 } }, finish: "end_turn" },
},
}),
},
}
}
test("POST /v1/responses returns a well-formed response object", async () => {
const handler = createProxyFetchHandler(createResponsesClient("Hello from Claude."))
const request = new Request("http://127.0.0.1:4010/v1/responses", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: "anthropic/claude-3-5-sonnet",
input: "Say hello.",
}),
})
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 200)
assert.equal(body.object, "response")
assert.equal(body.status, "completed")
assert.ok(body.id.startsWith("resp_"))
assert.equal(body.output_text, "Hello from Claude.")
assert.ok(Array.isArray(body.output))
assert.equal(body.output[0].role, "assistant")
assert.equal(body.usage.input_tokens, 20)
assert.equal(body.usage.output_tokens, 8)
assert.equal(body.usage.total_tokens, 28)
})
test("POST /v1/responses missing model returns 400", async () => {
const handler = createProxyFetchHandler(createResponsesClient())
const request = new Request("http://127.0.0.1:4010/v1/responses", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ input: "hi" }),
})
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 400)
assert.ok(body.error.message.includes("model"))
})
test("POST /v1/responses empty input returns 400", async () => {
const handler = createProxyFetchHandler(createResponsesClient())
const request = new Request("http://127.0.0.1:4010/v1/responses", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ model: "anthropic/claude-3-5-sonnet", input: " " }),
})
const response = await handler(request)
const body = await response.json()
assert.equal(response.status, 400)
assert.ok(body.error.message.includes("input"))
})
test("POST /v1/responses malformed JSON returns 400", async () => {
const handler = createProxyFetchHandler(createResponsesClient())
const request = new Request("http://127.0.0.1:4010/v1/responses", {