@justjoshn/pi-google-oauth-v2 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # pi-google-oauth-v2
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use a Google AI plan in Pi. The extension signs in with your Google account the way Google's Antigravity CLI does and sends requests to Code Assist, so they count against your plan's quota, not an API key.
4
+
5
+ ## Install
6
+
7
+ This extension needs Pi 1.5.2 or later. Install it with:
8
+
9
+ ```sh
10
+ pi install npm:@justjoshn/pi-google-oauth-v2
11
+ ```
12
+
13
+ To try it from this checkout, use `pi -e extensions/pi-google-oauth-v2`.
14
+
15
+ ## Sign in
16
+
17
+ 1. Start Pi and run `/login`.
18
+ 2. Select **Sign in with an account**, then **Google AI subscription**.
19
+ 3. Sign in in the browser with the Google account that has your plan.
20
+
21
+ Pi shows the plan tier and the Code Assist project that Google reports. Pi stores the tokens in `~/.pi/agent/auth.json` and refreshes them when they are about to expire.
22
+
23
+ If Pi runs on a machine without a browser, open the **Code page** link on another machine, sign in, and paste the code that the page shows.
24
+
25
+ `pi auth login` does not work for this provider. That command loads only Pi's built-in providers, not extension providers.
26
+
27
+ ## Pick a model
28
+
29
+ Run `/model` and pick a `google-oauth-v2` model. Pi asks Google for the models your plan serves and lists one entry per model family, such as `gemini-4-hydrogen` or `claude-sonnet-5-5`. Until the first refresh after sign-in, Pi lists `gemini-4-argon` and `gemini-3.8-flash`. Plan usage is not metered per token, so Pi shows no price.
30
+
31
+ Google serves each effort as its own model id, such as `gemini-4-hydrogen-high`. Pi's thinking level picks the id. Pi offers only the levels the family has, and no level sends `medium`. Google rejects a model it does not serve with its own error text, and Pi shows that text.
32
+
33
+ ## Set a project
34
+
35
+ Most personal accounts need no project. If `/login` fails and asks for `GOOGLE_CLOUD_PROJECT`, set it to your Google Cloud project ID (the string, not the number) and run `/login` again:
36
+
37
+ ```sh
38
+ GOOGLE_CLOUD_PROJECT=my-project-id pi
39
+ ```
40
+
41
+ Pi reads the variable only during `/login`. To change the project later, run `/login` again.
42
+
43
+ ## Plan support
44
+
45
+ Google's Antigravity documentation lists the Free, Google AI Pro, and Google AI Ultra plans. It does not list Google AI Plus. The extension does not block any plan. Google decides, and if it refuses your account, `/login` shows Google's message. If Google asks you to validate the account, `/login` shows the validation link. Validate the account in the browser, then run `/login` again.
46
+
47
+ ## How it works
48
+
49
+ Google retired Gemini CLI's OAuth client for individual plans. The extension now reuses the Antigravity CLI's public OAuth client and calls the same Code Assist endpoint, `daily-cloudcode-pa.googleapis.com/v1internal`, with the `User-Agent` and request shape that the Antigravity CLI sends. Google accepts a request only when it carries that `User-Agent`. Google can restrict this client, change the header it checks, or retire the endpoint without notice. If sign-in fails with a message that the client is no longer supported, Google changed the gate.
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@justjoshn/pi-google-oauth-v2",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Use a Google AI plan in Pi through its OAuth tokens, signing in as the Antigravity CLI.",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "license": "MIT",
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/just-joshn/pi-customizations.git",
15
+ "directory": "extensions/pi-google-oauth-v2"
16
+ },
17
+ "type": "module",
18
+ "engines": {
19
+ "node": ">=22.19.0"
20
+ },
21
+ "files": [
22
+ "src",
23
+ "!src/**/*.test.ts",
24
+ "README.md"
25
+ ],
26
+ "exports": {
27
+ ".": "./src/index.ts"
28
+ },
29
+ "pi": {
30
+ "extensions": [
31
+ "./src/index.ts"
32
+ ]
33
+ },
34
+ "scripts": {
35
+ "test": "vitest run",
36
+ "test:coverage": "vitest run --coverage",
37
+ "typecheck": "tsc -p ."
38
+ },
39
+ "peerDependencies": {
40
+ "@earendil-works/pi-ai": "*",
41
+ "@earendil-works/pi-coding-agent": "*"
42
+ },
43
+ "devDependencies": {
44
+ "@earendil-works/pi-ai": "1.5.2",
45
+ "@earendil-works/pi-coding-agent": "1.5.2",
46
+ "@types/node": "^22.19.0",
47
+ "@vitest/coverage-v8": "^5.0.2",
48
+ "typescript": "^7.0.2",
49
+ "vitest": "^5.0.2"
50
+ }
51
+ }
package/src/auth.ts ADDED
@@ -0,0 +1,155 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+
3
+ import type { FetchFunction, ModelAuth, OAuthAuth, OAuthCredential, ProviderAuthInteraction } from '@earendil-works/pi-ai';
4
+ import { readProjectOverride, resolveProject } from './code-assist.ts';
5
+ import { PRIVATE_PROJECT_HEADER } from './constants.ts';
6
+ import { LoopbackExpiredError, startLoopbackCallback } from './loopback.ts';
7
+
8
+ const ANTIGRAVITY_CLIENT_ID = '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com';
9
+ const ANTIGRAVITY_CLIENT_SECRET = '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';
10
+ const SCOPES = [
11
+ 'https://www.googleapis.com/auth/cloud-platform',
12
+ 'https://www.googleapis.com/auth/userinfo.email',
13
+ 'https://www.googleapis.com/auth/userinfo.profile',
14
+ 'https://www.googleapis.com/auth/cclog',
15
+ 'https://www.googleapis.com/auth/experimentsandconfigs',
16
+ 'https://www.googleapis.com/auth/aicode',
17
+ 'openid',
18
+ ];
19
+ const AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
20
+ const TOKEN_URL = 'https://oauth2.googleapis.com/token';
21
+ const MANUAL_REDIRECT_URI = 'https://antigravity.google/oauth-callback';
22
+
23
+ export type GoogleCredential = OAuthCredential & { projectId: string };
24
+
25
+ export interface GoogleOAuthDeps {
26
+ fetch?: FetchFunction;
27
+ env?: NodeJS.ProcessEnv;
28
+ }
29
+
30
+ class TokenRequestError extends Error {
31
+ readonly code: string;
32
+ constructor(code: string, description: string | undefined) {
33
+ super(`Google token request failed: ${code}${description ? `. ${description}` : ''}`);
34
+ this.code = code;
35
+ }
36
+ }
37
+
38
+ interface TokenResponse {
39
+ access_token: string;
40
+ expires_in: number;
41
+ refresh_token?: string;
42
+ }
43
+
44
+ export function createGoogleOAuth(deps: GoogleOAuthDeps = {}): OAuthAuth {
45
+ const fetchImpl: FetchFunction = (input, init) => (deps.fetch ?? globalThis.fetch)(input, init);
46
+ return {
47
+ name: 'Google AI subscription',
48
+ isSubscription: true,
49
+ loginLabel: 'Sign in with your Google AI plan',
50
+ login: (interaction) => login(interaction, fetchImpl, deps.env ?? process.env),
51
+ refresh: (credential, signal) => refresh(credential, signal, fetchImpl),
52
+ toAuth,
53
+ };
54
+ }
55
+
56
+ export function parseStoredCredential(credential: OAuthCredential): GoogleCredential {
57
+ const { access, refresh, expires, projectId } = credential;
58
+ if (typeof access !== 'string' || typeof refresh !== 'string' || typeof expires !== 'number' || !Number.isFinite(expires) || typeof projectId !== 'string' || !projectId) {
59
+ throw new Error('Google AI login is incomplete; run /login again');
60
+ }
61
+ return { ...credential, projectId };
62
+ }
63
+
64
+ export function buildAuthUrl(input: { redirectUri: string; state: string; codeChallenge: string }): string {
65
+ const params = new URLSearchParams({
66
+ client_id: ANTIGRAVITY_CLIENT_ID,
67
+ redirect_uri: input.redirectUri,
68
+ response_type: 'code',
69
+ scope: SCOPES.join(' '),
70
+ access_type: 'offline',
71
+ // Without prompt=consent Google omits refresh_token when the account already consented.
72
+ prompt: 'consent',
73
+ state: input.state,
74
+ code_challenge: input.codeChallenge,
75
+ code_challenge_method: 'S256',
76
+ });
77
+ return `${AUTH_URL}?${params}`;
78
+ }
79
+
80
+ async function postToken(body: Record<string, string>, fetchImpl: FetchFunction, signal: AbortSignal): Promise<TokenResponse> {
81
+ const response = await fetchImpl(TOKEN_URL, {
82
+ method: 'POST',
83
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
84
+ body: new URLSearchParams({ ...body, client_id: ANTIGRAVITY_CLIENT_ID, client_secret: ANTIGRAVITY_CLIENT_SECRET }),
85
+ signal,
86
+ });
87
+ const payload: unknown = await response.json().catch(() => undefined);
88
+ const fields = typeof payload === 'object' && payload !== null ? (payload as Record<string, unknown>) : {};
89
+ if (!response.ok) {
90
+ const description = fields['error_description'];
91
+ throw new TokenRequestError(typeof fields['error'] === 'string' ? fields['error'] : `HTTP ${response.status}`, typeof description === 'string' ? description : undefined);
92
+ }
93
+ const { access_token, expires_in, refresh_token } = fields;
94
+ if (typeof access_token !== 'string' || typeof expires_in !== 'number') throw new Error('Google token response was incomplete');
95
+ return { access_token, expires_in, ...(typeof refresh_token === 'string' && refresh_token ? { refresh_token } : {}) };
96
+ }
97
+
98
+ async function login(interaction: ProviderAuthInteraction, fetchImpl: FetchFunction, env: NodeJS.ProcessEnv): Promise<OAuthCredential> {
99
+ const envProject = readProjectOverride(env);
100
+ const verifier = randomBytes(32).toString('base64url');
101
+ const codeChallenge = createHash('sha256').update(verifier).digest('base64url');
102
+ const state = randomBytes(32).toString('hex');
103
+
104
+ const loopback = await startLoopbackCallback({ state, signal: interaction.signal });
105
+ const cancelPrompt = new AbortController();
106
+ try {
107
+ interaction.notify({
108
+ type: 'auth_url',
109
+ url: buildAuthUrl({ redirectUri: loopback.redirectUri, state, codeChallenge }),
110
+ instructions: 'Sign in with the Google account that has your AI plan.',
111
+ });
112
+ interaction.notify({
113
+ type: 'info',
114
+ message: 'No browser on this machine? Open the code page, then paste the code it shows.',
115
+ links: [{ url: buildAuthUrl({ redirectUri: MANUAL_REDIRECT_URI, state, codeChallenge }), label: 'Code page' }],
116
+ });
117
+ const pasted = interaction.prompt({ type: 'manual_code', message: 'Authorization code', signal: cancelPrompt.signal }).then((code) => ({ code: code.trim(), redirectUri: MANUAL_REDIRECT_URI }));
118
+ pasted.catch(() => undefined);
119
+ const callback = loopback.code.then(
120
+ (code) => ({ code, redirectUri: loopback.redirectUri }),
121
+ (error: unknown) => (error instanceof LoopbackExpiredError ? new Promise<never>(() => undefined) : Promise.reject(error)),
122
+ );
123
+ callback.catch(() => undefined);
124
+ const won = await Promise.race([callback, pasted]);
125
+ if (!won.code) throw new Error('No authorization code entered');
126
+
127
+ const tokens = await postToken({ grant_type: 'authorization_code', code: won.code, code_verifier: verifier, redirect_uri: won.redirectUri }, fetchImpl, interaction.signal);
128
+ if (!tokens.refresh_token) throw new Error('Google returned no refresh token; run /login again');
129
+
130
+ const project = await resolveProject({ accessToken: tokens.access_token, envProject, signal: interaction.signal, fetchImpl });
131
+ interaction.notify({ type: 'info', message: `Google AI plan: ${project.tierName || project.tierId}. Code Assist project: ${project.projectId}.` });
132
+ const credential: GoogleCredential = { type: 'oauth', access: tokens.access_token, refresh: tokens.refresh_token, expires: Date.now() + tokens.expires_in * 1000, projectId: project.projectId };
133
+ return credential;
134
+ } finally {
135
+ cancelPrompt.abort();
136
+ loopback.close();
137
+ }
138
+ }
139
+
140
+ async function refresh(credential: OAuthCredential, signal: AbortSignal, fetchImpl: FetchFunction): Promise<OAuthCredential> {
141
+ const stored = parseStoredCredential(credential);
142
+ try {
143
+ const tokens = await postToken({ grant_type: 'refresh_token', refresh_token: stored.refresh }, fetchImpl, signal);
144
+ // Google usually omits refresh_token on refresh, so the old one stays.
145
+ return { ...stored, type: 'oauth', access: tokens.access_token, expires: Date.now() + tokens.expires_in * 1000, refresh: tokens.refresh_token ?? stored.refresh };
146
+ } catch (error) {
147
+ if (error instanceof TokenRequestError && error.code === 'invalid_grant') throw new Error('Google refused the refresh token; run /login again');
148
+ throw error;
149
+ }
150
+ }
151
+
152
+ async function toAuth(credential: OAuthCredential): Promise<ModelAuth> {
153
+ const stored = parseStoredCredential(credential);
154
+ return { apiKey: stored.access, headers: { [PRIVATE_PROJECT_HEADER]: stored.projectId } };
155
+ }
@@ -0,0 +1,159 @@
1
+ import type { FetchFunction } from '@earendil-works/pi-ai';
2
+ import { ANTIGRAVITY_USER_AGENT, CODE_ASSIST_BASE_URL } from './constants.ts';
3
+
4
+ export class CodeAssistError extends Error {}
5
+
6
+ export class IneligibleTierError extends CodeAssistError {}
7
+
8
+ export class ValidationRequiredError extends CodeAssistError {
9
+ readonly validationUrl: string;
10
+ constructor(reasonMessage: string, validationUrl: string) {
11
+ super(`${reasonMessage} Validate at: ${validationUrl}`);
12
+ this.validationUrl = validationUrl;
13
+ }
14
+ }
15
+
16
+ export class ProjectRequiredError extends CodeAssistError {}
17
+
18
+ export interface ResolvedProject {
19
+ projectId: string;
20
+ tierId: string;
21
+ tierName: string;
22
+ }
23
+
24
+ export interface ResolveProjectInput {
25
+ accessToken: string;
26
+ envProject: string | undefined;
27
+ signal: AbortSignal;
28
+ fetchImpl: FetchFunction;
29
+ sleep?: (ms: number) => Promise<void>;
30
+ }
31
+
32
+ interface Tier {
33
+ id?: string;
34
+ name?: string;
35
+ isDefault?: boolean;
36
+ }
37
+
38
+ interface IneligibleTier {
39
+ reasonCode?: string;
40
+ reasonMessage?: string;
41
+ validationUrl?: string;
42
+ }
43
+
44
+ interface LoadCodeAssistResponse {
45
+ currentTier?: Tier | null;
46
+ allowedTiers?: Tier[] | null;
47
+ ineligibleTiers?: IneligibleTier[] | null;
48
+ cloudaicompanionProject?: string | null;
49
+ paidTier?: Tier | null;
50
+ }
51
+
52
+ interface Operation {
53
+ name?: string;
54
+ done?: boolean;
55
+ response?: { cloudaicompanionProject?: { id?: string } };
56
+ error?: { message?: string };
57
+ }
58
+
59
+ const METADATA = { ideType: 'ANTIGRAVITY' } as const;
60
+ const FREE_TIER = 'free-tier';
61
+ const LEGACY_TIER = 'legacy-tier';
62
+ const STANDARD_TIER = 'standard-tier';
63
+ const POLL_INTERVAL_MS = 5000;
64
+ const MAX_POLLS = 60;
65
+
66
+ export function readProjectOverride(env: NodeJS.ProcessEnv): string | undefined {
67
+ const value = (env['GOOGLE_CLOUD_PROJECT'] || env['GOOGLE_CLOUD_PROJECT_ID'] || '').trim();
68
+ if (!value) return undefined;
69
+ if (/^\d+$/.test(value)) throw new CodeAssistError('GOOGLE_CLOUD_PROJECT must be the project ID string, not its number');
70
+ return value;
71
+ }
72
+
73
+ export function codeAssistUrl(method: string): string {
74
+ return `${CODE_ASSIST_BASE_URL}:${method}`;
75
+ }
76
+
77
+ export function fetchAvailableModels(input: Pick<ResolveProjectInput, 'accessToken' | 'signal' | 'fetchImpl'> & { project: string }): Promise<unknown> {
78
+ return callCodeAssist<unknown>(input, 'POST', codeAssistUrl('fetchAvailableModels'), { project: input.project });
79
+ }
80
+
81
+ export async function resolveProject(input: ResolveProjectInput): Promise<ResolvedProject> {
82
+ const { envProject } = input;
83
+ const metadata = { ...METADATA, ...(envProject ? { duetProject: envProject } : {}) };
84
+
85
+ const load = await callCodeAssist<LoadCodeAssistResponse>(input, 'POST', codeAssistUrl('loadCodeAssist'), {
86
+ cloudaicompanionProject: envProject,
87
+ metadata,
88
+ });
89
+
90
+ if (!load.currentTier) {
91
+ const unsupported = load.ineligibleTiers?.find((tier) => tier.reasonCode === 'UNSUPPORTED_CLIENT');
92
+ if (unsupported) throw new IneligibleTierError(unsupported.reasonMessage ?? 'Google rejected this client (UNSUPPORTED_CLIENT).');
93
+ const validation = load.ineligibleTiers?.find((tier) => tier.reasonCode === 'VALIDATION_REQUIRED' && tier.validationUrl);
94
+ if (validation?.validationUrl) throw new ValidationRequiredError(validation.reasonMessage ?? 'Account validation required.', validation.validationUrl);
95
+ }
96
+
97
+ if (load.currentTier) {
98
+ const projectId = load.cloudaicompanionProject || envProject;
99
+ if (!projectId) throw missingProject(load);
100
+ return {
101
+ projectId,
102
+ tierId: load.paidTier?.id ?? load.currentTier.id ?? STANDARD_TIER,
103
+ tierName: load.paidTier?.name ?? load.currentTier.name ?? '',
104
+ };
105
+ }
106
+
107
+ const tier = load.allowedTiers?.find((candidate) => candidate.isDefault) ?? { id: LEGACY_TIER, name: '' };
108
+ const tierId = tier.id ?? STANDARD_TIER;
109
+ // The free tier uses a managed project. Sending one makes Google answer Precondition Failed.
110
+ const onboard = tierId === FREE_TIER ? { tierId, metadata: METADATA } : { tierId, cloudaicompanionProject: envProject, metadata };
111
+ let operation = await callCodeAssist<Operation>(input, 'POST', codeAssistUrl('onboardUser'), onboard);
112
+
113
+ const sleep = input.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
114
+ for (let polls = 0; !operation.done && operation.name; polls++) {
115
+ if (polls === MAX_POLLS) throw new CodeAssistError('Google Code Assist onboarding did not finish in time; run /login again');
116
+ await sleep(POLL_INTERVAL_MS);
117
+ operation = await callCodeAssist<Operation>(input, 'GET', `${CODE_ASSIST_BASE_URL}/${operation.name}`);
118
+ }
119
+ if (operation.error) throw new CodeAssistError(operation.error.message ?? 'Google Code Assist onboarding failed');
120
+
121
+ const projectId = operation.response?.cloudaicompanionProject?.id || envProject;
122
+ if (!projectId) throw missingProject(load);
123
+ return { projectId, tierId, tierName: tier.name ?? '' };
124
+ }
125
+
126
+ function missingProject(load: LoadCodeAssistResponse): CodeAssistError {
127
+ const reasons = (load.ineligibleTiers ?? []).map((tier) => tier.reasonMessage).filter((message): message is string => Boolean(message));
128
+ if (reasons.length > 0) return new IneligibleTierError(reasons.join(', '));
129
+ return new ProjectRequiredError('This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable, then running /login again');
130
+ }
131
+
132
+ async function callCodeAssist<T>(input: Pick<ResolveProjectInput, 'accessToken' | 'signal' | 'fetchImpl'>, method: 'GET' | 'POST', url: string, body?: object): Promise<T> {
133
+ const response = await input.fetchImpl(url, {
134
+ method,
135
+ headers: { Authorization: `Bearer ${input.accessToken}`, 'Content-Type': 'application/json', 'User-Agent': ANTIGRAVITY_USER_AGENT },
136
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
137
+ signal: input.signal,
138
+ });
139
+ const text = await response.text();
140
+ if (!response.ok) throw new CodeAssistError(googleErrorMessage(text) ?? `Google Code Assist request failed (HTTP ${response.status})`);
141
+ try {
142
+ return JSON.parse(text) as T;
143
+ } catch {
144
+ throw new CodeAssistError('Google Code Assist returned a response that is not JSON');
145
+ }
146
+ }
147
+
148
+ export function googleErrorMessage(text: string): string | undefined {
149
+ try {
150
+ const parsed: unknown = JSON.parse(text);
151
+ if (typeof parsed === 'object' && parsed !== null && 'error' in parsed) {
152
+ const { error } = parsed;
153
+ if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string' && error.message) return error.message;
154
+ }
155
+ } catch {
156
+ return undefined;
157
+ }
158
+ return undefined;
159
+ }
@@ -0,0 +1,16 @@
1
+ export const PROVIDER_ID = 'google-oauth-v2';
2
+ export const PROVIDER_DISPLAY_NAME = 'Google AI subscription';
3
+ export const API_ID = 'google-code-assist';
4
+ // Consumer plans are served by the daily ring. Production cloudcode-pa returns 429 RESOURCE_EXHAUSTED to them.
5
+ export const CODE_ASSIST_BASE_URL = 'https://daily-cloudcode-pa.googleapis.com/v1internal';
6
+ export const PRIVATE_PROJECT_HEADER = 'x-pi-google-oauth-v2-project';
7
+
8
+ const OS_TYPES: Record<string, string> = { darwin: 'darwin', linux: 'linux', win32: 'windows' };
9
+ const ARCHITECTURES: Record<string, string> = { arm64: 'arm64', x64: 'amd64' };
10
+
11
+ export function antigravityUserAgent(platform: string = process.platform, arch: string = process.arch): string {
12
+ return `antigravity/cli/1.5.9 (aidev_client; os_type=${OS_TYPES[platform] ?? platform}; arch=${ARCHITECTURES[arch] ?? arch}; cl=1021519450; auth_method=consumer)`;
13
+ }
14
+
15
+ // Google rejects a Code Assist request without this header as UNSUPPORTED_CLIENT, so every call must send it.
16
+ export const ANTIGRAVITY_USER_AGENT = antigravityUserAgent();
package/src/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { createProvider } from '@earendil-works/pi-ai';
2
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
3
+ import { createGoogleOAuth } from './auth.ts';
4
+ import { CODE_ASSIST_BASE_URL, PROVIDER_DISPLAY_NAME, PROVIDER_ID } from './constants.ts';
5
+ import { BASELINE_MODELS, createFetchModels } from './models.ts';
6
+ import { streamCodeAssist } from './stream.ts';
7
+
8
+ /** Registers the provider only. The factory starts no listener, timer, or request. */
9
+ export default function (pi: ExtensionAPI): void {
10
+ pi.registerProvider(
11
+ createProvider({
12
+ id: PROVIDER_ID,
13
+ name: PROVIDER_DISPLAY_NAME,
14
+ baseUrl: CODE_ASSIST_BASE_URL,
15
+ auth: { oauth: createGoogleOAuth() },
16
+ models: BASELINE_MODELS,
17
+ fetchModels: createFetchModels(),
18
+ api: { stream: streamCodeAssist, streamSimple: streamCodeAssist },
19
+ }),
20
+ );
21
+ }
@@ -0,0 +1,90 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import type { AddressInfo } from 'node:net';
4
+
5
+ export interface LoopbackCallback {
6
+ readonly redirectUri: string;
7
+ readonly code: Promise<string>;
8
+ close(): void;
9
+ }
10
+
11
+ /** The listener ended without a verdict from Google or the user, so another sign-in path may still finish. */
12
+ export class LoopbackExpiredError extends Error {}
13
+
14
+ export const LOOPBACK_TIMEOUT_MS = 5 * 60 * 1000;
15
+
16
+ const CALLBACK_PATH = '/oauth2callback';
17
+
18
+ function statesMatch(received: string | null, expected: string): boolean {
19
+ if (received === null) return false;
20
+ const a = Buffer.from(received);
21
+ const b = Buffer.from(expected);
22
+ return a.length === b.length && timingSafeEqual(a, b);
23
+ }
24
+
25
+ export async function startLoopbackCallback(input: { state: string; signal: AbortSignal }): Promise<LoopbackCallback> {
26
+ let resolve!: (code: string) => void;
27
+ let reject!: (error: Error) => void;
28
+ const code = new Promise<string>((onCode, onError) => {
29
+ resolve = onCode;
30
+ reject = onError;
31
+ });
32
+ code.catch(() => undefined);
33
+
34
+ const server = createServer((request, response) => {
35
+ const url = new URL(request.url ?? '/', 'http://127.0.0.1');
36
+ if (url.pathname !== CALLBACK_PATH) {
37
+ response.writeHead(404).end();
38
+ return;
39
+ }
40
+ if (!statesMatch(url.searchParams.get('state'), input.state)) {
41
+ response.writeHead(400, { 'Content-Type': 'text/plain' }).end('Invalid state');
42
+ return;
43
+ }
44
+ const error = url.searchParams.get('error');
45
+ const authorizationCode = url.searchParams.get('code');
46
+ if (!error && authorizationCode) {
47
+ resolve(authorizationCode);
48
+ response.writeHead(200, { 'Content-Type': 'text/plain' }).end('Signed in. You can close this tab and return to Pi.', close);
49
+ return;
50
+ }
51
+ const description = url.searchParams.get('error_description');
52
+ reject(new Error(error ? `Google sign-in failed: ${error}${description ? `. ${description}` : ''}` : 'Google sign-in returned no authorization code'));
53
+ response.writeHead(400, { 'Content-Type': 'text/plain' }).end('Sign-in failed. Return to Pi.', close);
54
+ });
55
+
56
+ const timer = setTimeout(() => {
57
+ reject(new LoopbackExpiredError('Google sign-in timed out'));
58
+ close();
59
+ }, LOOPBACK_TIMEOUT_MS);
60
+ const onAbort = () => {
61
+ reject(new Error('Google sign-in was cancelled'));
62
+ close();
63
+ };
64
+ input.signal.addEventListener('abort', onAbort, { once: true });
65
+
66
+ let closed = false;
67
+ function close(): void {
68
+ if (closed) return;
69
+ closed = true;
70
+ clearTimeout(timer);
71
+ input.signal.removeEventListener('abort', onAbort);
72
+ reject(new LoopbackExpiredError('Google sign-in listener closed'));
73
+ server.closeAllConnections();
74
+ server.close();
75
+ }
76
+
77
+ try {
78
+ await new Promise<void>((onListening, onError) => {
79
+ server.once('error', onError);
80
+ server.listen(0, '127.0.0.1', onListening);
81
+ });
82
+ } catch (error) {
83
+ close();
84
+ throw error;
85
+ }
86
+ const { port } = server.address() as AddressInfo;
87
+ if (input.signal.aborted) onAbort();
88
+
89
+ return { redirectUri: `http://127.0.0.1:${port}${CALLBACK_PATH}`, code, close };
90
+ }
package/src/models.ts ADDED
@@ -0,0 +1,107 @@
1
+ import type { Model, ModelThinkingLevel, RefreshModelsContext, ThinkingLevelMap } from '@earendil-works/pi-ai';
2
+ import { parseStoredCredential } from './auth.ts';
3
+ import { fetchAvailableModels } from './code-assist.ts';
4
+ import { API_ID, CODE_ASSIST_BASE_URL, PROVIDER_ID } from './constants.ts';
5
+
6
+ const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const;
7
+ type Effort = (typeof EFFORTS)[number];
8
+ const EFFORT_SUFFIX = new RegExp(`-(${EFFORTS.join('|')})$`);
9
+ const EFFORT_LABEL = / \((Low|Medium|High|XHigh|Max)\)$/;
10
+ // Pi offers a level unless its map entry is null, and Google has no wire id for these.
11
+ const LEVELS_WITHOUT_WIRE_ID: ModelThinkingLevel[] = ['off', 'minimal', 'low', 'medium', 'high'];
12
+
13
+ interface CatalogModel {
14
+ displayName?: string;
15
+ supportsImages?: boolean;
16
+ supportsThinking?: boolean;
17
+ maxTokens?: number;
18
+ maxOutputTokens?: number;
19
+ }
20
+
21
+ /** The slice of Code Assist's `fetchAvailableModels` response that the extension reads. */
22
+ export interface Catalog {
23
+ models?: Record<string, CatalogModel>;
24
+ agentModelSorts?: { groups?: { modelIds?: string[] }[] }[];
25
+ }
26
+
27
+ interface Variant {
28
+ wireId: string;
29
+ effort: Effort;
30
+ info: CatalogModel;
31
+ }
32
+
33
+ type CodeAssistModel = Model<typeof API_ID>;
34
+
35
+ function splitWireId(wireId: string): { base: string; effort: Effort } {
36
+ const match = EFFORT_SUFFIX.exec(wireId);
37
+ if (!match) return { base: wireId, effort: 'medium' };
38
+ return { base: wireId.slice(0, match.index), effort: match[1] as Effort };
39
+ }
40
+
41
+ function thinkingLevelMap(variants: Variant[], reasoning: boolean): ThinkingLevelMap {
42
+ if (!reasoning) return { off: (variants.find((variant) => variant.effort === 'medium') ?? variants[0])?.wireId ?? null };
43
+ const map: ThinkingLevelMap = {};
44
+ for (const level of LEVELS_WITHOUT_WIRE_ID) map[level] = null;
45
+ for (const variant of variants) map[variant.effort] = variant.wireId;
46
+ return map;
47
+ }
48
+
49
+ /** One Pi model per base family. Its thinking levels map to Google's per-effort wire ids. */
50
+ export function catalogModels(catalog: Catalog): CodeAssistModel[] {
51
+ const families = new Map<string, Variant[]>();
52
+ const shown = new Set((catalog.agentModelSorts ?? []).flatMap((sort) => (sort.groups ?? []).flatMap((group) => group.modelIds ?? [])));
53
+ for (const wireId of shown) {
54
+ const info = catalog.models?.[wireId];
55
+ if (!info || wireId.endsWith('-disabled')) continue;
56
+ const { base, effort } = splitWireId(wireId);
57
+ families.set(base, [...(families.get(base) ?? []), { wireId, effort, info }]);
58
+ }
59
+
60
+ return [...families].map(([id, variants]) => {
61
+ const reasoning = variants.some((variant) => variant.info.supportsThinking);
62
+ const first = variants[0]?.info;
63
+ return {
64
+ id,
65
+ name: (first?.displayName ?? id).replace(EFFORT_LABEL, ''),
66
+ api: API_ID,
67
+ provider: PROVIDER_ID,
68
+ baseUrl: CODE_ASSIST_BASE_URL,
69
+ reasoning,
70
+ input: variants.some((variant) => variant.info.supportsImages) ? ['text', 'image'] : ['text'],
71
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
72
+ contextWindow: Math.max(...variants.map((variant) => variant.info.maxTokens ?? 0)),
73
+ maxTokens: Math.max(...variants.map((variant) => variant.info.maxOutputTokens ?? 0)),
74
+ thinkingLevelMap: thinkingLevelMap(variants, reasoning),
75
+ };
76
+ });
77
+ }
78
+
79
+ const BASELINE_FAMILIES = [
80
+ ['gemini-4-argon', 'Gemini 4 Argon'],
81
+ ['gemini-3.8-flash', 'Gemini 3.8 Flash'],
82
+ ] as const;
83
+ const BASELINE_EFFORTS = [
84
+ ['low', 'Low'],
85
+ ['medium', 'Medium'],
86
+ ['high', 'High'],
87
+ ] as const;
88
+ const baselineWireIds = BASELINE_FAMILIES.flatMap(([id]) => BASELINE_EFFORTS.map(([effort]) => `${id}-${effort}`));
89
+
90
+ // Shown until the first live refresh. A live model with the same id replaces its entry.
91
+ export const BASELINE_MODELS: CodeAssistModel[] = catalogModels({
92
+ models: Object.fromEntries(
93
+ BASELINE_FAMILIES.flatMap(([id, name]) => BASELINE_EFFORTS.map(([effort, label]) => [`${id}-${effort}`, { displayName: `${name} (${label})`, supportsImages: true, supportsThinking: true, maxTokens: 1048576, maxOutputTokens: 65536 }])),
94
+ ),
95
+ agentModelSorts: [{ groups: [{ modelIds: baselineWireIds }] }],
96
+ });
97
+
98
+ export function createFetchModels(fetchImpl: typeof fetch = globalThis.fetch): (context: RefreshModelsContext) => Promise<CodeAssistModel[]> {
99
+ return async (context) => {
100
+ if (!context.allowNetwork || context.credential?.type !== 'oauth') return BASELINE_MODELS;
101
+ const { access, projectId } = parseStoredCredential(context.credential);
102
+ const catalog = (await fetchAvailableModels({ accessToken: access, project: projectId, signal: context.signal, fetchImpl })) as Catalog;
103
+ const models = catalogModels(catalog);
104
+ if (models.length === 0) throw new Error('Google returned no models for this account');
105
+ return models;
106
+ };
107
+ }
package/src/request.ts ADDED
@@ -0,0 +1,190 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ import { type Api, clampThinkingLevel, getCurrentSystemPrompt, getCurrentTools, type Model, type ModelThinkingLevel, type SimpleStreamOptions, type ToolCall, type TranscriptContext, toToolDeclaration } from '@earendil-works/pi-ai';
4
+
5
+ interface WirePart {
6
+ text?: string;
7
+ thought?: boolean;
8
+ thoughtSignature?: string;
9
+ inlineData?: { mimeType: string; data: string };
10
+ functionCall?: { id?: string; name: string; args: object };
11
+ functionResponse?: { id?: string; name: string; response: { output: string } | { error: string }; parts?: WirePart[] };
12
+ }
13
+
14
+ interface WireContent {
15
+ role: 'user' | 'model';
16
+ parts: WirePart[];
17
+ }
18
+
19
+ export interface CodeAssistRequestBody {
20
+ model: string;
21
+ project: string;
22
+ requestId: string;
23
+ userAgent: 'antigravity';
24
+ requestType: 'agent';
25
+ request: {
26
+ contents: WireContent[];
27
+ systemInstruction?: { role: 'user'; parts: WirePart[] };
28
+ tools?: { functionDeclarations: { name: string; description: string; parametersJsonSchema: unknown }[] }[];
29
+ toolConfig?: { functionCallingConfig: { mode: 'NONE' } };
30
+ generationConfig: { temperature?: number; maxOutputTokens?: number; thinkingConfig?: { includeThoughts: true; thinkingLevel: string } };
31
+ sessionId?: string;
32
+ };
33
+ }
34
+
35
+ const THINKING_LEVEL: Record<ModelThinkingLevel, string | undefined> = { off: undefined, minimal: 'LOW', low: 'LOW', medium: 'MEDIUM', high: 'HIGH', xhigh: 'HIGH', max: 'HIGH' };
36
+ // Code Assist answers 429 RESOURCE_EXHAUSTED to any system prompt saying it runs "inside pi"; the same prompt without the clause gets a 200.
37
+ const PI_HARNESS_CLAUSE = / running inside pi(?:, a coding agent harness)?(?=[.,])/gi;
38
+ const THOUGHT_SIGNATURE = /^[A-Za-z0-9+/]+={0,2}$/;
39
+ const JSON_SCHEMA_NAME_MAPS = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas', 'dependencies']);
40
+ const JSON_SCHEMA_SUBSCHEMAS = new Set([
41
+ 'additionalProperties',
42
+ 'unevaluatedProperties',
43
+ 'propertyNames',
44
+ 'items',
45
+ 'prefixItems',
46
+ 'additionalItems',
47
+ 'unevaluatedItems',
48
+ 'contains',
49
+ 'allOf',
50
+ 'anyOf',
51
+ 'oneOf',
52
+ 'not',
53
+ 'if',
54
+ 'then',
55
+ 'else',
56
+ 'contentSchema',
57
+ ]);
58
+
59
+ export function buildCodeAssistRequest(input: { model: Model<Api>; context: TranscriptContext; project: string; options: SimpleStreamOptions }): CodeAssistRequestBody {
60
+ const { model, context, project, options } = input;
61
+ const systemPrompt = getCurrentSystemPrompt(context.messages);
62
+ const tools = getCurrentTools(context.messages);
63
+ const level = clampThinkingLevel(model, options.reasoning ?? 'medium');
64
+ const thinkingLevel = THINKING_LEVEL[level];
65
+
66
+ return {
67
+ model: model.thinkingLevelMap?.[level] ?? model.id,
68
+ project,
69
+ requestId: randomUUID(),
70
+ userAgent: 'antigravity',
71
+ requestType: 'agent',
72
+ request: {
73
+ contents: convertMessages(model, context),
74
+ ...(systemPrompt ? { systemInstruction: { role: 'user' as const, parts: [{ text: scrub(systemPrompt.replace(PI_HARNESS_CLAUSE, '')) }] } } : {}),
75
+ ...(tools.length > 0
76
+ ? {
77
+ tools: [
78
+ {
79
+ functionDeclarations: tools.map((tool) => {
80
+ const declaration = toToolDeclaration(tool);
81
+ return { name: declaration.name, description: declaration.description, parametersJsonSchema: constToEnum(declaration.parameters) };
82
+ }),
83
+ },
84
+ ],
85
+ }
86
+ : {}),
87
+ ...(tools.length > 0 && options.toolChoice === 'none' ? { toolConfig: { functionCallingConfig: { mode: 'NONE' as const } } } : {}),
88
+ generationConfig: {
89
+ ...(options.temperature === undefined ? {} : { temperature: options.temperature }),
90
+ ...(options.maxTokens === undefined ? {} : { maxOutputTokens: options.maxTokens }),
91
+ ...(thinkingLevel ? { thinkingConfig: { includeThoughts: true as const, thinkingLevel } } : {}),
92
+ },
93
+ ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),
94
+ },
95
+ };
96
+ }
97
+
98
+ function scrub(text: string): string {
99
+ return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, '');
100
+ }
101
+
102
+ function geminiMajorVersion(modelId: string): number | undefined {
103
+ const match = /^gemini-(\d+)/.exec(modelId.toLowerCase());
104
+ return match?.[1] === undefined ? undefined : Number.parseInt(match[1], 10);
105
+ }
106
+
107
+ function convertMessages(model: Model<Api>, context: TranscriptContext): WireContent[] {
108
+ const major = geminiMajorVersion(model.id);
109
+ const needsCallIds = major !== undefined && major >= 3;
110
+ // Code Assist matches a functionResponse to its functionCall by this id on Gemini 3+, so both sides must sanitize identically.
111
+ const wireId = (id: string): { id?: string } => (needsCallIds ? { id: id.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64) } : {});
112
+ const contents: WireContent[] = [];
113
+ let pending: ToolCall[] = [];
114
+ const answered = new Set<string>();
115
+ // Code Assist wants every functionResponse of a round in one user turn, so Gemini 2.x image turns wait until the round ends.
116
+ const imageTurns: WireContent[] = [];
117
+
118
+ const pushToolResponse = (part: NonNullable<WirePart['functionResponse']>, trailingImages: WirePart[] = []): void => {
119
+ const last = contents.at(-1);
120
+ if (last?.role === 'user' && last.parts.some((candidate) => candidate.functionResponse)) last.parts.push({ functionResponse: part });
121
+ else contents.push({ role: 'user', parts: [{ functionResponse: part }] });
122
+ if (trailingImages.length > 0) imageTurns.push({ role: 'user', parts: [{ text: 'Tool result image:' }, ...trailingImages] });
123
+ };
124
+ // A functionCall without a functionResponse makes Code Assist reject the whole request.
125
+ const answerOrphans = (): void => {
126
+ for (const call of pending) {
127
+ if (!answered.has(call.id)) pushToolResponse({ ...wireId(call.id), name: call.name, response: { error: 'No result provided' } });
128
+ }
129
+ pending = [];
130
+ answered.clear();
131
+ contents.push(...imageTurns.splice(0));
132
+ };
133
+
134
+ for (const message of context.messages) {
135
+ if (message.role === 'user') {
136
+ answerOrphans();
137
+ const parts: WirePart[] =
138
+ typeof message.content === 'string' ? [{ text: scrub(message.content) }] : message.content.map((block) => (block.type === 'text' ? { text: scrub(block.text) } : { inlineData: { mimeType: block.mimeType, data: block.data } }));
139
+ if (parts.length > 0) contents.push({ role: 'user', parts });
140
+ } else if (message.role === 'assistant') {
141
+ answerOrphans();
142
+ if (message.stopReason === 'error' || message.stopReason === 'aborted') continue;
143
+ const sameModel = message.provider === model.provider && message.api === model.api && message.model === model.id;
144
+ const signed = (signature: string | undefined): { thoughtSignature?: string } => (sameModel && signature && signature.length % 4 === 0 && THOUGHT_SIGNATURE.test(signature) ? { thoughtSignature: signature } : {});
145
+ const parts: WirePart[] = [];
146
+ for (const block of message.content) {
147
+ if (block.type === 'text') {
148
+ const signature = signed(block.textSignature);
149
+ if (block.text.trim() || signature.thoughtSignature) parts.push({ text: scrub(block.text), ...signature });
150
+ } else if (block.type === 'thinking') {
151
+ if (!sameModel) continue;
152
+ const signature = signed(block.thinkingSignature);
153
+ if (block.thinking.trim() || signature.thoughtSignature) parts.push({ thought: true, text: scrub(block.thinking), ...signature });
154
+ } else {
155
+ parts.push({ functionCall: { ...wireId(block.id), name: block.name, args: block.arguments }, ...signed(block.thoughtSignature) });
156
+ }
157
+ }
158
+ pending = message.content.filter((block): block is ToolCall => block.type === 'toolCall');
159
+ if (parts.length > 0) contents.push({ role: 'model', parts });
160
+ } else if (message.role === 'toolResult') {
161
+ answered.add(message.toolCallId);
162
+ const text = message.content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join('\n');
163
+ const images: WirePart[] = message.content.flatMap((block) => (block.type === 'image' && model.input.includes('image') ? [{ inlineData: { mimeType: block.mimeType, data: block.data } }] : []));
164
+ const value = text.trim() ? scrub(text) : images.length > 0 ? '(see attached image)' : '';
165
+ const nested = major === undefined || major >= 3;
166
+ pushToolResponse({ ...wireId(message.toolCallId), name: message.toolName, response: message.isError ? { error: value } : { output: value }, ...(images.length > 0 && nested ? { parts: images } : {}) }, nested ? [] : images);
167
+ }
168
+ }
169
+ answerOrphans();
170
+ return contents;
171
+ }
172
+
173
+ /** Gemini ignores `const` inside parametersJsonSchema but honors a single-value `enum`. */
174
+ function constToEnum(schema: unknown, isNameMap = false): unknown {
175
+ if (Array.isArray(schema)) return schema.map((item) => constToEnum(item));
176
+ if (typeof schema !== 'object' || schema === null) return schema;
177
+ const rewritten: Record<string, unknown> = Object.fromEntries(
178
+ Object.entries(schema).map(([key, value]) => {
179
+ if (isNameMap || JSON_SCHEMA_SUBSCHEMAS.has(key)) return [key, constToEnum(value)];
180
+ if (JSON_SCHEMA_NAME_MAPS.has(key)) return [key, constToEnum(value, true)];
181
+ return [key, value];
182
+ }),
183
+ );
184
+ const constant = rewritten['const'];
185
+ if (!isNameMap && rewritten['enum'] === undefined && (typeof constant === 'string' || typeof constant === 'number')) {
186
+ const { const: _, ...rest } = rewritten;
187
+ return { ...rest, enum: [constant] };
188
+ }
189
+ return rewritten;
190
+ }
package/src/stream.ts ADDED
@@ -0,0 +1,294 @@
1
+ import {
2
+ type Api,
3
+ type AssistantMessage,
4
+ type AssistantMessageEventStream,
5
+ calculateCost,
6
+ createAssistantMessageEventStream,
7
+ type Model,
8
+ type SimpleStreamOptions,
9
+ type ToolCall,
10
+ type TranscriptContext,
11
+ uuidv7,
12
+ } from '@earendil-works/pi-ai';
13
+ import { CodeAssistError, googleErrorMessage } from './code-assist.ts';
14
+ import { ANTIGRAVITY_USER_AGENT, PRIVATE_PROJECT_HEADER } from './constants.ts';
15
+ import { buildCodeAssistRequest } from './request.ts';
16
+
17
+ interface CodeAssistChunk {
18
+ response?: {
19
+ candidates?: { content?: { parts?: ResponsePart[] }; finishReason?: string; finishMessage?: string }[];
20
+ usageMetadata?: { promptTokenCount?: number; cachedContentTokenCount?: number; candidatesTokenCount?: number; thoughtsTokenCount?: number; totalTokenCount?: number };
21
+ modelVersion?: string;
22
+ promptFeedback?: { blockReason?: string; blockReasonMessage?: string };
23
+ };
24
+ traceId?: string;
25
+ error?: { message?: string };
26
+ }
27
+
28
+ interface ResponsePart {
29
+ text?: string;
30
+ thought?: boolean;
31
+ thoughtSignature?: string;
32
+ functionCall?: { id?: string; name?: string; args?: ToolCall['arguments'] };
33
+ }
34
+
35
+ const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
36
+
37
+ // Google returns 429 RESOURCE_EXHAUSTED for a short-term capacity limit, so retry with the server's delay.
38
+ function retryDelayMs(body: string, headers: Headers): number | undefined {
39
+ const retryAfter = headers.get('retry-after');
40
+ if (retryAfter) {
41
+ const seconds = Number(retryAfter);
42
+ if (Number.isFinite(seconds)) return seconds * 1000;
43
+ const when = Date.parse(retryAfter);
44
+ if (!Number.isNaN(when)) return Math.max(0, when - Date.now());
45
+ }
46
+ const hinted = body.match(/"retryDelay":\s*"([0-9.]+)s"/i) ?? body.match(/retry in ([0-9.]+)\s*s/i);
47
+ return hinted?.[1] ? Number(hinted[1]) * 1000 : undefined;
48
+ }
49
+
50
+ function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
51
+ return new Promise((resolve, reject) => {
52
+ if (signal?.aborted) return reject(new Error('Request was aborted'));
53
+ const timer = setTimeout(resolve, ms);
54
+ signal?.addEventListener(
55
+ 'abort',
56
+ () => {
57
+ clearTimeout(timer);
58
+ reject(new Error('Request was aborted'));
59
+ },
60
+ { once: true },
61
+ );
62
+ });
63
+ }
64
+
65
+ /**
66
+ * Serves both stream and streamSimple. Never throws: every failure, including a missing token or
67
+ * project, ends the stream with an `error` event.
68
+ */
69
+ export function streamCodeAssist(model: Model<Api>, context: TranscriptContext, options: SimpleStreamOptions = {}): AssistantMessageEventStream {
70
+ const stream = createAssistantMessageEventStream();
71
+ const output: AssistantMessage = {
72
+ role: 'assistant',
73
+ content: [],
74
+ api: model.api,
75
+ provider: model.provider,
76
+ model: model.id,
77
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
78
+ stopReason: 'pending',
79
+ timestamp: Date.now(),
80
+ };
81
+
82
+ (async () => {
83
+ try {
84
+ const { project, headers } = takePrivateProjectHeader(options.headers);
85
+ if (!options.apiKey || !project) throw new Error('Google AI login is incomplete; run /login again');
86
+
87
+ let body: unknown = buildCodeAssistRequest({ model, context, project, options });
88
+ body = (await options.onPayload?.(body, model)) ?? body;
89
+
90
+ const doFetch = options.fetch ?? globalThis.fetch;
91
+ const url = `${model.baseUrl}:streamGenerateContent?alt=sse`;
92
+ const init: RequestInit = {
93
+ method: 'POST',
94
+ headers: { Authorization: `Bearer ${options.apiKey}`, 'Content-Type': 'application/json', Accept: 'text/event-stream', ...headers, 'User-Agent': ANTIGRAVITY_USER_AGENT },
95
+ body: JSON.stringify(body),
96
+ ...(options.signal ? { signal: options.signal } : {}),
97
+ };
98
+ const baseRetries = options.maxRetries ?? 0;
99
+ const maxRetryDelayMs = options.maxRetryDelayMs ?? 60_000;
100
+ let response: Response;
101
+ for (let attempt = 0; ; attempt++) {
102
+ response = await doFetch(url, init);
103
+ await options.onResponse?.({ status: response.status, headers: Object.fromEntries(response.headers) }, model);
104
+ if (response.ok) break;
105
+ const text = await response.text().catch(() => '');
106
+ const message = googleErrorMessage(text) ?? (response.statusText || 'request failed');
107
+ const quotaExhausted = /QUOTA_EXHAUSTED|Individual quota reached/i.test(text);
108
+ const capacityThrottle = response.status === 429 && !quotaExhausted;
109
+ if (!RETRYABLE_STATUS.has(response.status) || quotaExhausted || attempt >= baseRetries) {
110
+ // Google says "check quota" for a shared-capacity throttle too, which misreads as the user's own quota.
111
+ if (capacityThrottle) throw new Error('Google Code Assist is temporarily at capacity (429). This is shared capacity, not your plan quota. Try again in a moment.');
112
+ throw new Error(`Google Code Assist error (${response.status}): ${message}`);
113
+ }
114
+ const delay = Math.min(retryDelayMs(text, response.headers) ?? 1000 * 2 ** attempt, maxRetryDelayMs);
115
+ await sleep(delay, options.signal);
116
+ }
117
+
118
+ stream.push({ type: 'start', partial: output });
119
+ const reducer = new ResponseReducer(stream, output, model);
120
+ for await (const chunk of parseSse(response.body, options.signal)) {
121
+ await options.onProviderStreamEvent?.(chunk, model);
122
+ reducer.push(chunk);
123
+ }
124
+ if (options.signal?.aborted) throw new Error('Request was aborted');
125
+ reducer.finish();
126
+ stream.push({ type: 'done', reason: output.stopReason === 'toolUse' || output.stopReason === 'length' ? output.stopReason : 'stop', message: output });
127
+ } catch (error) {
128
+ output.stopReason = options.signal?.aborted ? 'aborted' : 'error';
129
+ output.errorMessage = error instanceof Error ? error.message : String(error);
130
+ stream.push({ type: 'error', reason: output.stopReason, error: output });
131
+ } finally {
132
+ stream.end();
133
+ }
134
+ })();
135
+
136
+ return stream;
137
+ }
138
+
139
+ function takePrivateProjectHeader(headers: SimpleStreamOptions['headers']): { project: string | undefined; headers: Record<string, string> } {
140
+ let project: string | undefined;
141
+ const forwarded: Record<string, string> = {};
142
+ for (const [name, value] of Object.entries(headers ?? {})) {
143
+ if (name.toLowerCase() === PRIVATE_PROJECT_HEADER) project = value ?? undefined;
144
+ else if (value !== null && name.toLowerCase() !== 'user-agent') forwarded[name] = value;
145
+ }
146
+ return { project, headers: forwarded };
147
+ }
148
+
149
+ async function* parseSse(body: ReadableStream<Uint8Array> | null, signal: AbortSignal | undefined): AsyncGenerator<CodeAssistChunk> {
150
+ if (!body) throw new Error('Google Code Assist returned an empty response');
151
+ const reader = body.getReader();
152
+ const decoder = new TextDecoder();
153
+ const onAbort = () => void reader.cancel().catch(() => undefined);
154
+ signal?.addEventListener('abort', onAbort, { once: true });
155
+ let buffered = '';
156
+ let dataLines: string[] = [];
157
+
158
+ const flush = (): CodeAssistChunk | undefined => {
159
+ if (dataLines.length === 0) return undefined;
160
+ const data = dataLines.join('\n');
161
+ dataLines = [];
162
+ try {
163
+ return JSON.parse(data) as CodeAssistChunk;
164
+ } catch {
165
+ throw new Error('Google Code Assist sent a malformed event');
166
+ }
167
+ };
168
+ const readLine = (line: string): CodeAssistChunk | undefined => {
169
+ if (line === '') return flush();
170
+ if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));
171
+ return undefined;
172
+ };
173
+
174
+ try {
175
+ for (;;) {
176
+ const { done, value } = await reader.read();
177
+ buffered += decoder.decode(value, { stream: !done });
178
+ const lines = buffered.split(/\r\n|\n|\r/);
179
+ buffered = done ? '' : (lines.pop() ?? '');
180
+ for (const line of lines) {
181
+ const chunk = readLine(line);
182
+ if (chunk) yield chunk;
183
+ }
184
+ if (done) break;
185
+ }
186
+ const last = flush();
187
+ if (last) yield last;
188
+ } finally {
189
+ signal?.removeEventListener('abort', onAbort);
190
+ reader.releaseLock();
191
+ }
192
+ }
193
+
194
+ const withGoogleMessage = (summary: string, message: string | undefined): string => (message ? `${summary}: ${message}` : summary);
195
+
196
+ class ResponseReducer {
197
+ private readonly stream: AssistantMessageEventStream;
198
+ private readonly output: AssistantMessage;
199
+ private readonly model: Model<Api>;
200
+ private open: 'text' | 'thinking' | undefined;
201
+ private finishReason: string | undefined;
202
+ private finishMessage: string | undefined;
203
+
204
+ constructor(stream: AssistantMessageEventStream, output: AssistantMessage, model: Model<Api>) {
205
+ this.stream = stream;
206
+ this.output = output;
207
+ this.model = model;
208
+ }
209
+
210
+ push(chunk: CodeAssistChunk): void {
211
+ if (chunk.error) throw new CodeAssistError(chunk.error.message ?? 'Google Code Assist returned an error');
212
+ if (chunk.traceId) this.output.responseId ||= chunk.traceId;
213
+ const response = chunk.response;
214
+ if (!response) return;
215
+ if (response.modelVersion) this.output.responseModel = response.modelVersion;
216
+ const feedback = response.promptFeedback;
217
+ if (feedback?.blockReason) throw new Error(withGoogleMessage(`Google blocked the prompt: ${feedback.blockReason}`, feedback.blockReasonMessage));
218
+
219
+ const candidate = response.candidates?.[0];
220
+ for (const part of candidate?.content?.parts ?? []) {
221
+ if (typeof part.text === 'string') this.appendText(part.text, part.thought === true, part.thoughtSignature);
222
+ else if (part.functionCall) this.pushToolCall(part.functionCall, part.thoughtSignature);
223
+ }
224
+ if (candidate?.finishReason) this.finishReason = candidate.finishReason;
225
+ if (candidate?.finishMessage) this.finishMessage = candidate.finishMessage;
226
+
227
+ const usage = response.usageMetadata;
228
+ if (usage) {
229
+ const cached = usage.cachedContentTokenCount ?? 0;
230
+ const thoughts = usage.thoughtsTokenCount ?? 0;
231
+ this.output.usage = {
232
+ input: (usage.promptTokenCount ?? 0) - cached,
233
+ output: (usage.candidatesTokenCount ?? 0) + thoughts,
234
+ cacheRead: cached,
235
+ cacheWrite: 0,
236
+ reasoning: thoughts,
237
+ totalTokens: usage.totalTokenCount ?? 0,
238
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
239
+ };
240
+ calculateCost(this.model, this.output.usage);
241
+ }
242
+ }
243
+
244
+ finish(): void {
245
+ this.closeOpen();
246
+ const reason = this.finishReason;
247
+ if (!reason) throw new Error('Google stream ended without a finish reason');
248
+ this.output.rawStopReason = reason;
249
+ if (reason === 'MAX_TOKENS') this.output.stopReason = 'length';
250
+ else if (reason === 'STOP') this.output.stopReason = this.output.content.some((block) => block.type === 'toolCall') ? 'toolUse' : 'stop';
251
+ else throw new Error(withGoogleMessage(`Google stopped with ${reason}`, this.finishMessage));
252
+ }
253
+
254
+ private appendText(text: string, thought: boolean, signature: string | undefined): void {
255
+ const kind = thought ? 'thinking' : 'text';
256
+ if (this.open !== kind) {
257
+ this.closeOpen();
258
+ this.output.content.push(thought ? { type: 'thinking', thinking: '' } : { type: 'text', text: '' });
259
+ this.open = kind;
260
+ this.stream.push({ type: thought ? 'thinking_start' : 'text_start', contentIndex: this.output.content.length - 1, partial: this.output });
261
+ }
262
+ const contentIndex = this.output.content.length - 1;
263
+ const block = this.output.content[contentIndex];
264
+ if (block?.type === 'thinking') {
265
+ block.thinking += text;
266
+ if (signature) block.thinkingSignature = signature;
267
+ this.stream.push({ type: 'thinking_delta', contentIndex, delta: text, partial: this.output });
268
+ } else if (block?.type === 'text') {
269
+ block.text += text;
270
+ if (signature) block.textSignature = signature;
271
+ this.stream.push({ type: 'text_delta', contentIndex, delta: text, partial: this.output });
272
+ }
273
+ }
274
+
275
+ private pushToolCall(call: NonNullable<ResponsePart['functionCall']>, signature: string | undefined): void {
276
+ this.closeOpen();
277
+ const duplicate = call.id !== undefined && this.output.content.some((block) => block.type === 'toolCall' && block.id === call.id);
278
+ const toolCall: ToolCall = { type: 'toolCall', id: call.id && !duplicate ? call.id : `call_${uuidv7()}`, name: call.name ?? '', arguments: call.args ?? {}, ...(signature ? { thoughtSignature: signature } : {}) };
279
+ this.output.content.push(toolCall);
280
+ const contentIndex = this.output.content.length - 1;
281
+ this.stream.push({ type: 'toolcall_start', contentIndex, partial: this.output });
282
+ this.stream.push({ type: 'toolcall_delta', contentIndex, delta: JSON.stringify(toolCall.arguments), partial: this.output });
283
+ this.stream.push({ type: 'toolcall_end', contentIndex, toolCall, partial: this.output });
284
+ }
285
+
286
+ private closeOpen(): void {
287
+ if (!this.open) return;
288
+ const contentIndex = this.output.content.length - 1;
289
+ const block = this.output.content[contentIndex];
290
+ if (block?.type === 'thinking') this.stream.push({ type: 'thinking_end', contentIndex, content: block.thinking, partial: this.output });
291
+ else if (block?.type === 'text') this.stream.push({ type: 'text_end', contentIndex, content: block.text, partial: this.output });
292
+ this.open = undefined;
293
+ }
294
+ }