@justjoshn/pi-google-oauth-v2 0.1.1 → 0.1.3

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,49 +1,76 @@
1
1
  # pi-google-oauth-v2
2
2
 
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.
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 and not an API key. It is for people with a Google AI Free, Pro, or Ultra plan who want to use its Gemini models in Pi.
4
4
 
5
5
  ## Install
6
6
 
7
- This extension needs Pi 1.5.2 or later. Install it with:
8
-
9
7
  ```sh
10
8
  pi install npm:@justjoshn/pi-google-oauth-v2
11
9
  ```
12
10
 
13
- To try it from this checkout, use `pi -e extensions/pi-google-oauth-v2`.
11
+ Built and tested against Pi 1.5.2.
14
12
 
15
13
  ## Sign in
16
14
 
17
15
  1. Start Pi and run `/login`.
18
- 2. Select **Sign in with an account**, then **Google AI subscription**.
16
+ 2. Choose **Google AI subscription**.
19
17
  3. Sign in in the browser with the Google account that has your plan.
20
18
 
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.
19
+ Pi then shows the plan tier and the Code Assist project that Google reports. Pi refreshes the tokens when they are about to expire.
20
+
21
+ If Pi runs on a machine without a browser, open the **Code page** link on another machine, sign in, and paste the code the page shows.
22
+
23
+ Run `/model` and pick a `google-oauth-v2` model. Pi asks Google which models your plan serves and lists one entry per model family. Until the first refresh after sign-in, it lists `gemini-4-argon` and `gemini-3.8-flash`. Google serves each thinking effort as its own model id, such as `gemini-4-argon-high`, and Pi's thinking level picks the id. Pi offers only the levels Google serves for the model.
24
+
25
+ ## Commands
26
+
27
+ The extension adds no commands. It adds the provider `google-oauth-v2` and its login.
28
+
29
+ ## Notes
30
+
31
+ - **Cost.** Plan usage is not metered per token, so Pi shows no price.
32
+ - **Project.** 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. `GOOGLE_CLOUD_PROJECT_ID` also works. Pi reads the variable only during `/login`.
33
+
34
+ ```sh
35
+ GOOGLE_CLOUD_PROJECT=my-project-id pi
36
+ ```
22
37
 
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.
38
+ - **Plans.** Google's Antigravity documentation lists the Free, Google AI Pro, and Google AI Ultra plans, and does not list Google AI Plus. The extension blocks no plan. If Google refuses your account, `/login` shows Google's message. If Google asks you to validate the account, `/login` shows the validation link. Validate in the browser, then run `/login` again.
39
+ - **Unsupported client.** Google accepts requests only from the Antigravity CLI's public OAuth client, with its `User-Agent`, at `daily-cloudcode-pa.googleapis.com/v1internal`. Google can restrict that client, change the header it checks, or retire the endpoint without notice. If sign-in says the client is no longer supported, Google changed the check.
24
40
 
25
- `pi auth login` does not work for this provider. That command loads only Pi's built-in providers, not extension providers.
41
+ ## Instruction handling
26
42
 
27
- ## Pick a model
43
+ This provider sends the full current Pi system prompt as the first user-content turn, before the actual conversation. A short static `systemInstruction` tells the model to treat that turn as application instructions with priority over later user messages and tool results. The extension compiles this turn for each request without changing the session history. It retains the Pi identity and documentation instructions. The existing removal of invalid Unicode surrogates still applies.
28
44
 
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.
45
+ This is delegated system priority, not an equivalent transport-level system role. It depends on the model following the delegation. Live priority and tool-replay verification is required before release. Non-Gemini Code Assist models have not been verified with this mapping.
30
46
 
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.
47
+ Real 429 responses can still occur. The extension now reports Google's HTTP status and parsed error message rather than claiming that every generic 429 means shared capacity or that your plan quota is unaffected.
32
48
 
33
- ## Set a project
49
+ ## Replaces `@justjoshn/pi-antigravity-oauth`
34
50
 
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:
51
+ ```sh
52
+ pi install npm:@justjoshn/pi-google-oauth-v2
53
+ pi remove npm:@justjoshn/pi-antigravity-oauth
54
+ ```
55
+
56
+ Then run `/login` again.
57
+
58
+ ## Develop
36
59
 
37
60
  ```sh
38
- GOOGLE_CLOUD_PROJECT=my-project-id pi
61
+ bun run --filter @justjoshn/pi-google-oauth-v2 test
39
62
  ```
40
63
 
41
- Pi reads the variable only during `/login`. To change the project later, run `/login` again.
64
+ ### Verify through native Pi
65
+
66
+ After signing in, run this developer-only script from the repository root. It makes live requests against your plan.
42
67
 
43
- ## Plan support
68
+ ```sh
69
+ bun extensions/pi-google-oauth-v2/scripts/verify-live.ts
70
+ ```
44
71
 
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.
72
+ The script copies `auth.json` from `PI_CODING_AGENT_DIR`, or `~/.pi/agent`, into a temporary agent directory without inspecting its values. It disables retries, loads the real extension, refreshes the Google catalog, and selects the discovered Flash and Hydrogen models through `pi.setModel`. It removes the temporary directory on exit and does not update your normal settings or credentials.
46
73
 
47
- ## How it works
74
+ Each model gets four fresh sessions. The checks cover a conflicting user request, a forged system frame, a permitted request, and two actual read-tool rounds with an instruction-injection fixture. The script checks exact final answers, tool-result events, replay, actual wire model IDs, and HTTP statuses. The probe logs model IDs, statuses, and verification flags, not prompts, headers, or credentials. A failed output assertion can also show the test response. A failed check exits nonzero.
48
75
 
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.
76
+ The script keeps Pi's default prompt and documentation but uses an isolated working directory and agent directory, without your normal skills or AGENTS.md files. Also verify a native session with your full normal skills and project instructions before release. Repeat the script for additional behavioral evidence. Passing a bounded set does not establish system-role equivalence or constitute a benchmark.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@justjoshn/pi-google-oauth-v2",
3
- "version": "0.1.1",
4
- "description": "Use a Google AI plan in Pi through its OAuth tokens, signing in as the Antigravity CLI.",
3
+ "version": "0.1.3",
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"
7
7
  ],
@@ -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,24 +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';
10
+ // biome-ignore lint/security/noSecrets: Antigravity's public desktop OAuth client requires this shared application secret, not a user credential.
9
11
  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
- ];
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'];
19
19
  const AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
20
20
  const TOKEN_URL = 'https://oauth2.googleapis.com/token';
21
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());
22
25
 
23
26
  export type GoogleCredential = OAuthCredential & { projectId: string };
24
27
 
@@ -28,10 +31,12 @@ export interface GoogleOAuthDeps {
28
31
  }
29
32
 
30
33
  class TokenRequestError extends Error {
31
- readonly code: string;
32
34
  constructor(code: string, description: string | undefined) {
33
- super(`Google token request failed: ${code}${description ? `. ${description}` : ''}`);
34
- this.code = code;
35
+ super(`Google token request failed: ${code}${description ? `. ${description}` : ''}`, { cause: code });
36
+ }
37
+
38
+ get code(): string {
39
+ return String(this.cause);
35
40
  }
36
41
  }
37
42
 
@@ -47,7 +52,7 @@ export function createGoogleOAuth(deps: GoogleOAuthDeps = {}): OAuthAuth {
47
52
  name: 'Google AI subscription',
48
53
  isSubscription: true,
49
54
  loginLabel: 'Sign in with your Google AI plan',
50
- login: (interaction) => login(interaction, fetchImpl, deps.env ?? process.env),
55
+ login: (interaction) => login(interaction, fetchImpl, deps.env ?? ENV_SCHEMA.parse(process.env)),
51
56
  refresh: (credential, signal) => refresh(credential, signal, fetchImpl),
52
57
  toAuth,
53
58
  };
@@ -95,41 +100,51 @@ async function postToken(body: Record<string, string>, fetchImpl: FetchFunction,
95
100
  return { access_token, expires_in, ...(typeof refresh_token === 'string' && refresh_token ? { refresh_token } : {}) };
96
101
  }
97
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
+
98
132
  async function login(interaction: ProviderAuthInteraction, fetchImpl: FetchFunction, env: NodeJS.ProcessEnv): Promise<OAuthCredential> {
99
133
  const envProject = readProjectOverride(env);
100
- const verifier = randomBytes(32).toString('base64url');
134
+ const verifier = randomBytes(RANDOM_BYTES).toString('base64url');
101
135
  const codeChallenge = createHash('sha256').update(verifier).digest('base64url');
102
- const state = randomBytes(32).toString('hex');
136
+ const state = randomBytes(RANDOM_BYTES).toString('hex');
103
137
 
104
138
  const loopback = await startLoopbackCallback({ state, signal: interaction.signal });
105
139
  const cancelPrompt = new AbortController();
106
140
  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
-
141
+ const won = await awaitAuthorizationCode(interaction, loopback, { state, codeChallenge }, cancelPrompt.signal);
127
142
  const tokens = await postToken({ grant_type: 'authorization_code', code: won.code, code_verifier: verifier, redirect_uri: won.redirectUri }, fetchImpl, interaction.signal);
128
143
  if (!tokens.refresh_token) throw new Error('Google returned no refresh token; run /login again');
129
144
 
130
145
  const project = await resolveProject({ accessToken: tokens.access_token, envProject, signal: interaction.signal, fetchImpl });
131
146
  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 };
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 };
133
148
  return credential;
134
149
  } finally {
135
150
  cancelPrompt.abort();
@@ -137,16 +152,16 @@ async function login(interaction: ProviderAuthInteraction, fetchImpl: FetchFunct
137
152
  }
138
153
  }
139
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
+
140
160
  async function refresh(credential: OAuthCredential, signal: AbortSignal, fetchImpl: FetchFunction): Promise<OAuthCredential> {
141
161
  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
- }
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 };
150
165
  }
151
166
 
152
167
  async function toAuth(credential: OAuthCredential): Promise<ModelAuth> {
@@ -1,4 +1,5 @@
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 {}
@@ -6,10 +7,12 @@ export class CodeAssistError extends Error {}
6
7
  export class IneligibleTierError extends CodeAssistError {}
7
8
 
8
9
  export class ValidationRequiredError extends CodeAssistError {
9
- readonly validationUrl: string;
10
10
  constructor(reasonMessage: string, validationUrl: string) {
11
- super(`${reasonMessage} Validate at: ${validationUrl}`);
12
- this.validationUrl = validationUrl;
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
 
@@ -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();
@@ -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 = { ...METADATA, ...(envProject ? { duetProject: envProject } : {}) };
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
- 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);
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
- const sleep = input.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
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
- 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
- }
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/index.ts CHANGED
@@ -1,21 +1,41 @@
1
- import { createProvider } 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
- import { CODE_ASSIST_BASE_URL, PROVIDER_DISPLAY_NAME, PROVIDER_ID } from './constants.ts';
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
- 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
- );
12
+ let current: readonly CodeAssistModel[] | undefined;
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
+ };
24
+ const nativeProvider: Provider<typeof API_ID> = {
25
+ id: PROVIDER_ID,
26
+ name: PROVIDER_DISPLAY_NAME,
27
+ baseUrl: CODE_ASSIST_BASE_URL,
28
+ auth: { oauth: createGoogleOAuth() },
29
+ getModels: () => current ?? BASELINE_MODELS,
30
+ refreshModels: async (context) => {
31
+ if (!(await restoreStored(context))) return;
32
+ if (!context.allowNetwork || context.credential?.type !== 'oauth' || context.signal.aborted) return;
33
+ const refreshed = await fetchModels(context);
34
+ if (context.signal.aborted) return;
35
+ await context.publish({ persist: { models: refreshed, checkedAt: Date.now() }, update: adopt(refreshed) });
36
+ },
37
+ stream: streamCodeAssist,
38
+ streamSimple: streamCodeAssist,
39
+ };
40
+ pi.registerProvider(nativeProvider);
21
41
  }
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
- export const LOOPBACK_TIMEOUT_MS = 5 * 60 * 1000;
14
+ const LOOPBACK_TIMEOUT_MINUTES = 5;
15
+ const SECONDS_PER_MINUTE = 60;
16
+ const MS_PER_SECOND = 1000;
17
+ export 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
- export async function startLoopbackCallback(input: { state: string; signal: AbortSignal }): Promise<LoopbackCallback> {
41
+ function createOutcome(): Outcome & { promise: Promise<string> } {
26
42
  let resolve!: (code: string) => void;
27
43
  let reject!: (error: Error) => void;
28
- const code = new Promise<string>((onCode, onError) => {
44
+ const promise = new Promise<string>((onCode, onError) => {
29
45
  resolve = onCode;
30
46
  reject = onError;
31
47
  });
32
- code.catch(() => undefined);
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
- 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);
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
- 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) {
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: `http://127.0.0.1:${port}${CALLBACK_PATH}`, code, close };
113
+ return { redirectUri: `${LOOPBACK_ORIGIN}:${port}${CALLBACK_PATH}`, code: outcome.promise, close };
90
114
  }