(accessToken: string)
| 638 | } |
| 639 | |
| 640 | async function ensureProjectContext(accessToken: string): Promise<string> { |
| 641 | if (!accessToken) { |
| 642 | throw new Error("Missing Google OAuth access token") |
| 643 | } |
| 644 | const configuredProjectId = |
| 645 | Env.get("GOOGLE_CLOUD_PROJECT") ?? Env.get("GCP_PROJECT") ?? Env.get("GCLOUD_PROJECT") |
| 646 | const cacheKey = configuredProjectId?.trim() || "default" |
| 647 | const cached = projectContextCache.get(cacheKey) |
| 648 | if (cached) return cached |
| 649 | const pending = projectContextPending.get(cacheKey) |
| 650 | if (pending) return pending |
| 651 | |
| 652 | const promise = (async () => { |
| 653 | const projectId = configuredProjectId?.trim() || undefined |
| 654 | if (projectId) { |
| 655 | projectContextCache.set(cacheKey, projectId) |
| 656 | return projectId |
| 657 | } |
| 658 | |
| 659 | const loadPayload = await loadManagedProject(accessToken, projectId) |
| 660 | if (loadPayload?.cloudaicompanionProject) { |
| 661 | const managedProjectId = loadPayload.cloudaicompanionProject |
| 662 | projectContextCache.set(cacheKey, managedProjectId) |
| 663 | return managedProjectId |
| 664 | } |
| 665 | |
| 666 | if (!loadPayload) { |
| 667 | throw new Error( |
| 668 | "Gemini requires a Google Cloud project. Enable the Gemini for Google Cloud API on a project you control.", |
| 669 | ) |
| 670 | } |
| 671 | |
| 672 | const currentTierId = loadPayload?.currentTier?.id ?? undefined |
| 673 | if (currentTierId && currentTierId !== "FREE") { |
| 674 | throw new Error( |
| 675 | "Gemini requires a Google Cloud project for non-free tiers. Set GOOGLE_CLOUD_PROJECT.", |
| 676 | ) |
| 677 | } |
| 678 | |
| 679 | const allowedTiers = Array.isArray(loadPayload?.allowedTiers) ? loadPayload.allowedTiers : [] |
| 680 | let defaultTierId: string | undefined |
| 681 | for (const tier of allowedTiers) { |
| 682 | if (tier?.isDefault) { |
| 683 | defaultTierId = tier.id |
| 684 | break |
| 685 | } |
| 686 | } |
| 687 | const tierId = defaultTierId ?? allowedTiers[0]?.id ?? "FREE" |
| 688 | |
| 689 | if (tierId !== "FREE") { |
| 690 | throw new Error( |
| 691 | "Gemini requires a Google Cloud project for non-free tiers. Set GOOGLE_CLOUD_PROJECT.", |
| 692 | ) |
| 693 | } |
| 694 | |
| 695 | const managedProjectId = await onboardManagedProject(accessToken, tierId, projectId) |
| 696 | if (!managedProjectId) { |
| 697 | throw new Error("Failed to resolve a managed Gemini project.") |
no test coverage detected