Repository navigation
Expand file tree
/
Copy pathcommandcode.test.ts
More file actions
818 lines (749 loc) · 29.1 KB
/
Copy pathcommandcode.test.ts
File metadata and controls
818 lines (749 loc) · 29.1 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
import { afterEach, describe, expect, it, vi } from "vitest";
import {
CommandCodeBillingClient,
CommandCodeClient,
CommandCodeHttpError,
parseCommandCodeEventLine,
parseCommandCodeStream,
} from "../src/commandcode.js";
import type { BridgeConfig, CommandCodeEvent, CommandCodeGenerateBody } from "../src/types.js";
import type { CommandCodeCredentialRouter } from "../src/credential-router.js";
function streamFromChunks(chunks: string[]): ReadableStream<Uint8Array> {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
controller.close();
},
});
}
const baseConfig: BridgeConfig = {
host: "127.0.0.1",
port: 9992,
apiBase: "https://api.commandcode.ai",
cliVersion: "1.14.0",
upstreamMode: "alpha",
zdr: false,
defaultModel: "deepseek/deepseek-v4-pro",
allowedModels: ["deepseek/deepseek-v4-pro", "deepseek/deepseek-v4-flash"],
allowUnknownModels: false,
bridgeApiKey: undefined,
bridgeApiKeySource: "none",
commandCodeApiKey: "alpha-secret",
commandCodeCredentials: [
{ id: "alpha", apiKey: "alpha-secret", weight: 1 },
{ id: "beta", apiKey: "beta-secret", weight: 1 },
],
commandCodeRoutingPolicy: "round_robin",
commandCodeBillingRefreshMs: 60_000,
commandCodeBillingTimeoutMs: 10_000,
commandCodeCredentialCooldownMs: 60_000,
commandCodeRetryMaxAttempts: 5,
commandCodeRetryBackoffMs: 1,
requestBodyLimitBytes: 1_048_576,
rateLimitMax: 60,
rateLimitWindow: "1 minute",
logLevel: "silent",
corsOrigin: undefined,
includeReasoning: false,
emptyVisibleResponsePolicy: "error_on_length",
emptyVisibleRetryMaxAttempts: 1,
emptyVisibleRetryBackoffMs: 250,
balanceAlerts: {
enabled: false,
minCurrentBalance: 1,
minExpiringBalance: 0,
maxRequiredDailyBurn: 0,
intervalMs: 60_000,
repeatMs: 3_600_000,
webhookUrl: undefined,
webhookBearer: undefined,
},
timeoutMs: 300_000,
};
const generateBody: CommandCodeGenerateBody = {
config: {
workingDir: "/tmp/workspace",
date: "2026-05-12",
environment: "test",
structure: [],
isGitRepo: false,
currentBranch: "main",
mainBranch: "main",
gitStatus: "",
recentCommits: [],
},
memory: null,
taste: null,
skills: null,
permissionMode: "standard",
params: {
model: "deepseek/deepseek-v4-pro",
messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
tools: [],
system: "",
stream: true,
},
threadId: "thread-test",
};
async function collectEvents(events: AsyncIterable<CommandCodeEvent>): Promise<CommandCodeEvent[]> {
const collected: CommandCodeEvent[] = [];
for await (const event of events) collected.push(event);
return collected;
}
function billingResponse(url: string): Response | undefined {
if (url.includes("/alpha/whoami")) return Response.json({ org: { id: "org_test" } });
if (url.includes("/alpha/billing/credits")) {
return Response.json({
credits: { monthlyCredits: 10, purchasedCredits: 0, freeCredits: 0 },
});
}
if (url.includes("/alpha/billing/subscriptions")) {
return Response.json({
data: {
currentPeriodStart: "2026-05-01T00:00:00.000Z",
currentPeriodEnd: "2099-01-01T00:00:00.000Z",
},
});
}
if (url.includes("/alpha/usage/summary")) return Response.json({ totalCost: 0, totalCount: 0 });
return undefined;
}
function postCalls(fetchMock: ReturnType<typeof vi.fn<typeof fetch>>) {
return fetchMock.mock.calls.filter(
(call) => (call[1] as RequestInit | undefined)?.method === "POST",
);
}
afterEach(() => {
vi.unstubAllGlobals();
});
describe("CommandCode stream parsing", () => {
it("parses raw JSON lines and SSE data lines", () => {
expect(parseCommandCodeEventLine('{"type":"text-delta","text":"x"}')).toEqual({
type: "text-delta",
text: "x",
});
expect(parseCommandCodeEventLine('data: {"type":"finish","finishReason":"stop"}')).toEqual({
type: "finish",
finishReason: "stop",
});
});
it("ignores comments, labels, done markers, and malformed lines", () => {
expect(parseCommandCodeEventLine(":")).toBeUndefined();
expect(parseCommandCodeEventLine("event: message")).toBeUndefined();
expect(parseCommandCodeEventLine("data: [DONE]")).toBeUndefined();
expect(parseCommandCodeEventLine("not-json")).toBeUndefined();
});
it("parses chunk boundaries safely", async () => {
const events = [];
for await (const event of parseCommandCodeStream(
streamFromChunks([
'{"type":"text-delta",',
'"text":"hel"}\n{"type":"finish","finishReason":"stop"}\n',
]),
)) {
events.push(event);
}
expect(events).toEqual([
{ type: "text-delta", text: "hel" },
{ type: "finish", finishReason: "stop" },
]);
});
it("parses structured upstream error events", () => {
expect(
parseCommandCodeEventLine(
'{"type":"error","error":{"type":"server_error","message":"Insufficient Balance","statusCode":402}}',
),
).toEqual({
type: "error",
error: { type: "server_error", message: "Insufficient Balance", statusCode: 402 },
});
});
it("keeps structured upstream HTTP error data", () => {
const error = new CommandCodeHttpError(400, "Bad Request", { error: { message: "bad" } });
expect(error.status).toBe(400);
expect(error.message).toContain("Bad Request");
expect(error.body).toEqual({ error: { message: "bad" } });
});
it("parses CommandCode 1.14.0 raw and SSE event variants", () => {
expect(parseCommandCodeEventLine('{"type":"reasoning-start"}')).toEqual({
type: "reasoning-start",
});
expect(parseCommandCodeEventLine('data: {"type":"reasoning-delta","text":"think"}')).toEqual({
type: "reasoning-delta",
text: "think",
});
expect(parseCommandCodeEventLine('{"type":"reasoning-end"}')).toEqual({
type: "reasoning-end",
});
expect(
parseCommandCodeEventLine(
'data: {"type":"tool-call","toolCallId":"call_0","toolName":"read_file","input":{"path":"input.txt"}}',
),
).toMatchObject({ type: "tool-call", toolCallId: "call_0", input: { path: "input.txt" } });
expect(
parseCommandCodeEventLine(
'data: {"type":"tool-call","toolCallId":"call_1","toolName":"read_file","args":{"path":"a.txt"}}',
),
).toEqual({
type: "tool-call",
toolCallId: "call_1",
toolName: "read_file",
args: { path: "a.txt" },
});
expect(
parseCommandCodeEventLine(
'{"type":"tool-result","toolCallId":"call_1","toolName":"read_file","result":"ok","isError":false}',
),
).toEqual({
type: "tool-result",
toolCallId: "call_1",
toolName: "read_file",
result: "ok",
isError: false,
});
expect(
parseCommandCodeEventLine(
'data: {"type":"tool-result","toolCallId":"call_2","toolName":"read_file","output":"failed","isError":true,"providerExecuted":true}',
),
).toMatchObject({
type: "tool-result",
toolCallId: "call_2",
output: "failed",
isError: true,
providerExecuted: true,
});
expect(parseCommandCodeEventLine('data: {"type":"error","error":"upstream failed"}')).toEqual({
type: "error",
error: "upstream failed",
});
});
it("keeps CommandCode 1.14.0 finish usage and abort-only streams intact", async () => {
const finished = await collectEvents(
parseCommandCodeStream(
streamFromChunks([
'{"type":"text-delta","text":"ok"}\n',
'data: {"type":"finish","finishReason":"stop","totalUsage":{"inputTokens":2,"outputTokens":1,"inputTokenDetails":{"cacheReadTokens":1,"cacheWriteTokens":0}}}\n',
]),
),
);
expect(finished).toEqual([
{ type: "text-delta", text: "ok" },
expect.objectContaining({
type: "finish",
finishReason: "stop",
totalUsage: {
inputTokens: 2,
outputTokens: 1,
inputTokenDetails: { cacheReadTokens: 1, cacheWriteTokens: 0 },
},
}),
]);
const aborted = await collectEvents(
parseCommandCodeStream(streamFromChunks(['data: {"type":"abort"}\n'])),
);
expect(aborted).toEqual([{ type: "abort" }]);
});
});
describe("CommandCode client credential routing", () => {
it("queries billing endpoints and maps a depletion snapshot", async () => {
const fetchMock = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
new Response(JSON.stringify({ org: { id: "org_123" } }), { status: 200 }),
)
.mockResolvedValueOnce(
new Response(
JSON.stringify({
credits: { monthlyCredits: 12, purchasedCredits: 3, freeCredits: 1, planId: "pro" },
windowLimits: {
limited: true,
exceeded: "weekly",
fiveHour: { used: 2.25, cap: 3, exceeded: false, resetAt: 1_786_091_731_770 },
weekly: { used: 6.24, cap: 6, exceeded: true, resetAt: 1_786_603_898_869 },
},
}),
{ status: 200 },
),
)
.mockResolvedValueOnce(
new Response(
JSON.stringify({
data: {
currentPeriodStart: "2026-05-01T00:00:00.000Z",
currentPeriodEnd: "2026-06-01T00:00:00.000Z",
planId: "pro-plan",
},
}),
{ status: 200 },
),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ totalCost: 4.5, totalCount: 9 }), { status: 200 }),
);
vi.stubGlobal("fetch", fetchMock);
const billingClient = new CommandCodeBillingClient(baseConfig);
const snapshot = await billingClient.getSnapshot({
id: "alpha",
apiKey: "alpha-secret",
weight: 1,
});
expect(fetchMock.mock.calls.map((call) => String(call[0]))).toEqual([
"https://api.commandcode.ai/alpha/whoami",
"https://api.commandcode.ai/alpha/billing/credits?orgId=org_123",
"https://api.commandcode.ai/alpha/billing/subscriptions?orgId=org_123",
"https://api.commandcode.ai/alpha/usage/summary?orgId=org_123&since=2026-05-01T00%3A00%3A00.000Z",
]);
expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({
"User-Agent": "cli",
"x-command-code-version": "1.14.0",
});
expect(snapshot).toMatchObject({
monthlyCredits: 12,
purchasedCredits: 3,
freeCredits: 1,
currentPeriodEnd: "2026-06-01T00:00:00.000Z",
planId: "pro-plan",
totalCost: 4.5,
totalCount: 9,
windowLimits: {
limited: true,
exceeded: "weekly",
fiveHour: { used: 2.25, cap: 3, exceeded: false, resetAt: 1_786_091_731_770 },
weekly: { used: 6.24, cap: 6, exceeded: true, resetAt: 1_786_603_898_869 },
},
});
});
it("uses configured credential pool instead of one fixed API key", async () => {
const fetchMock = vi.fn<typeof fetch>(async (input) => {
const url = String(input);
const billing = billingResponse(url);
if (billing) return billing;
return new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient(baseConfig);
await collectEvents(client.generate(generateBody));
await collectEvents(client.generate(generateBody));
const posts = postCalls(fetchMock);
expect(posts).toHaveLength(2);
expect((posts[0]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer alpha-secret",
"User-Agent": "cli",
});
expect((posts[1]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer beta-secret",
});
});
it("keeps one conversation on one key across turns when given a session key", async () => {
const fetchMock = vi.fn<typeof fetch>(async (input) => {
const url = String(input);
const billing = billingResponse(url);
if (billing) return billing;
return new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient(baseConfig);
await collectEvents(client.generate(generateBody, undefined, { sessionKey: "conversation-a" }));
await collectEvents(client.generate(generateBody, undefined, { sessionKey: "conversation-a" }));
const keys = postCalls(fetchMock).map(
(call) => ((call[1] as RequestInit).headers as Record<string, string>).Authorization,
);
expect(keys).toHaveLength(2);
expect(keys[1]).toBe(keys[0]);
});
it("fails over to another credential when an upstream stream error marks the first key depleted", async () => {
const postResponses = [
new Response(
'data: {"type":"error","error":{"message":"Insufficient Balance","statusCode":402}}\n',
{ status: 200 },
),
new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
),
];
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") return postResponses.shift()!;
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient(baseConfig);
const events = await collectEvents(client.generate(generateBody));
const posts = postCalls(fetchMock);
expect(posts).toHaveLength(2);
expect((posts[0]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer alpha-secret",
"User-Agent": "cli",
});
expect((posts[1]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer beta-secret",
});
expect(events).toContainEqual(expect.objectContaining({ type: "text-delta", text: "ok" }));
expect(events).not.toContainEqual(expect.objectContaining({ type: "error" }));
});
it("does not retry the same credential after an opaque retryable stream error", async () => {
const postResponses = [
new Response('data: {"type":"error","message":"temporary upstream error"}\n', {
status: 200,
}),
new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
),
];
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") return postResponses.shift()!;
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient({
...baseConfig,
commandCodeCredentials: [
{ id: "alpha", apiKey: "alpha-secret", weight: 100 },
{ id: "beta", apiKey: "beta-secret", weight: 1 },
],
});
const events = await collectEvents(client.generate(generateBody));
const posts = postCalls(fetchMock);
expect(posts).toHaveLength(2);
expect((posts[0]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer alpha-secret",
"User-Agent": "cli",
});
expect((posts[1]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer beta-secret",
});
expect(events).toContainEqual(expect.objectContaining({ type: "text-delta", text: "ok" }));
});
it("does not cool down a credential when a retried upstream error eventually succeeds", async () => {
const postResponses = [
new Response('data: {"type":"error","message":"temporary upstream error"}\n', {
status: 200,
}),
new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
),
];
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") return postResponses.shift()!;
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient({
...baseConfig,
commandCodeCredentials: [{ id: "alpha", apiKey: "alpha-secret", weight: 1 }],
});
const events = await collectEvents(client.generate(generateBody));
const posts = postCalls(fetchMock);
expect(posts).toHaveLength(2);
expect((posts[1]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer alpha-secret",
});
expect(events).toContainEqual(expect.objectContaining({ type: "text-delta", text: "ok" }));
const diagnostics = await client.getCredentialDiagnostics();
expect(diagnostics[0]?.disabledUntil).toBeNull();
});
it("serves through a credential cooldown instead of failing the request", async () => {
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") {
return new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
);
}
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient({
...baseConfig,
commandCodeCredentials: [{ id: "alpha", apiKey: "alpha-secret", weight: 1 }],
});
await collectEvents(client.generate(generateBody));
const router = (client as unknown as { router: CommandCodeCredentialRouter }).router;
router.recordFailure("alpha", { statusCode: 429 });
const diagnostics = await client.getCredentialDiagnostics();
expect(diagnostics[0]?.disabledUntil).not.toBeNull();
const events = await collectEvents(client.generate(generateBody));
expect(events).toContainEqual(expect.objectContaining({ type: "text-delta", text: "ok" }));
const posts = postCalls(fetchMock);
expect(posts).toHaveLength(2);
expect((posts[1]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer alpha-secret",
});
});
it("does not cool down the credential when the provider reports at capacity without a status", async () => {
let postCount = 0;
const atCapacity =
'data: {"type":"error","message":"The request limited providers for this model and they are currently at capacity. Providers considered: deepseek."}\n';
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") {
postCount += 1;
if (postCount === 1) return new Response(atCapacity, { status: 200 });
return new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
);
}
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient({
...baseConfig,
commandCodeCredentials: [{ id: "alpha", apiKey: "alpha-secret", weight: 1 }],
commandCodeRetryMaxAttempts: 1,
});
const events = await collectEvents(client.generate(generateBody));
expect(events).toContainEqual(expect.objectContaining({ type: "error" }));
const diagnostics = await client.getCredentialDiagnostics();
expect(diagnostics[0]?.disabledUntil).toBeNull();
const retryEvents = await collectEvents(client.generate(generateBody));
expect(retryEvents).toContainEqual(expect.objectContaining({ type: "text-delta", text: "ok" }));
expect(postCalls(fetchMock)).toHaveLength(2);
});
it("does not cool down the credential when a provider-scoped 429 exhausts retries", async () => {
let postCount = 0;
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") {
postCount += 1;
if (postCount === 1) return new Response("at capacity", { status: 429 });
return new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
);
}
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient({
...baseConfig,
commandCodeCredentials: [{ id: "alpha", apiKey: "alpha-secret", weight: 1 }],
commandCodeRetryMaxAttempts: 1,
});
await expect(collectEvents(client.generate(generateBody))).rejects.toBeInstanceOf(
CommandCodeHttpError,
);
const diagnostics = await client.getCredentialDiagnostics();
expect(diagnostics[0]?.disabledUntil).toBeNull();
const events = await collectEvents(client.generate(generateBody));
expect(events).toContainEqual(expect.objectContaining({ type: "text-delta", text: "ok" }));
expect(postCalls(fetchMock)).toHaveLength(2);
});
it("marks the credential as billing when a 400 reports insufficient credits", async () => {
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") {
return Response.json(
{
success: false,
error: {
code: "BAD_REQUEST",
status: 400,
message:
"You have insufficient credits to make this request. Please purchase more credits to continue using the service.",
docs: "https://commandcode.ai/docs/reference/errors/bad_request",
},
},
{ status: 400 },
);
}
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient({
...baseConfig,
commandCodeCredentials: [{ id: "alpha", apiKey: "alpha-secret", weight: 1 }],
});
await expect(collectEvents(client.generate(generateBody))).rejects.toBeInstanceOf(
CommandCodeHttpError,
);
const diagnostics = await client.getCredentialDiagnostics();
expect(diagnostics[0]?.disabledUntil).not.toBeNull();
});
it("does not cool down the credential for a plain 400 bad request", async () => {
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") {
return Response.json(
{ error: { code: "BAD_REQUEST", message: "Model not allowed for this plan." } },
{ status: 400 },
);
}
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient({
...baseConfig,
commandCodeCredentials: [{ id: "alpha", apiKey: "alpha-secret", weight: 1 }],
});
await expect(collectEvents(client.generate(generateBody))).rejects.toBeInstanceOf(
CommandCodeHttpError,
);
const diagnostics = await client.getCredentialDiagnostics();
expect(diagnostics[0]?.disabledUntil).toBeNull();
await expect(collectEvents(client.generate(generateBody))).rejects.toBeInstanceOf(
CommandCodeHttpError,
);
expect(postCalls(fetchMock)).toHaveLength(2);
});
it("rotates to the next credential when a 400 reports insufficient credits", async () => {
const postResponses = [
Response.json(
{
success: false,
error: {
code: "BAD_REQUEST",
status: 400,
message:
"You have insufficient credits to make this request. Please purchase more credits to continue using the service.",
},
},
{ status: 400 },
),
new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
),
];
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") return postResponses.shift()!;
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient(baseConfig);
const events = await collectEvents(client.generate(generateBody));
const posts = postCalls(fetchMock);
expect(posts).toHaveLength(2);
expect((posts[0]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer alpha-secret",
});
expect((posts[1]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer beta-secret",
});
expect(events).toContainEqual(expect.objectContaining({ type: "text-delta", text: "ok" }));
expect(events).not.toContainEqual(expect.objectContaining({ type: "error" }));
const diagnostics = await client.getCredentialDiagnostics();
expect(diagnostics[0]?.disabledUntil).not.toBeNull();
expect(diagnostics[1]?.disabledUntil).toBeNull();
});
it("fails fast on a plain 400 instead of rotating credentials", async () => {
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") {
return Response.json(
{ error: { code: "BAD_REQUEST", message: "Model not allowed for this plan." } },
{ status: 400 },
);
}
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient(baseConfig);
await expect(collectEvents(client.generate(generateBody))).rejects.toMatchObject({
status: 400,
});
expect(postCalls(fetchMock)).toHaveLength(1);
});
it("rotates to the next credential when the first key is forbidden", async () => {
const postResponses = [
Response.json({ error: { message: "key revoked" } }, { status: 403 }),
new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
),
];
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") return postResponses.shift()!;
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient(baseConfig);
const events = await collectEvents(client.generate(generateBody));
const posts = postCalls(fetchMock);
expect(posts).toHaveLength(2);
expect((posts[0]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer alpha-secret",
});
expect((posts[1]?.[1] as RequestInit).headers).toMatchObject({
Authorization: "Bearer beta-secret",
});
expect(events).toContainEqual(expect.objectContaining({ type: "text-delta", text: "ok" }));
});
it("releases the credential without cooldown when the caller aborts mid-stream", async () => {
let hanging = true;
let postStarted: () => void = () => undefined;
const postStartedPromise = new Promise<void>((resolve) => {
postStarted = resolve;
});
const fetchMock = vi.fn<typeof fetch>(async (input, init) => {
const billing = billingResponse(String(input));
if (billing) return billing;
if (init?.method === "POST") {
if (!hanging) {
return new Response(
'data: {"type":"text-delta","text":"ok"}\ndata: {"type":"finish","finishReason":"stop"}\n',
{ status: 200 },
);
}
postStarted();
const callerSignal = init.signal;
return new Response(
new ReadableStream<Uint8Array>({
start(controller) {
callerSignal?.addEventListener(
"abort",
() => {
controller.error(new DOMException("This operation was aborted", "AbortError"));
},
{ once: true },
);
},
}),
{ status: 200 },
);
}
throw new Error(`Unexpected fetch ${String(input)}`);
});
vi.stubGlobal("fetch", fetchMock);
const client = new CommandCodeClient(baseConfig);
const abortController = new AbortController();
const iteration = collectEvents(client.generate(generateBody, abortController.signal));
await postStartedPromise;
abortController.abort();
await expect(iteration).rejects.toMatchObject({ name: "AbortError" });
const diagnostics = await client.getCredentialDiagnostics();
for (const diagnostic of diagnostics) {
expect(diagnostic.inFlight).toBe(0);
expect(diagnostic.disabledUntil).toBeNull();
}
hanging = false;
const events = await collectEvents(client.generate(generateBody));
expect(events).toContainEqual(expect.objectContaining({ type: "text-delta", text: "ok" }));
});
});