Repository navigation
Expand file tree
/
Copy pathcommandcode.ts
More file actions
583 lines (533 loc) · 20.7 KB
/
Copy pathcommandcode.ts
File metadata and controls
583 lines (533 loc) · 20.7 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
import {
CommandCodeCredentialRouter,
type CommandCodeCredentialDiagnostic,
isInsufficientCreditsMessage,
NoAvailableCommandCodeCredentialError,
type SelectCredentialOptions,
} from "./credential-router.js";
import type {
BridgeConfig,
CommandCodeBillingSnapshot,
CommandCodeCredential,
CommandCodeEvent,
CommandCodeGenerateBody,
CommandCodeGenerateOptions,
CommandCodeUpstream,
CommandCodeUsageWindow,
CommandCodeWindowLimits,
} from "./types.js";
export class CommandCodeHttpError extends Error {
public readonly status: number;
public readonly statusText: string;
public readonly body: unknown;
public constructor(status: number, statusText: string, body: unknown) {
super(`CommandCode upstream returned ${status} ${statusText}`);
this.name = "CommandCodeHttpError";
this.status = status;
this.statusText = statusText;
this.body = body;
}
}
export class CommandCodeAuthError extends Error {
public constructor() {
super(
"CommandCode API key is missing. Set COMMANDCODE_API_KEY or provide ~/.commandcode/auth.json.",
);
this.name = "CommandCodeAuthError";
}
}
function isCommandCodeEvent(value: unknown): value is CommandCodeEvent {
return (
typeof value === "object" &&
value !== null &&
typeof (value as { type?: unknown }).type === "string"
);
}
export function parseCommandCodeEventLine(line: string): CommandCodeEvent | undefined {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith(":")) return undefined;
if (trimmed.startsWith("event:")) return undefined;
const payload = trimmed.startsWith("data:") ? trimmed.slice("data:".length).trim() : trimmed;
if (!payload || payload === "[DONE]") return undefined;
try {
const parsed = JSON.parse(payload) as unknown;
return isCommandCodeEvent(parsed) ? parsed : undefined;
} catch {
return undefined;
}
}
export async function* parseCommandCodeStream(
stream: ReadableStream<Uint8Array>,
): AsyncIterable<CommandCodeEvent> {
const decoder = new TextDecoder();
const reader = stream.getReader();
let buffer = "";
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split(/\r?\n/);
buffer = lines.pop() ?? "";
for (const line of lines) {
const event = parseCommandCodeEventLine(line);
if (event) yield event;
}
}
buffer += decoder.decode();
const event = parseCommandCodeEventLine(buffer);
if (event) yield event;
} finally {
await reader.cancel().catch(() => undefined);
reader.releaseLock();
}
}
async function responseBody(response: Response): Promise<unknown> {
const text = await response.text();
if (!text) return undefined;
try {
return JSON.parse(text) as unknown;
} catch {
return text;
}
}
export { responseBody };
function slugFromWorkingDir(workingDir: string): string {
const last = workingDir.split(/[\\/]/).filter(Boolean).pop() ?? "workspace";
return last.replace(/[^a-zA-Z0-9_.-]/g, "-").slice(0, 80) || "workspace";
}
export function createTimeoutSignal(timeoutMs: number): AbortSignal {
const timeoutFactory = (
AbortSignal as typeof AbortSignal & { timeout?: (milliseconds: number) => AbortSignal }
).timeout;
if (typeof timeoutFactory === "function") return timeoutFactory(timeoutMs);
const controller = new AbortController();
const timeout = setTimeout(
() => controller.abort(new Error(`Timed out after ${timeoutMs}ms`)),
timeoutMs,
);
timeout.unref?.();
return controller.signal;
}
export function combineAbortSignals(signals: AbortSignal[]): AbortSignal {
const anyFactory = (
AbortSignal as typeof AbortSignal & { any?: (signals: AbortSignal[]) => AbortSignal }
).any;
if (typeof anyFactory === "function") return anyFactory(signals);
const controller = new AbortController();
const abortFrom = (signal: AbortSignal) => {
controller.abort(signal.reason);
};
for (const signal of signals) {
if (signal.aborted) {
abortFrom(signal);
break;
}
signal.addEventListener("abort", () => abortFrom(signal), { once: true });
}
return controller.signal;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function stringValue(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
function numberValue(value: unknown): number {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string") {
const parsed = Number(value);
if (Number.isFinite(parsed)) return parsed;
}
return 0;
}
function buildEndpoint(
endpoint: string,
params: Record<string, string | null | undefined> = {},
): string {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== null) search.set(key, value);
}
const query = search.toString();
return query ? `${endpoint}?${query}` : endpoint;
}
function errorStatusCode(event: CommandCodeEvent): number | undefined {
if (event.type !== "error") return undefined;
const error = isRecord(event.error) ? event.error : undefined;
const statusCode = numberValue(
error?.statusCode ?? error?.status ?? event.statusCode ?? event.status,
);
return statusCode > 0 ? statusCode : undefined;
}
function errorStatusCodeFromUnknown(error: unknown): number | undefined {
return error instanceof CommandCodeHttpError ? error.status : undefined;
}
export function shouldRetryStatus(statusCode: number | undefined, errorMessage?: string): boolean {
return (
statusCode === undefined ||
statusCode === 401 ||
statusCode === 402 ||
statusCode === 403 ||
statusCode === 429 ||
statusCode >= 500 ||
// A bare 400 is client-scoped and must fail fast, but the
// insufficient-credits variant blames this credential only: another key can
// still serve the request, so rotate instead of failing.
(statusCode === 400 && isInsufficientCreditsMessage(errorMessage))
);
}
function isClientVisibleEvent(event: CommandCodeEvent): boolean {
return ["text-delta", "reasoning-delta", "tool-call", "finish"].includes(event.type);
}
export function isFatalCredFailure(statusCode: number | undefined, errorMessage?: string): boolean {
return (
statusCode === 401 ||
statusCode === 402 ||
statusCode === 403 ||
// A bare 400 is provider-scoped (bad model, invalid body), but the same
// status with an insufficient-credits body blames this credential only.
(statusCode === 400 && isInsufficientCreditsMessage(errorMessage))
);
}
/** Extracts the upstream error text from a parsed HTTP or SSE body for failure classification. */
export function upstreamErrorMessage(body: unknown): string | undefined {
if (typeof body === "string") return body;
if (!isRecord(body)) return undefined;
const error = isRecord(body.error) ? body.error : undefined;
const message = error?.message ?? body.message;
return typeof message === "string" && message.length > 0 ? message : undefined;
}
export function retryBackoff(attempt: number, baseMs: number): Promise<void> {
const delay = Math.min(Math.max(1, baseMs) * 2 ** attempt, 2_000);
return new Promise((resolve) => setTimeout(resolve, delay));
}
function usageWindowValue(value: unknown): CommandCodeUsageWindow | undefined {
if (!isRecord(value)) return undefined;
const used =
typeof value.used === "number" && Number.isFinite(value.used) ? value.used : undefined;
const cap = typeof value.cap === "number" && Number.isFinite(value.cap) ? value.cap : undefined;
const resetAt =
typeof value.resetAt === "number" && Number.isFinite(value.resetAt) ? value.resetAt : undefined;
if (used === undefined || cap === undefined || resetAt === undefined) return undefined;
return { used, cap, exceeded: value.exceeded === true, resetAt };
}
function windowLimitsValue(value: unknown): CommandCodeWindowLimits | undefined {
if (!isRecord(value)) return undefined;
const fiveHour = usageWindowValue(value.fiveHour);
const weekly = usageWindowValue(value.weekly);
const exceeded = typeof value.exceeded === "string" ? value.exceeded : null;
const limits: CommandCodeWindowLimits = {
limited: value.limited === true,
exceeded,
};
if (fiveHour) limits.fiveHour = fiveHour;
if (weekly) limits.weekly = weekly;
if (!fiveHour && !weekly && !limits.limited) return undefined;
return limits;
}
export class CommandCodeBillingClient {
private readonly config: BridgeConfig;
public constructor(config: BridgeConfig) {
this.config = config;
}
public async getSnapshot(
credential: CommandCodeCredential,
signal?: AbortSignal,
): Promise<CommandCodeBillingSnapshot> {
const effectiveSignal = signal ?? createTimeoutSignal(this.config.commandCodeBillingTimeoutMs);
const whoami = await this.getJson("/alpha/whoami", credential, effectiveSignal);
const org = isRecord(whoami) && isRecord(whoami.org) ? whoami.org : undefined;
const orgId = stringValue(org?.id) ?? null;
const credits = await this.getJson(
buildEndpoint("/alpha/billing/credits", { orgId }),
credential,
effectiveSignal,
);
const subscription = await this.getJson(
buildEndpoint("/alpha/billing/subscriptions", { orgId }),
credential,
effectiveSignal,
);
const subscriptionData =
isRecord(subscription) && isRecord(subscription.data) ? subscription.data : undefined;
const currentPeriodStart = stringValue(subscriptionData?.currentPeriodStart);
const summary = await this.getJson(
buildEndpoint("/alpha/usage/summary", { orgId, since: currentPeriodStart }),
credential,
effectiveSignal,
).catch(() => undefined);
const creditData = isRecord(credits) && isRecord(credits.credits) ? credits.credits : undefined;
const snapshot: CommandCodeBillingSnapshot = {
fetchedAt: Date.now(),
monthlyCredits: numberValue(creditData?.monthlyCredits),
purchasedCredits: numberValue(creditData?.purchasedCredits),
freeCredits: numberValue(creditData?.freeCredits),
currentPeriodEnd: stringValue(subscriptionData?.currentPeriodEnd) ?? null,
planId: stringValue(subscriptionData?.planId) ?? stringValue(creditData?.planId) ?? null,
};
const windowLimits = isRecord(credits) ? windowLimitsValue(credits.windowLimits) : undefined;
if (windowLimits) snapshot.windowLimits = windowLimits;
if (isRecord(summary)) {
const totalCost = numberValue(summary.totalCost);
const totalCount = numberValue(summary.totalCount);
snapshot.totalCost = totalCost;
snapshot.totalCount = totalCount;
}
return snapshot;
}
private async getJson(
endpoint: string,
credential: CommandCodeCredential,
signal?: AbortSignal,
): Promise<unknown> {
const init: RequestInit = {
method: "GET",
headers: this.headers(credential),
};
if (signal) init.signal = signal;
const response = await fetch(`${this.config.apiBase}${endpoint}`, init);
if (!response.ok) {
throw new CommandCodeHttpError(
response.status,
response.statusText,
await responseBody(response),
);
}
return responseBody(response);
}
private headers(credential: CommandCodeCredential): Record<string, string> {
return {
"Content-Type": "application/json",
Authorization: `Bearer ${credential.apiKey}`,
"User-Agent": "cli",
"x-cli-environment": "production",
"x-command-code-version": this.config.cliVersion,
};
}
}
export function createCommandCodeCredentialRouter(
config: BridgeConfig,
): CommandCodeCredentialRouter {
const billingClient = new CommandCodeBillingClient(config);
return new CommandCodeCredentialRouter({
credentials: config.commandCodeCredentials,
policy: config.commandCodeRoutingPolicy,
fallbackPolicy: config.commandCodeFallbackRoutingPolicy ?? "round_robin",
maxInFlightPerCredential: config.commandCodeMaxInFlightPerCredential ?? 4,
maxTotalInFlight: config.commandCodeMaxTotalInFlight,
billingRefreshMs: config.commandCodeBillingRefreshMs,
billingTimeoutMs: config.commandCodeBillingTimeoutMs,
cooldownMs: config.commandCodeCredentialCooldownMs,
billingProvider: (credential: CommandCodeCredential, signal: AbortSignal) =>
billingClient.getSnapshot(credential, signal),
validateBillingBeforeSelect: true,
...(config.sessionAffinityTtlMs !== undefined
? { sessionTtlMs: config.sessionAffinityTtlMs }
: {}),
});
}
export class CommandCodeClient implements CommandCodeUpstream {
private readonly config: BridgeConfig;
private readonly router: CommandCodeCredentialRouter;
public constructor(config: BridgeConfig) {
this.config = config;
this.router = createCommandCodeCredentialRouter(config);
}
public removeCredential(id: string): boolean {
return this.router.removeCredential(id);
}
public async getCredentialDiagnostics(
options: { refresh?: boolean } = {},
): Promise<CommandCodeCredentialDiagnostic[]> {
await this.router.refreshAllBilling({ force: options.refresh ?? false });
return this.router.diagnostics();
}
public async *generate(
body: CommandCodeGenerateBody,
signal?: AbortSignal,
options: CommandCodeGenerateOptions = {},
): AsyncIterable<CommandCodeEvent> {
if (this.router.credentialCount === 0) throw new CommandCodeAuthError();
const timeoutSignal = createTimeoutSignal(this.config.timeoutMs);
const effectiveSignal = signal ? combineAbortSignals([signal, timeoutSignal]) : timeoutSignal;
let lastError: unknown;
const maxAttempts = Math.max(1, this.config.commandCodeRetryMaxAttempts ?? 5);
const fatalIds = new Set<string>();
const retryableFailed = new Set<string>();
attemptLoop: for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
let credential: CommandCodeCredential;
try {
const selectOptions: SelectCredentialOptions = {
model: body.params.model,
ignoreCooldown: attempt > 0,
...(options.sessionKey ? { sessionKey: options.sessionKey } : {}),
};
if (fatalIds.size + retryableFailed.size > 0) {
selectOptions.excludeIds = new Set([...fatalIds, ...retryableFailed]);
}
credential = await this.router.select(selectOptions);
} catch (error) {
if (retryableFailed.size > 0) {
retryableFailed.clear();
credential = await this.router.select({
model: body.params.model,
ignoreCooldown: true,
...(options.sessionKey ? { sessionKey: options.sessionKey } : {}),
});
} else if (attempt === 0 && error instanceof NoAvailableCommandCodeCredentialError) {
// A cooldown is a preference, not a hard gate: when every credential is
// cooling down, serve with one anyway instead of failing the request.
credential = await this.router.select({
model: body.params.model,
ignoreCooldown: true,
});
} else {
if (lastError instanceof Error) throw lastError;
throw error;
}
}
let finalized = false;
const finalizeSuccess = () => {
if (finalized) return;
this.router.recordSuccess(credential.id);
finalized = true;
};
const finalizeFailure = (statusCode?: number, errorMessage?: string) => {
if (finalized) return;
this.router.recordFailure(credential.id, {
...(statusCode !== undefined ? { statusCode } : {}),
...(errorMessage !== undefined ? { errorMessage } : {}),
});
finalized = true;
};
const finalizeRelease = () => {
if (finalized) return;
this.router.release(credential.id);
finalized = true;
};
try {
const response = await this.fetchGenerate(body, credential, effectiveSignal);
if (!response.ok) {
const error = new CommandCodeHttpError(
response.status,
response.statusText,
await responseBody(response),
);
lastError = error;
const upstreamMessage = upstreamErrorMessage(error.body);
const fatal = isFatalCredFailure(response.status, upstreamMessage);
const willRetry =
attempt < maxAttempts - 1 &&
shouldRetryStatus(response.status, upstreamMessage) &&
!effectiveSignal.aborted;
// Only credential-scoped failures may start a cooldown. Provider-scoped
// statuses like 429/5xx hit every credential at once, so cooling them
// down would bench the whole pool over a single upstream incident.
if (fatal) finalizeFailure(response.status, upstreamMessage);
else finalizeRelease();
if (willRetry) {
if (fatal) fatalIds.add(credential.id);
else retryableFailed.add(credential.id);
await retryBackoff(attempt, this.config.commandCodeRetryBackoffMs ?? 250);
continue;
}
throw error;
}
if (!response.body) {
const error = new CommandCodeHttpError(
response.status,
response.statusText,
"Upstream response body is empty",
);
lastError = error;
const willRetry = attempt < maxAttempts - 1 && !effectiveSignal.aborted;
finalizeRelease();
if (willRetry) {
retryableFailed.add(credential.id);
await retryBackoff(attempt, this.config.commandCodeRetryBackoffMs ?? 250);
continue;
}
throw error;
}
let emittedVisibleEvent = false;
for await (const event of parseCommandCodeStream(response.body)) {
const statusCode = errorStatusCode(event);
if (event.type === "error") {
lastError = new CommandCodeHttpError(
statusCode ?? 502,
"CommandCode stream error",
event,
);
const upstreamMessage = upstreamErrorMessage(event);
const fatal =
statusCode !== undefined && isFatalCredFailure(statusCode, upstreamMessage);
const willRetry =
!emittedVisibleEvent &&
attempt < maxAttempts - 1 &&
shouldRetryStatus(statusCode, upstreamMessage) &&
!effectiveSignal.aborted;
if (fatal) finalizeFailure(statusCode, upstreamMessage);
else finalizeRelease();
if (willRetry) {
if (fatal) fatalIds.add(credential.id);
else retryableFailed.add(credential.id);
await retryBackoff(attempt, this.config.commandCodeRetryBackoffMs ?? 250);
continue attemptLoop;
}
yield event;
return;
}
if (isClientVisibleEvent(event)) emittedVisibleEvent = true;
yield event;
}
finalizeSuccess();
return;
} catch (error) {
const statusCode = errorStatusCodeFromUnknown(error);
lastError = error;
const upstreamMessage =
error instanceof CommandCodeHttpError ? upstreamErrorMessage(error.body) : undefined;
const fatal = statusCode !== undefined && isFatalCredFailure(statusCode, upstreamMessage);
const willRetry =
signal?.aborted !== true &&
attempt < maxAttempts - 1 &&
shouldRetryStatus(statusCode, upstreamMessage) &&
!effectiveSignal.aborted;
if (fatal) finalizeFailure(statusCode, upstreamMessage);
else finalizeRelease();
if (willRetry) {
if (fatal) fatalIds.add(credential.id);
else retryableFailed.add(credential.id);
await retryBackoff(attempt, this.config.commandCodeRetryBackoffMs ?? 250);
continue;
}
throw error;
}
}
if (lastError instanceof Error) throw lastError;
throw new NoAvailableCommandCodeCredentialError();
}
private fetchGenerate(
body: CommandCodeGenerateBody,
credential: CommandCodeCredential,
signal: AbortSignal,
): Promise<Response> {
return fetch(`${this.config.apiBase}/alpha/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${credential.apiKey}`,
"User-Agent": "cli",
"x-cli-environment": "production",
"x-command-code-version": this.config.cliVersion,
"x-project-slug": slugFromWorkingDir(body.config.workingDir),
"x-taste-learning": "false",
...(this.config.zdr ? { "x-cmd-zdr": "1" } : {}),
...(body.threadId ? { "x-session-id": body.threadId } : {}),
},
body: JSON.stringify(body),
signal,
});
}
}