@heyhuynhgiabuu/pi-oauth-antigravity 0.1.0
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/CHANGELOG.md +24 -0
- package/LICENSE +21 -0
- package/README.md +91 -0
- package/dist/auth/index.d.ts +2 -0
- package/dist/auth/index.js +1 -0
- package/dist/auth/oauth.d.ts +18 -0
- package/dist/auth/oauth.js +374 -0
- package/dist/client/client.d.ts +35 -0
- package/dist/client/client.js +448 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.js +1 -0
- package/dist/diagnostics/diagnostics.d.ts +31 -0
- package/dist/diagnostics/diagnostics.js +68 -0
- package/dist/diagnostics/index.d.ts +1 -0
- package/dist/diagnostics/index.js +1 -0
- package/dist/image/image.d.ts +62 -0
- package/dist/image/image.js +244 -0
- package/dist/image/index.d.ts +1 -0
- package/dist/image/index.js +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +182 -0
- package/dist/models/index.d.ts +1 -0
- package/dist/models/index.js +1 -0
- package/dist/models/models.d.ts +44 -0
- package/dist/models/models.js +377 -0
- package/dist/stream/index.d.ts +1 -0
- package/dist/stream/index.js +1 -0
- package/dist/stream/stream.d.ts +24 -0
- package/dist/stream/stream.js +879 -0
- package/dist/types/enums.d.ts +41 -0
- package/dist/types/enums.js +49 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.js +2 -0
- package/dist/types/types.d.ts +259 -0
- package/dist/types/types.js +2 -0
- package/dist/usage/index.d.ts +1 -0
- package/dist/usage/index.js +1 -0
- package/dist/usage/usage.d.ts +8 -0
- package/dist/usage/usage.js +388 -0
- package/dist/utils/http.d.ts +7 -0
- package/dist/utils/http.js +81 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.js +3 -0
- package/dist/utils/security.d.ts +8 -0
- package/dist/utils/security.js +60 -0
- package/dist/utils/util.d.ts +40 -0
- package/dist/utils/util.js +176 -0
- package/package.json +73 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.1.0] - 2026-09-02
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **Google Antigravity OAuth Provider**: Complete PKCE browser flow with local loopback callback (`localhost:51121`) and headless paste-URL support.
|
|
12
|
+
- **Gemini 3.8 Flash Day-One Support**: Support for `gemini-3.8-flash` with dynamic effort-tier routing (`-low`, `-medium`, `-high`), 65,536 max output token limits, and fallback chain.
|
|
13
|
+
- **Prompt Cache Affinity & Trajectory Chaining**:
|
|
14
|
+
- Deterministic 63-bit session IDs derived from initial turn content to preserve KV-cache cluster routing.
|
|
15
|
+
- Trajectory state tracking (`agentId`, `trajectoryId`, `stepIndex`).
|
|
16
|
+
- Response ID chaining via `labels.last_execution_id` from SSE responses.
|
|
17
|
+
- Endpoint stickiness (`lastGoodEndpoint`) across Cloud Code Assist cluster endpoints.
|
|
18
|
+
- Cross-process session state persistence in `.pi/agent/cache/antigravity-sessions.json` to retain affinity across Pi restarts.
|
|
19
|
+
- **Image Generation**: Built-in `generate_image` tool and `/antigravity.image` command powered by Google's image models with aspect-ratio validation and directory containment.
|
|
20
|
+
- **Slash Commands**:
|
|
21
|
+
- `/antigravity.usage` for session token statistics and cache metrics.
|
|
22
|
+
- `/antigravity.models` for model catalog discovery.
|
|
23
|
+
- `/antigravity.doctor` for connection health and token validation.
|
|
24
|
+
- **Test Suite**: 42 unit tests covering catalog routing, fallbacks, thinking, message conversion, security, session affinity, and cross-process restart persistence.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 huynhgiabuu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# @heyhuynhgiabuu/pi-oauth-antigravity
|
|
2
|
+
|
|
3
|
+
Google Antigravity OAuth provider extension for [Pi](https://pi.dev). Connects Pi directly to Google Cloud Code Assist / Antigravity with zero-friction OAuth login, day-one support for **Gemini 3.8 Flash**, prompt-cache session affinity, and image generation.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Google OAuth Login**: Browser-based PKCE flow with local loopback callback (`localhost:51121`) and headless paste-URL fallback. Automatically handles token refresh with `AbortSignal` forwarding.
|
|
8
|
+
- **Day-One Gemini 3.8 Flash**: First-class support for `gemini-3.8-flash` with dynamic effort-tier routing (`-low`, `-medium`, `-high`), 65,536 max output token clamping, and fallback resilience.
|
|
9
|
+
- **Prompt Cache Affinity & Trajectory Chaining**:
|
|
10
|
+
- Deterministic 63-bit session IDs derived from initial turn content.
|
|
11
|
+
- Monotonic trajectory tracking (`agentId`, `trajectoryId`, `stepIndex`).
|
|
12
|
+
- Response ID chaining via `labels.last_execution_id`.
|
|
13
|
+
- Endpoint stickiness to prevent cluster hopping across Google's daily and fallback endpoints.
|
|
14
|
+
- Cross-restart session state persistence (`.pi/agent/cache/antigravity-sessions.json`) to maintain cluster affinity across quick Pi restarts.
|
|
15
|
+
- **Image Generation**: Built-in `generate_image` tool and `/antigravity.image` command powered by Google's image models with aspect-ratio selection and safe directory containment.
|
|
16
|
+
- **Diagnostic & Usage Tools**:
|
|
17
|
+
- `/antigravity.usage` — token counts, cache read efficiency, and session metrics.
|
|
18
|
+
- `/antigravity.models` — backend discovery of available Cloud Code Assist models.
|
|
19
|
+
- `/antigravity.doctor` — connection check, token expiry inspection, and diagnostic dump.
|
|
20
|
+
|
|
21
|
+
## Supported Models
|
|
22
|
+
|
|
23
|
+
| Public Model ID | Backend Wire ID | Max Output | Context Window |
|
|
24
|
+
| :--- | :--- | :--- | :--- |
|
|
25
|
+
| `antigravity/gemini-3.8-flash` | `gemini-3.8-flash-{low,medium,high}` | 65,536 | 1,048,576 |
|
|
26
|
+
| `antigravity/gemini-3.7-flash` | `gemini-3.7-flash-{low,medium,high}` | 65,536 | 1,048,576 |
|
|
27
|
+
| `antigravity/gemini-3.7-flash-thinking` | `gemini-3.7-flash-thinking` | 65,536 | 1,048,576 |
|
|
28
|
+
| `antigravity/gemini-3.6-flash` | `gemini-3.6-flash-{low,medium,high}` | 65,536 | 1,048,576 |
|
|
29
|
+
| `antigravity/gemini-3.5-flash` | `gemini-3.5-flash` | 8,192 | 1,048,576 |
|
|
30
|
+
| `antigravity/gemini-3.1-pro` | `gemini-3.1-pro` | 65,536 | 1,048,576 |
|
|
31
|
+
| `antigravity/claude-sonnet-4-6` | `claude-sonnet-4-6` | 64,000 | 200,000 |
|
|
32
|
+
| `antigravity/claude-opus-4-6` | `claude-opus-4-6` | 64,000 | 200,000 |
|
|
33
|
+
| `antigravity/gpt-oss-120b` | `gpt-oss-120b` | 8,192 | 131,072 |
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
Install directly into Pi via npm:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pi install npm:@heyhuynhgiabuu/pi-oauth-antigravity
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Or run directly from source:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pi -e /path/to/pi-oauth-antigravity/dist/index.js
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Setup & Login
|
|
50
|
+
|
|
51
|
+
1. Run Pi and start the OAuth login:
|
|
52
|
+
```bash
|
|
53
|
+
pi auth login --provider antigravity
|
|
54
|
+
```
|
|
55
|
+
2. Your browser will open the Google Sign-In page. Sign in with your Google account.
|
|
56
|
+
3. Once authenticated, the extension saves credentials and discovers your available Cloud Code Assist project.
|
|
57
|
+
4. Select or switch to any Antigravity model:
|
|
58
|
+
```bash
|
|
59
|
+
pi --model antigravity/gemini-3.8-flash
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Slash Commands
|
|
63
|
+
|
|
64
|
+
- `/antigravity.usage` — View current session usage, cached token statistics, and cost estimates.
|
|
65
|
+
- `/antigravity.models` — List dynamically fetched and statically registered models.
|
|
66
|
+
- `/antigravity.doctor` — Diagnose OAuth state, refresh token health, and endpoint connectivity.
|
|
67
|
+
- `/antigravity.image <prompt> [--aspect 1:1|16:9|...]` — Generate images directly to your project.
|
|
68
|
+
|
|
69
|
+
## Development
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
# Install dependencies
|
|
73
|
+
npm install
|
|
74
|
+
|
|
75
|
+
# Run unit tests (42 tests)
|
|
76
|
+
npm test
|
|
77
|
+
|
|
78
|
+
# Typecheck
|
|
79
|
+
npm run typecheck
|
|
80
|
+
|
|
81
|
+
# Build TypeScript to dist/
|
|
82
|
+
npm run build
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Credits & Upstream
|
|
86
|
+
|
|
87
|
+
Vendored and adapted from [Rahularya01/pi-antigravity](https://github.com/Rahularya01/pi-antigravity) (MIT License) with prompt-cache session affinity, day-one Gemini 3.8 Flash catalog, response chaining, and cross-process persistence.
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
|
|
91
|
+
[MIT](LICENSE) © 2026 huynhgiabuu
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { loginAntigravity, refreshAntigravityToken, getApiKey, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, AUTH_URL, TOKEN_URL, SCOPES, CALLBACK_HOST, OAUTH_CALLBACK_TIMEOUT_MS, } from "./oauth.js";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { AntigravityOAuthCredentials } from "../types/types.js";
|
|
3
|
+
export declare const REDIRECT_URI = "http://localhost:51121/oauth-callback";
|
|
4
|
+
export declare const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
|
|
5
|
+
export declare const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
6
|
+
export declare const OAUTH_CALLBACK_TIMEOUT_MS: number;
|
|
7
|
+
export declare const SCOPES: string[];
|
|
8
|
+
/**
|
|
9
|
+
* Default OAuth client is Google's public Antigravity desktop client (not a private app secret).
|
|
10
|
+
* Prefer ANTIGRAVITY_CLIENT_ID / ANTIGRAVITY_CLIENT_SECRET when you manage your own OAuth app.
|
|
11
|
+
*/
|
|
12
|
+
export declare const CLIENT_ID: string;
|
|
13
|
+
export declare const CLIENT_SECRET: string;
|
|
14
|
+
export declare const CALLBACK_HOST: string;
|
|
15
|
+
export declare function loginAntigravity(callbacks: OAuthLoginCallbacks): Promise<AntigravityOAuthCredentials>;
|
|
16
|
+
export declare function refreshAntigravityToken(credentials: OAuthCredentials, signal?: AbortSignal): Promise<AntigravityOAuthCredentials>;
|
|
17
|
+
export declare function getApiKey(credentials: OAuthCredentials): string;
|
|
18
|
+
export type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { defaultProjectId, loadCodeAssist } from "../client/client.js";
|
|
4
|
+
import { escapeHtml, antigravityEnv } from "../utils/util.js";
|
|
5
|
+
import { resolveCallbackHost, redactSecrets } from "../utils/security.js";
|
|
6
|
+
export const REDIRECT_URI = "http://localhost:51121/oauth-callback";
|
|
7
|
+
export const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
|
|
8
|
+
export const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
9
|
+
export const OAUTH_CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;
|
|
10
|
+
export const SCOPES = [
|
|
11
|
+
"https://www.googleapis.com/auth/aicode",
|
|
12
|
+
"https://www.googleapis.com/auth/cloud-platform",
|
|
13
|
+
"https://www.googleapis.com/auth/userinfo.email",
|
|
14
|
+
"https://www.googleapis.com/auth/userinfo.profile",
|
|
15
|
+
"https://www.googleapis.com/auth/cclog",
|
|
16
|
+
"https://www.googleapis.com/auth/experimentsandconfigs",
|
|
17
|
+
];
|
|
18
|
+
/**
|
|
19
|
+
* Default OAuth client is Google's public Antigravity desktop client (not a private app secret).
|
|
20
|
+
* Prefer ANTIGRAVITY_CLIENT_ID / ANTIGRAVITY_CLIENT_SECRET when you manage your own OAuth app.
|
|
21
|
+
*/
|
|
22
|
+
export const CLIENT_ID = antigravityEnv("CLIENT_ID") ||
|
|
23
|
+
atob("MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlc" +
|
|
24
|
+
"C5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ==");
|
|
25
|
+
export const CLIENT_SECRET = antigravityEnv("CLIENT_SECRET") || atob("R09DU1BYLUs1OEZXUjQ" + "4NkxkTEoxbUxCOHNYQzR6NnFEQWY=");
|
|
26
|
+
export const CALLBACK_HOST = resolveCallbackHost();
|
|
27
|
+
function oauthCallbackHeaders(contentType = "text/html; charset=utf-8") {
|
|
28
|
+
return {
|
|
29
|
+
"Content-Type": contentType,
|
|
30
|
+
"Cache-Control": "no-store",
|
|
31
|
+
"X-Content-Type-Options": "nosniff",
|
|
32
|
+
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'",
|
|
33
|
+
"Referrer-Policy": "no-referrer",
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function sanitizeOAuthProviderError(text) {
|
|
37
|
+
const redacted = redactSecrets(text).trim();
|
|
38
|
+
try {
|
|
39
|
+
const parsed = JSON.parse(redacted);
|
|
40
|
+
const parts = [parsed.error, parsed.error_description].filter((part) => typeof part === "string" && part.length > 0);
|
|
41
|
+
if (parts.length)
|
|
42
|
+
return parts.join(": ").slice(0, 300);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// not JSON
|
|
46
|
+
}
|
|
47
|
+
return redacted.slice(0, 300) || "unknown OAuth provider error";
|
|
48
|
+
}
|
|
49
|
+
function base64Url(buffer) {
|
|
50
|
+
return buffer.toString("base64url");
|
|
51
|
+
}
|
|
52
|
+
function generatePKCE() {
|
|
53
|
+
const verifier = base64Url(randomBytes(32));
|
|
54
|
+
const challenge = base64Url(createHash("sha256").update(verifier).digest());
|
|
55
|
+
return { verifier, challenge };
|
|
56
|
+
}
|
|
57
|
+
async function getUserEmail(token) {
|
|
58
|
+
try {
|
|
59
|
+
const res = await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json", {
|
|
60
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
61
|
+
});
|
|
62
|
+
if (!res.ok)
|
|
63
|
+
return undefined;
|
|
64
|
+
const data = (await res.json());
|
|
65
|
+
return data.email;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function closeServerGracefully(server) {
|
|
72
|
+
if ("closeAllConnections" in server && typeof server.closeAllConnections === "function") {
|
|
73
|
+
server.closeAllConnections();
|
|
74
|
+
}
|
|
75
|
+
server.close();
|
|
76
|
+
}
|
|
77
|
+
function startCallbackServer(expectedState) {
|
|
78
|
+
return new Promise((resolve, reject) => {
|
|
79
|
+
let settled = false;
|
|
80
|
+
let timeout;
|
|
81
|
+
let resolveCode;
|
|
82
|
+
let rejectCode;
|
|
83
|
+
const codePromise = new Promise((res, rej) => {
|
|
84
|
+
resolveCode = res;
|
|
85
|
+
rejectCode = rej;
|
|
86
|
+
});
|
|
87
|
+
const finish = (fn) => {
|
|
88
|
+
if (settled)
|
|
89
|
+
return;
|
|
90
|
+
settled = true;
|
|
91
|
+
if (timeout)
|
|
92
|
+
clearTimeout(timeout);
|
|
93
|
+
fn();
|
|
94
|
+
};
|
|
95
|
+
const server = createServer((req, res) => {
|
|
96
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
97
|
+
res.writeHead(405, oauthCallbackHeaders("text/plain; charset=utf-8"));
|
|
98
|
+
res.end("Method Not Allowed");
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const url = new URL(req.url || "", REDIRECT_URI);
|
|
102
|
+
if (url.pathname !== "/oauth-callback") {
|
|
103
|
+
res.writeHead(404, oauthCallbackHeaders());
|
|
104
|
+
res.end("Antigravity OAuth callback route not found.");
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const error = url.searchParams.get("error");
|
|
108
|
+
const code = url.searchParams.get("code");
|
|
109
|
+
const state = url.searchParams.get("state");
|
|
110
|
+
if (error) {
|
|
111
|
+
const safe = escapeHtml(error.slice(0, 200));
|
|
112
|
+
res.writeHead(400, oauthCallbackHeaders());
|
|
113
|
+
res.end(`Antigravity authentication failed: ${safe}`);
|
|
114
|
+
finish(() => rejectCode(new Error(`OAuth error: ${error.slice(0, 200)}`)));
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (!code || !state) {
|
|
118
|
+
res.writeHead(400, oauthCallbackHeaders());
|
|
119
|
+
res.end("Antigravity authentication failed: missing code or state.");
|
|
120
|
+
finish(() => rejectCode(new Error("Missing code or state in OAuth callback")));
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (state !== expectedState) {
|
|
124
|
+
res.writeHead(400, oauthCallbackHeaders());
|
|
125
|
+
res.end("Antigravity authentication failed: invalid state.");
|
|
126
|
+
finish(() => rejectCode(new Error("OAuth state mismatch")));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
res.writeHead(200, oauthCallbackHeaders());
|
|
130
|
+
res.end("Antigravity authentication complete. You can close this window and return to Pi.");
|
|
131
|
+
finish(() => resolveCode({ code, state }));
|
|
132
|
+
});
|
|
133
|
+
server.on("error", (err) => {
|
|
134
|
+
if (err.code === "EADDRINUSE") {
|
|
135
|
+
reject(new Error("Port 51121 is already in use by another process. Please close the process using port 51121 and retry /login antigravity."));
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
reject(err);
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
let closed = false;
|
|
142
|
+
const close = () => {
|
|
143
|
+
if (closed)
|
|
144
|
+
return;
|
|
145
|
+
closed = true;
|
|
146
|
+
closeServerGracefully(server);
|
|
147
|
+
};
|
|
148
|
+
const cleanup = () => {
|
|
149
|
+
finish(() => rejectCode(new Error("OAuth callback cancelled")));
|
|
150
|
+
close();
|
|
151
|
+
};
|
|
152
|
+
server.listen(51121, CALLBACK_HOST, () => {
|
|
153
|
+
timeout = setTimeout(() => {
|
|
154
|
+
finish(() => rejectCode(new Error("OAuth callback timed out waiting for browser login")));
|
|
155
|
+
close();
|
|
156
|
+
}, OAUTH_CALLBACK_TIMEOUT_MS);
|
|
157
|
+
resolve({ server, waitForCode: () => codePromise, cleanup });
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
function credentialProjectId(credentials) {
|
|
162
|
+
const projectId = credentials.projectId;
|
|
163
|
+
return typeof projectId === "string" ? projectId : undefined;
|
|
164
|
+
}
|
|
165
|
+
function credentialEmail(credentials) {
|
|
166
|
+
const email = credentials.email;
|
|
167
|
+
return typeof email === "string" ? email : undefined;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Parse a callback URL (or bare query string) pasted by the user from a
|
|
171
|
+
* remote/headless browser that could not reach the local callback server.
|
|
172
|
+
* Returns the validated {code, state} or throws a descriptive error. The checks
|
|
173
|
+
* mirror the local callback server so a pasted URL is accepted under the exact
|
|
174
|
+
* same rules as a same-machine browser redirect.
|
|
175
|
+
*/
|
|
176
|
+
function parsePastedCallback(raw, expectedState) {
|
|
177
|
+
const text = (raw ?? "").trim();
|
|
178
|
+
if (!text) {
|
|
179
|
+
throw new Error("No callback pasted. Paste the full URL from your browser's address bar (http://localhost:51121/oauth-callback?…).");
|
|
180
|
+
}
|
|
181
|
+
let url;
|
|
182
|
+
try {
|
|
183
|
+
url = new URL(text);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
// Bare query string: "state=…&code=…" or "?state=…&code=…"
|
|
187
|
+
const qs = text.startsWith("?") ? text.slice(1) : text;
|
|
188
|
+
url = new URL(`http://localhost:51121/oauth-callback?${qs}`);
|
|
189
|
+
}
|
|
190
|
+
const error = url.searchParams.get("error");
|
|
191
|
+
if (error)
|
|
192
|
+
throw new Error(`OAuth error from browser: ${error.slice(0, 200)}`);
|
|
193
|
+
const code = url.searchParams.get("code");
|
|
194
|
+
const state = url.searchParams.get("state");
|
|
195
|
+
if (!code || !state) {
|
|
196
|
+
throw new Error("Pasted text is missing 'code' or 'state'. Paste the FULL callback URL from your browser's address bar (http://localhost:51121/oauth-callback?…).");
|
|
197
|
+
}
|
|
198
|
+
if (state !== expectedState) {
|
|
199
|
+
throw new Error("State mismatch: that callback is from a different sign-in. Re-run /login antigravity, sign in again, and paste the new URL.");
|
|
200
|
+
}
|
|
201
|
+
return { code, state };
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Resolve the authorization code from either the local callback server (browser
|
|
205
|
+
* on the same machine) or a pasted callback URL (browser on a remote/headless
|
|
206
|
+
* machine that cannot reach localhost:51121). Whichever provides a valid code
|
|
207
|
+
* first wins; the losing path is cancelled. Honors callbacks.signal for cancel.
|
|
208
|
+
*/
|
|
209
|
+
async function acquireAuthCode(expectedState, opts) {
|
|
210
|
+
const { waitForCode, callbacks } = opts;
|
|
211
|
+
// Signals the losing candidate(s) to stop once the race settles.
|
|
212
|
+
const settle = new AbortController();
|
|
213
|
+
const candidates = [waitForCode()];
|
|
214
|
+
// Manual paste path: offered whenever the callback surface can prompt.
|
|
215
|
+
if (typeof callbacks.onPrompt === "function") {
|
|
216
|
+
const promptLoop = async () => {
|
|
217
|
+
let promptMessage = "Remote/headless machine (your browser can't reach localhost:51121)? " +
|
|
218
|
+
"After signing in, paste the full callback URL shown in your browser's address bar.";
|
|
219
|
+
while (true) {
|
|
220
|
+
if (callbacks.signal?.aborted || settle.signal.aborted) {
|
|
221
|
+
throw new Error("Login cancelled");
|
|
222
|
+
}
|
|
223
|
+
let text;
|
|
224
|
+
try {
|
|
225
|
+
text = await callbacks.onPrompt({
|
|
226
|
+
message: promptMessage,
|
|
227
|
+
placeholder: "http://localhost:51121/oauth-callback?state=…&code=…",
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
// Prompt/transport failure — propagate, do not retry.
|
|
232
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
233
|
+
}
|
|
234
|
+
if (callbacks.signal?.aborted || settle.signal.aborted) {
|
|
235
|
+
throw new Error("Login cancelled");
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
return parsePastedCallback(text, expectedState);
|
|
239
|
+
}
|
|
240
|
+
catch (err) {
|
|
241
|
+
if (callbacks.signal?.aborted || settle.signal.aborted) {
|
|
242
|
+
throw new Error("Login cancelled", { cause: err });
|
|
243
|
+
}
|
|
244
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
245
|
+
promptMessage = `Invalid callback (${errorMessage}). Please paste the full URL:`;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
candidates.push(promptLoop());
|
|
250
|
+
}
|
|
251
|
+
// Flow cancellation (escape) aborts the whole login when a signal is provided.
|
|
252
|
+
let removeAbortListener;
|
|
253
|
+
if (callbacks.signal) {
|
|
254
|
+
candidates.push(new Promise((_resolve, reject) => {
|
|
255
|
+
const signal = callbacks.signal;
|
|
256
|
+
if (signal.aborted)
|
|
257
|
+
return reject(new Error("Login cancelled"));
|
|
258
|
+
const onAbort = () => reject(new Error("Login cancelled"));
|
|
259
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
260
|
+
removeAbortListener = () => signal.removeEventListener("abort", onAbort);
|
|
261
|
+
}));
|
|
262
|
+
}
|
|
263
|
+
// Suppress unhandled rejections from losing candidates after the race settles.
|
|
264
|
+
for (const candidate of candidates) {
|
|
265
|
+
candidate.catch(() => { });
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
return await Promise.race(candidates);
|
|
269
|
+
}
|
|
270
|
+
finally {
|
|
271
|
+
settle.abort();
|
|
272
|
+
removeAbortListener?.();
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
export async function loginAntigravity(callbacks) {
|
|
276
|
+
const { verifier, challenge } = generatePKCE();
|
|
277
|
+
// State must be independent of the PKCE verifier so a leaked callback URL
|
|
278
|
+
// cannot also disclose the code_verifier needed to mint tokens.
|
|
279
|
+
const state = base64Url(randomBytes(32));
|
|
280
|
+
const { waitForCode, cleanup } = await startCallbackServer(state);
|
|
281
|
+
try {
|
|
282
|
+
const authParams = new URLSearchParams({
|
|
283
|
+
client_id: CLIENT_ID,
|
|
284
|
+
response_type: "code",
|
|
285
|
+
redirect_uri: REDIRECT_URI,
|
|
286
|
+
scope: SCOPES.join(" "),
|
|
287
|
+
code_challenge: challenge,
|
|
288
|
+
code_challenge_method: "S256",
|
|
289
|
+
state,
|
|
290
|
+
access_type: "offline",
|
|
291
|
+
prompt: "consent",
|
|
292
|
+
});
|
|
293
|
+
callbacks.onAuth({
|
|
294
|
+
url: `${AUTH_URL}?${authParams.toString()}`,
|
|
295
|
+
instructions: "Complete Google sign-in. Pi captures the local callback automatically — or, on a remote/headless machine, paste the callback URL when prompted.",
|
|
296
|
+
});
|
|
297
|
+
const { code, state: returnedState } = await acquireAuthCode(state, {
|
|
298
|
+
waitForCode,
|
|
299
|
+
callbacks,
|
|
300
|
+
});
|
|
301
|
+
if (returnedState !== state)
|
|
302
|
+
throw new Error("OAuth state mismatch");
|
|
303
|
+
const tokenResponse = await fetch(TOKEN_URL, {
|
|
304
|
+
method: "POST",
|
|
305
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
306
|
+
body: new URLSearchParams({
|
|
307
|
+
client_id: CLIENT_ID,
|
|
308
|
+
client_secret: CLIENT_SECRET,
|
|
309
|
+
code,
|
|
310
|
+
grant_type: "authorization_code",
|
|
311
|
+
redirect_uri: REDIRECT_URI,
|
|
312
|
+
code_verifier: verifier,
|
|
313
|
+
}).toString(),
|
|
314
|
+
});
|
|
315
|
+
if (!tokenResponse.ok) {
|
|
316
|
+
throw new Error(`Token exchange failed: ${sanitizeOAuthProviderError(await tokenResponse.text())}`);
|
|
317
|
+
}
|
|
318
|
+
const tokenData = (await tokenResponse.json());
|
|
319
|
+
if (!tokenData.refresh_token) {
|
|
320
|
+
throw new Error("No refresh token received. Re-run /login antigravity and allow offline access.");
|
|
321
|
+
}
|
|
322
|
+
const [email, discoveredProject] = await Promise.all([
|
|
323
|
+
getUserEmail(tokenData.access_token),
|
|
324
|
+
loadCodeAssist(tokenData.access_token),
|
|
325
|
+
]);
|
|
326
|
+
return {
|
|
327
|
+
refresh: tokenData.refresh_token,
|
|
328
|
+
access: tokenData.access_token,
|
|
329
|
+
expires: Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000,
|
|
330
|
+
projectId: discoveredProject || defaultProjectId(email || "antigravity-default"),
|
|
331
|
+
email,
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
finally {
|
|
335
|
+
cleanup();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
export async function refreshAntigravityToken(credentials, signal) {
|
|
339
|
+
const response = await fetch(TOKEN_URL, {
|
|
340
|
+
method: "POST",
|
|
341
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
342
|
+
body: new URLSearchParams({
|
|
343
|
+
client_id: CLIENT_ID,
|
|
344
|
+
client_secret: CLIENT_SECRET,
|
|
345
|
+
refresh_token: credentials.refresh,
|
|
346
|
+
grant_type: "refresh_token",
|
|
347
|
+
}).toString(),
|
|
348
|
+
signal,
|
|
349
|
+
});
|
|
350
|
+
if (!response.ok) {
|
|
351
|
+
throw new Error(`Antigravity token refresh failed: ${sanitizeOAuthProviderError(await response.text())}`);
|
|
352
|
+
}
|
|
353
|
+
const data = (await response.json());
|
|
354
|
+
// Every refresh mints a brand-new access token, so loadCodeAssist's token-keyed cache
|
|
355
|
+
// can never hit here — skip the extra round-trip entirely when we already know the
|
|
356
|
+
// project id (the normal case; it's set at login and doesn't change token to token).
|
|
357
|
+
const existingProjectId = credentialProjectId(credentials);
|
|
358
|
+
const discoveredProject = existingProjectId ? undefined : await loadCodeAssist(data.access_token);
|
|
359
|
+
const email = credentialEmail(credentials);
|
|
360
|
+
return {
|
|
361
|
+
...credentials,
|
|
362
|
+
refresh: data.refresh_token || credentials.refresh,
|
|
363
|
+
access: data.access_token,
|
|
364
|
+
expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,
|
|
365
|
+
projectId: existingProjectId || discoveredProject || defaultProjectId(email || "antigravity-default"),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
export function getApiKey(credentials) {
|
|
369
|
+
const email = credentialEmail(credentials);
|
|
370
|
+
return JSON.stringify({
|
|
371
|
+
token: credentials.access,
|
|
372
|
+
projectId: credentialProjectId(credentials) || defaultProjectId(email || "antigravity-default"),
|
|
373
|
+
});
|
|
374
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { AntigravityApiKey, DynamicModelInfo } from "../types/types.js";
|
|
2
|
+
export declare const DEFAULT_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
|
|
3
|
+
export declare const ENDPOINT_FALLBACKS: string[];
|
|
4
|
+
/** UUID-shaped stable id from a seed (account email preferred over cwd). */
|
|
5
|
+
export declare function stableProjectId(seed: string): string;
|
|
6
|
+
/**
|
|
7
|
+
* Fallback project id when discovery fails.
|
|
8
|
+
* Prefer ANTIGRAVITY_PROJECT_ID, then a stable seed (email), never process.cwd().
|
|
9
|
+
*/
|
|
10
|
+
export declare function defaultProjectId(seed?: string): string;
|
|
11
|
+
/** @deprecated Use defaultProjectId(seed); kept for scripts that imported the old constant. */
|
|
12
|
+
export declare const DEFAULT_PROJECT_ID: string;
|
|
13
|
+
export declare function endpointCandidates(preferredEndpoint?: string): string[];
|
|
14
|
+
export declare function antigravityHeaders(token: string): Record<string, string>;
|
|
15
|
+
export declare function jsonOrTextError(text: string): string;
|
|
16
|
+
export declare function parseApiKey(apiKeyRaw: string | undefined): AntigravityApiKey;
|
|
17
|
+
export declare function extractProjectId(data: unknown): string | undefined;
|
|
18
|
+
/** Runtime ids look like gemini-*, claude-*, gpt-oss-*, never MODEL_PLACEHOLDER_* enums. */
|
|
19
|
+
export declare function isUsableRuntimeModelId(id: string): boolean;
|
|
20
|
+
export declare function fetchAvailableRuntimeModel(token: string, projectId: string, requestedRuntimeModel: string): Promise<DynamicModelInfo | undefined>;
|
|
21
|
+
export declare function clearModelCache(): void;
|
|
22
|
+
/** Discover project id with a short in-memory LRU cache keyed by access token. */
|
|
23
|
+
export declare function loadCodeAssist(token: string): Promise<string | undefined>;
|
|
24
|
+
export declare function clearProjectCache(): void;
|
|
25
|
+
export declare function resolveProjectId(opts: {
|
|
26
|
+
token: string;
|
|
27
|
+
credentialProjectId?: string;
|
|
28
|
+
email?: string;
|
|
29
|
+
warmedProject?: string | null;
|
|
30
|
+
}): string;
|
|
31
|
+
/** Build a diagnostic suffix using the active request bag. */
|
|
32
|
+
export declare function formatRequestDiagnostics(extra: {
|
|
33
|
+
projectId: string;
|
|
34
|
+
runtimeModel: string;
|
|
35
|
+
}): string;
|