@justjoshn/pi-google-oauth-v2 0.1.2 → 0.1.4
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/package.json +4 -1
- package/src/auth.ts +60 -46
- package/src/code-assist.ts +45 -27
- package/src/constants.ts +1 -1
- package/src/index.ts +16 -19
- package/src/loopback.ts +60 -36
- package/src/models.ts +15 -12
- package/src/request.ts +138 -91
- package/src/stream-reducer.ts +165 -0
- package/src/stream.ts +154 -238
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@justjoshn/pi-google-oauth-v2",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"description": "Use a Google AI plan in Pi by signing in with your Google account, with no API key.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package"
|
|
@@ -47,5 +47,8 @@
|
|
|
47
47
|
"@vitest/coverage-v8": "^5.0.2",
|
|
48
48
|
"typescript": "^7.0.2",
|
|
49
49
|
"vitest": "^5.0.2"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"zod": "^4"
|
|
50
53
|
}
|
|
51
54
|
}
|
package/src/auth.ts
CHANGED
|
@@ -1,25 +1,27 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
2
|
|
|
3
3
|
import type { FetchFunction, ModelAuth, OAuthAuth, OAuthCredential, ProviderAuthInteraction } from '@earendil-works/pi-ai';
|
|
4
|
+
import { z } from 'zod';
|
|
4
5
|
import { readProjectOverride, resolveProject } from './code-assist.ts';
|
|
5
6
|
import { PRIVATE_PROJECT_HEADER } from './constants.ts';
|
|
6
|
-
import { LoopbackExpiredError, startLoopbackCallback } from './loopback.ts';
|
|
7
|
+
import { type LoopbackCallback, LoopbackExpiredError, startLoopbackCallback } from './loopback.ts';
|
|
7
8
|
|
|
8
9
|
const ANTIGRAVITY_CLIENT_ID = '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com';
|
|
9
10
|
// biome-ignore lint/security/noSecrets: Antigravity's public desktop OAuth client requires this shared application secret, not a user credential.
|
|
10
11
|
const ANTIGRAVITY_CLIENT_SECRET = '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';
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
'openid',
|
|
19
|
-
];
|
|
12
|
+
const SCOPE_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform';
|
|
13
|
+
const SCOPE_USER_EMAIL = 'https://www.googleapis.com/auth/userinfo.email';
|
|
14
|
+
const SCOPE_USER_PROFILE = 'https://www.googleapis.com/auth/userinfo.profile';
|
|
15
|
+
const SCOPE_CCLOG = 'https://www.googleapis.com/auth/cclog';
|
|
16
|
+
const SCOPE_EXPERIMENTS = 'https://www.googleapis.com/auth/experimentsandconfigs';
|
|
17
|
+
const SCOPE_AICODE = 'https://www.googleapis.com/auth/aicode';
|
|
18
|
+
const SCOPES = [SCOPE_CLOUD_PLATFORM, SCOPE_USER_EMAIL, SCOPE_USER_PROFILE, SCOPE_CCLOG, SCOPE_EXPERIMENTS, SCOPE_AICODE, 'openid'];
|
|
20
19
|
const AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
|
|
21
20
|
const TOKEN_URL = 'https://oauth2.googleapis.com/token';
|
|
22
21
|
const MANUAL_REDIRECT_URI = 'https://antigravity.google/oauth-callback';
|
|
22
|
+
const RANDOM_BYTES = 32;
|
|
23
|
+
const MS_PER_SECOND = 1000;
|
|
24
|
+
const ENV_SCHEMA = z.record(z.string(), z.string().optional());
|
|
23
25
|
|
|
24
26
|
export type GoogleCredential = OAuthCredential & { projectId: string };
|
|
25
27
|
|
|
@@ -29,10 +31,12 @@ export interface GoogleOAuthDeps {
|
|
|
29
31
|
}
|
|
30
32
|
|
|
31
33
|
class TokenRequestError extends Error {
|
|
32
|
-
readonly code: string;
|
|
33
34
|
constructor(code: string, description: string | undefined) {
|
|
34
|
-
super(`Google token request failed: ${code}${description ? `. ${description}` : ''}
|
|
35
|
-
|
|
35
|
+
super(`Google token request failed: ${code}${description ? `. ${description}` : ''}`, { cause: code });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
get code(): string {
|
|
39
|
+
return String(this.cause);
|
|
36
40
|
}
|
|
37
41
|
}
|
|
38
42
|
|
|
@@ -48,7 +52,7 @@ export function createGoogleOAuth(deps: GoogleOAuthDeps = {}): OAuthAuth {
|
|
|
48
52
|
name: 'Google AI subscription',
|
|
49
53
|
isSubscription: true,
|
|
50
54
|
loginLabel: 'Sign in with your Google AI plan',
|
|
51
|
-
login: (interaction) => login(interaction, fetchImpl, deps.env ?? process.env),
|
|
55
|
+
login: (interaction) => login(interaction, fetchImpl, deps.env ?? ENV_SCHEMA.parse({ ...process.env })),
|
|
52
56
|
refresh: (credential, signal) => refresh(credential, signal, fetchImpl),
|
|
53
57
|
toAuth,
|
|
54
58
|
};
|
|
@@ -62,7 +66,7 @@ export function parseStoredCredential(credential: OAuthCredential): GoogleCreden
|
|
|
62
66
|
return { ...credential, projectId };
|
|
63
67
|
}
|
|
64
68
|
|
|
65
|
-
|
|
69
|
+
function buildAuthUrl(input: { redirectUri: string; state: string; codeChallenge: string }): string {
|
|
66
70
|
const params = new URLSearchParams({
|
|
67
71
|
client_id: ANTIGRAVITY_CLIENT_ID,
|
|
68
72
|
redirect_uri: input.redirectUri,
|
|
@@ -96,41 +100,51 @@ async function postToken(body: Record<string, string>, fetchImpl: FetchFunction,
|
|
|
96
100
|
return { access_token, expires_in, ...(typeof refresh_token === 'string' && refresh_token ? { refresh_token } : {}) };
|
|
97
101
|
}
|
|
98
102
|
|
|
103
|
+
interface AuthorizationResult {
|
|
104
|
+
code: string;
|
|
105
|
+
redirectUri: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function awaitAuthorizationCode(interaction: ProviderAuthInteraction, loopback: LoopbackCallback, pkce: { state: string; codeChallenge: string }, cancelPrompt: AbortSignal): Promise<AuthorizationResult> {
|
|
109
|
+
const { state, codeChallenge } = pkce;
|
|
110
|
+
interaction.notify({
|
|
111
|
+
type: 'auth_url',
|
|
112
|
+
url: buildAuthUrl({ redirectUri: loopback.redirectUri, state, codeChallenge }),
|
|
113
|
+
instructions: 'Sign in with the Google account that has your AI plan.',
|
|
114
|
+
});
|
|
115
|
+
interaction.notify({
|
|
116
|
+
type: 'info',
|
|
117
|
+
message: 'No browser on this machine? Open the code page, then paste the code it shows.',
|
|
118
|
+
links: [{ url: buildAuthUrl({ redirectUri: MANUAL_REDIRECT_URI, state, codeChallenge }), label: 'Code page' }],
|
|
119
|
+
});
|
|
120
|
+
const pasted = interaction.prompt({ type: 'manual_code', message: 'Authorization code', signal: cancelPrompt }).then((code): AuthorizationResult => ({ code: code.trim(), redirectUri: MANUAL_REDIRECT_URI }));
|
|
121
|
+
pasted.catch(() => undefined);
|
|
122
|
+
const callback = loopback.code.then(
|
|
123
|
+
(code): AuthorizationResult => ({ code, redirectUri: loopback.redirectUri }),
|
|
124
|
+
(error: unknown) => (error instanceof LoopbackExpiredError ? new Promise<never>(() => undefined) : Promise.reject(error)),
|
|
125
|
+
);
|
|
126
|
+
callback.catch(() => undefined);
|
|
127
|
+
const won = await Promise.race([callback, pasted]);
|
|
128
|
+
if (!won.code) throw new Error('No authorization code entered');
|
|
129
|
+
return won;
|
|
130
|
+
}
|
|
131
|
+
|
|
99
132
|
async function login(interaction: ProviderAuthInteraction, fetchImpl: FetchFunction, env: NodeJS.ProcessEnv): Promise<OAuthCredential> {
|
|
100
133
|
const envProject = readProjectOverride(env);
|
|
101
|
-
const verifier = randomBytes(
|
|
134
|
+
const verifier = randomBytes(RANDOM_BYTES).toString('base64url');
|
|
102
135
|
const codeChallenge = createHash('sha256').update(verifier).digest('base64url');
|
|
103
|
-
const state = randomBytes(
|
|
136
|
+
const state = randomBytes(RANDOM_BYTES).toString('hex');
|
|
104
137
|
|
|
105
138
|
const loopback = await startLoopbackCallback({ state, signal: interaction.signal });
|
|
106
139
|
const cancelPrompt = new AbortController();
|
|
107
140
|
try {
|
|
108
|
-
interaction.
|
|
109
|
-
type: 'auth_url',
|
|
110
|
-
url: buildAuthUrl({ redirectUri: loopback.redirectUri, state, codeChallenge }),
|
|
111
|
-
instructions: 'Sign in with the Google account that has your AI plan.',
|
|
112
|
-
});
|
|
113
|
-
interaction.notify({
|
|
114
|
-
type: 'info',
|
|
115
|
-
message: 'No browser on this machine? Open the code page, then paste the code it shows.',
|
|
116
|
-
links: [{ url: buildAuthUrl({ redirectUri: MANUAL_REDIRECT_URI, state, codeChallenge }), label: 'Code page' }],
|
|
117
|
-
});
|
|
118
|
-
const pasted = interaction.prompt({ type: 'manual_code', message: 'Authorization code', signal: cancelPrompt.signal }).then((code) => ({ code: code.trim(), redirectUri: MANUAL_REDIRECT_URI }));
|
|
119
|
-
pasted.catch(() => undefined);
|
|
120
|
-
const callback = loopback.code.then(
|
|
121
|
-
(code) => ({ code, redirectUri: loopback.redirectUri }),
|
|
122
|
-
(error: unknown) => (error instanceof LoopbackExpiredError ? new Promise<never>(() => undefined) : Promise.reject(error)),
|
|
123
|
-
);
|
|
124
|
-
callback.catch(() => undefined);
|
|
125
|
-
const won = await Promise.race([callback, pasted]);
|
|
126
|
-
if (!won.code) throw new Error('No authorization code entered');
|
|
127
|
-
|
|
141
|
+
const won = await awaitAuthorizationCode(interaction, loopback, { state, codeChallenge }, cancelPrompt.signal);
|
|
128
142
|
const tokens = await postToken({ grant_type: 'authorization_code', code: won.code, code_verifier: verifier, redirect_uri: won.redirectUri }, fetchImpl, interaction.signal);
|
|
129
143
|
if (!tokens.refresh_token) throw new Error('Google returned no refresh token; run /login again');
|
|
130
144
|
|
|
131
145
|
const project = await resolveProject({ accessToken: tokens.access_token, envProject, signal: interaction.signal, fetchImpl });
|
|
132
146
|
interaction.notify({ type: 'info', message: `Google AI plan: ${project.tierName || project.tierId}. Code Assist project: ${project.projectId}.` });
|
|
133
|
-
const credential: GoogleCredential = { type: 'oauth', access: tokens.access_token, refresh: tokens.refresh_token, expires: Date.now() + tokens.expires_in *
|
|
147
|
+
const credential: GoogleCredential = { type: 'oauth', access: tokens.access_token, refresh: tokens.refresh_token, expires: Date.now() + tokens.expires_in * MS_PER_SECOND, projectId: project.projectId };
|
|
134
148
|
return credential;
|
|
135
149
|
} finally {
|
|
136
150
|
cancelPrompt.abort();
|
|
@@ -138,16 +152,16 @@ async function login(interaction: ProviderAuthInteraction, fetchImpl: FetchFunct
|
|
|
138
152
|
}
|
|
139
153
|
}
|
|
140
154
|
|
|
155
|
+
function rejectRefresh(error: unknown): never {
|
|
156
|
+
if (error instanceof TokenRequestError && error.code === 'invalid_grant') throw new Error('Google refused the refresh token; run /login again');
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
|
|
141
160
|
async function refresh(credential: OAuthCredential, signal: AbortSignal, fetchImpl: FetchFunction): Promise<OAuthCredential> {
|
|
142
161
|
const stored = parseStoredCredential(credential);
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
return { ...stored, type: 'oauth', access: tokens.access_token, expires: Date.now() + tokens.expires_in * 1000, refresh: tokens.refresh_token ?? stored.refresh };
|
|
147
|
-
} catch (error) {
|
|
148
|
-
if (error instanceof TokenRequestError && error.code === 'invalid_grant') throw new Error('Google refused the refresh token; run /login again');
|
|
149
|
-
throw error;
|
|
150
|
-
}
|
|
162
|
+
const tokens = await postToken({ grant_type: 'refresh_token', refresh_token: stored.refresh }, fetchImpl, signal).catch(rejectRefresh);
|
|
163
|
+
// Google usually omits refresh_token on refresh, so the old one stays.
|
|
164
|
+
return { ...stored, type: 'oauth', access: tokens.access_token, expires: Date.now() + tokens.expires_in * MS_PER_SECOND, refresh: tokens.refresh_token ?? stored.refresh };
|
|
151
165
|
}
|
|
152
166
|
|
|
153
167
|
async function toAuth(credential: OAuthCredential): Promise<ModelAuth> {
|
package/src/code-assist.ts
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
import type { FetchFunction } from '@earendil-works/pi-ai';
|
|
2
|
+
import { z } from 'zod';
|
|
2
3
|
import { ANTIGRAVITY_USER_AGENT, CODE_ASSIST_BASE_URL } from './constants.ts';
|
|
3
4
|
|
|
4
5
|
export class CodeAssistError extends Error {}
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
class IneligibleTierError extends CodeAssistError {}
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
readonly validationUrl: string;
|
|
9
|
+
class ValidationRequiredError extends CodeAssistError {
|
|
10
10
|
constructor(reasonMessage: string, validationUrl: string) {
|
|
11
|
-
super(`${reasonMessage} Validate at: ${validationUrl}
|
|
12
|
-
|
|
11
|
+
super(`${reasonMessage} Validate at: ${validationUrl}`, { cause: validationUrl });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
get validationUrl(): string {
|
|
15
|
+
return String(this.cause);
|
|
13
16
|
}
|
|
14
17
|
}
|
|
15
18
|
|
|
16
|
-
|
|
19
|
+
class ProjectRequiredError extends CodeAssistError {}
|
|
17
20
|
|
|
18
21
|
export interface ResolvedProject {
|
|
19
22
|
projectId: string;
|
|
@@ -62,6 +65,8 @@ const LEGACY_TIER = 'legacy-tier';
|
|
|
62
65
|
const STANDARD_TIER = 'standard-tier';
|
|
63
66
|
const POLL_INTERVAL_MS = 5000;
|
|
64
67
|
const MAX_POLLS = 60;
|
|
68
|
+
const JSON_BODY = z.json();
|
|
69
|
+
const GOOGLE_ERROR_BODY = z.object({ error: z.object({ message: z.string().min(1) }) });
|
|
65
70
|
|
|
66
71
|
export function readProjectOverride(env: NodeJS.ProcessEnv): string | undefined {
|
|
67
72
|
const value = (env['GOOGLE_CLOUD_PROJECT'] || env['GOOGLE_CLOUD_PROJECT_ID'] || '').trim();
|
|
@@ -70,7 +75,7 @@ export function readProjectOverride(env: NodeJS.ProcessEnv): string | undefined
|
|
|
70
75
|
return value;
|
|
71
76
|
}
|
|
72
77
|
|
|
73
|
-
|
|
78
|
+
function codeAssistUrl(method: string): string {
|
|
74
79
|
return `${CODE_ASSIST_BASE_URL}:${method}`;
|
|
75
80
|
}
|
|
76
81
|
|
|
@@ -78,21 +83,27 @@ export function fetchAvailableModels(input: Pick<ResolveProjectInput, 'accessTok
|
|
|
78
83
|
return callCodeAssist<unknown>(input, 'POST', codeAssistUrl('fetchAvailableModels'), { project: input.project });
|
|
79
84
|
}
|
|
80
85
|
|
|
86
|
+
function buildMetadata(envProject: string | undefined): Record<string, string> {
|
|
87
|
+
return { ...METADATA, ...(envProject ? { duetProject: envProject } : {}) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function assertEligible(load: LoadCodeAssistResponse): void {
|
|
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
|
+
|
|
81
97
|
export async function resolveProject(input: ResolveProjectInput): Promise<ResolvedProject> {
|
|
82
98
|
const { envProject } = input;
|
|
83
|
-
const metadata =
|
|
99
|
+
const metadata = buildMetadata(envProject);
|
|
84
100
|
|
|
85
101
|
const load = await callCodeAssist<LoadCodeAssistResponse>(input, 'POST', codeAssistUrl('loadCodeAssist'), {
|
|
86
102
|
cloudaicompanionProject: envProject,
|
|
87
103
|
metadata,
|
|
88
104
|
});
|
|
89
105
|
|
|
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
|
-
}
|
|
106
|
+
if (!load.currentTier) assertEligible(load);
|
|
96
107
|
|
|
97
108
|
if (load.currentTier) {
|
|
98
109
|
const projectId = load.cloudaicompanionProject || envProject;
|
|
@@ -104,18 +115,30 @@ export async function resolveProject(input: ResolveProjectInput): Promise<Resolv
|
|
|
104
115
|
};
|
|
105
116
|
}
|
|
106
117
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
let operation = await callCodeAssist<Operation>(input, 'POST', codeAssistUrl('onboardUser'), onboard);
|
|
118
|
+
return onboardUser(input, load, metadata);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const defaultSleep = (ms: number): Promise<void> => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
112
122
|
|
|
113
|
-
|
|
123
|
+
async function pollOperation(input: ResolveProjectInput, initial: Operation): Promise<Operation> {
|
|
124
|
+
const sleep = input.sleep ?? defaultSleep;
|
|
125
|
+
let operation = initial;
|
|
114
126
|
for (let polls = 0; !operation.done && operation.name; polls++) {
|
|
115
127
|
if (polls === MAX_POLLS) throw new CodeAssistError('Google Code Assist onboarding did not finish in time; run /login again');
|
|
116
128
|
await sleep(POLL_INTERVAL_MS);
|
|
117
129
|
operation = await callCodeAssist<Operation>(input, 'GET', `${CODE_ASSIST_BASE_URL}/${operation.name}`);
|
|
118
130
|
}
|
|
131
|
+
return operation;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function onboardUser(input: ResolveProjectInput, load: LoadCodeAssistResponse, metadata: Record<string, string>): Promise<ResolvedProject> {
|
|
135
|
+
const { envProject } = input;
|
|
136
|
+
const tier = load.allowedTiers?.find((candidate) => candidate.isDefault) ?? { id: LEGACY_TIER, name: '' };
|
|
137
|
+
const tierId = tier.id ?? STANDARD_TIER;
|
|
138
|
+
// The free tier uses a managed project. Sending one makes Google answer Precondition Failed.
|
|
139
|
+
const onboard = tierId === FREE_TIER ? { tierId, metadata: METADATA } : { tierId, cloudaicompanionProject: envProject, metadata };
|
|
140
|
+
const started = await callCodeAssist<Operation>(input, 'POST', codeAssistUrl('onboardUser'), onboard);
|
|
141
|
+
const operation = await pollOperation(input, started);
|
|
119
142
|
if (operation.error) throw new CodeAssistError(operation.error.message ?? 'Google Code Assist onboarding failed');
|
|
120
143
|
|
|
121
144
|
const projectId = operation.response?.cloudaicompanionProject?.id || envProject;
|
|
@@ -139,7 +162,7 @@ async function callCodeAssist<T>(input: Pick<ResolveProjectInput, 'accessToken'
|
|
|
139
162
|
const text = await response.text();
|
|
140
163
|
if (!response.ok) throw new CodeAssistError(googleErrorMessage(text) ?? `Google Code Assist request failed (HTTP ${response.status})`);
|
|
141
164
|
try {
|
|
142
|
-
return JSON.parse(text) as T;
|
|
165
|
+
return JSON_BODY.parse(JSON.parse(text)) as T;
|
|
143
166
|
} catch {
|
|
144
167
|
throw new CodeAssistError('Google Code Assist returned a response that is not JSON');
|
|
145
168
|
}
|
|
@@ -147,13 +170,8 @@ async function callCodeAssist<T>(input: Pick<ResolveProjectInput, 'accessToken'
|
|
|
147
170
|
|
|
148
171
|
export function googleErrorMessage(text: string): string | undefined {
|
|
149
172
|
try {
|
|
150
|
-
|
|
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
|
-
}
|
|
173
|
+
return GOOGLE_ERROR_BODY.safeParse(JSON.parse(text)).data?.error.message;
|
|
155
174
|
} catch {
|
|
156
175
|
return undefined;
|
|
157
176
|
}
|
|
158
|
-
return undefined;
|
|
159
177
|
}
|
package/src/constants.ts
CHANGED
|
@@ -8,7 +8,7 @@ export const PRIVATE_PROJECT_HEADER = 'x-pi-google-oauth-v2-project';
|
|
|
8
8
|
const OS_TYPES: Record<string, string> = { darwin: 'darwin', linux: 'linux', win32: 'windows' };
|
|
9
9
|
const ARCHITECTURES: Record<string, string> = { arm64: 'arm64', x64: 'amd64' };
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
function antigravityUserAgent(platform: string = process.platform, arch: string = process.arch): string {
|
|
12
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
13
|
}
|
|
14
14
|
|
package/src/index.ts
CHANGED
|
@@ -1,14 +1,26 @@
|
|
|
1
|
-
import { hasApi, type Model, type Provider } from '@earendil-works/pi-ai';
|
|
1
|
+
import { hasApi, type Model, type Provider, type RefreshModelsContext } from '@earendil-works/pi-ai';
|
|
2
2
|
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
3
|
import { createGoogleOAuth } from './auth.ts';
|
|
4
4
|
import { API_ID, CODE_ASSIST_BASE_URL, PROVIDER_DISPLAY_NAME, PROVIDER_ID } from './constants.ts';
|
|
5
5
|
import { BASELINE_MODELS, createFetchModels } from './models.ts';
|
|
6
6
|
import { streamCodeAssist } from './stream.ts';
|
|
7
7
|
|
|
8
|
+
type CodeAssistModel = Model<typeof API_ID>;
|
|
9
|
+
|
|
8
10
|
/** Registers the provider only. The factory starts no listener, timer, or request. */
|
|
9
11
|
export default function (pi: ExtensionAPI): void {
|
|
10
|
-
let current: readonly
|
|
12
|
+
let current: readonly CodeAssistModel[] | undefined;
|
|
11
13
|
const fetchModels = createFetchModels();
|
|
14
|
+
const adopt =
|
|
15
|
+
(models: readonly CodeAssistModel[]): (() => void) =>
|
|
16
|
+
() => {
|
|
17
|
+
current = models;
|
|
18
|
+
};
|
|
19
|
+
const restoreStored = async (context: RefreshModelsContext): Promise<boolean> => {
|
|
20
|
+
if (!context.stored) return true;
|
|
21
|
+
const restored = context.stored.models.filter((model): model is CodeAssistModel => model.provider === PROVIDER_ID && hasApi(model, API_ID));
|
|
22
|
+
return context.publish({ update: adopt(restored) });
|
|
23
|
+
};
|
|
12
24
|
const nativeProvider: Provider<typeof API_ID> = {
|
|
13
25
|
id: PROVIDER_ID,
|
|
14
26
|
name: PROVIDER_DISPLAY_NAME,
|
|
@@ -16,26 +28,11 @@ export default function (pi: ExtensionAPI): void {
|
|
|
16
28
|
auth: { oauth: createGoogleOAuth() },
|
|
17
29
|
getModels: () => current ?? BASELINE_MODELS,
|
|
18
30
|
refreshModels: async (context) => {
|
|
19
|
-
if (context
|
|
20
|
-
const restored = context.stored.models.filter((model): model is Model<typeof API_ID> => model.provider === PROVIDER_ID && hasApi(model, API_ID));
|
|
21
|
-
if (
|
|
22
|
-
!(await context.publish({
|
|
23
|
-
update: () => {
|
|
24
|
-
current = restored;
|
|
25
|
-
},
|
|
26
|
-
}))
|
|
27
|
-
)
|
|
28
|
-
return;
|
|
29
|
-
}
|
|
31
|
+
if (!(await restoreStored(context))) return;
|
|
30
32
|
if (!context.allowNetwork || context.credential?.type !== 'oauth' || context.signal.aborted) return;
|
|
31
33
|
const refreshed = await fetchModels(context);
|
|
32
34
|
if (context.signal.aborted) return;
|
|
33
|
-
await context.publish({
|
|
34
|
-
persist: { models: refreshed, checkedAt: Date.now() },
|
|
35
|
-
update: () => {
|
|
36
|
-
current = refreshed;
|
|
37
|
-
},
|
|
38
|
-
});
|
|
35
|
+
await context.publish({ persist: { models: refreshed, checkedAt: Date.now() }, update: adopt(refreshed) });
|
|
39
36
|
},
|
|
40
37
|
stream: streamCodeAssist,
|
|
41
38
|
streamSimple: streamCodeAssist,
|
package/src/loopback.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { timingSafeEqual } from 'node:crypto';
|
|
2
|
-
import { createServer } from 'node:http';
|
|
2
|
+
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
|
|
3
3
|
import type { AddressInfo } from 'node:net';
|
|
4
4
|
|
|
5
5
|
export interface LoopbackCallback {
|
|
@@ -11,9 +11,25 @@ export interface LoopbackCallback {
|
|
|
11
11
|
/** The listener ended without a verdict from Google or the user, so another sign-in path may still finish. */
|
|
12
12
|
export class LoopbackExpiredError extends Error {}
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
const LOOPBACK_TIMEOUT_MINUTES = 5;
|
|
15
|
+
const SECONDS_PER_MINUTE = 60;
|
|
16
|
+
const MS_PER_SECOND = 1000;
|
|
17
|
+
const LOOPBACK_TIMEOUT_MS = LOOPBACK_TIMEOUT_MINUTES * SECONDS_PER_MINUTE * MS_PER_SECOND;
|
|
15
18
|
|
|
16
19
|
const CALLBACK_PATH = '/oauth2callback';
|
|
20
|
+
const ROOT_PATH = '/';
|
|
21
|
+
const LOOPBACK_HOST = '127.0.0.1';
|
|
22
|
+
const LOOPBACK_ORIGIN = 'http://127.0.0.1';
|
|
23
|
+
const EPHEMERAL_PORT = 0;
|
|
24
|
+
const HTTP_OK = 200;
|
|
25
|
+
const HTTP_BAD_REQUEST = 400;
|
|
26
|
+
const HTTP_NOT_FOUND = 404;
|
|
27
|
+
const PLAIN_TEXT = { 'Content-Type': 'text/plain' };
|
|
28
|
+
|
|
29
|
+
interface Outcome {
|
|
30
|
+
resolve(code: string): void;
|
|
31
|
+
reject(error: Error): void;
|
|
32
|
+
}
|
|
17
33
|
|
|
18
34
|
function statesMatch(received: string | null, expected: string): boolean {
|
|
19
35
|
if (received === null) return false;
|
|
@@ -22,43 +38,56 @@ function statesMatch(received: string | null, expected: string): boolean {
|
|
|
22
38
|
return a.length === b.length && timingSafeEqual(a, b);
|
|
23
39
|
}
|
|
24
40
|
|
|
25
|
-
|
|
41
|
+
function createOutcome(): Outcome & { promise: Promise<string> } {
|
|
26
42
|
let resolve!: (code: string) => void;
|
|
27
43
|
let reject!: (error: Error) => void;
|
|
28
|
-
const
|
|
44
|
+
const promise = new Promise<string>((onCode, onError) => {
|
|
29
45
|
resolve = onCode;
|
|
30
46
|
reject = onError;
|
|
31
47
|
});
|
|
32
|
-
|
|
48
|
+
promise.catch(() => undefined);
|
|
49
|
+
return { promise, resolve, reject };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function handleRequest(request: IncomingMessage, response: ServerResponse, state: string, outcome: Outcome, close: () => void): void {
|
|
53
|
+
const url = new URL(request.url ?? ROOT_PATH, LOOPBACK_ORIGIN);
|
|
54
|
+
if (url.pathname !== CALLBACK_PATH) {
|
|
55
|
+
response.writeHead(HTTP_NOT_FOUND).end();
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (!statesMatch(url.searchParams.get('state'), state)) {
|
|
59
|
+
response.writeHead(HTTP_BAD_REQUEST, PLAIN_TEXT).end('Invalid state');
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const error = url.searchParams.get('error');
|
|
63
|
+
const authorizationCode = url.searchParams.get('code');
|
|
64
|
+
if (!error && authorizationCode) {
|
|
65
|
+
outcome.resolve(authorizationCode);
|
|
66
|
+
response.writeHead(HTTP_OK, PLAIN_TEXT).end('Signed in. You can close this tab and return to Pi.', close);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const description = url.searchParams.get('error_description');
|
|
70
|
+
outcome.reject(new Error(error ? `Google sign-in failed: ${error}${description ? `. ${description}` : ''}` : 'Google sign-in returned no authorization code'));
|
|
71
|
+
response.writeHead(HTTP_BAD_REQUEST, PLAIN_TEXT).end('Sign-in failed. Return to Pi.', close);
|
|
72
|
+
}
|
|
33
73
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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);
|
|
74
|
+
function listen(server: Server): Promise<void> {
|
|
75
|
+
return new Promise<void>((onListening, onError) => {
|
|
76
|
+
server.once('error', onError);
|
|
77
|
+
server.listen(EPHEMERAL_PORT, LOOPBACK_HOST, onListening);
|
|
54
78
|
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function startLoopbackCallback(input: { state: string; signal: AbortSignal }): Promise<LoopbackCallback> {
|
|
82
|
+
const outcome = createOutcome();
|
|
83
|
+
const server = createServer((request, response) => handleRequest(request, response, input.state, outcome, close));
|
|
55
84
|
|
|
56
85
|
const timer = setTimeout(() => {
|
|
57
|
-
reject(new LoopbackExpiredError('Google sign-in timed out'));
|
|
86
|
+
outcome.reject(new LoopbackExpiredError('Google sign-in timed out'));
|
|
58
87
|
close();
|
|
59
88
|
}, LOOPBACK_TIMEOUT_MS);
|
|
60
89
|
const onAbort = () => {
|
|
61
|
-
reject(new Error('Google sign-in was cancelled'));
|
|
90
|
+
outcome.reject(new Error('Google sign-in was cancelled'));
|
|
62
91
|
close();
|
|
63
92
|
};
|
|
64
93
|
input.signal.addEventListener('abort', onAbort, { once: true });
|
|
@@ -69,22 +98,17 @@ export async function startLoopbackCallback(input: { state: string; signal: Abor
|
|
|
69
98
|
closed = true;
|
|
70
99
|
clearTimeout(timer);
|
|
71
100
|
input.signal.removeEventListener('abort', onAbort);
|
|
72
|
-
reject(new LoopbackExpiredError('Google sign-in listener closed'));
|
|
101
|
+
outcome.reject(new LoopbackExpiredError('Google sign-in listener closed'));
|
|
73
102
|
server.closeAllConnections();
|
|
74
103
|
server.close();
|
|
75
104
|
}
|
|
76
105
|
|
|
77
|
-
|
|
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) {
|
|
106
|
+
await listen(server).catch((error: unknown) => {
|
|
83
107
|
close();
|
|
84
108
|
throw error;
|
|
85
|
-
}
|
|
109
|
+
});
|
|
86
110
|
const { port } = server.address() as AddressInfo;
|
|
87
111
|
if (input.signal.aborted) onAbort();
|
|
88
112
|
|
|
89
|
-
return { redirectUri:
|
|
113
|
+
return { redirectUri: `${LOOPBACK_ORIGIN}:${port}${CALLBACK_PATH}`, code: outcome.promise, close };
|
|
90
114
|
}
|
package/src/models.ts
CHANGED
|
@@ -40,24 +40,23 @@ function splitWireId(wireId: string): { base: string; effort: Effort } {
|
|
|
40
40
|
|
|
41
41
|
function thinkingLevelMap(variants: Variant[], reasoning: boolean): ThinkingLevelMap {
|
|
42
42
|
if (!reasoning) return { off: (variants.find((variant) => variant.effort === 'medium') ?? variants[0])?.wireId ?? null };
|
|
43
|
-
const map
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
return map;
|
|
43
|
+
const unmapped = Object.fromEntries(LEVELS_WITHOUT_WIRE_ID.map((level) => [level, null]));
|
|
44
|
+
const mapped = Object.fromEntries(variants.map((variant) => [variant.effort, variant.wireId]));
|
|
45
|
+
return { ...unmapped, ...mapped } as ThinkingLevelMap;
|
|
47
46
|
}
|
|
48
47
|
|
|
49
48
|
/** One Pi model per base family. Its thinking levels map to Google's per-effort wire ids. */
|
|
50
|
-
|
|
51
|
-
const families = new Map<string, Variant[]>();
|
|
49
|
+
function catalogModels(catalog: Catalog): CodeAssistModel[] {
|
|
52
50
|
const shown = new Set((catalog.agentModelSorts ?? []).flatMap((sort) => (sort.groups ?? []).flatMap((group) => group.modelIds ?? [])));
|
|
53
|
-
|
|
51
|
+
const entries = [...shown].flatMap((wireId): { base: string; variant: Variant }[] => {
|
|
54
52
|
const info = catalog.models?.[wireId];
|
|
55
|
-
if (!info || wireId.endsWith('-disabled'))
|
|
53
|
+
if (!info || wireId.endsWith('-disabled')) return [];
|
|
56
54
|
const { base, effort } = splitWireId(wireId);
|
|
57
|
-
|
|
58
|
-
}
|
|
55
|
+
return [{ base, variant: { wireId, effort, info } }];
|
|
56
|
+
});
|
|
57
|
+
const families = [...new Set(entries.map((entry) => entry.base))].map((id) => ({ id, variants: entries.filter((entry) => entry.base === id).map((entry) => entry.variant) }));
|
|
59
58
|
|
|
60
|
-
return
|
|
59
|
+
return families.map(({ id, variants }) => {
|
|
61
60
|
const reasoning = variants.some((variant) => variant.info.supportsThinking);
|
|
62
61
|
const first = variants[0]?.info;
|
|
63
62
|
return {
|
|
@@ -76,6 +75,8 @@ export function catalogModels(catalog: Catalog): CodeAssistModel[] {
|
|
|
76
75
|
});
|
|
77
76
|
}
|
|
78
77
|
|
|
78
|
+
const BASELINE_CONTEXT_WINDOW = 1_048_576;
|
|
79
|
+
const BASELINE_MAX_OUTPUT_TOKENS = 65_536;
|
|
79
80
|
const BASELINE_FAMILIES = [
|
|
80
81
|
['gemini-4-argon', 'Gemini 4 Argon'],
|
|
81
82
|
['gemini-3.8-flash', 'Gemini 3.8 Flash'],
|
|
@@ -89,7 +90,9 @@ const baselineWireIds = BASELINE_FAMILIES.flatMap(([id]) => BASELINE_EFFORTS.map
|
|
|
89
90
|
|
|
90
91
|
export const BASELINE_MODELS: CodeAssistModel[] = catalogModels({
|
|
91
92
|
models: Object.fromEntries(
|
|
92
|
-
BASELINE_FAMILIES.flatMap(([id, name]) =>
|
|
93
|
+
BASELINE_FAMILIES.flatMap(([id, name]) =>
|
|
94
|
+
BASELINE_EFFORTS.map(([effort, label]) => [`${id}-${effort}`, { displayName: `${name} (${label})`, supportsImages: true, supportsThinking: true, maxTokens: BASELINE_CONTEXT_WINDOW, maxOutputTokens: BASELINE_MAX_OUTPUT_TOKENS }]),
|
|
95
|
+
),
|
|
93
96
|
),
|
|
94
97
|
agentModelSorts: [{ groups: [{ modelIds: baselineWireIds }] }],
|
|
95
98
|
});
|