@zhexin/pi-agy 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jiang zhexin
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 CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # Pi AGY
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Antigravity OAuth provider for the [Pi](https://pi.dev) coding agent.
4
+
5
+ ## Quick start
6
+
7
+ ```bash
8
+ pi install npm:@zhexin/pi-agy
9
+
10
+ pi auth login agy
11
+ ```
12
+
13
+ ## License
14
+
15
+ MIT
package/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./src/index.ts";
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@zhexin/pi-agy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Antigravity OAuth provider for the Pi agent.",
4
+ "version": "0.0.1",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "pi-package",
9
+ "antigravity",
10
+ "oauth"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/jiang-zhexin/pi-pi.git",
15
+ "directory": "packages/agy"
16
+ },
17
+ "homepage": "https://github.com/jiang-zhexin/pi-pi/tree/HEAD/packages/agy#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/jiang-zhexin/pi-pi/issues"
20
+ },
21
+ "files": [
22
+ "src/*",
23
+ "index.ts"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public",
27
+ "registry": "https://registry.npmjs.org/"
28
+ },
29
+ "exports": {
30
+ ".": "./index.ts"
31
+ },
32
+ "peerDependencies": {
33
+ "@earendil-works/pi-ai": "*",
34
+ "@earendil-works/pi-coding-agent": "*"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "@earendil-works/pi-ai": {
38
+ "optional": true
39
+ },
40
+ "@earendil-works/pi-coding-agent": {
41
+ "optional": true
42
+ }
43
+ },
44
+ "pi": {
45
+ "extensions": [
46
+ "./index.ts"
47
+ ]
48
+ }
49
+ }
package/src/api.ts ADDED
@@ -0,0 +1,241 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { once } from "node:events";
3
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
4
+ import { createInterface } from "node:readline";
5
+ import { Readable } from "node:stream";
6
+
7
+ import {
8
+ clampThinkingLevel,
9
+ lazyStream,
10
+ type GoogleOptions,
11
+ type Model,
12
+ type ModelThinkingLevel,
13
+ type ProviderStreams,
14
+ type SimpleStreamOptions,
15
+ type StreamOptions,
16
+ type TranscriptContext,
17
+ } from "@earendil-works/pi-ai";
18
+ import { clampMaxTokensToContext } from "@earendil-works/pi-ai/api/simple-options";
19
+ import { googleGenerativeAIApi } from "@earendil-works/pi-ai/compat";
20
+
21
+ import { endpointUrl, PROJECT_HEADER, USER_AGENT } from "./ccpa.ts";
22
+
23
+ async function readBody(request: IncomingMessage): Promise<unknown> {
24
+ const chunks: Buffer[] = [];
25
+ let size = 0;
26
+ for await (const chunk of request) {
27
+ size += chunk.length;
28
+ if (size > 64 * 1024 * 1024) throw new Error("AGY request exceeds 64 MiB.");
29
+ chunks.push(chunk);
30
+ }
31
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
32
+ }
33
+
34
+ async function unwrap(
35
+ upstream: Response,
36
+ response: ServerResponse,
37
+ signal: AbortSignal,
38
+ ): Promise<void> {
39
+ if (!upstream.body) throw new Error("AGY returned an empty response body.");
40
+ const input = Readable.fromWeb(upstream.body).setEncoding("utf8");
41
+ const lines = createInterface({ input, crlfDelay: Infinity });
42
+ let data: string[] = [];
43
+ const flush = async () => {
44
+ if (!data.length) return;
45
+ const text = data.join("\n");
46
+ data = [];
47
+ if (text === "[DONE]") return;
48
+ const event = JSON.parse(text) as { response?: unknown };
49
+ if (!response.write(`data: ${JSON.stringify(event.response ?? event)}\n\n`)) {
50
+ await once(response, "drain", { signal });
51
+ }
52
+ };
53
+ try {
54
+ for await (const line of lines) {
55
+ signal.throwIfAborted();
56
+ if (!line) await flush();
57
+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
58
+ }
59
+ await flush();
60
+ } finally {
61
+ lines.close();
62
+ input.destroy();
63
+ }
64
+ }
65
+
66
+ async function bridge(
67
+ model: Model<string>,
68
+ backendId: string,
69
+ access: string,
70
+ project: string,
71
+ endpoint: string,
72
+ options: StreamOptions,
73
+ ) {
74
+ const key = randomBytes(32).toString("base64url");
75
+ const forward = async (request: IncomingMessage, response: ServerResponse) => {
76
+ const supplied = request.headers["x-goog-api-key"];
77
+ if (
78
+ typeof supplied !== "string" ||
79
+ Buffer.byteLength(supplied) !== Buffer.byteLength(key) ||
80
+ !timingSafeEqual(Buffer.from(supplied), Buffer.from(key)) ||
81
+ request.headers.origin
82
+ ) {
83
+ response.writeHead(401).end();
84
+ return;
85
+ }
86
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
87
+ const match = /^\/models\/([^/]+):streamGenerateContent$/.exec(url.pathname);
88
+ if (request.method !== "POST" || !match?.[1]) {
89
+ response.writeHead(404).end();
90
+ return;
91
+ }
92
+ const disconnected = new AbortController();
93
+ response.on("close", () => disconnected.abort());
94
+ const signal = AbortSignal.any([
95
+ disconnected.signal,
96
+ AbortSignal.timeout(options.timeoutMs ?? 300_000),
97
+ ...(options.signal ? [options.signal] : []),
98
+ ]);
99
+ const body = await readBody(request);
100
+ const upstream = await (options.fetch ?? fetch)(
101
+ `${endpoint}/v1internal:streamGenerateContent?alt=sse`,
102
+ {
103
+ method: "POST",
104
+ headers: {
105
+ Authorization: `Bearer ${access}`,
106
+ "Content-Type": "application/json",
107
+ "User-Agent": USER_AGENT,
108
+ },
109
+ body: JSON.stringify({ project, model: backendId, request: body }),
110
+ signal,
111
+ redirect: "error",
112
+ },
113
+ );
114
+ try {
115
+ await options.onResponse?.(
116
+ { status: upstream.status, headers: Object.fromEntries(upstream.headers) },
117
+ model,
118
+ );
119
+ response.writeHead(upstream.status, {
120
+ "Content-Type":
121
+ upstream.headers.get("content-type") ??
122
+ (upstream.ok ? "text/event-stream" : "application/json"),
123
+ ...(upstream.headers.has("retry-after")
124
+ ? { "Retry-After": upstream.headers.get("retry-after")! }
125
+ : {}),
126
+ });
127
+ if (upstream.ok) await unwrap(upstream, response, signal);
128
+ else response.write(Buffer.from(await upstream.arrayBuffer()));
129
+ response.end();
130
+ } finally {
131
+ if (upstream.body && !upstream.body.locked) await upstream.body.cancel().catch(() => {});
132
+ }
133
+ };
134
+ const server = createServer((request, response) => {
135
+ void forward(request, response).catch((error: unknown) => {
136
+ if (response.destroyed) return;
137
+ if (response.headersSent) response.destroy(error instanceof Error ? error : undefined);
138
+ else
139
+ response.writeHead(502, { "Content-Type": "application/json" }).end(
140
+ JSON.stringify({
141
+ error: {
142
+ code: 502,
143
+ message: error instanceof Error ? error.message : "AGY forwarding failed",
144
+ },
145
+ }),
146
+ );
147
+ });
148
+ });
149
+ await new Promise<void>((resolve, reject) => {
150
+ server.once("error", reject);
151
+ server.listen(0, "127.0.0.1", resolve);
152
+ });
153
+ server.unref();
154
+ const address = server.address();
155
+ if (!address || typeof address === "string") {
156
+ server.close();
157
+ throw new Error("Could not start the AGY request adapter.");
158
+ }
159
+ return {
160
+ key,
161
+ baseUrl: `http://127.0.0.1:${address.port}`,
162
+ close() {
163
+ server.close();
164
+ server.closeAllConnections();
165
+ },
166
+ };
167
+ }
168
+
169
+ const google = googleGenerativeAIApi();
170
+
171
+ function stream(
172
+ method: "stream" | "streamSimple",
173
+ model: Model<string>,
174
+ context: TranscriptContext,
175
+ options: SimpleStreamOptions & GoogleOptions = {},
176
+ ) {
177
+ return lazyStream(
178
+ model,
179
+ async () => {
180
+ options.signal?.throwIfAborted();
181
+ const headers = new Headers();
182
+ for (const [name, value] of Object.entries({ ...model.headers, ...options.headers }))
183
+ if (value !== null) headers.set(name, value);
184
+ const project = headers.get(PROJECT_HEADER);
185
+ if (!options.apiKey || !project) throw new Error("Run /login agy to authenticate.");
186
+ const requestedLevel =
187
+ method === "streamSimple"
188
+ ? (options.reasoning ?? "off")
189
+ : options.thinking?.enabled
190
+ ? ((options.thinking.level?.toLowerCase() as ModelThinkingLevel | undefined) ??
191
+ "medium")
192
+ : "off";
193
+ const level = clampThinkingLevel(model, requestedLevel);
194
+ const backendId = model.thinkingLevelMap?.[level];
195
+ const adapter = await bridge(
196
+ model,
197
+ backendId ?? model.id,
198
+ options.apiKey,
199
+ project,
200
+ endpointUrl(model.baseUrl),
201
+ options,
202
+ );
203
+ const { fetch: _fetch, onResponse: _onResponse, ...innerOptions } = options;
204
+ headers.delete(PROJECT_HEADER);
205
+ headers.delete("authorization");
206
+ headers.delete("x-goog-api-key");
207
+ return (async function* () {
208
+ try {
209
+ // AGY selects thinking effort through the backend ID, not Gemini's thinking config.
210
+ yield* google[backendId ? "stream" : method](
211
+ { ...model, baseUrl: adapter.baseUrl, headers: Object.fromEntries(headers) },
212
+ context,
213
+ {
214
+ ...innerOptions,
215
+ maxTokens:
216
+ method === "streamSimple"
217
+ ? clampMaxTokensToContext(
218
+ model,
219
+ context,
220
+ innerOptions.maxTokens ?? model.maxTokens,
221
+ )
222
+ : (innerOptions.maxTokens ?? model.maxTokens),
223
+ ...(backendId ? { thinking: { enabled: true } } : {}),
224
+ apiKey: adapter.key,
225
+ headers: Object.fromEntries(headers),
226
+ },
227
+ );
228
+ } finally {
229
+ adapter.close();
230
+ }
231
+ })();
232
+ },
233
+ undefined,
234
+ options.signal,
235
+ );
236
+ }
237
+
238
+ export const api: ProviderStreams = {
239
+ stream: (model, context, options) => stream("stream", model, context, options),
240
+ streamSimple: (model, context, options) => stream("streamSimple", model, context, options),
241
+ };
package/src/auth.ts ADDED
@@ -0,0 +1,159 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+
4
+ import type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from "@earendil-works/pi-ai";
5
+
6
+ import { agyCredential, jsonRequest, onboard, PROJECT_HEADER } from "./ccpa.ts";
7
+
8
+ const CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
9
+ const CLIENT_SECRET = "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";
10
+ const SCOPES = ["cloud-platform", "userinfo.email", "aicode"].map(
11
+ (scope) => `https://www.googleapis.com/auth/${scope}`,
12
+ );
13
+
14
+ type Token = { access_token: string; refresh_token?: string; expires_in: number };
15
+
16
+ async function exchange(params: Record<string, string>, signal: AbortSignal): Promise<Token> {
17
+ const token = await jsonRequest<Token>(
18
+ "https://oauth2.googleapis.com/token",
19
+ {
20
+ method: "POST",
21
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
22
+ body: new URLSearchParams({
23
+ client_id: CLIENT_ID,
24
+ client_secret: CLIENT_SECRET,
25
+ ...params,
26
+ }).toString(),
27
+ },
28
+ signal,
29
+ );
30
+ if (
31
+ typeof token.access_token !== "string" ||
32
+ !token.access_token ||
33
+ !Number.isFinite(token.expires_in) ||
34
+ token.expires_in <= 0 ||
35
+ (token.refresh_token !== undefined && typeof token.refresh_token !== "string")
36
+ ) {
37
+ throw new Error("Google returned an invalid OAuth token response.");
38
+ }
39
+ return token;
40
+ }
41
+
42
+ async function login(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {
43
+ const signal = AbortSignal.any([interaction.signal, AbortSignal.timeout(300_000)]);
44
+ signal.throwIfAborted();
45
+ const verifier = randomBytes(32).toString("base64url");
46
+ const state = randomBytes(32).toString("base64url");
47
+ const callback = Promise.withResolvers<string>();
48
+ void callback.promise.catch(() => {});
49
+ let claimed = false;
50
+ const server = createServer((request, response) => {
51
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
52
+ response.setHeader("Content-Type", "text/plain; charset=utf-8");
53
+ response.setHeader("Cache-Control", "no-store");
54
+ if (request.method !== "GET" || url.pathname !== "/") {
55
+ response.writeHead(404).end("Not found");
56
+ } else if (
57
+ url.searchParams.getAll("state").length !== 1 ||
58
+ url.searchParams.get("state") !== state
59
+ ) {
60
+ response.writeHead(400).end("Invalid OAuth state");
61
+ } else if (claimed) {
62
+ response.writeHead(409).end("Callback already received");
63
+ } else if (url.searchParams.has("error")) {
64
+ claimed = true;
65
+ response.writeHead(400).end("Authorization failed. Return to Pi.");
66
+ callback.reject(new Error(`Google authorization failed: ${url.searchParams.get("error")}`));
67
+ } else if (url.searchParams.getAll("code").length !== 1 || !url.searchParams.get("code")) {
68
+ response.writeHead(400).end("Missing authorization code");
69
+ } else {
70
+ claimed = true;
71
+ response.end("Authorization received. Return to Pi to finish signing in.");
72
+ callback.resolve(url.searchParams.get("code")!);
73
+ }
74
+ });
75
+ const onAbort = () =>
76
+ callback.reject(
77
+ new Error(interaction.signal.aborted ? "Login cancelled" : "AGY login timed out."),
78
+ );
79
+ try {
80
+ await new Promise<void>((resolve, reject) => {
81
+ server.once("error", reject);
82
+ server.listen(0, "127.0.0.1", resolve);
83
+ });
84
+ server.on("error", (error) => callback.reject(error));
85
+ signal.addEventListener("abort", onAbort, { once: true });
86
+ signal.throwIfAborted();
87
+ const address = server.address();
88
+ if (!address || typeof address === "string")
89
+ throw new Error("Could not start the OAuth callback listener.");
90
+ const redirectUri = `http://127.0.0.1:${address.port}/`;
91
+ const params = new URLSearchParams({
92
+ client_id: CLIENT_ID,
93
+ redirect_uri: redirectUri,
94
+ response_type: "code",
95
+ scope: SCOPES.join(" "),
96
+ access_type: "offline",
97
+ prompt: "consent",
98
+ state,
99
+ code_challenge: createHash("sha256").update(verifier).digest("base64url"),
100
+ code_challenge_method: "S256",
101
+ });
102
+ interaction.notify({
103
+ type: "auth_url",
104
+ url: `https://accounts.google.com/o/oauth2/v2/auth?${params}`,
105
+ instructions: "Complete Google sign-in in the browser on this machine.",
106
+ });
107
+ const code = await callback.promise;
108
+ const token = await exchange(
109
+ {
110
+ grant_type: "authorization_code",
111
+ code,
112
+ code_verifier: verifier,
113
+ redirect_uri: redirectUri,
114
+ },
115
+ signal,
116
+ );
117
+ if (!token.refresh_token)
118
+ throw new Error("Google returned no refresh token. Run /login agy again and grant consent.");
119
+ interaction.notify({
120
+ type: "progress",
121
+ message: "Resolving AGY project and model endpoint...",
122
+ });
123
+ const backend = await onboard(token.access_token, signal);
124
+ return {
125
+ type: "oauth",
126
+ access: token.access_token,
127
+ refresh: token.refresh_token,
128
+ expires: Date.now() + token.expires_in * 1000,
129
+ ...backend,
130
+ };
131
+ } finally {
132
+ signal.removeEventListener("abort", onAbort);
133
+ server.close();
134
+ server.closeAllConnections();
135
+ }
136
+ }
137
+
138
+ export const oauth: OAuthAuth = {
139
+ name: "Antigravity",
140
+ isSubscription: true,
141
+ login,
142
+ async refresh(credential, signal) {
143
+ agyCredential(credential);
144
+ const token = await exchange(
145
+ { grant_type: "refresh_token", refresh_token: credential.refresh },
146
+ signal,
147
+ );
148
+ return {
149
+ ...credential,
150
+ access: token.access_token,
151
+ refresh: token.refresh_token || credential.refresh,
152
+ expires: Date.now() + token.expires_in * 1000,
153
+ };
154
+ },
155
+ async toAuth(credential) {
156
+ const { access, project, endpoint } = agyCredential(credential);
157
+ return { apiKey: access, baseUrl: endpoint, headers: { [PROJECT_HEADER]: project } };
158
+ },
159
+ };
package/src/ccpa.ts ADDED
@@ -0,0 +1,222 @@
1
+ import { arch, platform } from "node:os";
2
+ import { setTimeout } from "node:timers/promises";
3
+
4
+ import type {
5
+ Model,
6
+ ModelThinkingLevel,
7
+ OAuthCredential,
8
+ ThinkingLevelMap,
9
+ } from "@earendil-works/pi-ai";
10
+
11
+ const PROD = "https://cloudcode-pa.googleapis.com";
12
+ const DAILY = "https://daily-cloudcode-pa.googleapis.com";
13
+ export const PROJECT_HEADER = "x-agy-project";
14
+ export const USER_AGENT = `antigravity/acp/1.5.0 (aidev_client; os_type=${platform() === "win32" ? "windows" : platform()}; arch=${arch() === "x64" ? "amd64" : arch()}; proxy_client=antigravity/sdk)`;
15
+
16
+ export type AgyCredential = OAuthCredential & { project: string; endpoint: string };
17
+
18
+ type LoadResult = {
19
+ currentTier?: { id?: string };
20
+ paidTier?: { usesGcpTos?: boolean };
21
+ cloudaicompanionProject?: string;
22
+ allowedTiers?: { id?: string }[];
23
+ ineligibleTiers?: { reasonMessage?: string }[];
24
+ };
25
+
26
+ type Catalog = {
27
+ models: Record<
28
+ string,
29
+ {
30
+ displayName?: string;
31
+ maxTokens: number;
32
+ maxOutputTokens: number;
33
+ recommended?: boolean;
34
+ }
35
+ >;
36
+ agentModelSorts: {
37
+ groups: {
38
+ modelIds: string[];
39
+ }[];
40
+ }[];
41
+ };
42
+
43
+ export function endpointUrl(value: string): string {
44
+ if (value !== PROD && value !== DAILY)
45
+ throw new Error("Invalid AGY endpoint. Run /login agy again.");
46
+ return value;
47
+ }
48
+
49
+ export function agyCredential(credential: OAuthCredential): AgyCredential {
50
+ if (
51
+ typeof credential.project !== "string" ||
52
+ !credential.project ||
53
+ typeof credential.endpoint !== "string"
54
+ ) {
55
+ throw new Error("AGY credentials are incomplete. Run /login agy again.");
56
+ }
57
+ endpointUrl(credential.endpoint);
58
+ return credential as AgyCredential;
59
+ }
60
+
61
+ export async function jsonRequest<T>(
62
+ url: string,
63
+ init: RequestInit,
64
+ signal: AbortSignal,
65
+ ): Promise<T> {
66
+ const response = await fetch(url, {
67
+ ...init,
68
+ redirect: "error",
69
+ signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
70
+ });
71
+ const body = (await response.json().catch(() => undefined)) as
72
+ | {
73
+ error?: string | { message?: string };
74
+ error_description?: string;
75
+ }
76
+ | undefined;
77
+ if (!response.ok) {
78
+ const message =
79
+ body?.error_description ??
80
+ (typeof body?.error === "string" ? body.error : body?.error?.message);
81
+ throw new Error(`AGY request failed (HTTP ${response.status})${message ? `: ${message}` : ""}`);
82
+ }
83
+ if (!body || typeof body !== "object" || Array.isArray(body))
84
+ throw new Error("AGY returned an invalid JSON response.");
85
+ return body as T;
86
+ }
87
+
88
+ function rpc<T>(
89
+ access: string,
90
+ endpoint: string,
91
+ method: string,
92
+ body: unknown,
93
+ signal: AbortSignal,
94
+ ): Promise<T> {
95
+ return jsonRequest<T>(
96
+ `${endpointUrl(endpoint)}/v1internal:${method}`,
97
+ {
98
+ method: "POST",
99
+ headers: {
100
+ Authorization: `Bearer ${access}`,
101
+ "Content-Type": "application/json",
102
+ "User-Agent": USER_AGENT,
103
+ },
104
+ body: JSON.stringify(body),
105
+ },
106
+ signal,
107
+ );
108
+ }
109
+
110
+ export async function onboard(
111
+ access: string,
112
+ signal: AbortSignal,
113
+ ): Promise<{ project: string; endpoint: string }> {
114
+ const load = (endpoint: string) =>
115
+ rpc<LoadResult>(
116
+ access,
117
+ endpoint,
118
+ "loadCodeAssist",
119
+ { metadata: { ideType: "ANTIGRAVITY" } },
120
+ signal,
121
+ );
122
+ let result = await load(PROD);
123
+ const endpoint = result.paidTier?.usesGcpTos ? PROD : DAILY;
124
+ if (!result.currentTier || !result.cloudaicompanionProject) {
125
+ if (!result.allowedTiers?.some((tier) => tier.id === "free-tier")) {
126
+ throw new Error(
127
+ result.ineligibleTiers?.find((tier) => tier.reasonMessage)?.reasonMessage ??
128
+ "This account is not eligible for AGY free-tier.",
129
+ );
130
+ }
131
+ type Operation = { name?: string; done?: boolean; error?: { message?: string } };
132
+ let operation = await rpc<Operation>(
133
+ access,
134
+ endpoint,
135
+ "onboardUser",
136
+ {
137
+ tierId: "free-tier",
138
+ metadata: { ideType: "ANTIGRAVITY" },
139
+ },
140
+ signal,
141
+ );
142
+ const operationName = operation.name;
143
+ for (let attempt = 0; !operation.done; attempt++) {
144
+ if (!operationName) throw new Error("AGY onboarding returned no operation name.");
145
+ if (attempt === 30) throw new Error("AGY onboarding timed out.");
146
+ await setTimeout(1000, undefined, { signal });
147
+ operation = await jsonRequest<Operation>(
148
+ `${endpoint}/v1internal/${operationName.split("/").map(encodeURIComponent).join("/")}`,
149
+ {
150
+ headers: { Authorization: `Bearer ${access}`, "User-Agent": USER_AGENT },
151
+ },
152
+ signal,
153
+ );
154
+ }
155
+ if (operation.error) throw new Error(operation.error.message ?? "AGY onboarding failed.");
156
+ result = await load(endpoint);
157
+ }
158
+ if (typeof result.cloudaicompanionProject !== "string" || !result.cloudaicompanionProject)
159
+ throw new Error("AGY returned no managed project.");
160
+ return { project: result.cloudaicompanionProject, endpoint };
161
+ }
162
+
163
+ export async function fetchModels(
164
+ credential: AgyCredential,
165
+ signal: AbortSignal,
166
+ ): Promise<Model<"google-generative-ai">[]> {
167
+ const catalog = await rpc<Catalog>(
168
+ credential.access,
169
+ credential.endpoint,
170
+ "fetchAvailableModels",
171
+ { project: credential.project },
172
+ signal,
173
+ );
174
+ const ids = catalog.agentModelSorts.flatMap((sort) =>
175
+ sort.groups.flatMap((group) => group.modelIds),
176
+ );
177
+
178
+ const variants = ids.map((id) => {
179
+ const info = catalog.models[id]!;
180
+ const match = /^(.*)-(off|minimal|low|medium|high|xhigh|max)$/.exec(id);
181
+ const modelId = match?.[1] ?? id;
182
+ const level = match?.[2] as ModelThinkingLevel | undefined;
183
+ const name = info.displayName || modelId;
184
+ return {
185
+ id,
186
+ modelId,
187
+ level,
188
+ name: level ? name.replace(new RegExp(`\\s*\\(${level}\\)\\s*$`, "i"), "") : name,
189
+ contextWindow: info.maxTokens,
190
+ maxOutputTokens: info.maxOutputTokens,
191
+ };
192
+ });
193
+ const models = [...Map.groupBy(variants, ({ modelId }) => modelId)].map(
194
+ ([id, variants]): Model<"google-generative-ai"> => {
195
+ const levels = variants.flatMap(({ level, id }) => (level ? [[level, id]] : []));
196
+ const thinkingLevelMap: ThinkingLevelMap = {
197
+ off: null,
198
+ minimal: null,
199
+ low: null,
200
+ medium: null,
201
+ high: null,
202
+ xhigh: null,
203
+ max: null,
204
+ ...Object.fromEntries(levels),
205
+ };
206
+ return {
207
+ id,
208
+ name: variants[0]!.name,
209
+ provider: "agy",
210
+ api: "google-generative-ai",
211
+ baseUrl: credential.endpoint,
212
+ reasoning: true,
213
+ thinkingLevelMap,
214
+ input: ["text", "image"],
215
+ contextWindow: variants[0]!.contextWindow,
216
+ maxTokens: variants[0]!.maxOutputTokens,
217
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
218
+ };
219
+ },
220
+ );
221
+ return models;
222
+ }
package/src/index.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { createProvider } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+
4
+ import { api } from "./api.ts";
5
+ import { oauth } from "./auth.ts";
6
+ import { agyCredential, fetchModels } from "./ccpa.ts";
7
+
8
+ export default function (pi: ExtensionAPI): void {
9
+ pi.on("before_agent_start", async (event, ctx) => {
10
+ if (ctx.model?.provider !== "agy") return;
11
+ return {
12
+ systemPrompt: event.systemPrompt
13
+ .replace(
14
+ "You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code.",
15
+ "You are a coding assistant.",
16
+ )
17
+ .replace(/<docs>[\s\S]*?<\/docs>/, ""),
18
+ };
19
+ });
20
+
21
+ pi.registerProvider(
22
+ createProvider({
23
+ id: "agy",
24
+ name: "Antigravity",
25
+ auth: { oauth },
26
+ models: [],
27
+ async fetchModels({ credential, signal }) {
28
+ if (credential?.type !== "oauth") throw new Error("Run /login agy to authenticate.");
29
+ return fetchModels(agyCredential(credential), signal);
30
+ },
31
+ api,
32
+ }),
33
+ );
34
+ }