File size: 17,062 Bytes
7a1ad33 | 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 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { AuthClient } from 'google-auth-library';
import {
UserTierId,
type CodeAssistGlobalUserSettingResponse,
type LoadCodeAssistRequest,
type LoadCodeAssistResponse,
type LongRunningOperationResponse,
type OnboardUserRequest,
type SetCodeAssistGlobalUserSettingRequest,
type ClientMetadata,
type RetrieveUserQuotaRequest,
type RetrieveUserQuotaResponse,
type FetchAdminControlsRequest,
type FetchAdminControlsResponse,
type ConversationOffered,
type ConversationInteraction,
type StreamingLatency,
type RecordCodeAssistMetricsRequest,
type GeminiUserTier,
type Credits,
} from './types.js';
import type {
ListExperimentsRequest,
ListExperimentsResponse,
} from './experiments/types.js';
import type {
CountTokensParameters,
CountTokensResponse,
EmbedContentParameters,
EmbedContentResponse,
GenerateContentParameters,
GenerateContentResponse,
} from '@google/genai';
import * as readline from 'node:readline';
import { Readable } from 'node:stream';
import type { ContentGenerator } from '../core/contentGenerator.js';
import type { Config } from '../config/config.js';
import {
G1_CREDIT_TYPE,
getG1CreditBalance,
isOverageEligibleModel,
shouldAutoUseCredits,
} from '../billing/billing.js';
import { logBillingEvent, logInvalidChunk } from '../telemetry/loggers.js';
import { coreEvents } from '../utils/events.js';
import { CreditsUsedEvent } from '../telemetry/billingEvents.js';
import {
fromCountTokenResponse,
fromGenerateContentResponse,
toCountTokenRequest,
toGenerateContentRequest,
type CaCountTokenResponse,
type CaGenerateContentResponse,
} from './converter.js';
import {
formatProtoJsonDuration,
recordConversationOffered,
} from './telemetry.js';
import { getClientMetadata } from './experiments/client_metadata.js';
import { InvalidChunkEvent, type LlmRole } from '../telemetry/types.js';
/** HTTP options to be used in each of the requests. */
export interface HttpOptions {
/** Additional HTTP headers to be sent with the request. */
headers?: Record<string, string>;
}
export const CODE_ASSIST_ENDPOINT = 'https://cloudcode-pa.googleapis.com';
export const CODE_ASSIST_API_VERSION = 'v1internal';
const GENERATE_CONTENT_RETRY_DELAY_IN_MILLISECONDS = 1000;
export class CodeAssistServer implements ContentGenerator {
constructor(
readonly client: AuthClient,
readonly projectId?: string,
readonly httpOptions: HttpOptions = {},
readonly sessionId?: string,
readonly userTier?: UserTierId,
readonly userTierName?: string,
readonly paidTier?: GeminiUserTier,
readonly config?: Config,
) {}
getEffectiveSessionId(): string | undefined {
return this.config?.getSessionId() ?? this.sessionId;
}
async generateContentStream(
req: GenerateContentParameters,
userPromptId: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
role: LlmRole,
): Promise<AsyncGenerator<GenerateContentResponse>> {
const autoUse = this.config
? shouldAutoUseCredits(
this.config.getBillingSettings().overageStrategy,
getG1CreditBalance(this.paidTier),
)
: false;
const modelIsEligible = isOverageEligibleModel(req.model);
const shouldEnableCredits = modelIsEligible && autoUse;
if (shouldEnableCredits && !this.config?.getCreditsNotificationShown()) {
this.config?.setCreditsNotificationShown(true);
coreEvents.emitFeedback('info', 'Using AI Credits for this request.');
}
const enabledCreditTypes = shouldEnableCredits
? ([G1_CREDIT_TYPE] as string[])
: undefined;
const responses =
await this.requestStreamingPost<CaGenerateContentResponse>(
'streamGenerateContent',
toGenerateContentRequest(
req,
userPromptId,
this.projectId,
this.getEffectiveSessionId(),
enabledCreditTypes,
),
req.config?.abortSignal,
);
const streamingLatency: StreamingLatency = {};
const start = Date.now();
let isFirst = true;
return (async function* (
server: CodeAssistServer,
): AsyncGenerator<GenerateContentResponse> {
let totalConsumed = 0;
let lastRemaining = 0;
for await (const response of responses) {
if (isFirst) {
streamingLatency.firstMessageLatency = formatProtoJsonDuration(
Date.now() - start,
);
isFirst = false;
}
streamingLatency.totalLatency = formatProtoJsonDuration(
Date.now() - start,
);
const translatedResponse = fromGenerateContentResponse(response);
await recordConversationOffered(
server,
response.traceId,
translatedResponse,
streamingLatency,
req.config?.abortSignal,
server.getEffectiveSessionId(), // Use sessionId as trajectoryId
);
if (response.consumedCredits) {
for (const credit of response.consumedCredits) {
if (credit.creditType === G1_CREDIT_TYPE && credit.creditAmount) {
totalConsumed += parseInt(credit.creditAmount, 10) || 0;
}
}
}
if (response.remainingCredits) {
// Sum all G1 credit entries for consistency with getG1CreditBalance
lastRemaining = response.remainingCredits.reduce((sum, credit) => {
if (credit.creditType === G1_CREDIT_TYPE && credit.creditAmount) {
return sum + (parseInt(credit.creditAmount, 10) || 0);
}
return sum;
}, 0);
server.updateCredits(response.remainingCredits);
}
yield translatedResponse;
}
// Emit credits used telemetry after the stream completes
if (totalConsumed > 0 && server.config) {
logBillingEvent(
server.config,
new CreditsUsedEvent(
req.model ?? 'unknown',
totalConsumed,
lastRemaining,
),
);
}
})(this);
}
async generateContent(
req: GenerateContentParameters,
userPromptId: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
role: LlmRole,
): Promise<GenerateContentResponse> {
const start = Date.now();
const response = await this.requestPost<CaGenerateContentResponse>(
'generateContent',
toGenerateContentRequest(
req,
userPromptId,
this.projectId,
this.getEffectiveSessionId(),
undefined,
),
req.config?.abortSignal,
GENERATE_CONTENT_RETRY_DELAY_IN_MILLISECONDS,
);
const duration = formatProtoJsonDuration(Date.now() - start);
const streamingLatency: StreamingLatency = {
totalLatency: duration,
firstMessageLatency: duration,
};
const translatedResponse = fromGenerateContentResponse(response);
await recordConversationOffered(
this,
response.traceId,
translatedResponse,
streamingLatency,
req.config?.abortSignal,
this.getEffectiveSessionId(), // Use sessionId as trajectoryId
);
if (response.remainingCredits) {
this.updateCredits(response.remainingCredits);
}
return translatedResponse;
}
private updateCredits(remainingCredits: Credits[]): void {
if (!this.paidTier) {
return;
}
// Replace the G1 credits entries with the latest remaining amounts.
// Non-G1 credits are preserved as-is.
const nonG1Credits = (this.paidTier.availableCredits ?? []).filter(
(c) => c.creditType !== G1_CREDIT_TYPE,
);
const updatedG1Credits = remainingCredits.filter(
(c) => c.creditType === G1_CREDIT_TYPE,
);
this.paidTier.availableCredits = [...nonG1Credits, ...updatedG1Credits];
}
async onboardUser(
req: OnboardUserRequest,
): Promise<LongRunningOperationResponse> {
return this.requestPost<LongRunningOperationResponse>('onboardUser', req);
}
async getOperation(name: string): Promise<LongRunningOperationResponse> {
return this.requestGetOperation<LongRunningOperationResponse>(name);
}
async loadCodeAssist(
req: LoadCodeAssistRequest,
): Promise<LoadCodeAssistResponse> {
try {
return await this.requestPost<LoadCodeAssistResponse>(
'loadCodeAssist',
req,
);
} catch (e) {
if (isVpcScAffectedUser(e)) {
return {
currentTier: { id: UserTierId.STANDARD },
};
} else if (
isPermissionDeniedError(e) &&
req.cloudaicompanionProject === 'cloudshell-gca'
) {
throw new Error(
'Access to the default Cloud Shell Gemini project was denied.\n' +
'Please set your own Google Cloud project by running:\n' +
'gcloud config set project [PROJECT_ID]\n' +
'or setting export GOOGLE_CLOUD_PROJECT=...',
);
} else {
throw e;
}
}
}
async refreshAvailableCredits(): Promise<void> {
if (!this.paidTier) {
return;
}
const res = await this.loadCodeAssist({
cloudaicompanionProject: this.projectId,
metadata: {
ideType: 'IDE_UNSPECIFIED',
platform: 'PLATFORM_UNSPECIFIED',
pluginType: 'GEMINI',
duetProject: this.projectId,
},
mode: 'HEALTH_CHECK',
});
if (res.paidTier?.availableCredits) {
this.paidTier.availableCredits = res.paidTier.availableCredits;
}
}
async fetchAdminControls(
req: FetchAdminControlsRequest,
): Promise<FetchAdminControlsResponse> {
return this.requestPost<FetchAdminControlsResponse>(
'fetchAdminControls',
req,
);
}
async getCodeAssistGlobalUserSetting(): Promise<CodeAssistGlobalUserSettingResponse> {
return this.requestGet<CodeAssistGlobalUserSettingResponse>(
'getCodeAssistGlobalUserSetting',
);
}
async setCodeAssistGlobalUserSetting(
req: SetCodeAssistGlobalUserSettingRequest,
): Promise<CodeAssistGlobalUserSettingResponse> {
return this.requestPost<CodeAssistGlobalUserSettingResponse>(
'setCodeAssistGlobalUserSetting',
req,
);
}
async countTokens(req: CountTokensParameters): Promise<CountTokensResponse> {
const resp = await this.requestPost<CaCountTokenResponse>(
'countTokens',
toCountTokenRequest(req),
);
return fromCountTokenResponse(resp);
}
async embedContent(
_req: EmbedContentParameters,
): Promise<EmbedContentResponse> {
throw Error();
}
async listExperiments(
metadata: ClientMetadata,
): Promise<ListExperimentsResponse> {
if (!this.projectId) {
throw new Error('projectId is not defined for CodeAssistServer.');
}
const projectId = this.projectId;
const req: ListExperimentsRequest = {
project: projectId,
metadata: { ...metadata, duetProject: projectId },
};
return this.requestPost<ListExperimentsResponse>('listExperiments', req);
}
async retrieveUserQuota(
req: RetrieveUserQuotaRequest,
): Promise<RetrieveUserQuotaResponse> {
return this.requestPost<RetrieveUserQuotaResponse>(
'retrieveUserQuota',
req,
);
}
async recordConversationOffered(
conversationOffered: ConversationOffered,
): Promise<void> {
if (!this.projectId) {
return;
}
await this.recordCodeAssistMetrics({
project: this.projectId,
metadata: await getClientMetadata(),
metrics: [{ conversationOffered, timestamp: new Date().toISOString() }],
});
}
async recordConversationInteraction(
interaction: ConversationInteraction,
): Promise<void> {
if (!this.projectId) {
return;
}
await this.recordCodeAssistMetrics({
project: this.projectId,
metadata: await getClientMetadata(),
metrics: [
{
conversationInteraction: interaction,
timestamp: new Date().toISOString(),
},
],
});
}
async recordCodeAssistMetrics(
request: RecordCodeAssistMetricsRequest,
): Promise<void> {
return this.requestPost<void>('recordCodeAssistMetrics', request);
}
async requestPost<T>(
method: string,
req: object,
signal?: AbortSignal,
retryDelay: number = 100,
): Promise<T> {
const res = await this.client.request<T>({
url: this.getMethodUrl(method),
method: 'POST',
headers: {
'Content-Type': 'application/json',
...this.httpOptions.headers,
},
responseType: 'json',
body: JSON.stringify(req),
signal,
retryConfig: {
retryDelay,
retry: 3,
noResponseRetries: 3,
statusCodesToRetry: [
[429, 429],
[499, 499],
[500, 599],
],
},
});
return res.data;
}
private async makeGetRequest<T>(
url: string,
signal?: AbortSignal,
): Promise<T> {
const res = await this.client.request<T>({
url,
method: 'GET',
headers: {
'Content-Type': 'application/json',
...this.httpOptions.headers,
},
responseType: 'json',
signal,
});
return res.data;
}
async requestGet<T>(method: string, signal?: AbortSignal): Promise<T> {
return this.makeGetRequest<T>(this.getMethodUrl(method), signal);
}
async requestGetOperation<T>(name: string, signal?: AbortSignal): Promise<T> {
return this.makeGetRequest<T>(this.getOperationUrl(name), signal);
}
async requestStreamingPost<T>(
method: string,
req: object,
signal?: AbortSignal,
): Promise<AsyncGenerator<T>> {
const res = await this.client.request<AsyncIterable<unknown>>({
url: this.getMethodUrl(method),
method: 'POST',
params: {
alt: 'sse',
},
headers: {
'Content-Type': 'application/json',
...this.httpOptions.headers,
},
responseType: 'stream',
body: JSON.stringify(req),
signal,
retry: false,
});
return (async function* (server: CodeAssistServer): AsyncGenerator<T> {
const rl = readline.createInterface({
input: Readable.from(res.data),
crlfDelay: Infinity, // Recognizes '\r\n' and '\n' as line breaks
});
let bufferedLines: string[] = [];
for await (const line of rl) {
if (line.startsWith('data: ')) {
bufferedLines.push(line.slice(6).trim());
} else if (line === '') {
if (bufferedLines.length === 0) {
continue; // no data to yield
}
const chunk = bufferedLines.join('\n');
try {
yield JSON.parse(chunk);
} catch {
if (server.config) {
logInvalidChunk(
server.config,
// Don't include the chunk content in the log for security/privacy reasons.
new InvalidChunkEvent('Malformed JSON chunk'),
);
}
}
bufferedLines = []; // Reset the buffer after yielding
}
// Ignore other lines like comments or id fields
}
})(this);
}
private getBaseUrl(): string {
const endpoint =
process.env['CODE_ASSIST_ENDPOINT'] ?? CODE_ASSIST_ENDPOINT;
const version =
process.env['CODE_ASSIST_API_VERSION'] || CODE_ASSIST_API_VERSION;
return `${endpoint}/${version}`;
}
getMethodUrl(method: string): string {
return `${this.getBaseUrl()}:${method}`;
}
getOperationUrl(name: string): string {
return `${this.getBaseUrl()}/${name}`;
}
}
interface VpcScErrorResponse {
response?: {
data?: {
error?: {
details?: unknown[];
};
};
};
}
function isVpcScErrorResponse(error: unknown): error is VpcScErrorResponse & {
response: {
data: {
error: {
details: unknown[];
};
};
};
} {
return (
!!error &&
typeof error === 'object' &&
'response' in error &&
!!error.response &&
typeof error.response === 'object' &&
'data' in error.response &&
!!error.response.data &&
typeof error.response.data === 'object' &&
'error' in error.response.data &&
!!error.response.data.error &&
typeof error.response.data.error === 'object' &&
'details' in error.response.data.error &&
Array.isArray(error.response.data.error.details)
);
}
function isVpcScAffectedUser(error: unknown): boolean {
if (isVpcScErrorResponse(error)) {
return error.response.data.error.details.some(
(detail: unknown) =>
detail &&
typeof detail === 'object' &&
'reason' in detail &&
detail.reason === 'SECURITY_POLICY_VIOLATED',
);
}
return false;
}
function isPermissionDeniedError(error: unknown): boolean {
return (
!!error &&
typeof error === 'object' &&
'response' in error &&
!!error.response &&
typeof error.response === 'object' &&
'status' in error.response &&
error.response.status === 403
);
}
|