Repository navigation
Expand file tree
/
Copy pathopencode-go.spec.ts
More file actions
2828 lines (2467 loc) · 114 KB
/
Copy pathopencode-go.spec.ts
File metadata and controls
2828 lines (2467 loc) · 114 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
// npx vitest run src/api/providers/__tests__/opencode-go.spec.ts
// Mock vscode first to avoid import errors
vitest.mock("vscode", () => ({
workspace: {
getConfiguration: () => ({
get: (_key: string, defaultValue?: unknown) => defaultValue,
}),
},
}))
import {
Anthropic,
APIConnectionTimeoutError as AnthropicTimeoutError,
APIUserAbortError as AnthropicAbortError,
} from "@anthropic-ai/sdk"
import OpenAI, { APIConnectionTimeoutError, APIUserAbortError } from "openai"
import {
opencodeGoDefaultModelId,
opencodeGoModels,
isOpencodeGoAnthropicFormatModel,
isOpencodeGoResponsesFormatModel,
} from "@roo-code/types"
import { OpencodeGoHandler } from "../opencode-go"
import { getModels } from "../fetchers/modelCache"
import { ApiHandlerOptions } from "../../../shared/api"
import { Package } from "../../../shared/package"
import { asyncStreamFrom, collectStream } from "../../../test-utils/stream"
import { clearAllMocks } from "../../../test-utils/reset"
import { makeCreateMessageMetadata } from "../../../test-utils/api"
vitest.mock("openai")
vitest.mock("delay", () => ({
default: vitest.fn(function () {
return Promise.resolve()
}),
}))
vitest.mock("../fetchers/modelCache", () => ({
getModels: vitest.fn().mockImplementation(function () {
return Promise.resolve({
// Use the native registry entry so capability flags (reasoning
// effort, preserveReasoning, prompt cache) are exercised.
"glm-5.1": { ...opencodeGoModels["glm-5.1"] },
// Anthropic-format model used to exercise the /v1/messages path.
"qwen3.7-max": { ...opencodeGoModels["qwen3.7-max"] },
// Responses-format models (Zoo-Code-Org/Zoo-Code#1431 and issue #1979).
"gpt-5.6-luna": { ...opencodeGoModels["gpt-5.6-luna"] },
"gpt-6-luna": { ...opencodeGoModels["gpt-6-luna"] },
"grok-4.6": { ...opencodeGoModels["grok-4.6"] },
"muse-spark-1.3-contributor": { ...opencodeGoModels["muse-spark-1.3-contributor"] },
"muse-spark-1.2-contributor": { ...opencodeGoModels["muse-spark-1.2-contributor"] },
})
}),
refreshModels: vitest.fn().mockImplementation(function () {
return Promise.resolve({
"glm-5.1": { ...opencodeGoModels["glm-5.1"] },
"qwen3.7-max": { ...opencodeGoModels["qwen3.7-max"] },
"gpt-5.6-luna": { ...opencodeGoModels["gpt-5.6-luna"] },
"gpt-6-luna": { ...opencodeGoModels["gpt-6-luna"] },
"grok-4.6": { ...opencodeGoModels["grok-4.6"] },
"muse-spark-1.3-contributor": { ...opencodeGoModels["muse-spark-1.3-contributor"] },
"muse-spark-1.2-contributor": { ...opencodeGoModels["muse-spark-1.2-contributor"] },
})
}),
getModelsFromCache: vitest.fn().mockReturnValue(undefined),
}))
const mockCreate = vitest.fn()
const mockAnthropicCreate = vitest.fn()
const mockResponsesCreate = vitest.fn()
;(OpenAI as any).mockImplementation(function () {
return {
chat: { completions: { create: mockCreate } },
responses: { create: mockResponsesCreate },
}
})
// The real SDK error classes are re-exported alongside the mocked client so
// tests can emulate the SDK's abort/timeout rejections and the provider's
// instanceof checks resolve against the same class identity.
vitest.mock("@anthropic-ai/sdk", async () => {
const actual = await vi.importActual<typeof import("@anthropic-ai/sdk")>("@anthropic-ai/sdk")
return {
...actual,
Anthropic: vitest.fn(function () {
return {
messages: {
create: mockAnthropicCreate,
},
}
}),
}
})
describe("OpencodeGoHandler", () => {
const mockOptions: ApiHandlerOptions = {
opencodeGoApiKey: "test-key",
opencodeGoModelId: "glm-5.1",
}
beforeEach(() => {
clearAllMocks()
mockCreate.mockClear()
mockAnthropicCreate.mockClear()
mockResponsesCreate.mockClear()
})
it("initializes the OpenAI client with the Opencode Go base URL and key", () => {
const handler = new OpencodeGoHandler(mockOptions)
expect(handler).toBeInstanceOf(OpencodeGoHandler)
expect(OpenAI).toHaveBeenCalledWith(
expect.objectContaining({
baseURL: "https://opencode.ai/zen/go/v1",
apiKey: "test-key",
defaultHeaders: expect.objectContaining({ "User-Agent": `ZooCode/${Package.version}` }),
}),
)
})
it("initializes an Anthropic client rooted at /zen/go (SDK appends /v1/messages)", () => {
new OpencodeGoHandler(mockOptions)
expect(Anthropic).toHaveBeenCalledWith(
expect.objectContaining({
// The Anthropic SDK posts to `/v1/messages`, so the base URL must
// NOT include the trailing `/v1` used by the OpenAI client.
baseURL: "https://opencode.ai/zen/go",
apiKey: "test-key",
defaultHeaders: expect.objectContaining({ "User-Agent": `ZooCode/${Package.version}` }),
}),
)
})
describe("fetchModel", () => {
it("returns the configured model info with native capability flags", async () => {
const handler = new OpencodeGoHandler(mockOptions)
const result = await handler.fetchModel()
expect(result.id).toBe("glm-5.1")
// Native registry values for glm-5.1.
expect(result.info.maxTokens).toBe(131_072)
expect(result.info.contextWindow).toBe(204_800)
expect(result.info.supportsPromptCache).toBe(true)
expect(result.info.supportsReasoningEffort).toEqual(["disable", "medium"])
expect(result.info.preserveReasoning).toBe(true)
expect(result.info.supportsMaxTokens).toBe(true)
})
it("falls back to the default model id when none is configured", async () => {
const handler = new OpencodeGoHandler({ opencodeGoApiKey: "test-key" })
const result = await handler.fetchModel()
expect(result.id).toBe(opencodeGoDefaultModelId)
})
})
describe("createMessage", () => {
beforeEach(() => {
mockCreate.mockImplementation(async () =>
asyncStreamFrom([
{
choices: [
{
delta: {
content: "Hello",
reasoning_content: "thinking…",
tool_calls: [
{
index: 0,
id: "call_1",
function: { name: "read_file", arguments: '{"path":' },
},
],
},
index: 0,
},
],
usage: null,
},
{
choices: [{ delta: {}, index: 0 }],
usage: {
prompt_tokens: 12,
completion_tokens: 7,
total_tokens: 19,
prompt_tokens_details: { cached_tokens: 4 },
},
},
]),
)
})
it("streams text, reasoning, tool-call and usage chunks", async () => {
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
const chunks = await collectStream(handler.createMessage("You are helpful.", messages))
expect(chunks).toContainEqual({ type: "text", text: "Hello" })
expect(chunks).toContainEqual({ type: "reasoning", text: "thinking…" })
expect(chunks).toContainEqual({
type: "tool_call_partial",
index: 0,
id: "call_1",
name: "read_file",
arguments: '{"path":',
})
expect(chunks).toContainEqual({
type: "usage",
inputTokens: 12,
outputTokens: 7,
cacheReadTokens: 4,
})
})
it("requests a streaming completion with usage included and native max tokens", async () => {
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
await collectStream(handler.createMessage("sys", messages))
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
model: "glm-5.1",
stream: true,
stream_options: { include_usage: true },
// glm-5.1 maxTokens (131_072) is clamped to 20% of its 204_800
// context window => 40_960.
max_completion_tokens: 40_960,
temperature: expect.any(Number),
}),
expect.objectContaining({ signal: expect.any(AbortSignal) }),
)
})
it("sends the stable conversation ID to chat completions", async () => {
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
await collectStream(handler.createMessage("sys", messages, { taskId: "conversation-123" }))
expect(mockCreate.mock.calls[0][1]?.headers).toMatchObject({
"x-opencode-session": "conversation-123",
})
})
it("falls back to a stable per-instance session ID when no taskId is provided", async () => {
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
await collectStream(handler.createMessage("sys", messages))
const sessionId = mockCreate.mock.calls[0][1]?.headers["x-opencode-session"]
expect(sessionId).toEqual(expect.any(String))
// The same handler instance reuses its session ID across requests.
await collectStream(handler.createMessage("sys", messages))
expect(mockCreate.mock.calls[1][1]?.headers["x-opencode-session"]).toBe(sessionId)
})
it("forwards the model's default reasoning_effort for reasoning-capable models", async () => {
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
await collectStream(handler.createMessage("sys", messages))
// glm-5.1 advertises supportsReasoningEffort with a default of "medium".
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
model: "glm-5.1",
reasoning_effort: "medium",
}),
expect.objectContaining({ signal: expect.any(AbortSignal) }),
)
})
it("omits reasoning_effort when the user disables reasoning", async () => {
const handler = new OpencodeGoHandler({ ...mockOptions, reasoningEffort: "disable" })
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
await collectStream(handler.createMessage("sys", messages))
const callArgs = mockCreate.mock.calls[0][0] as Record<string, unknown>
expect(callArgs.reasoning_effort).toBeUndefined()
})
it("uses convertToR1Format for preserveReasoning models to keep interleaved thinking", async () => {
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [{ type: "text", text: "Hi" }],
},
]
await collectStream(handler.createMessage("sys", messages))
const callArgs = mockCreate.mock.calls[0][0] as { messages: Array<{ role: string }> }
// The system prompt is prepended, then the R1-converted user message.
expect(callArgs.messages[0]).toEqual({ role: "system", content: "sys" })
// convertToR1Format keeps a single user turn as one user message.
expect(callArgs.messages.filter((m) => m.role === "user")).toHaveLength(1)
})
it("streams reasoning chunks from delta.reasoning_content", async () => {
mockCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{ choices: [{ delta: { reasoning_content: "thinking..." }, index: 0 }] },
{ choices: [{ delta: { content: "answer" }, index: 0 }] },
{
choices: [{ delta: {}, index: 0 }],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
},
]),
)
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
const chunks = await collectStream(handler.createMessage("sys", messages))
expect(chunks).toContainEqual({ type: "reasoning", text: "thinking..." })
})
it("falls back to delta.reasoning when reasoning_content is absent", async () => {
mockCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{ choices: [{ delta: { reasoning: "router-style thought" }, index: 0 }] },
{
choices: [{ delta: {}, index: 0 }],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
},
]),
)
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
const chunks = await collectStream(handler.createMessage("sys", messages))
expect(chunks).toContainEqual({ type: "reasoning", text: "router-style thought" })
})
it("prefers delta.reasoning_content over delta.reasoning when both are present", async () => {
mockCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{
choices: [
{
delta: {
reasoning_content: "primary thought",
reasoning: "fallback thought",
},
index: 0,
},
],
},
{
choices: [{ delta: {}, index: 0 }],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
},
]),
)
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
const chunks = await collectStream(handler.createMessage("sys", messages))
const reasoningChunks = chunks.filter((chunk) => chunk.type === "reasoning")
expect(reasoningChunks).toEqual([{ type: "reasoning", text: "primary thought" }])
})
it("uses convertToOpenAiMessages for non-preserveReasoning models", async () => {
// kimi-k2.6 has no preserveReasoning flag, so messages bypass
// convertToR1Format and go through the plain OpenAI converter.
vitest.mocked(getModels).mockImplementationOnce(async () => ({
"kimi-k2.6": { ...opencodeGoModels["kimi-k2.6"] },
}))
mockCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{ choices: [{ delta: { content: "Hi" }, index: 0 }] },
{
choices: [{ delta: {}, index: 0 }],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
},
]),
)
const handler = new OpencodeGoHandler({ ...mockOptions, opencodeGoModelId: "kimi-k2.6" })
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
await collectStream(handler.createMessage("sys", messages))
const callArgs = mockCreate.mock.calls[0][0] as { messages: Array<{ role: string }> }
expect(callArgs.messages[0]).toEqual({ role: "system", content: "sys" })
// A single user turn stays a single user message after OpenAI conversion.
expect(callArgs.messages.filter((m) => m.role === "user")).toHaveLength(1)
})
it("preserves reasoning across a tool-call continuation for MiMo V2.6 Flash", async () => {
// Xiaomi's deep-thinking guide requires the reasoning from the assistant
// turn to be passed back on the tool-call continuation. MiMo V2.6 must
// therefore convert through convertToR1Format (preserveReasoning) and
// keep the reasoning -> tool_call -> tool_result history intact.
vitest.mocked(getModels).mockImplementationOnce(async () => ({
"mimo-v2.6-flash": { ...opencodeGoModels["mimo-v2.6-flash"] },
}))
mockCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{ choices: [{ delta: { content: "Done" }, index: 0 }] },
{
choices: [{ delta: {}, index: 0 }],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
},
]),
)
const handler = new OpencodeGoHandler({ ...mockOptions, opencodeGoModelId: "mimo-v2.6-flash" })
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "Read the config file" },
{
role: "assistant",
content: [
{ type: "text", text: "I will read it." },
{ type: "tool_use", id: "call_mimo_1", name: "read_file", input: { path: "config.json" } },
],
reasoning_content: "The user wants the config contents.",
} as Anthropic.Messages.MessageParam,
{
role: "user",
content: [
{ type: "tool_result", tool_use_id: "call_mimo_1", content: '{"a":1}' },
{ type: "text", text: "<environment_details>cwd: /repo</environment_details>" },
],
},
]
await collectStream(handler.createMessage("sys", messages))
const callArgs = mockCreate.mock.calls[0][0] as {
model: string
messages: Array<Record<string, unknown>>
}
expect(callArgs.model).toBe("mimo-v2.6-flash")
// Index 0 is the system prompt; the converted history follows it.
expect(callArgs.messages[0]).toEqual({ role: "system", content: "sys" })
const [, userMessage, assistantMessage, toolMessage] = callArgs.messages
expect(userMessage).toEqual({ role: "user", content: "Read the config file" })
// The assistant turn keeps both its reasoning and its tool call.
expect(assistantMessage).toMatchObject({
role: "assistant",
reasoning_content: "The user wants the config contents.",
})
expect(assistantMessage.tool_calls).toEqual([
{
id: "call_mimo_1",
type: "function",
function: { name: "read_file", arguments: '{"path":"config.json"}' },
},
])
// The tool result follows as a tool message, with the trailing
// environment details merged in so no user turn drops the reasoning.
expect(toolMessage).toEqual({
role: "tool",
tool_call_id: "call_mimo_1",
content: '{"a":1}\n\n<environment_details>cwd: /repo</environment_details>',
})
expect(callArgs.messages.filter((message) => message.role === "user")).toHaveLength(1)
})
it("emits a usage chunk with zeroed tokens when the stream reports no usage", async () => {
mockCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{ choices: [{ delta: { content: "Hi" }, index: 0 }] },
{
choices: [{ delta: {}, index: 0 }],
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
},
]),
)
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
const chunks = await collectStream(handler.createMessage("sys", messages))
expect(chunks).toContainEqual({ type: "usage", inputTokens: 0, outputTokens: 0 })
})
it("honors includeMaxTokens/modelMaxTokens override for max_completion_tokens", async () => {
const handler = new OpencodeGoHandler({ ...mockOptions, includeMaxTokens: true, modelMaxTokens: 999 })
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hi" }]
await collectStream(handler.createMessage("sys", messages))
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({ max_completion_tokens: 999 }),
expect.objectContaining({ signal: expect.any(AbortSignal) }),
)
})
it("rethrows non-abort errors from the OpenAI stream unchanged", async () => {
// A mid-stream failure that is not an abort (e.g. a connection
// reset) must propagate unchanged — the catch only normalizes
// aborts to a DOM-standard AbortError.
const streamError = new Error("connection reset")
mockCreate.mockImplementation(async () =>
(async function* () {
yield { choices: [{ delta: { content: "partial" }, index: 0 }], index: 0 }
throw streamError
})(),
)
const handler = new OpencodeGoHandler(mockOptions)
const error = await collectStream(handler.createMessage("sys", [{ role: "user", content: "hi" }])).then(
() => undefined,
(e: unknown) => e,
)
expect(error).toBe(streamError)
})
it("skips empty choices, empty deltas and tool calls without a function field", async () => {
// Full-list assertions: a frame without choices[0], a delta without
// content/tool_calls, and a tool call missing `function` must each
// contribute nothing except the partial tool call with undefined
// name/arguments (toEqual ignores undefined-valued keys).
mockCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{ choices: [], index: 0 },
{ choices: [{ delta: {}, index: 0 }], index: 0 },
{
choices: [{ delta: { tool_calls: [{ index: 0, id: "call_1" }] }, index: 0 }],
index: 0,
},
{
choices: [{ delta: {}, index: 0 }],
index: 0,
usage: { prompt_tokens: 1, completion_tokens: 2 },
},
]),
)
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "hi" }]
const chunks = await collectStream(handler.createMessage("sys", messages))
expect(chunks).toEqual([
{ type: "tool_call_partial", index: 0, id: "call_1" },
{ type: "usage", inputTokens: 1, outputTokens: 2 },
])
})
it("emits the text delta and the usage chunk with cached tokens from the final frame", async () => {
mockCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{ choices: [{ delta: { content: "hi" }, index: 0 }], index: 0 },
{
choices: [{ delta: {}, index: 0 }],
index: 0,
usage: {
prompt_tokens: 4,
completion_tokens: 9,
prompt_tokens_details: { cached_tokens: 6 },
},
},
]),
)
const handler = new OpencodeGoHandler(mockOptions)
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "hi" }]
const chunks = await collectStream(handler.createMessage("sys", messages))
expect(chunks).toEqual([
{ type: "text", text: "hi" },
{ type: "usage", inputTokens: 4, outputTokens: 9, cacheReadTokens: 6 },
])
})
})
it("completePrompt settles on the abort while model resolution is pending", async () => {
// The catalog lookup parks forever, so the prompt can only settle through
// the cancellation scope around the lookup; without it the handler waits
// for the catalog and then issues the SDK request.
let releaseGate!: () => void
const gate = new Promise<void>((resolve) => {
releaseGate = resolve
})
let markLookupParked!: () => void
const lookupParked = new Promise<void>((resolve) => {
markLookupParked = resolve
})
vitest.mocked(getModels).mockImplementationOnce(async () => {
markLookupParked()
await gate
return {}
})
const handler = new OpencodeGoHandler(mockOptions)
const controller = new AbortController()
const completion = handler.completePrompt("ping", { abortSignal: controller.signal })
await lookupParked
controller.abort()
const error = await completion.then(
() => undefined,
(caught: unknown) => caught,
)
// Release the parked lookup so the disposable mock does not leak into the
// next test in the file.
releaseGate()
expect(mockCreate).not.toHaveBeenCalled()
expect(error).toMatchObject({ name: "AbortError" })
expect((error as Error).message).toBe("The Opencode Go request was aborted")
})
describe("createMessage abort signal bridging", () => {
beforeEach(() => {
// Each test's mock must be scoped to that test. Some tests here never
// call the mock, so a per-test implementation would otherwise stay in
// the queue and be consumed by a later test.
mockCreate.mockReset()
mockAnthropicCreate.mockReset()
mockResponsesCreate.mockReset()
})
it("rejects with an AbortError when the external signal is already aborted", async () => {
// A pre-aborted request must fail fast before any model-catalog or
// SDK work starts: the standardized AbortError wins over any
// resolution failure, and the request itself never begins.
let capturedSignal: AbortSignal | undefined
mockCreate.mockImplementationOnce(async (_params: unknown, options: { signal?: AbortSignal }) => {
capturedSignal = options?.signal
throw new DOMException("The operation was aborted.", "AbortError")
})
const handler = new OpencodeGoHandler(mockOptions)
const controller = new AbortController()
controller.abort()
const stream = handler.createMessage(
"sys",
[{ role: "user", content: "hi" }],
makeCreateMessageMetadata({ abortSignal: controller.signal }),
)
const error = await collectStream(stream).then(
() => undefined,
(e: unknown) => e,
)
// The fast-fail guard throws before the request starts.
expect(mockCreate).not.toHaveBeenCalled()
// Pre-flight cancellation must skip the model catalog entirely:
// the getModels mock must remain uncalled, not just the SDK create.
expect(vitest.mocked(getModels)).not.toHaveBeenCalled()
expect(capturedSignal).toBeUndefined()
expect(error).toMatchObject({ name: "AbortError" })
expect((error as Error).message).toBe("The Opencode Go request was aborted")
})
it("rejects with the standardized AbortError when the external signal aborts while model resolution is pending", async () => {
// The model catalog stays pending while the external signal aborts:
// the resolution race must settle with the standardized AbortError
// before the lookup is released, and the request itself must never
// start. A bridge-only fix would let the lookup finish and abort the
// internal controller after the fact; this gate proves the prompt
// settles on the abort itself.
let releaseResolution!: () => void
const resolutionGate = new Promise<void>((resolve) => {
releaseResolution = resolve
})
let markLookupParked!: () => void
const lookupParked = new Promise<void>((resolve) => {
markLookupParked = resolve
})
vitest.mocked(getModels).mockImplementationOnce(async () => {
markLookupParked()
await resolutionGate
return { "glm-5.1": { ...opencodeGoModels["glm-5.1"] } }
})
const handler = new OpencodeGoHandler(mockOptions)
const controller = new AbortController()
const consumed = collectStream(
handler.createMessage(
"sys",
[{ role: "user", content: "hi" }],
makeCreateMessageMetadata({ abortSignal: controller.signal }),
),
)
// Let the lookup park on the gate, then abort while it is still pending.
await lookupParked
controller.abort()
const error = await consumed.then(
() => undefined,
(e: unknown) => e,
)
// The catalog lookup was attempted but the prompt must have settled
// on the abort itself, before the lookup was released: no SDK call.
expect(vitest.mocked(getModels)).toHaveBeenCalledTimes(1)
expect(mockCreate).not.toHaveBeenCalled()
expect(error).toMatchObject({ name: "AbortError" })
expect((error as Error).message).toBe("The Opencode Go request was aborted")
// Releasing the lookup afterwards must not start a late request.
releaseResolution()
// A late request is an absence, so poll the observable call count for a bounded window
// (vitest 4.1.12 here resolves waitFor at the timeout rather than rejecting, measured)
// and the assertion below is what fails when the late request appears.
await vitest.waitFor(() => mockCreate.mock.calls.length > 0).catch(() => undefined)
expect(mockCreate).not.toHaveBeenCalled()
})
it("propagates a raw model-lookup failure unchanged when no abort signal is present", async () => {
// Without an abort signal the resolution must not be wrapped or
// normalized: a catalog failure keeps its own identity so callers
// can distinguish a lookup failure from a cancellation.
const lookupError = new Error("catalog offline")
vitest.mocked(getModels).mockRejectedValueOnce(lookupError)
const handler = new OpencodeGoHandler(mockOptions)
const error = await collectStream(handler.createMessage("sys", [{ role: "user", content: "hi" }])).then(
() => undefined,
(e: unknown) => e,
)
expect(error).toBe(lookupError)
expect(mockCreate).not.toHaveBeenCalled()
})
it("normalizes an abort-flavored model-lookup failure to the provider AbortError", async () => {
// A lookup that fails with an AbortError-shaped error (e.g. the
// catalog fetch itself was aborted) must settle with the provider's
// standardized AbortError, not the raw error shape.
const abortFlavored = new Error("The operation was aborted.")
abortFlavored.name = "AbortError"
vitest.mocked(getModels).mockRejectedValueOnce(abortFlavored)
const handler = new OpencodeGoHandler(mockOptions)
const error = await collectStream(handler.createMessage("sys", [{ role: "user", content: "hi" }])).then(
() => undefined,
(e: unknown) => e,
)
expect(error).not.toBe(abortFlavored)
expect(error).toMatchObject({ name: "AbortError" })
expect((error as Error).message).toBe("The Opencode Go request was aborted")
expect(mockCreate).not.toHaveBeenCalled()
})
it("aborts the in-flight request when the external signal fires mid-stream", async () => {
// The mock polls the INTERNAL controller signal instead of waiting
// for an "abort" event: bounded polling means the test can never
// hang if the bridge stops forwarding aborts, and it rejects as
// soon as the bridge aborts the controller.
let capturedSignal: AbortSignal | undefined
mockCreate.mockImplementationOnce(async (_params: unknown, options: { signal?: AbortSignal }) => {
capturedSignal = options?.signal
return (async function* () {
yield { choices: [{ delta: { content: "partial" }, index: 0 }], index: 0 }
// Reached only when the consumer asks for the next chunk, i.e. the first chunk is
// delivered: fire the caller's abort here so the abort is mid-stream by construction.
controller.abort()
if (capturedSignal?.aborted) {
throw new DOMException("The operation was aborted.", "AbortError")
}
})()
})
const handler = new OpencodeGoHandler(mockOptions)
const controller = new AbortController()
const consumed = collectStream(
handler.createMessage(
"sys",
[{ role: "user", content: "hi" }],
makeCreateMessageMetadata({ abortSignal: controller.signal }),
),
)
// Let the request start and the first chunk be yielded before aborting.
// The mock calls controller.abort() the moment the first chunk has been consumed,
const error = await consumed.then(
() => undefined,
(e: unknown) => e,
)
expect(capturedSignal?.aborted).toBe(true)
expect(error).toMatchObject({ name: "AbortError" })
expect((error as Error).message).toBe("The Opencode Go request was aborted")
})
it("detaches the bridged abort listener when the request completes normally", async () => {
// The listener is added with { once: true }, so it only detaches on
// abort. A task-scoped signal spanning many requests must not
// accumulate a listener per request: assert explicit removal after a
// normal (non-aborted) completion.
mockCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{
choices: [{ delta: { content: "ok" }, index: 0 }],
index: 0,
},
{
choices: [{ delta: {}, index: 0 }],
index: 0,
usage: { prompt_tokens: 2, completion_tokens: 3 },
},
]),
)
const handler = new OpencodeGoHandler(mockOptions)
const controller = new AbortController()
const removeListenerSpy = vi.spyOn(controller.signal, "removeEventListener")
const addEventListenerSpy = vi.spyOn(controller.signal, "addEventListener")
const stream = handler.createMessage(
"sys",
[{ role: "user", content: "hi" }],
makeCreateMessageMetadata({ abortSignal: controller.signal }),
)
const chunks = await collectStream(stream)
expect(chunks).toContainEqual({ type: "text", text: "ok" })
// Assert the exact listener reference so a bridge that removes a
// different callback than the one it registered cannot pass.
// The rejectOnAbort race registers its own "abort" listener on the
// same external signal during model resolution, so the first "abort"
// registration is the race's, not the bridge's. Target the last
// registration so the options/removal assertions below cannot be
// satisfied by the race's listener.
const abortAddCalls = addEventListenerSpy.mock.calls.filter(([event]) => event === "abort")
const addedListener = abortAddCalls[abortAddCalls.length - 1]?.[1]
expect(typeof addedListener).toBe("function")
// The listener is registered with { once: true } — assert the exact
// options so a bridge that drops them (and relies on the finally
// block alone for single-shot semantics) is caught.
expect(addEventListenerSpy).toHaveBeenCalledWith("abort", addedListener, { once: true })
expect(removeListenerSpy).toHaveBeenCalledWith("abort", addedListener)
expect(controller.signal.aborted).toBe(false)
})
it("detaches the bridged abort listener when request preparation throws", async () => {
// The OpenAI-format body is built after the abort bridge is registered, and the
// conversions can throw synchronously (a malformed tool payload, for example).
// A bridge left on a task-scoped signal accumulates one listener per failed
// request, so the failed preparation must detach it too.
class FailingPreparationHandler extends OpencodeGoHandler {
protected override convertToolsForOpenAI(_tools: unknown): never {
throw new Error("malformed tool payload")
}
}
const handler = new FailingPreparationHandler(mockOptions)
const controller = new AbortController()
const removeListenerSpy = vi.spyOn(controller.signal, "removeEventListener")
const addEventListenerSpy = vi.spyOn(controller.signal, "addEventListener")
const stream = handler.createMessage(
"sys",
[{ role: "user", content: "hi" }],
makeCreateMessageMetadata({
abortSignal: controller.signal,
tools: [{ type: "function", function: { name: "probe" } }],
}),
)
await expect(collectStream(stream)).rejects.toThrow("malformed tool payload")
const abortAddCalls = addEventListenerSpy.mock.calls.filter(([event]) => event === "abort")
const addedListener = abortAddCalls[abortAddCalls.length - 1]?.[1]
expect(typeof addedListener).toBe("function")
expect(removeListenerSpy).toHaveBeenCalledWith("abort", addedListener)
})
it("detaches the bridged abort listener from the Anthropic-format path", async () => {
// The Anthropic branch (streamAnthropicMessage) has its own finally
// block that removes the bridged listener; assert explicit removal
// after a normal (non-aborted) completion on that path too.
mockAnthropicCreate.mockImplementationOnce(async () =>
asyncStreamFrom([
{ type: "message_start", message: { usage: { input_tokens: 1, output_tokens: 0 } } },
{ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } },
{ type: "message_delta", usage: { output_tokens: 1 } },
{ type: "message_stop" },
]),
)
const handler = new OpencodeGoHandler({
opencodeGoApiKey: "test-key",
opencodeGoModelId: "qwen3.7-max",
})
const controller = new AbortController()
const removeListenerSpy = vi.spyOn(controller.signal, "removeEventListener")
const addEventListenerSpy = vi.spyOn(controller.signal, "addEventListener")
const stream = handler.createMessage(
"sys",
[{ role: "user", content: "hi" }],
makeCreateMessageMetadata({ abortSignal: controller.signal }),
)
const chunks = await collectStream(stream)
expect(chunks).toContainEqual({ type: "text", text: "ok" })
// The rejectOnAbort race registers its own "abort" listener on the
// same external signal during model resolution, so the first "abort"
// registration is the race's, not the bridge's. Target the last
// registration so the options/removal assertions below cannot be
// satisfied by the race's listener.
const abortAddCalls = addEventListenerSpy.mock.calls.filter(([event]) => event === "abort")
const addedListener = abortAddCalls[abortAddCalls.length - 1]?.[1]
expect(typeof addedListener).toBe("function")
expect(addEventListenerSpy).toHaveBeenCalledWith("abort", addedListener, { once: true })
expect(removeListenerSpy).toHaveBeenCalledWith("abort", addedListener)
expect(controller.signal.aborted).toBe(false)
})
})
describe("completePrompt", () => {
it("returns the message content for a non-streaming completion", async () => {
mockCreate.mockResolvedValue({ choices: [{ message: { content: "the answer" } }] })
const handler = new OpencodeGoHandler(mockOptions)
expect(await handler.completePrompt("ping")).toBe("the answer")
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
model: "glm-5.1",
stream: false,
// glm-5.1 maxTokens (131_072) clamped to 20% of 204_800 => 40_960.
max_completion_tokens: 40_960,
reasoning_effort: "medium",
}),
expect.objectContaining({
headers: expect.objectContaining({ "x-opencode-session": expect.any(String) }),
}),
)
})
it("wraps errors with an Opencode Go-specific message", async () => {
mockCreate.mockRejectedValue(new Error("boom"))
const handler = new OpencodeGoHandler(mockOptions)
await expect(handler.completePrompt("ping")).rejects.toThrow("Opencode Go completion error: boom")
})
it("rethrows non-Error values unchanged", async () => {
mockCreate.mockRejectedValue("not an error")
const handler = new OpencodeGoHandler(mockOptions)
await expect(handler.completePrompt("ping")).rejects.toBe("not an error")
})
it("returns an empty string when no content is returned", async () => {
mockCreate.mockResolvedValue({ choices: [] })
const handler = new OpencodeGoHandler(mockOptions)
expect(await handler.completePrompt("ping")).toBe("")
})
it("honors includeMaxTokens/modelMaxTokens override for max_completion_tokens", async () => {
mockCreate.mockResolvedValue({ choices: [{ message: { content: "ok" } }] })
const handler = new OpencodeGoHandler({ ...mockOptions, includeMaxTokens: true, modelMaxTokens: 4321 })
await handler.completePrompt("ping")
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({ max_completion_tokens: 4321 }),
expect.objectContaining({
headers: expect.objectContaining({ "x-opencode-session": expect.any(String) }),
}),
)
})
it("sends the per-instance session ID on non-streaming completions", async () => {
mockCreate.mockResolvedValue({ choices: [{ message: { content: "ok" } }] })
const handler = new OpencodeGoHandler(mockOptions)
await handler.completePrompt("ping")
const sessionId = mockCreate.mock.calls[0][1]?.headers["x-opencode-session"]
expect(sessionId).toEqual(expect.any(String))
// completePrompt has no taskId metadata, so the per-instance ID is
// reused across calls on the same handler.
await handler.completePrompt("ping")
expect(mockCreate.mock.calls[1][1]?.headers["x-opencode-session"]).toBe(sessionId)
})
})
describe("Anthropic-format models (qwen3.7-max)", () => {
// qwen3.7-max is only reachable via the Anthropic Messages endpoint
// (/v1/messages); sending it to /v1/chat/completions is what produces
// "401 Model qwen3.7-max is not supported for format oa-compat".
const anthropicOptions: ApiHandlerOptions = {
opencodeGoApiKey: "test-key",
opencodeGoModelId: "qwen3.7-max",
}
beforeEach(() => {
mockAnthropicCreate.mockImplementation(async () =>
asyncStreamFrom([
{
type: "message_start",