### Example Usage of startGeminiDebugRequest Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/DebugUtilities.md Provides an example of how to start a debug request context, capturing details of a Gemini API content generation request, including the original and resolved URLs, method, headers, and body. ```typescript const debugContext = startGeminiDebugRequest({ originalUrl: "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent", resolvedUrl: "https://cloudcode-pa.googleapis.com/v1internal:generateContent", method: "POST", headers: { "Authorization": "Bearer ...", "Content-Type": "application/json" }, body: JSON.stringify({ contents: [...] }), streaming: false, projectId: "my-project" }); ``` -------------------------------- ### Install Gemini Auth Plugin Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/configuration.md Install the opencode-gemini-auth plugin from the npm registry. For local development, use a file path. ```json { "plugin": ["opencode-gemini-auth@latest"] } ``` -------------------------------- ### fetchWithRetry Example Usage Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/Retry.md Demonstrates how to use `fetchWithRetry` for making POST requests. It includes basic error handling for the response. ```typescript const response = await fetchWithRetry( "https://cloudcode-pa.googleapis.com/v1internal:generateContent", { method: "POST", headers: { "Authorization": "Bearer token" }, body: JSON.stringify({ ... }) } ); if (response.ok) { // Succeeded (either first attempt or after retry) } else { // Failed after all retries } ``` -------------------------------- ### Opencode Configuration for GeminiCLIOAuthPlugin Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/GeminiCLIOAuthPlugin.md Example Opencode configuration to load the GeminiCLIOAuthPlugin. This snippet shows how to include the plugin in your Opencode configuration file and set a project ID. ```json { "plugin": ["opencode-gemini-auth@latest"], "provider": { "google": { "options": { "projectId": "my-google-cloud-project" } } } } ``` -------------------------------- ### Clone Gemini CLI for Local Mirror Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/README.md Clone the official Gemini CLI repository to a local directory for parity checks. This is an optional setup step. ```bash git clone https://github.com/google-gemini/gemini-cli.git .local/gemini-cli ``` -------------------------------- ### Install Gemini Auth Plugin for Opencode Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/README.md Add the opencode-gemini-auth plugin to your Opencode configuration file to enable authentication with your Google account. ```json { "$schema": "https://opencode.ai/config.json", "plugin": ["opencode-gemini-auth@latest"] } ``` -------------------------------- ### Set Proxy for Google API Calls Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/README.md Configure the HTTP proxy for Google API calls by setting the OPENCODE_GEMINI_AUTH_PROXY environment variable before starting Opencode. ```bash OPENCODE_GEMINI_AUTH_PROXY=http://127.0.0.1:8080 opencode ``` -------------------------------- ### Clone Opencode Gemini Auth Plugin Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/README.md Clone the Opencode Gemini Auth plugin repository and install its dependencies locally. This is the first step for local development. ```bash git clone https://github.com/jenslys/opencode-gemini-auth.git cd opencode-gemini-auth bun install ``` -------------------------------- ### Example Debug Log Messages Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/DebugUtilities.md Illustrates the format of debug messages, including timestamp, log level, source component, and message content. ```text 2026-06-18T12:00:00.123Z [DEBUG] OAuth: OAuth authorize: https://accounts.google.com/o/oauth2/v2/auth?... 2026-06-18T12:00:05.456Z [DEBUG] OAuth: OAuth exchange: POST https://oauth2.googleapis.com/token 2026-06-18T12:00:06.789Z [DEBUG] OAuth: OAuth exchange response: 200 OK 2026-06-18T12:00:07.012Z [DEBUG] Request: Request transformation: model=gemini-2.5-pro action=generateContent ``` -------------------------------- ### Configure Thinking Config for Different Model Types Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/README.md Example showing how to configure 'thinkingConfig' for both Gemini 3 models (using 'thinkingLevel') and Gemini 2.5 models (using 'thinkingBudget'). ```json { "provider": { "google": { "models": { "gemini-3-pro-preview": { "options": { "thinkingConfig": { "thinkingLevel": "high", "includeThoughts": true } } }, "gemini-2.5-flash": { "options": { "thinkingConfig": { "thinkingBudget": 8192, "includeThoughts": true } } } } } } } ``` -------------------------------- ### Set Opencode Proxy Configuration Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/configuration.md Set the OPENCODE_GEMINI_AUTH_PROXY environment variable before starting Opencode to route traffic through an HTTP proxy. This is useful for corporate networks, VPC-SC environments, or when network security requires it. ```bash # Set before starting Opencode OPENCODE_GEMINI_AUTH_PROXY=http://proxy-server:8080 opencode ``` -------------------------------- ### Example Usage of logGeminiDebugMessage Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/DebugUtilities.md Shows how to log specific debug messages, including URLs and model IDs, using the `logGeminiDebugMessage` function. ```typescript logGeminiDebugMessage(`OAuth refresh attempt 1: POST ${tokenUrl}`); logGeminiDebugMessage(`Code Assist models visible: ${modelIds.join(", ")}`); ``` -------------------------------- ### Enable Opencode Debug Logging Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/configuration.md Enable debug mode by setting the OPENCODE_GEMINI_DEBUG environment variable to 1 before starting Opencode. This generates detailed log files for troubleshooting the OAuth flow, project loading, and API requests. ```bash OPENCODE_GEMINI_DEBUG=1 opencode ``` -------------------------------- ### onboardManagedProject() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Onboards a new managed project. ```APIDOC ## onboardManagedProject() ### Description Onboards a new managed project. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified) ``` -------------------------------- ### Example Usage of isGeminiDebugEnabled and logGeminiDebugMessage Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/DebugUtilities.md Demonstrates how to use `isGeminiDebugEnabled` to conditionally log a debug message using `logGeminiDebugMessage`. ```typescript if (isGeminiDebugEnabled()) { logGeminiDebugMessage("Token refresh initiated"); } ``` -------------------------------- ### Login to Opencode Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/README.md Run this command in your terminal to initiate the Opencode authentication process. ```bash opencode auth login ``` -------------------------------- ### createGeminiQuotaTool() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Creates a tool for managing Gemini API quotas. ```APIDOC ## createGeminiQuotaTool() ### Description Creates a tool for managing Gemini API quotas. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified, likely a quota tool object) ``` -------------------------------- ### prepareGeminiRequest() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/RequestHandling.md Rewrites OpenAI-style requests into the Gemini Code Assist request shape, handling URL transformation, authorization, and request body normalization. ```APIDOC ## prepareGeminiRequest() ### Description Rewrites OpenAI-style requests into Gemini Code Assist request shape. ### Function Signature ```typescript export function prepareGeminiRequest( input: RequestInfo, init: RequestInit | undefined, accessToken: string, projectId: string, thinkingConfigDefaults?: ThinkingConfigDefaults ): { request: RequestInfo; init: RequestInit; streaming: boolean; requestedModel?: string; } ``` ### Parameters #### Path Parameters - `input` (RequestInfo) - Required - Request URL or Request object - `init` (RequestInit) - Optional - Request options (headers, body, method) - `accessToken` (string) - Required - OAuth access token - `projectId` (string) - Required - Google Cloud project ID - `thinkingConfigDefaults` (ThinkingConfigDefaults) - Optional - Default thinking configs per model ### Return Type ```typescript { request: RequestInfo; // Transformed URL init: RequestInit; // Updated headers and body streaming: boolean; // Is response streaming (SSE)? requestedModel?: string; // Original model requested } ``` ### Behavior 1. **URL Detection** — Checks if request is for `generativelanguage.googleapis.com` 2. **Authorization Header** — Sets `Authorization: Bearer {accessToken}`, removes API key headers 3. **URL Transformation** — Converts to Code Assist endpoint: - `https://cloudcode-pa.googleapis.com/v1internal:{action}` - Appends `?alt=sse` for streaming 4. **Body Transformation** — For JSON bodies: - Parses request payload - Normalizes OpenAI tool call format - Adds thought signatures to function calls - Normalizes thinking config (moves from root to `generationConfig`) - Normalizes system instructions - Normalizes cached content references - Strips thought parts from history - Wraps in project/model envelope 5. **Headers** — Sets: - `User-Agent` — Gemini CLI user agent with model name - `x-activity-request-id` — Unique request ID for tracing - `Accept: text/event-stream` — For streaming requests ### Example ```typescript const prepared = prepareGeminiRequest( "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ contents: [{ role: "user", parts: [{ text: "Hello" }] }], generationConfig: { maxOutputTokens: 1000 } }) }, "access_token_xyz", "my-project" ); // prepared.request = "https://cloudcode-pa.googleapis.com/v1internal:generateContent" // prepared.streaming = false // prepared.init.headers includes Authorization and User-Agent ``` ### Source Location `src/plugin/request/prepare.ts:21-100` ``` -------------------------------- ### Clear Opencode Plugin Cache Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/README.md Clear the cached plugin from Opencode's node_modules directory to ensure a fresh installation. This is necessary when updating the plugin. ```bash # Clear the specific plugin cache rm -rf ~/.cache/opencode/node_modules/opencode-gemini-auth # Run Opencode to trigger a fresh install opencode ``` -------------------------------- ### GeminiCLIOAuthPlugin Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/README.md Main plugin entry point. Registers auth methods, tools, and fetch interceptor. ```APIDOC ## GeminiCLIOAuthPlugin ### Description Main plugin entry point. Registers auth methods, tools, and fetch interceptor. ### Entry `export const GeminiCLIOAuthPlugin = async ({ client }: PluginContext)` ``` -------------------------------- ### Configure Google Provider Top-Level Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/configuration.md Set up the Google provider with a project ID and define model whitelists and blacklists. This configuration also allows for specific model options, such as thinking configurations. ```json { "provider": { "google": { "options": { "projectId": "my-google-cloud-project" }, "whitelist": ["model-id-1", "model-id-2"], "blacklist": ["model-id-3"], "models": { "gemini-2.5-pro": { "options": { "thinkingConfig": { "thinkingBudget": 8192, "includeThoughts": true } } } } } } } ``` -------------------------------- ### Configure Opencode for Local Plugin Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/README.md Update your Opencode configuration to use a local version of the plugin by providing a file:// URL. Replace with the absolute path to your local plugin directory. ```json { "plugin": ["file:///absolute/path/to/opencode-gemini-auth"] } ``` -------------------------------- ### Retrieve User Quota Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/Quota.md Call this function to get quota information for the authenticated user and project. It returns null on error. Ensure you have a valid OAuth access token and project ID. ```typescript export async function retrieveUserQuota( accessToken: string, projectId: string, userAgentModel?: string ): Promise ``` ```typescript interface RetrieveUserQuotaResponse { buckets?: RetrieveUserQuotaBucket[]; } interface RetrieveUserQuotaBucket { remainingAmount?: string; // Remaining count (string number) remainingFraction?: number; // Remaining as 0.0-1.0 resetTime?: string; // ISO 8601 reset timestamp tokenType?: string; // "REQUESTS" or "TOKENS" modelId?: string; // Model identifier (may end in _vertex) } ``` ```typescript const quota = await retrieveUserQuota(accessToken, "my-project"); if (quota?.buckets) { for (const bucket of quota.buckets) { console.log(`${bucket.modelId}: ${bucket.remainingFraction * 100}%`); } } ``` -------------------------------- ### authorizeGemini() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/OAuth.md Builds the Gemini OAuth authorization URL including PKCE challenge. This function generates a PKCE pair, constructs the authorization URL with specified client ID, scopes, and redirect URI, and includes CSRF protection. ```APIDOC ## authorizeGemini() ### Description Builds the Gemini OAuth authorization URL including PKCE challenge. ### Function Signature ```typescript export async function authorizeGemini(): Promise ``` ### Parameters None. ### Return Type ```typescript interface GeminiAuthorization { url: string; // Full OAuth authorization URL ready for browser verifier: string; // PKCE verifier for token exchange state: string; // CSRF protection state parameter } ``` ### Behavior - Generates a PKCE pair (challenge and verifier) using S256 method - Creates a random 32-byte hex state value for CSRF protection - Constructs authorization URL with: - Client ID: `681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com` - Scopes: cloud-platform, userinfo.email, userinfo.profile - Redirect URI: `http://localhost:8085/oauth2callback` - Access type: offline (for refresh token) - Prompt: consent (to force user consent) ### Example ```typescript const auth = await authorizeGemini(); console.log(auth.url); // User pastes into browser // After Google redirects with code and state, exchange with: const result = await exchangeGeminiWithVerifier(code, auth.verifier); ``` ``` -------------------------------- ### startGeminiDebugRequest() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/DebugUtilities.md Initiates a debug context for an outgoing Gemini API request. This function captures essential request details for logging and troubleshooting, returning a context object or null if debugging is not active. ```APIDOC ## startGeminiDebugRequest(options: { originalUrl: string; resolvedUrl: string; method: string; headers: Record | Headers; body?: string; streaming: boolean; projectId?: string; }): GeminiDebugContext | null ### Description Starts a debug context for a specific Gemini API request. This function captures details about the request, such as URLs, method, headers, and body, to facilitate debugging. It returns a `GeminiDebugContext` object if debugging is enabled, otherwise `null`. ### Function Signature ```typescript export function startGeminiDebugRequest(options: { originalUrl: string; resolvedUrl: string; method: string; headers: Record | Headers; body?: string; streaming: boolean; projectId?: string; }): GeminiDebugContext | null ``` ### Parameters #### Parameters - **originalUrl** (string) - Required - The original request URL. - **resolvedUrl** (string) - Required - The transformed URL after any internal routing or resolution. - **method** (string) - Required - The HTTP method used for the request (e.g., GET, POST). - **headers** (Headers or object) - Required - The request headers. - **body** (string) - Optional - The request body, if any. - **streaming** (boolean) - Required - Indicates whether the response is expected to be streamed. - **projectId** (string) - Optional - The Google Cloud project ID associated with the request. ### Return Type `GeminiDebugContext | null` — Returns a `GeminiDebugContext` object containing request details if debug mode is enabled. Returns `null` if debug mode is not enabled, ensuring no overhead when debugging is off. ### Behavior - Returns `null` if debug is not enabled, preventing any overhead. - Creates a context object that can be used for subsequent logging related to this request. - Sanitizes and truncates the request body for privacy and to manage log size. ### Example ```typescript const debugContext = startGeminiDebugRequest({ originalUrl: "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent", resolvedUrl: "https://cloudcode-pa.googleapis.com/v1internal:generateContent", method: "POST", headers: { "Authorization": "Bearer ...", "Content-Type": "application/json" }, body: JSON.stringify({ contents: [...] }), streaming: false, projectId: "my-project" }); ``` ``` -------------------------------- ### Start Gemini Debug Request Context Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/DebugUtilities.md Initiates a debug context for an outgoing API request if debugging is enabled. It captures request details like URL, method, headers, and body, returning a context object or null if debugging is off. ```typescript export function startGeminiDebugRequest(options: { originalUrl: string; resolvedUrl: string; method: string; headers: Record | Headers; body?: string; streaming: boolean; projectId?: string; }): GeminiDebugContext | null ``` -------------------------------- ### onboardManagedProject Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/ProjectManagement.md Onboards a managed project for the user, optionally retrying until completion. It handles the initial request and subsequent polling for operation status. ```APIDOC ## onboardManagedProject() ### Description Onboards a managed project for the user, optionally retrying until completion. ### Function Signature ```typescript export async function onboardManagedProject( accessToken: string, tierId: string, projectId?: string, userAgentModel?: string, attempts?: number, delayMs?: number ): Promise ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None #### Function Parameters - **accessToken** (string) - Required - OAuth access token - **tierId** (string) - Required - Tier to onboard (e.g., "free-tier") - **projectId** (string) - Optional - Google Cloud project for non-free tiers - **userAgentModel** (string) - Optional - Model for User-Agent - **attempts** (number) - Optional - Max polling attempts (Default: 10) - **delayMs** (number) - Optional - Delay between polling (ms) (Default: 5000) ### Return Type `string | undefined` — Onboarded project ID, or undefined if failed/timeout ### Behavior 1. **Initial Request** — POST `:onboardUser` with tier and project 2. **Poll for completion** — If operation not done: - Wait `delayMs` milliseconds - GET operation status by name - Repeat until done or attempts exhausted 3. **Return project** — Returns `response.cloudaicompanionProject.id` if done ### API Endpoint - Initial: `POST https://cloudcode-pa.googleapis.com/v1internal:onboardUser` - Poll: `GET https://cloudcode-pa.googleapis.com/v1internal/{operation.name}` ### Errors - Throws `ProjectIdRequiredError` if non-free tier with no project - Returns `undefined` on HTTP errors or timeout ### Example ```typescript const projectId = await onboardManagedProject( accessToken, "free-tier", undefined, // no project needed for free tier "gemini-2.5-pro" ); if (projectId) { console.log("Onboarded:", projectId); } ``` ``` -------------------------------- ### createGeminiQuotaTool Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/Quota.md Creates an Opencode plugin tool for querying Gemini Code Assist quota. This tool, when executed, performs authentication checks, token refreshes, project resolution, and fetches quota information, presenting it in a human-readable format. ```APIDOC ## createGeminiQuotaTool() ### Description Creates an Opencode plugin tool for querying Gemini Code Assist quota. The tool executes without arguments and handles authentication, token refresh, project resolution, and quota retrieval, formatting the output for readability. ### Method Signature ```typescript export function createGeminiQuotaTool( dependencies: { client: PluginClient; getAuthResolver: () => GetAuth | undefined; getConfiguredProjectId: () => string | undefined; getUserAgentModel: () => string | undefined; } ): ToolDefinition ``` ### Parameters #### Dependencies - **client** (`PluginClient`) - Plugin client for auth. - **getAuthResolver** (`() => GetAuth | undefined`) - Function returning current auth resolver. - **getConfiguredProjectId** (`() => string | undefined`) - Function returning configured project ID. - **getUserAgentModel** (`() => string | undefined`) - Function returning current request model. ### Return Type `ToolDefinition` — Tool registered as `gemini_quota` ### Tool Behavior 1. **Auth Validation**: Checks if auth is initialized and OAuth. 2. **Token Refresh**: Refreshes access token if expired. 3. **Project Resolution**: Resolves Google Cloud project ID. 4. **Quota Retrieval**: Fetches quota buckets via `retrieveUserQuota()`. 5. **Formatting**: Formats output as human-readable table with model variants, remaining quota, reset time, and token type. ### Tool Output Example ``` Gemini quota usage for project `my-project` ↳ Variant Remaining Reset Gemini 3.0 (1 model, 2 buckets) base model ▓▓▓▓▓▓░░░░░░░░░░░░░░░░░░ 60.0% (1.2K left) resets in 1h ↳ vertex ▓▓▓▓▓▓▓▓░░░░░░░░░░░░░░░░ 80.0% (1.6K left) resets in 1h ``` ### Error Handling Returns descriptive messages on errors such as: - "Google auth not initialized" - "OAuth required" - "Token refresh failed" - "Project ID not resolved" - "No quota buckets available" - "Quota lookup failed: {error}" ### Example Usage ```typescript // Tool is invoked via CLI command: /gquota // Internally: const tool = createGeminiQuotaTool({ client, getAuthResolver: () => currentGetAuth, getConfiguredProjectId: () => latestProjectId, getUserAgentModel: () => latestModel }); const result = await tool.execute(); console.log(result); ``` ``` -------------------------------- ### GeminiCLIOAuthPlugin Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Main plugin entry point for authentication. Allows registration of providers, auth methods, and fetch interceptors. Also details environment variables and configuration. ```APIDOC ## GeminiCLIOAuthPlugin() ### Description Initializes the GeminiCLIOAuthPlugin, allowing for the registration of authentication providers, methods, and fetch interceptors. ### Signature `GeminiCLIOAuthPlugin()` ### Configuration - Environment variables - Configuration settings ``` -------------------------------- ### Build Gemini OAuth Authorization URL with PKCE Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/OAuth.md Generates the full OAuth authorization URL and PKCE verifier. Use this URL to initiate the user's login flow with Google. The verifier is essential for the subsequent token exchange. ```typescript const auth = await authorizeGemini(); console.log(auth.url); // User pastes into browser // After Google redirects with code and state, exchange with: const result = await exchangeGeminiWithVerifier(code, auth.verifier); ``` -------------------------------- ### Environment Variable for Project ID Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/errors.md Illustrates setting the Google Cloud project ID using an environment variable for Opencode. ```bash OPENCODE_GEMINI_PROJECT_ID=your-project-id opencode ``` -------------------------------- ### prepareGeminiRequest() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Transforms an outgoing request to be compatible with the Gemini API. ```APIDOC ## prepareGeminiRequest() ### Description Transforms an outgoing request to be compatible with the Gemini API. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified, likely a transformed request object) ``` -------------------------------- ### Provider Interface Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/types.md Provider configuration from Opencode, includes model costs and options. ```typescript interface Provider { models?: Record; options?: Record; } ``` -------------------------------- ### Configure Model Options and Cost Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/configuration.md Define or override metadata and options for specific models, including thinking configurations and cost parameters for input, output, and cache. ```json { "models": { "gemini-2.5-pro": { "options": { "thinkingConfig": { "thinkingBudget": 8192, "includeThoughts": true } }, "cost": { "input": 0.00075, "output": 0.003, "cache": { "read": 0.0001875, "write": 0.00075 } } } } } ``` -------------------------------- ### Onboard Managed Project Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/ProjectManagement.md Onboards a managed project for the user. Optionally retries until completion. Use this function when you need to provision a new project for a user, especially for free tiers where a specific project ID is not required. ```typescript export async function onboardManagedProject( accessToken: string, tierId: string, projectId?: string, userAgentModel?: string, attempts?: number, delayMs?: number ): Promise ``` ```typescript const projectId = await onboardManagedProject( accessToken, "free-tier", undefined, // no project needed for free tier "gemini-2.5-pro" ); if (projectId) { console.log("Onboarded:", projectId); } ``` -------------------------------- ### Create OAuth Authorize Method Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/OAuthAuthorization.md Initializes the OAuth authorization callback handler. It can optionally accept functions to retrieve the configured project ID and user agent model. ```typescript export function createOAuthAuthorizeMethod(options?: { getConfiguredProjectId?: () => Promise | string | undefined; getUserAgentModel?: () => Promise | string | undefined; }): () => Promise<{ url: string; instructions: string; method: string; callback: (() => Promise) | ((callbackUrl: string) => Promise); }> ``` -------------------------------- ### Create Gemini Quota Tool Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/Quota.md Creates a plugin tool for querying Gemini Code Assist quota. This tool handles authentication, project resolution, and quota retrieval, formatting the output into a human-readable table. ```typescript export function createGeminiQuotaTool( dependencies: { client: PluginClient; getAuthResolver: () => GetAuth | undefined; getConfiguredProjectId: () => string | undefined; getUserAgentModel: () => string | undefined; } ): ToolDefinition ``` ```typescript // Tool is invoked via CLI command: /gquota // Internally: const tool = createGeminiQuotaTool({ client, getAuthResolver: () => currentGetAuth, getConfiguredProjectId: () => latestProjectId, getUserAgentModel: () => latestModel }); const result = await tool.execute(); console.log(result); ``` -------------------------------- ### Query Gemini Quota Buckets Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/README.md The plugin queries quota buckets using the `/gquota` command. The output displays remaining quota, reset times, and token types for different model variants. ```bash Gemini quota usage for project `my-project` ↳ Variant Remaining Reset Gemini 3.0 (1 model, 2 buckets) base model ▓▓▓▓▓░░░░░░░░░░░░░░░░░░ 75.0% (1.5K left) resets in 2h ↳ vertex ▓▓▓▓░░░░░░░░░░░░░░░░░░░░░ 50.0% (1.0K left) resets in 2h ``` -------------------------------- ### Browser-Based OAuth Authorization Flow Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/OAuthAuthorization.md Demonstrates the interactive OAuth authorization flow. It sets up the authorize method, displays instructions, and handles both automatic callback detection and manual URL/code pasting. ```typescript const authorizeMethod = createOAuthAuthorizeMethod({ getConfiguredProjectId: async () => { const config = await client.config.get(); return config.data?.provider?.google?.options?.projectId; } }); const auth = await authorizeMethod(); console.log(auth.instructions); // "Complete the sign-in flow in your browser. We'll automatically detect the redirect back to localhost." if (auth.method === "auto") { const result = await auth.callback(); // Listener captured callback, browser closed } else { // Manual fallback: user pastes URL console.log(auth.url); const result = await auth.callback( "http://localhost:8085/oauth2callback?code=xyz&state=abc" ); } ``` -------------------------------- ### Configure Google Cloud Project Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/README.md Provide your Google Cloud project ID in this JSON configuration to set up the Gemini OAuth plugin. This is required for the plugin to interact with Google Cloud services. ```json { "provider": { "google": { "options": { "projectId": "your-google-cloud-project" } } } } ``` -------------------------------- ### ProviderModel Interface Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/types.md Model pricing and options, including input, output, and cache costs. ```typescript interface ProviderModel { cost?: { input: number; // Input token cost output: number; // Output token cost cache?: { read: number; // Cached content read cost write: number; // Cached content write cost }; }; [key: string]: unknown; } ``` -------------------------------- ### formatGeminiQuotaOutput Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/Quota.md Formats quota buckets into human-readable text with progress bars and timing. It sorts and groups buckets for a clear display. ```APIDOC ## formatGeminiQuotaOutput() ### Description Formats quota buckets into human-readable text with progress bars and timing. ### Function Signature ```typescript export function formatGeminiQuotaOutput( projectId: string, buckets: RetrieveUserQuotaBucket[] ): string ``` ### Parameters - `projectId` (string): Project ID (for header) - `buckets` (RetrieveUserQuotaBucket[]): Quota buckets from API ### Return Type `string` — Multi-line formatted quota display ### Features 1. **Sorting** — Buckets sorted by model ID, token type, reset time 2. **Grouping** — Models grouped by base model and variant 3. **Versioning** — Groups sorted by Gemini version (descending) 4. **Progress Bar** — 20-character bar showing fraction used (▓ filled, ░ empty) 5. **Percentage** — Fraction as percentage (clamped 0-100) 6. **Remaining Count** — Locale-formatted integer if available 7. **Reset Timing** — Relative time (e.g., "resets in 2h 30m") 8. **Token Type** — Column shown only if not uniform "REQUESTS" ### Example ```typescript const output = formatGeminiQuotaOutput("my-project", buckets); console.log(output); // Output shown in quota section above ``` ``` -------------------------------- ### Headless Environment OAuth Authorization Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/OAuthAuthorization.md Illustrates the OAuth authorization process in a headless or SSH environment where a browser cannot be opened. The user is prompted to manually paste the authorization URL or code. ```typescript // In SSH or headless environment const authorizeMethod = createOAuthAuthorizeMethod(); const auth = await authorizeMethod(); console.log(auth.url); // "https://accounts.google.com/o/oauth2/v2/auth?..." console.log(auth.instructions); // "Complete OAuth in your browser, then paste the full redirected URL or just the authorization code." const result = await auth.callback("4/0Adeu5BX..."); // Paste just the code ``` -------------------------------- ### authorizeGemini() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Initiates the OAuth authorization flow to generate an authorization URL for Gemini. ```APIDOC ## authorizeGemini() ### Description Generates an authorization URL for the Gemini OAuth flow. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified, likely a URL string) ``` -------------------------------- ### Request and Response Handling Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Handles transformations between OpenAI and Gemini request/response formats, including URL, headers, body, and response normalization. ```APIDOC ## prepareGeminiRequest() ### Description Transforms a request URL, headers, and body for Gemini. ### Signature `prepareGeminiRequest()` ``` ```APIDOC ## transformGeminiResponse() ### Description Normalizes a Gemini response and extracts usage information. ### Signature `transformGeminiResponse()` ``` ```APIDOC ## isGenerativeLanguageRequest() / parseGenerativeLanguageRequest() ### Description Utility functions to detect and parse Generative Language API requests. ### Signatures `isGenerativeLanguageRequest()` `parseGenerativeLanguageRequest()` ``` -------------------------------- ### Configure Thinking Configuration per Model Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/configuration.md Set specific thinking configurations for different models, adjusting thinking level, budget, and whether to include thoughts. ```json { "models": { "gemini-3-pro-preview": { "options": { "thinkingConfig": { "thinkingLevel": "high", "includeThoughts": true } } }, "gemini-3-flash-preview": { "options": { "thinkingConfig": { "thinkingLevel": "low", "includeThoughts": false } } }, "gemini-2.5-flash": { "options": { "thinkingConfig": { "thinkingBudget": 4096, "includeThoughts": true } } } } } ``` -------------------------------- ### retrieveUserQuota() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Fetches the user's quota buckets from the Gemini API. ```APIDOC ## retrieveUserQuota() ### Description Fetches the user's quota buckets from the Gemini API. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified, likely quota bucket information) ``` -------------------------------- ### Opencode Gemini Auth Configuration Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/configuration.md This JSON configuration defines the plugins, provider settings, and model configurations for Opencode Gemini Auth. It specifies the project ID, thinking budget, and whitelisted models, with options to override settings for specific models. ```json { "plugin": ["opencode-gemini-auth@latest"], "provider": { "google": { "options": { "projectId": "my-company-project", "thinkingConfig": { "thinkingBudget": 5000, "includeThoughts": false } }, "whitelist": [ "gemini-3-pro-preview", "gemini-3-flash-preview", "gemini-2.5-pro", "gemini-2.5-flash" ], "models": { "gemini-3-pro-preview": { "options": { "thinkingConfig": { "thinkingLevel": "high", "includeThoughts": true } } }, "gemini-2.5-pro": { "options": { "thinkingConfig": { "thinkingBudget": 8192, "includeThoughts": true } } } } } } } ``` -------------------------------- ### Configure Gemini 2.5 Thinking Settings Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/configuration.md Configure the thinking budget in tokens and whether to include internal reasoning for Gemini 2.5 models. 'thinkingBudget' is a numeric token count. ```json { "provider": { "google": { "models": { "gemini-2.5-pro": { "options": { "thinkingConfig": { "thinkingBudget": 8192, "includeThoughts": true } } }, "gemini-2.5-flash": { "options": { "thinkingConfig": { "thinkingBudget": 4096 } } } } } } } ``` -------------------------------- ### formatGeminiQuotaOutput() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Formats the output of Gemini quota information for display. ```APIDOC ## formatGeminiQuotaOutput() ### Description Formats the output of Gemini quota information for display. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified, likely a formatted string or object) ``` -------------------------------- ### createOAuthAuthorizeMethod Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/api-reference/OAuthAuthorization.md Creates the OAuth authorization callback handler, supporting both automatic callback listener and manual code entry. It determines the environment, sets up a listener if possible, generates an authorization URL, and provides a callback function to complete the authorization process. ```APIDOC ## createOAuthAuthorizeMethod() ### Description Creates the OAuth authorization callback handler, supporting both automatic callback listener and manual code entry. It determines the environment, sets up a listener if possible, generates an authorization URL, and provides a callback function to complete the authorization process. ### Function Signature ```typescript export function createOAuthAuthorizeMethod(options?: { getConfiguredProjectId?: () => Promise | string | undefined; getUserAgentModel?: () => Promise | string | undefined; }): () => Promise<{ url: string; instructions: string; method: string; callback: (() => Promise) | ((callbackUrl: string) => Promise); }>; ``` ### Parameters #### Function Options - **getConfiguredProjectId** (function) - Optional - Returns configured project ID (sync or async). - **getUserAgentModel** (function) - Optional - Returns current model name (sync or async). ### Return Type An asynchronous function that returns authorization details: ```typescript { url: string; // OAuth authorization URL for user instructions: string; // User-facing instructions method: string; // "auto" (browser callback) or "code" (manual) callback: function; // Function to complete authorization } ``` ### Behavior 1. **Environment Detection**: Detects SSH environment and `OPENCODE_HEADLESS` variable to determine callback mode. 2. **Callback Listener Setup**: Attempts to start a local listener on `http://localhost:8085/oauth2callback`, falling back to manual code entry if the listener fails. 3. **Authorization URL Creation**: Generates the authorization URL and opens the browser if not in a headless environment. 4. **Callback Modes**: Supports 'auto' mode where a listener captures the callback, or 'code' mode where the user manually pastes the URL or code. 5. **Project Hydration**: Optionally resolves and updates the project ID and refresh token after a successful token exchange. ### Error Handling - **Callback listener failures**: Logs a warning and falls back to manual mode. - **Authorization exchange failures**: Returns a `{type: "failed", error: ...}` object and logs the error. - **State mismatch**: In auto mode, ignores the callback and waits for the next redirect. In manual mode, returns an error. - **Malformed auth code**: In auto mode, ignores and waits for the next redirect. In manual mode, returns an error. ### Example: Browser-Based (Interactive) ```typescript const authorizeMethod = createOAuthAuthorizeMethod({ getConfiguredProjectId: async () => { const config = await client.config.get(); return config.data?.provider?.google?.options?.projectId; } }); const auth = await authorizeMethod(); console.log(auth.instructions); // "Complete the sign-in flow in your browser. We'll automatically detect the redirect back to localhost." if (auth.method === "auto") { const result = await auth.callback(); // Listener captured callback, browser closed } else { // Manual fallback: user pastes URL console.log(auth.url); const result = await auth.callback( "http://localhost:8085/oauth2callback?code=xyz&state=abc" ); } ``` ### Example: Headless Environment ```typescript // In SSH or headless environment const authorizeMethod = createOAuthAuthorizeMethod(); const auth = await authorizeMethod(); console.log(auth.url); // "https://accounts.google.com/o/oauth2/v2/auth?வதற்கான" console.log(auth.instructions); // "Complete OAuth in your browser, then paste the full redirected URL or just the authorization code." const result = await auth.callback("4/0Adeu5BX..."); // Paste just the code ``` ### Callback Input Parsing The callback accepts several input formats: | Format | Example | Parsed | |--------|---------|--------| | Full URL | `http://localhost:8085/oauth2callback?code=abc&state=xyz` | code + state | | Query string | `?code=abc&state=xyz` | code + state | | Query string | `code=abc&state=xyz` | code + state | | Code only | `4/0Adeu5BX...` | code only | ### Internal State Parameter - Generated via `randomBytes(32).toString("hex")`. - Validates exact match in callback. - Protects against CSRF attacks. ``` -------------------------------- ### OAuth PKCE Flow Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Handles the OAuth2 Proof Key for Code Exchange (PKCE) flow, including generating authorization URLs and exchanging codes for tokens. ```APIDOC ## authorizeGemini() ### Description Generates an authorization URL for the Gemini OAuth2 PKCE flow. ### Signature `authorizeGemini()` ### Details - Generates authorization URL with PKCE parameters. ``` ```APIDOC ## exchangeGeminiWithVerifier() ### Description Exchanges an authorization code for OAuth tokens using the PKCE verifier. ### Signature `exchangeGeminiWithVerifier()` ### Details - Exchanges code for tokens. - Returns token response structure. ``` -------------------------------- ### Project Management Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Manages Google Cloud project context, including resolving, caching, and invalidating project IDs, and handling project onboarding. ```APIDOC ## ensureProjectContext() ### Description Resolves and caches the Google Cloud project ID. ### Signature `ensureProjectContext()` ``` ```APIDOC ## resolveProjectContextFromAccessToken() ### Description Resolves the project context from an access token, handling onboarding and loading. ### Signature `resolveProjectContextFromAccessToken()` ``` ```APIDOC ## invalidateProjectContextCache() ### Description Clears the cached project context. ### Signature `invalidateProjectContextCache()` ``` ```APIDOC ## loadManagedProject() ### Description Fetches information about a managed Google Cloud project. ### Signature `loadManagedProject()` ``` ```APIDOC ## onboardManagedProject() ### Description Onboards a project to the free or standard tier, including polling for status. ### Signature `onboardManagedProject()` ``` -------------------------------- ### createOAuthAuthorizeMethod() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Builds the method for handling OAuth authorization callbacks. ```APIDOC ## createOAuthAuthorizeMethod() ### Description Builds the method for handling OAuth authorization callbacks. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified) ``` -------------------------------- ### PluginContext Interface Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/types.md The PluginContext is passed to the plugin's entry point, providing access to the PluginClient for interacting with the Opencode platform. ```APIDOC ## PluginContext Context passed to plugin entry point. ```typescript interface PluginContext { client: PluginClient; } ``` ``` -------------------------------- ### exchangeGeminiWithVerifier() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Exchanges an authorization code for an access token with Gemini. ```APIDOC ## exchangeGeminiWithVerifier() ### Description Exchanges an authorization code for an access token with Gemini. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified, likely an access token object) ``` -------------------------------- ### OnboardUserPayload Interface Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/types.md Defines the response structure from the onboarding endpoint. It indicates whether onboarding is complete and provides an operation ID for polling if it's not. ```typescript interface OnboardUserPayload { name?: string; // Operation name for polling done?: boolean; // Is onboarding complete? response?: { cloudaicompanionProject?: { id?: string; // Onboarded project ID }; }; } ``` -------------------------------- ### loadManagedProject() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Loads information about a managed project. ```APIDOC ## loadManagedProject() ### Description Loads information about a managed project. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified, likely a project object) ``` -------------------------------- ### PluginClient Interface Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/types.md The PluginClient interface allows plugins to interact with the Opencode platform. It provides methods for managing authentication credentials, retrieving configuration, and displaying toast notifications. ```APIDOC ## PluginClient Interface for plugin to interact with Opencode: - **auth.set(input: { path: { id: string }; body: OAuthAuthDetails }): Promise** — Save updated credentials. - **config.get(options?: unknown): Promise<{ data?: Config } | undefined>** — Load Opencode configuration. - **tui.showToast(input: { body: { title?: string; message: string; variant: "info" | "success" | "warning" | "error"; duration?: number; } }): Promise** — Display notification messages. ``` -------------------------------- ### formatDebugBodyPreview() Source: https://github.com/jenslys/opencode-gemini-auth/blob/main/_autodocs/INDEX.md Formats a preview of a request or response body, truncating if necessary. ```APIDOC ## formatDebugBodyPreview() ### Description Formats a preview of a request or response body, truncating if necessary for debugging purposes. ### Method (Not specified, likely a function call in an SDK) ### Parameters (No parameters specified) ### Response (No response details specified, likely a formatted string) ```