Repository navigation
Expand file tree
/
Copy pathcommandcode.ts
More file actions
440 lines (398 loc) · 14.1 KB
/
Copy pathcommandcode.ts
File metadata and controls
440 lines (398 loc) · 14.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
import {
CommandCodeCredentialRouter,
type CommandCodeCredentialDiagnostic,
NoAvailableCommandCodeCredentialError,
} from "./credential-router.js";
import type {
BridgeConfig,
CommandCodeBillingSnapshot,
CommandCodeCredential,
CommandCodeEvent,
CommandCodeGenerateBody,
CommandCodeUpstream,
} 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 {
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;
}
}
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";
}
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;
}
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;
}
function shouldRetry(statusCode: number | undefined): boolean {
return (
statusCode === undefined ||
statusCode === 401 ||
statusCode === 402 ||
statusCode === 429 ||
statusCode >= 500
);
}
function isClientVisibleEvent(event: CommandCodeEvent): boolean {
return ["text-delta", "reasoning-delta", "tool-call", "finish"].includes(event.type);
}
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,
};
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}`,
"x-cli-environment": "production",
"x-command-code-version": this.config.cliVersion,
};
}
}
export class CommandCodeClient implements CommandCodeUpstream {
private readonly config: BridgeConfig;
private readonly router: CommandCodeCredentialRouter;
public constructor(config: BridgeConfig) {
this.config = config;
const billingClient = new CommandCodeBillingClient(config);
const routerOptions = {
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,
};
this.router = new CommandCodeCredentialRouter(routerOptions);
}
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,
): 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.router.credentialCount);
const attemptedIds = new Set<string>();
attemptLoop: for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
let credential: CommandCodeCredential;
try {
credential = await this.router.select({
model: body.params.model,
excludeIds: attemptedIds,
});
} catch (error) {
if (lastError instanceof Error) throw lastError;
throw error;
}
attemptedIds.add(credential.id);
let finalized = false;
const finalizeSuccess = () => {
if (finalized) return;
this.router.recordSuccess(credential.id);
finalized = true;
};
const finalizeFailure = (statusCode?: number) => {
if (finalized) return;
if (statusCode === undefined) this.router.recordFailure(credential.id);
else this.router.recordFailure(credential.id, { statusCode });
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),
);
finalizeFailure(response.status);
lastError = error;
if (
attempt < maxAttempts - 1 &&
shouldRetry(response.status) &&
!effectiveSignal.aborted
) {
continue;
}
throw error;
}
if (!response.body) {
const error = new CommandCodeHttpError(
response.status,
response.statusText,
"Upstream response body is empty",
);
finalizeFailure(response.status);
lastError = error;
if (attempt < maxAttempts - 1 && !effectiveSignal.aborted) continue;
throw error;
}
let emittedVisibleEvent = false;
for await (const event of parseCommandCodeStream(response.body)) {
const statusCode = errorStatusCode(event);
if (event.type === "error") {
finalizeFailure(statusCode);
lastError = new CommandCodeHttpError(
statusCode ?? 502,
"CommandCode stream error",
event,
);
if (
!emittedVisibleEvent &&
attempt < maxAttempts - 1 &&
shouldRetry(statusCode) &&
!effectiveSignal.aborted
) {
continue attemptLoop;
}
yield event;
return;
}
if (isClientVisibleEvent(event)) emittedVisibleEvent = true;
yield event;
}
finalizeSuccess();
return;
} catch (error) {
const statusCode = errorStatusCodeFromUnknown(error);
finalizeFailure(statusCode);
lastError = error;
if (attempt < maxAttempts - 1 && shouldRetry(statusCode) && !effectiveSignal.aborted)
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}`,
"x-cli-environment": "production",
"x-command-code-version": this.config.cliVersion,
"x-project-slug": slugFromWorkingDir(body.config.workingDir),
"x-taste-learning": "false",
"x-co-flag": "false",
"x-session-id": body.threadId,
},
body: JSON.stringify(body),
signal,
});
}
}