File size: 10,483 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 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
UserTierId,
IneligibleTierReasonCode,
type ClientMetadata,
type GeminiUserTier,
type IneligibleTier,
type LoadCodeAssistResponse,
type OnboardUserRequest,
} from './types.js';
import { CodeAssistServer, type HttpOptions } from './server.js';
import type { AuthClient } from 'google-auth-library';
import { ChangeAuthRequestedError } from '../utils/errors.js';
import { ValidationRequiredError } from '../utils/googleQuotaErrors.js';
import { debugLogger } from '../utils/debugLogger.js';
import { createCache, type CacheService } from '../utils/cache.js';
import type { Config } from '../config/config.js';
import {
logOnboardingStart,
logOnboardingSuccess,
OnboardingStartEvent,
OnboardingSuccessEvent,
} from '../telemetry/index.js';
export class ProjectIdRequiredError extends Error {
constructor() {
super(
'This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID env var. See https://goo.gle/gemini-cli-auth-docs#workspace-gca',
);
this.name = 'ProjectIdRequiredError';
}
}
export class InvalidNumericProjectIdError extends Error {
constructor(projectId: string) {
super(
`Invalid Google Cloud Project ID: "${projectId}". The GOOGLE_CLOUD_PROJECT (or GOOGLE_CLOUD_PROJECT_ID) environment variable must be set to your string-based Project ID (e.g., "my-project-123"), not your numeric Project Number. Please update your environment variables.`,
);
this.name = 'InvalidNumericProjectIdError';
}
}
/**
* Error thrown when user cancels the validation process.
* This is a non-recoverable error that should result in auth failure.
*/
export class ValidationCancelledError extends Error {
constructor() {
super('User cancelled account validation');
this.name = 'ValidationCancelledError';
}
}
export class IneligibleTierError extends Error {
readonly ineligibleTiers: IneligibleTier[];
constructor(ineligibleTiers: IneligibleTier[]) {
const reasons = ineligibleTiers.map((t) => t.reasonMessage).join(', ');
super(reasons);
this.name = 'IneligibleTierError';
this.ineligibleTiers = ineligibleTiers;
}
}
export interface UserData {
projectId: string;
userTier: UserTierId;
userTierName?: string;
paidTier?: GeminiUserTier;
hasOnboardedPreviously?: boolean;
}
// Cache to store the results of setupUser to avoid redundant network calls.
// The cache is keyed by the AuthClient instance. Inside each entry, we use
// another cache keyed by project ID to ensure correctness if environment changes.
let userDataCache = createCache<
AuthClient,
CacheService<string | undefined, Promise<UserData>>
>({
storage: 'weakmap',
});
/**
* Resets the user data cache. Used exclusively for test isolation.
* @internal
*/
export function resetUserDataCacheForTesting() {
userDataCache = createCache<
AuthClient,
CacheService<string | undefined, Promise<UserData>>
>({
storage: 'weakmap',
});
}
/**
* Sets up the user by loading their Code Assist configuration and onboarding if needed.
*
* Tier eligibility:
* - FREE tier: Eligibility is determined by the Code Assist server response.
* - STANDARD tier: User is always eligible if they have a valid project ID.
*
* If no valid project ID is available (from env var or server response):
* - Surfaces ineligibility reasons for the FREE tier from the server.
* - Throws ProjectIdRequiredError if no ineligibility reasons are available.
*
* Handles VALIDATION_REQUIRED via the optional validation handler, allowing
* retry, auth change, or cancellation.
*
* @param client - The authenticated client to use for API calls
* @param config - The CLI configuration
* @param httpOptions - Optional HTTP options
* @returns The user's project ID, tier ID, and tier name
* @throws {ValidationRequiredError} If account validation is required
* @throws {ProjectIdRequiredError} If no project ID is available and required
* @throws {ValidationCancelledError} If user cancels validation
* @throws {ChangeAuthRequestedError} If user requests to change auth method
*/
export async function setupUser(
client: AuthClient,
config: Config,
httpOptions: HttpOptions = {},
): Promise<UserData> {
const projectId =
process.env['GOOGLE_CLOUD_PROJECT'] ||
process.env['GOOGLE_CLOUD_PROJECT_ID'] ||
undefined;
if (projectId && /^\d+$/.test(projectId)) {
throw new InvalidNumericProjectIdError(projectId);
}
const projectCache = userDataCache.getOrCreate(client, () =>
createCache<string | undefined, Promise<UserData>>({
storage: 'map',
defaultTtl: 30000, // 30 seconds
}),
);
return projectCache.getOrCreate(projectId, () =>
_doSetupUser(client, projectId, config, httpOptions),
);
}
/**
* Internal implementation of the user setup logic.
*/
async function _doSetupUser(
client: AuthClient,
projectId: string | undefined,
config: Config,
httpOptions: HttpOptions = {},
): Promise<UserData> {
const caServer = new CodeAssistServer(
client,
projectId,
httpOptions,
'',
undefined,
undefined,
);
const coreClientMetadata: ClientMetadata = {
ideType: 'IDE_UNSPECIFIED',
platform: 'PLATFORM_UNSPECIFIED',
pluginType: 'GEMINI',
};
const validationHandler = config.getValidationHandler();
let loadRes: LoadCodeAssistResponse;
while (true) {
loadRes = await caServer.loadCodeAssist({
cloudaicompanionProject: projectId,
metadata: {
...coreClientMetadata,
duetProject: projectId,
},
});
try {
validateLoadCodeAssistResponse(loadRes);
break;
} catch (e) {
if (e instanceof ValidationRequiredError && validationHandler) {
const intent = await validationHandler(
e.validationLink,
e.validationDescription,
);
if (intent === 'verify') {
continue;
}
if (intent === 'change_auth') {
throw new ChangeAuthRequestedError();
}
throw new ValidationCancelledError();
}
throw e;
}
}
if (loadRes.currentTier) {
if (!loadRes.paidTier?.id && !loadRes.currentTier.id) {
debugLogger.warn(
'Warning: Code Assist API did not return a user tier ID. Defaulting to STANDARD tier.',
);
}
if (!loadRes.cloudaicompanionProject) {
if (projectId) {
return {
projectId,
userTier:
loadRes.paidTier?.id ??
loadRes.currentTier.id ??
UserTierId.STANDARD,
userTierName: loadRes.paidTier?.name ?? loadRes.currentTier.name,
paidTier: loadRes.paidTier ?? undefined,
hasOnboardedPreviously:
loadRes.currentTier.hasOnboardedPreviously ?? true,
};
}
// If user is not setup for standard tier, inform them about all other tiers they are ineligible for.
throwIneligibleOrProjectIdError(loadRes);
}
return {
projectId: loadRes.cloudaicompanionProject,
userTier:
loadRes.paidTier?.id ?? loadRes.currentTier.id ?? UserTierId.STANDARD,
userTierName: loadRes.paidTier?.name ?? loadRes.currentTier.name,
paidTier: loadRes.paidTier ?? undefined,
hasOnboardedPreviously:
loadRes.currentTier.hasOnboardedPreviously ?? true,
};
}
const tier = getOnboardTier(loadRes);
if (!tier.id) {
debugLogger.warn(
'Warning: Code Assist API did not return an onboarding tier ID. Defaulting to STANDARD tier.',
);
}
let onboardReq: OnboardUserRequest;
if (tier.id === UserTierId.FREE) {
// The free tier uses a managed google cloud project. Setting a project in the `onboardUser` request causes a `Precondition Failed` error.
onboardReq = {
tierId: tier.id,
cloudaicompanionProject: undefined,
metadata: coreClientMetadata,
};
} else {
onboardReq = {
tierId: tier.id,
cloudaicompanionProject: projectId,
metadata: {
...coreClientMetadata,
duetProject: projectId,
},
};
}
logOnboardingStart(config, new OnboardingStartEvent());
const onboardingStartTime = Date.now();
let lroRes = await caServer.onboardUser(onboardReq);
if (!lroRes.done && lroRes.name) {
const operationName = lroRes.name;
while (!lroRes.done) {
await new Promise((f) => setTimeout(f, 5000));
lroRes = await caServer.getOperation(operationName);
}
}
logOnboardingSuccess(
config,
new OnboardingSuccessEvent(tier.name, Date.now() - onboardingStartTime),
);
if (!lroRes.response?.cloudaicompanionProject?.id) {
if (projectId) {
return {
projectId,
userTier: tier.id ?? UserTierId.STANDARD,
userTierName: tier.name,
hasOnboardedPreviously: tier.hasOnboardedPreviously ?? false,
};
}
throwIneligibleOrProjectIdError(loadRes);
}
return {
projectId: lroRes.response.cloudaicompanionProject.id,
userTier: tier.id ?? UserTierId.STANDARD,
userTierName: tier.name,
hasOnboardedPreviously: tier.hasOnboardedPreviously ?? false,
};
}
function throwIneligibleOrProjectIdError(res: LoadCodeAssistResponse): never {
if (res.ineligibleTiers && res.ineligibleTiers.length > 0) {
throw new IneligibleTierError(res.ineligibleTiers);
}
throw new ProjectIdRequiredError();
}
function getOnboardTier(res: LoadCodeAssistResponse): GeminiUserTier {
for (const tier of res.allowedTiers || []) {
if (tier.isDefault) {
return tier;
}
}
return {
name: '',
description: '',
id: UserTierId.LEGACY,
userDefinedCloudaicompanionProject: true,
};
}
function validateLoadCodeAssistResponse(res: LoadCodeAssistResponse): void {
if (!res) {
throw new Error('LoadCodeAssist returned empty response');
}
if (
!res.currentTier &&
res.ineligibleTiers &&
res.ineligibleTiers.length > 0
) {
const validationTier = res.ineligibleTiers.find(
(t) =>
t.validationUrl &&
t.reasonCode === IneligibleTierReasonCode.VALIDATION_REQUIRED,
);
const validationUrl = validationTier?.validationUrl;
if (validationTier && validationUrl) {
throw new ValidationRequiredError(
`Account validation required: ${validationTier.reasonMessage}`,
undefined,
validationUrl,
validationTier.reasonMessage,
);
}
}
}
|