### Install dependencies and build the plugin Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/README.md Run these commands in the cloned repository to install dependencies and build the source code before local testing. ```bash npm install npm run build ``` -------------------------------- ### Usage example with v2PluginDefinition Source: https://github.com/anthonyhaussman/opencode-agy-auth Imports v2PluginDefinition and setupOpenCodeV2 from the package root. v2PluginDefinition is already exported and invoked by the OpenCode v2 runtime via Plugin.define; manual setup is optional. Logs the plugin id "google-agy". ```ts import { v2PluginDefinition, setupOpenCodeV2 } from "@anthonyhaussman/opencode-agy-auth"; // v2PluginDefinition is already exported by the package root; setup is invoked // by the OpenCode v2 runtime through Plugin.define. console.log(v2PluginDefinition.id); // "google-agy" // Manually invoking the setup against a v2 plugin context: // await setupOpenCodeV2(ctx); ``` -------------------------------- ### Install plugin via npm Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/README.md Install the plugin from npm using the package name @anthonyhaussman/opencode-agy-auth. ```bash npm install @anthonyhaussman/opencode-agy-auth ``` -------------------------------- ### Named export: setupOpenCodeV2 Source: https://github.com/anthonyhaussman/opencode-agy-auth A v2 setup adapter that initializes the plugin in OpenCode v2. ```APIDOC ## Named export: setupOpenCodeV2 ### Description A v2 setup adapter (`(ctx: OpenCodeV2PluginContext) => Promise`) that sets up the plugin for OpenCode v2. ### Signature ```ts (ctx: OpenCodeV2PluginContext) => Promise ``` ``` -------------------------------- ### Named export: v2PluginDefinition Source: https://github.com/anthonyhaussman/opencode-agy-auth An OpenCodeV2PluginDefinition object with id 'google-agy' and a setup function. ```APIDOC ## Named export: v2PluginDefinition ### Description An `OpenCodeV2PluginDefinition` (`{ id: 'google-agy', setup }`) that defines the plugin for OpenCode v2. ### Example ```ts const v2PluginDefinition: OpenCodeV2PluginDefinition = { id: 'google-agy', setup, }; ``` ``` -------------------------------- ### Usage example with createSignatureCache Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to instantiate the cache with a config, store thinking data, retrieve it, flush, and shut down. The example uses a 30-second write interval and 1-hour memory TTL. ```ts import { createSignatureCache } from "./src/sdk/cache/signature-cache.js"; const cache = createSignatureCache({ enabled: true, memory_ttl_seconds: 3600, disk_ttl_seconds: 86400, write_interval_seconds: 30, }); if (cache) { cache.storeThinking("turn:abc", "full thinking chain", "sig-1", ["tool-1"]); const data = cache.retrieveThinking("turn:abc"); // { text, signature, toolIds } await cache.flush(); cache.shutdown(); } ``` -------------------------------- ### Build verification commands Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/AGENTS.md Run these commands to install dependencies, test, typecheck, build, and verify the plugin. The smoke test verifies dist/index.js loads without error, and the plugin-scanner enforces a security/quality score of at least 80. ```bash npm install # updates package-lock.json npm test # run unit test suite npm run test:coverage # run tests with v8 code coverage enforcement npm run typecheck # tsc type check npm run build # tsup bundle + tsc declaration emit npm run smoke:node-import # verify dist/index.js loads without error pipx run plugin-scanner scan . # verify security and quality compliance (score >= 80) ``` -------------------------------- ### Run full verification suite Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/AGENTS.md Execute the full verification suite: `npm install && npm run test:coverage && npm run typecheck && npm run build && npm run smoke:node-import`. All tests and quality gates must pass cleanly. ```bash npm install && npm run test:coverage && npm run typecheck && npm run build && npm run smoke:node-import ``` -------------------------------- ### Usage example for request helpers Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to use isGenerativeLanguageRequest, parseGenerativeLanguageRequest, and injectResponseIdFromTrace together. The example uses a generativelanguage.googleapis.com URL and demonstrates the expected return values, including the responseId injection. ```ts import { isGenerativeLanguageRequest, parseGenerativeLanguageRequest, injectResponseIdFromTrace, } from "./src/sdk/request/shared.js"; const url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-argon-high:streamGenerateContent"; isGenerativeLanguageRequest(url); // true parseGenerativeLanguageRequest(url); // { requestedModel: "gemini-4-argon-high", effectiveModel: "gemini-4-argon-high", action: "streamGenerateContent" } injectResponseIdFromTrace({ traceId: "t-1", response: { candidates: [] } }); // { traceId: "t-1", response: { candidates: [], responseId: "t-1" } } ``` -------------------------------- ### Usage example for quota tools Source: https://github.com/anthonyhaussman/opencode-agy-auth Demonstrates creating both quota tools and executing the quota tool. The execute call returns a string or object with content; the comment shows the expected output format. ```TypeScript import { createAgyQuotaTool, AGY_QUOTA_TOOL_NAME } from "./src/plugin/quota.js"; import { createAgyQuotaSummaryTool } from "./src/plugin/quota-summary.js"; const quotaTool = createAgyQuotaTool({ client, getAuthResolver: () => getAuth, getConfiguredProjectId: () => "my-project", getUserAgentModel: () => "gemini-3.8-flash", }); const output = await quotaTool.execute({}, { sessionID: "s1" }); console.log(typeof output === "string" ? output : output.content); // "Agy quota usage for project `my-project` ..." ``` -------------------------------- ### Usage example for prepareAgyRequest Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to call prepareAgyRequest with a model URL, request init, access token, GCP project, and model options. The returned request URL is rewritten to an internal endpoint and streaming is enabled; the result can be passed directly to fetch. ```typescript import { prepareAgyRequest } from "./src/sdk/request/prepare.js"; const result = prepareAgyRequest( "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-argon:streamGenerateContent", { method: "POST", headers: {}, body: JSON.stringify({ contents: [{ role: "user", parts: [{ text: "hi" }] }] }) }, "ya29.access-token", "my-gcp-project", { models: { "gemini-4-argon": { thinkingBudget: 8000, includeThoughts: true } } }, ); // result.request -> "https://daily-cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse" // result.streaming -> true const response = await fetch(result.request, result.init); ``` -------------------------------- ### Usage example for header utilities Source: https://github.com/anthonyhaussman/opencode-agy-auth Demonstrates importing and using getSafeHeader, setSafeHeaders, and toUrlString. setSafeHeaders creates a Headers object with Authorization and User-Agent, getSafeHeader performs case-insensitive lookup, and toUrlString returns the URL string. ```typescript import { getSafeHeader, setSafeHeaders, toUrlString } from "./src/plugin/headers.js"; const headers = setSafeHeaders(undefined, { Authorization: "Bearer xyz", "User-Agent": "antigravity/cli/1.5.1 linux/x64", }) as Headers; getSafeHeader(headers, "authorization"); // "Bearer xyz" toUrlString("https://daily-cloudcode-pa.googleapis.com/v1internal:listExperiments"); // "https://daily-cloudcode-pa.googleapis.com/v1internal:listExperiments" ``` -------------------------------- ### Usage example for fetchAvailableModels and related SDK functions Source: https://github.com/anthonyhaussman/opencode-agy-auth Imports and calls loadManagedProject, retrieveUserQuota, fetchAvailableModels, and onboardManagedProject. fetchAvailableModels throws an Error with status text on non-OK responses; network errors propagate. ```TypeScript import { loadManagedProject, onboardManagedProject } from "./src/sdk/fetch_project.js"; import { retrieveUserQuota } from "./src/sdk/fetch_quota.js"; import { fetchAvailableModels } from "./src/sdk/fetch_models.js"; const payload = await loadManagedProject(accessToken, "my-project"); const quota = await retrieveUserQuota(accessToken, "my-project"); const models = await fetchAvailableModels(accessToken, "my-project"); const managedId = await onboardManagedProject(accessToken, "legacy-tier", "my-project", undefined, 5, 2000); ``` -------------------------------- ### User agent usage example Source: https://github.com/anthonyhaussman/opencode-agy-auth Imports and calls `buildAgyCliUserAgent` with a model argument. The comment shows the expected output format, e.g., `"antigravity/cli/1.5.1 linux/x64"`. ```typescript import { buildAgyCliUserAgent, getAgyCliVersion } from "./src/sdk/user-agent.js"; buildAgyCliUserAgent("gemini-4-argon"); // "antigravity/cli/1.5.1 linux/x64" ``` -------------------------------- ### Install @alpha distribution tag via npm Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/README.md Use this command to install the bleeding-edge pre-release version of the plugin. The @alpha tag contains experimental features and may be unstable, so it is intended only for testing and development. ```bash npm install @anthonyhaussman/opencode-agy-auth@alpha ``` -------------------------------- ### Usage example for TurnStateTracker Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to instantiate the tracker with disk persistence (default) or memory-only mode, update state after a response, check for thinking recovery, and shut down. The commented line demonstrates memory-only mode. ```typescript import { TurnStateTracker } from "./src/sdk/request/turn-state-tracker.js"; // Disk persistence enabled (default) const tracker = new TurnStateTracker(true); // Memory-only mode — no filesystem access // const tracker = new TurnStateTracker(false); tracker.updateAfterResponse("session-1", { inToolLoop: true, turnHasThinking: true, lastModelHasThinking: true, lastModelHasToolCalls: true, }); if (tracker.needsThinkingRecovery("session-1")) { // state.inToolLoop && !state.turnHasThinking -> recover the conversation } const state = tracker.getState("session-1"); tracker.shutdown(); ``` -------------------------------- ### Find prior bump commits Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/AGENTS.md Run `git log --oneline | grep "bump agy cli"` to see examples of prior bump commits that follow a consistent pattern. ```bash git log --oneline | grep "bump agy cli" ``` -------------------------------- ### Usage example for traffic and toast functions Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to import and call simulateClientBackgroundTraffic, buildTrajectoryAnalyticsBody, and maybeShowAgyCapacityToast. The buildTrajectoryAnalyticsBody call returns a body with startStepIndex '0'. ```TypeScript import { simulateClientBackgroundTraffic, buildTrajectoryAnalyticsBody } from "./src/plugin/traffic.js"; import { maybeShowAgyCapacityToast } from "./src/plugin/notify.js"; simulateClientBackgroundTraffic(accessToken, "my-project", "gemini-3.8-flash"); const body = buildTrajectoryAnalyticsBody(); console.log(body.startStepIndex); // "0" await maybeShowAgyCapacityToast(client, response, "my-project", "gemini-4-argon"); ``` -------------------------------- ### Terminal hyperlink usage example Source: https://github.com/anthonyhaussman/opencode-agy-auth Imports and calls `formatHyperlink` with a URL and text. Falls back to `"docs (https://example.com)"` when OSC 8 hyperlinks are not supported. ```typescript import { formatHyperlink } from "./src/sdk/terminal-hyperlink.js"; formatHyperlink("https://example.com", "docs"); // falls back to "docs (https://example.com)" when unsupported ``` -------------------------------- ### Usage example for authorizeAgy and exchangeAgyWithVerifier Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows the intended flow: call authorizeAgy to get the authorization URL and verifier, display the URL, then after the user provides the code, call exchangeAgyWithVerifier with the code and verifier. The result is checked for success or failure, logging the access token, expiry, and email on success, or the error on failure. ```ts import { authorizeAgy, exchangeAgyWithVerifier } from "./src/sdk/oauth.js"; const authorization = await authorizeAgy(); console.log("Open this URL in a browser:", authorization.url); // After the user pastes the redirect URL / code: const result = await exchangeAgyWithVerifier(code, authorization.verifier); if (result.type === "success") { console.log(result.access, result.expires, result.email); } else { console.error("Exchange failed:", result.error); } ``` -------------------------------- ### OpenCodeV2PluginDefinition interface and defineOpenCodeV2Plugin Source: https://github.com/anthonyhaussman/opencode-agy-auth Defines the plugin structure with an id and setup function. The defineOpenCodeV2Plugin helper returns the definition unchanged. ```typescript export interface OpenCodeV2PluginDefinition { id: string; setup: (ctx: OpenCodeV2PluginContext) => Promise | void; } export function defineOpenCodeV2Plugin( def: OpenCodeV2PluginDefinition, ): OpenCodeV2PluginDefinition { return def; } ``` -------------------------------- ### Usage example for refreshAccessToken and parseRefreshParts Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to import and use refreshAccessToken and parseRefreshParts. If refresh fails, it logs a warning and suggests re-authenticating with `opencode auth login`; otherwise it logs the new access token and parsed refresh parts. ```ts import { refreshAccessToken, parseRefreshParts } from "./src/plugin/token.js"; // parseRefreshParts is exported from src/plugin/auth.js import { parseRefreshParts } from "./src/plugin/auth.js"; const auth = { type: "oauth", access, refresh, expires } as OAuthAuthDetails; const refreshed = await refreshAccessToken(auth, client); if (!refreshed) { console.warn("Token refresh failed — re-authenticate with `opencode auth login`"); } else { console.log(refreshed.access, parseRefreshParts(refreshed.refresh)); } ``` -------------------------------- ### Usage example for transformAgyResponse Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to call transformAgyResponse with a streaming fetch response, then read the normalized SSE body. The example uses a specific endpoint and model ID. ```ts import { transformAgyResponse } from "./src/sdk/request/response.js"; const raw = await fetch("https://daily-cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse", init); const normalized = await transformAgyResponse(raw, true, null, "gemini-4-argon", "my-session"); const reader = normalized.body!.getReader(); // consume SSE events; each data payload matches the Gemini streaming schema ``` -------------------------------- ### Usage example for createOAuthAuthorizeMethod Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to create an authorize method with a configured project ID and custom browser opener, then invoke it and handle the callback. The callback URL is parsed for `code` and `state`; on failure, the result type is `'failed'` with an error message. ```typescript import { createOAuthAuthorizeMethod } from "./src/plugin/oauth-authorize.js"; const authorize = createOAuthAuthorizeMethod({ getConfiguredProjectId: () => "my-gcp-project", openBrowser: (url) => console.log("Open:", url), }); const session = await authorize(); console.log(session.url, session.method); // "code" const result = await session.callback("https://antigravity.google/oauth-callback?code=abc&state=xyz"); if (result.type === "failed") { console.error("Login failed:", result.error); } ``` -------------------------------- ### Usage example with ToolMapper and restoreToolNamesInResponse Source: https://github.com/anthonyhaussman/opencode-agy-auth Demonstrates registering a tool name, mapping to Gemini and back, and restoring the original name in a response body using restoreToolNamesInResponse. ```typescript import { ToolMapper, getToolMapper, restoreToolNamesInResponse } from "./src/sdk/request/tool-mapper.js"; const mapper = getToolMapper("session-x"); mapper.registerFromFunctionDeclarations([{ functionDeclarations: [{ name: "my-tool" }] }]); mapper.toGemini("my-tool"); // "my_tool" mapper.fromGemini("my_tool"); // "my-tool" const body = { response: { candidates: [{ content: { parts: [{ functionCall: { name: "my_tool" } }] } }] } }; restoreToolNamesInResponse(body, mapper); // body.response.candidates[0].content.parts[0].functionCall.name === "my-tool" ``` -------------------------------- ### new SignatureCache(config) Source: https://github.com/anthonyhaussman/opencode-agy-auth Constructor for the SignatureCache class. Initializes the cache with the given configuration, loading disk data and starting timers when enabled. ```APIDOC ## new SignatureCache(config) ### Description Constructor for the SignatureCache class. Initializes the cache with the given configuration, loading disk data and starting timers when enabled. ### Method Constructor ### Signature `constructor(config: SignatureCacheConfig)` ### Parameters - `config.enabled` (boolean) - Required - When false, every method is a no-op and no disk I/O occurs; the factory returns `null` instead of an instance. - `config.memory_ttl_seconds` (number) - Required - TTL for memory entries (`retrieve`/`has` return null past it). - `config.disk_ttl_seconds` (number) - Required - TTL for entries loaded from / merged into the disk file. - `config.write_interval_seconds` (number) - Required - Background `setInterval` flush cadence. ### Behavior When `enabled`, the constructor loads the disk file and starts two timers: write flush (every `write_interval_seconds`) and memory GC (every 30 min). ``` -------------------------------- ### Usage example for resolveConfiguredProjectId and resolveConfiguredProjectIdFromConfig Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to import and call the functions. The first call returns 'provider-project' because provider options rank above configProjectId. The second call reads from config.provider['google-agy'].options.projectId. ```TypeScript import { resolveConfiguredProjectId, resolveConfiguredProjectIdFromConfig } from "./src/plugin/provider.js"; const projectId = resolveConfiguredProjectId({ configProjectId: "cached-project", provider: { options: { projectId: "provider-project" } } as any, }); // returns "provider-project" because provider options rank above configProjectId const fromConfig = resolveConfiguredProjectIdFromConfig({ provider: { "google-agy": { options: { projectId: "cfg-project" } } }, } as any); ``` -------------------------------- ### Formatting helpers usage example Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows importing buildProgressBar and formatRelativeResetTime from quota-utils.js. buildProgressBar(0.42) returns a 20-character bar with 8 filled and 12 empty cells; formatRelativeResetTime returns 'resets in 1h' for a timestamp 3.6e6 ms in the future. ```TypeScript import { buildProgressBar, formatRelativeResetTime } from "./src/plugin/quota-utils.js"; buildProgressBar(0.42); // "▓▓▓▓▓▓▓▓░░░░░░░░░░░░" formatRelativeResetTime(new Date(Date.now() + 3.6e6).toISOString()); // "resets in 1h" ``` -------------------------------- ### fetchWithRetry usage example Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to use fetchWithRetry with a POST request, handle a 429 response by classifying the quota response, and shut down cooldown persistence. ```typescript import { fetchWithRetry, shutdownRetryCooldowns } from "./src/sdk/retry/index.js"; import { isRetryableStatus, resolveRetryDelayMs } from "./src/sdk/retry/helpers.js"; import { classifyQuotaResponse } from "./src/sdk/retry/quota.js"; const response = await fetchWithRetry("https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota", { method: "POST", body: JSON.stringify({ project: "p" }), }); if (response.status === 429) { const ctx = await classifyQuotaResponse(response); console.log(ctx?.reason, ctx?.terminal, ctx?.retryDelayMs); } shutdownRetryCooldowns(); ``` -------------------------------- ### Default export: DualOpenCodePlugin Source: https://github.com/anthonyhaussman/opencode-agy-auth The default export is a DualOpenCodePlugin that combines the v2 plugin definition (id/setup) with the v1 plugin's server field (AgyCLIOAuthPlugin). Runtime detection is automatic: OpenCode v1 loads it through server, OpenCode v2 through setup. ```typescript const dualPlugin: DualOpenCodePlugin = { ...v2PluginDefinition, server: AgyCLIOAuthPlugin, }; export default dualPlugin; ``` -------------------------------- ### Usage example with ensureProjectContext and invalidateProjectContextCache Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to resolve the effective project ID and then invalidate the cache for a refresh token. The auth record may be enriched with |projectId|managedProjectId. ```TypeScript import { ensureProjectContext, invalidateProjectContextCache } from "./src/plugin/project/context.js"; const ctx = await ensureProjectContext(authRecord, client, "my-project"); console.log(ctx.effectiveProjectId); // managed or configured project id console.log(ctx.auth.refresh); // possibly enriched with |projectId|managedProjectId invalidateProjectContextCache(authRecord.refresh); ``` -------------------------------- ### sanitizeToolName examples Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows the output of sanitizeToolName for various inputs: replaces non-alphanumeric characters with underscores, prepends underscore if the result doesn't start with a letter or underscore, and returns 'unnamed_tool' for empty or non-string input. ```typescript sanitizeToolName("my-tool"); // "my_tool" sanitizeToolName("atlassian:get-issue"); // "atlassian_get_issue" sanitizeToolName("9lives"); // "_9lives" ``` -------------------------------- ### Import root package Source: https://github.com/anthonyhaussman/opencode-agy-auth The only resolvable import from the published package is the root due to the strict exports map and tsup bundling. Deep paths like @anthonyhaussman/opencode-agy-auth/sdk/request/turn-state-tracker are not exposed; use source-relative module paths when consuming internals. ```ts import opencodeAgyAuth, { AgyCLIOAuthPlugin, setupOpenCodeV2 } from "@anthonyhaussman/opencode-agy-auth"; ``` -------------------------------- ### onboardManagedProject(accessToken, tier, projectId, ...) Source: https://github.com/anthonyhaussman/opencode-agy-auth Onboards a managed project with the specified tier and project ID. Returns undefined on non-OK statuses and network errors. ```APIDOC ## onboardManagedProject(accessToken, tier, projectId, ...) ### Description Onboards a managed project with the specified tier and project ID. Returns undefined on non-OK statuses and network errors. ### Parameters #### Path Parameters - **accessToken** (string) - Required - Access token for authentication - **tier** (string) - Required - The tier for the project - **projectId** (string) - Required - The project identifier - **additional parameters** - Optional - Additional parameters as shown in usage example ### Error Handling - **Non-OK status**: Returns `undefined` - **Network error**: Returns `undefined` ``` -------------------------------- ### Configure both plugins in opencode.json Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/README.md Register both @anthonyhaussman/opencode-agy-auth and opencode-quota plugins together, with the same google-agy provider configuration. ```json { "$schema": "https://opencode.ai/config.json", "plugin": [ "@anthonyhaussman/opencode-agy-auth", "opencode-quota" ], "provider": { "google-agy": { "options": { "projectId": "your-google-cloud-project-id" } } } } ``` -------------------------------- ### setupOpenCodeV2(ctx) Source: https://github.com/anthonyhaussman/opencode-agy-auth Initializes the OpenCode V2 plugin by setting up disk signature cache, turn state tracker, cooldown persistence, and applying transforms to provider, model, catalog, tool, command, integration, and AISDK hooks. This function is invoked by the OpenCode v2 runtime through Plugin.define. ```APIDOC ## setupOpenCodeV2(ctx) ### Description Initializes the OpenCode V2 plugin by setting up disk signature cache, turn state tracker, cooldown persistence, and applying transforms to provider, model, catalog, tool, command, integration, and AISDK hooks. This function is invoked by the OpenCode v2 runtime through Plugin.define. ### Method Function call ### Signature ```ts export async function setupOpenCodeV2(ctx: OpenCodeV2PluginContext): Promise ``` ### Parameters - **ctx** (OpenCodeV2PluginContext) - Required - The plugin context containing optional registries for catalog, provider, model, tool, command, session, aisdk, integration, and location. Only the ones present are used. ### Return Value - Promise - Resolves when setup is complete. ### Usage Example ```ts import { v2PluginDefinition, setupOpenCodeV2 } from "@anthonyhaussman/opencode-agy-auth"; // v2PluginDefinition is already exported by the package root; setup is invoked // by the OpenCode v2 runtime through Plugin.define. console.log(v2PluginDefinition.id); // "google-agy" // Manually invoking the setup against a v2 plugin context: // await setupOpenCodeV2(ctx); ``` ``` -------------------------------- ### createV2PluginDefinition() Source: https://github.com/anthonyhaussman/opencode-agy-auth Returns the identical singleton as v2PluginDefinition. It exists for test symmetry and can be used to obtain the plugin definition programmatically. ```APIDOC ## createV2PluginDefinition() ### Description Returns the identical singleton as v2PluginDefinition. It exists for test symmetry and can be used to obtain the plugin definition programmatically. ### Method Function call ### Signature ```ts createV2PluginDefinition() ``` ### Return Value - The same plugin definition object as `v2PluginDefinition`. ### Usage Example ```ts import { createV2PluginDefinition } from "@anthonyhaussman/opencode-agy-auth"; const def = createV2PluginDefinition(); console.log(def.id); // "google-agy" ``` ``` -------------------------------- ### onboardManagedProject(accessToken, tierId, projectId?, userAgentModel?, attempts?, delayMs?) Source: https://github.com/anthonyhaussman/opencode-agy-auth Onboards a managed project for a given tier. It POSTs the project metadata to the :onboardUser endpoint and polls for completion if necessary, returning the managed project ID or undefined on failure. ```APIDOC ## `onboardManagedProject(accessToken, tierId, projectId?, userAgentModel?, attempts = 10, delayMs = 5000): Promise` ### Description Onboards a managed project for a given tier. It POSTs the project metadata to the `:onboardUser` endpoint and polls for completion if necessary, returning the managed project ID or undefined on failure. ### Parameters - **accessToken** (string) - Required - The access token for authentication. - **tierId** (string) - Required - The tier identifier. If `'free-tier'`, no `cloudaicompanionProject` is required; otherwise, `projectId` is required. - **projectId** (string) - Optional - The project ID. Required for non-free tiers; throws `ProjectIdRequiredError` if missing. - **userAgentModel** (string) - Optional - The user agent model. - **attempts** (number) - Optional - Number of polling attempts (default: 10). - **delayMs** (number) - Optional - Delay between polls in milliseconds (default: 5000). ### Behavior - For free tier, metadata is sent without `duetProject` and no `cloudaicompanionProject` is required. - For non-free tiers, throws `ProjectIdRequiredError` if `projectId` is missing. - POSTs `{ tierId, metadata, cloudaicompanionProject? }` to `:onboardUser`. - If the response has `!payload.done && payload.name`, polls `GET {endpoint}/v1internal/{payload.name}` every `delayMs` up to `attempts` times. ### Returns - **Promise** - The managed project ID (`payload.response.cloudaicompanionProject.id`), falls back to `projectId` when done, else `undefined`. All failures log and return `undefined`. ``` -------------------------------- ### resolveModelTier usage example Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows how to call resolveModelTier with different model names and optional headers to override the tier. The function returns the mapped model name or the original if no mapping exists. ```TypeScript import { resolveModelTier, TIER_MAPPING, STATIC_MODELS_SIMPLE } from "./src/plugin/tier.js"; resolveModelTier("gemini-4-argon"); // "gemini-4-argon-medium" resolveModelTier("gemini-4-argon@high"); // "gemini-4-argon-high" resolveModelTier("gemini-4-argon", { headers: { "x-agy-tier": "low" } }); // "gemini-4-argon-low" resolveModelTier("gpt-oss-120b-medium"); // unchanged (no mapping) ``` -------------------------------- ### setOpenBrowserLauncherForTesting(launcher) Source: https://github.com/anthonyhaussman/opencode-agy-auth Replaces the module-level openBrowserLauncher for testing purposes. Passing null restores the default launcher. ```APIDOC ## setOpenBrowserLauncherForTesting(launcher) ### Description Replaces the module-level `openBrowserLauncher` (null restores the default). Under `NODE_ENV === 'test'` / `VITEST` with the default launcher, browser opening is skipped entirely. ### Method Function ### Signature ```ts export function setOpenBrowserLauncherForTesting(launcher: typeof openBrowserLauncher | null): void; ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `launcher` | `typeof openBrowserLauncher \| null` | yes | The launcher function to use, or null to restore the default | ``` -------------------------------- ### Named export: GoogleOAuthPlugin Source: https://github.com/anthonyhaussman/opencode-agy-auth Alias of AgyCLIOAuthPlugin for backward compatibility. ```APIDOC ## Named export: GoogleOAuthPlugin ### Description Alias of `AgyCLIOAuthPlugin` (backward-compatible name). ### Signature Same as `AgyCLIOAuthPlugin`. ``` -------------------------------- ### ./scripts/fetch-models.mjs --verbose Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/AGENTS.md Alternative command to refresh `models.json` with verbose output. The script reads `~/.local/share/opencode/auth.json`, refreshes the OAuth token, calls `fetchAvailableModels`, and writes the response to `models.json`. ```bash ./scripts/fetch-models.mjs --verbose ``` -------------------------------- ### Verify pinned release tag exists Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/docs/release-promotion.md Run after the pinned release to confirm the tag was created before removing the release-as override. Must print X.Y.Z-alpha.N. ```bash git fetch --tags origin && git tag --list 'X.Y.Z*' ``` -------------------------------- ### setupOpenCodeV2 signature Source: https://github.com/anthonyhaussman/opencode-agy-auth Shows the async function signature and the ordered steps it performs: disk cache/turn state/cooldown initialization, optional transforms for provider/model/catalog/tool/command/integration, an aisdk hook, and session hooks. Only registries present in the context are used, guarded by optional chaining. ```ts export async function setupOpenCodeV2(ctx: OpenCodeV2PluginContext): Promise { // 0. initDiskSignatureCache / initTurnStateTracker / initCooldownPersistence // 1. ctx.provider?.transform / ctx.model?.transform / ctx.catalog?.transform // 2. ctx.tool.transform // 3. ctx.command.transform // 4. ctx.integration?.transform // 5. ctx.aisdk?.hook('sdk', ...) // 6. registerV2SessionHooks(ctx) } ``` -------------------------------- ### Push promotion commit to main Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/docs/release-promotion.md Push the promotion commit to `main` so release-please re-reads the config and opens a stable release PR. If there are no new Conventional Commits since the last alpha tag, release-please will not open a stable PR; push a no-op Conventional Commit or temporarily add `"release-as": "X.Y.Z"` to the config. ```bash git push origin main ``` -------------------------------- ### Configure OpenCode to use local plugin path Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/README.md Add the absolute local path to the plugin in your opencode.json (or ~/.config/opencode/opencode.json for global testing). OpenCode also supports dropping plugin files directly into the .opencode/plugins/ folder. ```json { "$schema": "https://opencode.ai/config.json", "plugin": ["/absolute/path/to/opencode-agy-auth"] } ``` -------------------------------- ### sanitizeToolName(name: string): string Source: https://github.com/anthonyhaussman/opencode-agy-auth Sanitizes a client tool name into a Gemini-valid name. Empty or non-string input returns "unnamed_tool", non-alphanumeric characters are replaced with underscores, and an underscore is prepended if the result doesn't start with a letter or underscore. ```APIDOC ## sanitizeToolName(name: string): string ### Description Sanitizes a client tool name into a Gemini-valid name. Empty or non-string input returns "unnamed_tool", non-alphanumeric characters are replaced with underscores, and an underscore is prepended if the result doesn't start with a letter or underscore. ### Parameters - **name** (string) - Required - The original tool name to sanitize ### Returns - **string** - The sanitized Gemini-valid tool name ### Example ```ts sanitizeToolName("my-tool"); // "my_tool" sanitizeToolName("atlassian:get-issue"); // "atlassian_get_issue" sanitizeToolName("9lives"); // "_9lives" ``` ``` -------------------------------- ### Resume alpha: set prerelease and bump manifest anchor Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/docs/release-promotion.md After the stable tag is published, flip the config back and bump the manifest anchor to the new stable version. The JSON comments are shown as in the source. ```json // .release-please-config.json "prerelease": true // .release-please-manifest.json { ".": "X.Y.Z" } ``` -------------------------------- ### Proxy-aware fetch wrapper Source: https://github.com/anthonyhaussman/opencode-agy-auth Wraps `fetch`; when `process.env.OPENCODE_AGY_AUTH_PROXY` is set, passes `{ ...init, proxy }` (a `BunRequestInit` extension). Used by every remote call in the project. ```typescript export function agyFetch(input: RequestInfo | URL, init?: RequestInit): Promise; // :3 ``` -------------------------------- ### Usage: transformOpenAIToolCalls and addThoughtSignaturesToFunctionCalls Source: https://github.com/anthonyhaussman/opencode-agy-auth Imports the conversion functions and a tool mapper, then converts an OpenAI-style assistant message with tool_calls into Gemini functionCall parts. The example shows the resulting parts array with the thoughtSignature sentinel. addThoughtSignaturesToFunctionCalls is then called on the payload to add the sentinel to any functionCall parts lacking it. ```typescript import { transformOpenAIToolCalls, addThoughtSignaturesToFunctionCalls } from "./src/sdk/request/openai.js"; import { getToolMapper } from "./src/sdk/request/tool-mapper.js"; const mapper = getToolMapper("session-1"); const payload: Record = { messages: [{ role: "assistant", content: "Calling a tool", tool_calls: [{ id: "tc-1", function: { name: "my-tool", arguments: '{"q":"x"}' } }], }], }; transformOpenAIToolCalls(payload, mapper); // payload.messages[0].parts = [{ text: "Calling a tool" }, // { functionCall: { id: "tc-1", name: "my_tool", args: { q: "x" } }, // thoughtSignature: "skip_thought_signature_validator" }] addThoughtSignaturesToFunctionCalls(payload); ``` -------------------------------- ### Inspect local agy binary for internal RPC routes Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/AGENTS.md Run this command to discover internal RPC routes, header adjustments, or payload changes in the local agy binary. Diffing binary strings against the previous version reveals unannounced backend protocol changes. ```bash strings $(readlink -f $(which agy)) | grep -E 'v1internal|daily-cloudcode|CodeAssist' ``` -------------------------------- ### retrieveUserQuotaSummary(accessToken, projectId, userAgentModel?) Source: https://github.com/anthonyhaussman/opencode-agy-auth Retrieves a summary of the user quota for a given project. It POSTs the project ID and returns the parsed JSON response or null on any non-OK response or network error. ```APIDOC ## `retrieveUserQuotaSummary(accessToken: string, projectId: string, userAgentModel?: string): Promise` ### Description Retrieves a summary of the user quota for a given project. It POSTs the project ID and returns the parsed JSON response or null on any non-OK response or network error. ### Parameters - **accessToken** (string) - Required - The access token for authentication. - **projectId** (string) - Required - The project ID. - **userAgentModel** (string) - Optional - The user agent model. ### Returns - **Promise** - The parsed response or null on failure. `RetrieveUserQuotaSummaryResponse = { groups?: QuotaSummaryGroup[]; buckets?: QuotaSummaryBucket[]; description?: string }`. ``` -------------------------------- ### Configure plugin in opencode.json Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/README.md Register the plugin and specify your Google Cloud Project ID in the OpenCode configuration file (opencode.json). ```json { "$schema": "https://opencode.ai/config.json", "plugin": ["@anthonyhaussman/opencode-agy-auth"], "provider": { "google-agy": { "options": { "projectId": "your-google-cloud-project-id" } } } } ``` -------------------------------- ### fetchAvailableModels(accessToken, projectId, userAgentModel?) Source: https://github.com/anthonyhaussman/opencode-agy-auth Fetches available models for a project by POSTing the project ID. Throws an Error with status details on non-OK responses, and returns a FetchAvailableModelsResponse containing model information and related identifiers. ```APIDOC ## fetchAvailableModels(accessToken, projectId, userAgentModel?) ### Description Fetches available models for a project by POSTing the project ID. Throws an Error with status details on non-OK responses, and returns a FetchAvailableModelsResponse containing model information and related identifiers. ### Method POST ### Parameters #### Path Parameters - **accessToken** (string) - Required - Access token for authentication - **projectId** (string) - Required - The project identifier - **userAgentModel** (optional) - Optional - User agent model parameter #### Request Body - **project** (string) - Required - The project ID to fetch models for ### Response #### Success Response - **models** - Available models list - **defaultAgentModelId** - Default agent model identifier - **agentModelSorts** - Agent model sort order - **commandModelIds** - Command model identifiers - **tabModelIds** - Tab model identifiers - **imageGenerationModelIds** - Image generation model identifiers - **mqueryModelIds** - Mquery model identifiers - **webSearchModelIds** - Web search model identifiers - **deprecatedModelIds** - Deprecated model identifiers - **commitMessageModelIds** - Commit message model identifiers - **audioTranscriptionModelIds** - Audio transcription model identifiers - **experimentIds** - Experiment identifiers - **tieredModelIds** - Tiered model identifiers - **[key: string]: unknown** - Additional unknown properties ### Error Handling - **Non-OK status**: Throws `new Error("Google API returned status ${status} ${statusText}: ${details}")` - **Network error**: Propagates (no catch) ``` -------------------------------- ### Commit resume alpha changes Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/docs/release-promotion.md Commit the config and manifest changes to resume the alpha track. The next feat: or fix: on main opens a release PR for X.Y.Z+1-alpha.1 (or X.(Y+1).0-alpha.1 if a feat: lands). ```bash git add .release-please-config.json .release-please-manifest.json git commit -m "chore(release): resume alpha track from X.Y.Z" git push origin main ``` -------------------------------- ### Commit the promotion change Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/docs/release-promotion.md Stage and commit the one-line change to `.release-please-config.json` with the message `chore(release): promote to stable track`. ```bash git add .release-please-config.json git commit -m "chore(release): promote to stable track" ``` -------------------------------- ### Named export: defineOpenCodeV2Plugin Source: https://github.com/anthonyhaussman/opencode-agy-auth An identity helper for v2 plugin definitions. ```APIDOC ## Named export: defineOpenCodeV2Plugin ### Description An identity helper for v2 plugin definitions. ### Signature ```ts // from src/plugin/types.ts:83 ``` ``` -------------------------------- ### setOpenBrowserLauncherForTesting function signature Source: https://github.com/anthonyhaussman/opencode-agy-auth Replaces the module-level `openBrowserLauncher` for testing; pass `null` to restore the default. Under `NODE_ENV === 'test'` or `VITEST` with the default launcher, browser opening is skipped entirely. ```typescript export function setOpenBrowserLauncherForTesting(launcher: typeof openBrowserLauncher | null): void; ``` -------------------------------- ### Create streaming transformer with signature store Source: https://github.com/anthonyhaussman/opencode-agy-auth Imports SDK functions from './src/sdk/request/thinking.js' and sets up a signature store, decoder, and streaming transformer with callbacks for cache signatures and turn state updates. The transformer is applied to a response body stream. Note: hashString is sha256 truncated to 16 hex chars, matching SIGNATURE_TEXT_HASH_HEX_LEN. ```ts import { createSignatureStore, createStreamingTransformer, transformSseEvent, deduplicateThinkingText, cacheThinkingSignaturesFromResponse, } from "./src/sdk/request/thinking.js"; const store = createSignatureStore(); const decoder = new TextDecoder(); const transformer = createStreamingTransformer(store, { onCacheSignature: (key, text, sig) => console.log("cached", key, sig), onTurnStateUpdate: (key, state) => console.log(key, state), }, { signatureSessionKey: "sess-1", cacheSignatures: true }); const stream = new Response(readable).body!.pipeThrough(transformer); // consume stream... ``` -------------------------------- ### retrieveUserQuotaSummary(accessToken, projectId) Source: https://github.com/anthonyhaussman/opencode-agy-auth Retrieves a summary of user quota information for a project. Returns null silently on non-OK statuses and network errors. ```APIDOC ## retrieveUserQuotaSummary(accessToken, projectId) ### Description Retrieves a summary of user quota information for a project. Returns null silently on non-OK statuses and network errors. ### Parameters #### Path Parameters - **accessToken** (string) - Required - Access token for authentication - **projectId** (string) - Required - The project identifier ### Error Handling - **Non-OK status**: Returns `null` (silent) - **Network error**: Returns `null` ``` -------------------------------- ### Check pending dependency updates Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/AGENTS.md Run `npm outdated` to identify all pending patch, minor, and major updates. Upgrade outdated dependencies, evaluating breaking changes for majors like Vitest, `@opencode-ai/*`, `@ai-sdk/*`, `@types/node`. Run `npm test` immediately after upgrading to verify backward compatibility. ```bash npm outdated ``` -------------------------------- ### Change prerelease to false in .release-please-config.json Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/docs/release-promotion.md Edit the `packages."."` object in `.release-please-config.json` to set `"prerelease": false` instead of `true`. This switches release-please from the alpha prerelease track to the stable track. ```json "prerelease": true ``` ```json "prerelease": false ``` -------------------------------- ### POST {codeAssistEndpoint}/v1internal:retrieveUserQuotaSummary Source: https://github.com/anthonyhaussman/opencode-agy-auth Retrieves a summary of the user's quota information for a specified project. Returns grouped quota data with detailed bucket information including display names, windows, and remaining amounts. ```APIDOC ## [POST] {codeAssistEndpoint}/v1internal:retrieveUserQuotaSummary ### Description Retrieves a summary of the user's quota information for a specified project. Returns grouped quota data with detailed bucket information including display names, windows, and remaining amounts. ### Method POST ### Endpoint {codeAssistEndpoint}/v1internal:retrieveUserQuotaSummary ### Parameters #### Request Body - **project** (string) - Required - The project ID ### Response #### Success Response (200) - **groups** (array) - Optional - List of quota groups - **displayName** - Optional - **description** - Optional - **buckets** - Optional - **buckets** (array) - Optional - List of quota buckets - **bucketId** - Optional - **displayName** - Optional - **description** - Optional - **window** - Optional - **remaining** - Optional - **remainingFraction** - Optional - **remainingAmount** - Optional - **disabled** - Optional - **resetTime** - Optional - **description** (string) - Optional ### Errors Any non-OK status or network error returns null (silent). Consumed by resolveQuotaResetDelay for 429 retry planning. ``` -------------------------------- ### TurnStateTracker diskEnabled parameter Source: https://github.com/anthonyhaussman/opencode-agy-auth/blob/main/README.md Shows how to instantiate TurnStateTracker with disk persistence enabled (default) or disabled for memory-only mode. When diskEnabled is false, all state is lost on process exit, useful in restricted environments. ```typescript import { TurnStateTracker } from "@anthonyhaussman/opencode-agy-auth/sdk/request/turn-state-tracker"; // Disk persistence enabled (default) const tracker = new TurnStateTracker(true); // Memory-only mode - no filesystem reads or writes const tracker = new TurnStateTracker(false); ```