@aibridge/driver-agy 0.0.2
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 +21 -0
- package/dist/index.d.mts +131 -0
- package/dist/index.mjs +271 -0
- package/package.json +46 -0
- package/src/agy.test.ts +41 -0
- package/src/agy.ts +34 -0
- package/src/agyQuota.test.ts +126 -0
- package/src/agyQuota.ts +222 -0
- package/src/index.ts +15 -0
- package/src/probe.ts +26 -0
- package/src/registry.ts +8 -0
- package/src/run.test.ts +154 -0
- package/src/run.ts +126 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jason Yu
|
|
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/dist/index.d.mts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { runCaptured } from "@aibridge/proc";
|
|
2
|
+
//#region src/agy.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Helper for building Antigravity CLI (`agy`) print arguments.
|
|
5
|
+
*
|
|
6
|
+
* agy resets its own working directory (it emits "Shell cwd was reset …") and
|
|
7
|
+
* treats its --add-dir workspace as "the current directory", ignoring the cwd
|
|
8
|
+
* it was spawned with. So to let the delegate edit the CALLER's repo we must
|
|
9
|
+
* pass that dir explicitly as the FIRST --add-dir (its primary workspace) and
|
|
10
|
+
* anchor the prompt to it — otherwise file edits land in a throwaway dir and
|
|
11
|
+
* never reach the codebase.
|
|
12
|
+
*/
|
|
13
|
+
interface AgyPrintArgs {
|
|
14
|
+
readonly model: string;
|
|
15
|
+
readonly printTimeoutSec: number;
|
|
16
|
+
readonly skipPermissions?: boolean;
|
|
17
|
+
readonly addDirs?: readonly string[];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Assemble the `agy -p …` argv.
|
|
21
|
+
*/
|
|
22
|
+
declare function buildAgyPrintArgs(prompt: string, opts: AgyPrintArgs): string[];
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/agyQuota.d.ts
|
|
25
|
+
/**
|
|
26
|
+
* agy quota via the Google Cloud Code API, reusing agy's OWN cached OAuth
|
|
27
|
+
* token — no separate login. Mechanism learned from
|
|
28
|
+
* github.com/skainguyen1412/antigravity-usage (reimplemented, not vendored):
|
|
29
|
+
*
|
|
30
|
+
* 1. Read `~/.gemini/antigravity-cli/antigravity-oauth-token`
|
|
31
|
+
* ({ token: { access_token, refresh_token, expiry } }) — agy refreshes
|
|
32
|
+
* this file itself whenever it runs. If expired, refresh in-memory via
|
|
33
|
+
* Google's token endpoint with Antigravity's installed-app client
|
|
34
|
+
* (public by design for installed apps); we NEVER write agy's file.
|
|
35
|
+
* 2. POST cloudcode-pa.googleapis.com/v1internal:loadCodeAssist
|
|
36
|
+
* (metadata ideType ANTIGRAVITY / pluginType GEMINI) → project id.
|
|
37
|
+
* 3. POST /v1internal:fetchAvailableModels { project } — the
|
|
38
|
+
* `User-Agent: antigravity` header is MANDATORY (403 without it).
|
|
39
|
+
* → models keyed by id, each with quotaInfo.remainingFraction (0..1)
|
|
40
|
+
* and quotaInfo.resetTime (ISO timestamp).
|
|
41
|
+
*
|
|
42
|
+
* Model `label`s match the names agy uses (e.g. "Gemini 3.5 Flash (Low)").
|
|
43
|
+
*/
|
|
44
|
+
interface AgyModelQuota {
|
|
45
|
+
readonly modelId: string;
|
|
46
|
+
readonly label: string;
|
|
47
|
+
readonly remainingFraction: number | undefined;
|
|
48
|
+
readonly exhausted: boolean;
|
|
49
|
+
readonly resetTime: string | undefined;
|
|
50
|
+
}
|
|
51
|
+
interface AgyQuotaSnapshot {
|
|
52
|
+
readonly fetchedAt: string;
|
|
53
|
+
readonly groups: readonly AgyQuotaGroup[];
|
|
54
|
+
readonly models: readonly AgyModelQuota[];
|
|
55
|
+
}
|
|
56
|
+
interface AgyQuotaBucket {
|
|
57
|
+
readonly bucketId: string;
|
|
58
|
+
readonly displayName: string;
|
|
59
|
+
readonly window: string;
|
|
60
|
+
readonly remainingFraction: number;
|
|
61
|
+
readonly resetTime: string | undefined;
|
|
62
|
+
}
|
|
63
|
+
interface AgyQuotaGroup {
|
|
64
|
+
readonly displayName: string;
|
|
65
|
+
readonly description: string | undefined;
|
|
66
|
+
readonly buckets: readonly AgyQuotaBucket[];
|
|
67
|
+
}
|
|
68
|
+
interface RawBucket {
|
|
69
|
+
bucketId?: string;
|
|
70
|
+
displayName?: string;
|
|
71
|
+
window?: string;
|
|
72
|
+
remainingFraction?: number;
|
|
73
|
+
resetTime?: string;
|
|
74
|
+
}
|
|
75
|
+
declare function parseQuotaGroups(groups: readonly {
|
|
76
|
+
displayName?: string;
|
|
77
|
+
description?: string;
|
|
78
|
+
buckets?: RawBucket[];
|
|
79
|
+
}[]): AgyQuotaGroup[];
|
|
80
|
+
declare function agyTokenPath(): string;
|
|
81
|
+
interface RawModelInfo {
|
|
82
|
+
displayName?: string;
|
|
83
|
+
label?: string;
|
|
84
|
+
quotaInfo?: {
|
|
85
|
+
remainingFraction?: number;
|
|
86
|
+
isExhausted?: boolean;
|
|
87
|
+
resetTime?: string;
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
declare function parseModels(modelsById: Record<string, RawModelInfo>): AgyModelQuota[];
|
|
91
|
+
declare function fetchAgyQuota(): Promise<AgyQuotaSnapshot>;
|
|
92
|
+
declare function findModelQuota(snapshot: AgyQuotaSnapshot, labelOrId: string): AgyModelQuota | undefined;
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/probe.d.ts
|
|
95
|
+
type Availability = {
|
|
96
|
+
readonly ok: true;
|
|
97
|
+
readonly version: string;
|
|
98
|
+
} | {
|
|
99
|
+
readonly ok: false;
|
|
100
|
+
readonly error: string;
|
|
101
|
+
};
|
|
102
|
+
declare function probe(run?: typeof runCaptured): Promise<Availability>;
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/registry.d.ts
|
|
105
|
+
declare const AGY_CANONICAL_TO_NATIVE: Record<string, string>;
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region src/run.d.ts
|
|
108
|
+
interface DelegationTask {
|
|
109
|
+
readonly prompt: string;
|
|
110
|
+
readonly tools: boolean;
|
|
111
|
+
readonly timeoutSec: number;
|
|
112
|
+
readonly cwd: string;
|
|
113
|
+
readonly backendModel: string | undefined;
|
|
114
|
+
readonly effort?: string | undefined;
|
|
115
|
+
readonly onStdout?: (chunk: string) => void;
|
|
116
|
+
readonly onStderr?: (chunk: string) => void;
|
|
117
|
+
readonly onSpawn?: (pid: number) => void;
|
|
118
|
+
}
|
|
119
|
+
type DelegationResult = {
|
|
120
|
+
readonly ok: true;
|
|
121
|
+
readonly response: string;
|
|
122
|
+
readonly exitCode: number;
|
|
123
|
+
} | {
|
|
124
|
+
readonly ok: false;
|
|
125
|
+
readonly kind: 'not-found' | 'spawn' | 'timeout' | 'no-answer';
|
|
126
|
+
readonly message: string;
|
|
127
|
+
readonly exitCode: number | null;
|
|
128
|
+
};
|
|
129
|
+
declare function run(task: DelegationTask, exec?: typeof runCaptured): Promise<DelegationResult>;
|
|
130
|
+
//#endregion
|
|
131
|
+
export { AGY_CANONICAL_TO_NATIVE, type AgyModelQuota, type AgyPrintArgs, type AgyQuotaBucket, type AgyQuotaGroup, type AgyQuotaSnapshot, type Availability, type DelegationResult, type DelegationTask, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, parseModels, parseQuotaGroups, probe, run };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
2
|
+
import { homedir, tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { isNotFound, runCaptured, stripAnsi } from "@aibridge/proc";
|
|
5
|
+
//#region src/agy.ts
|
|
6
|
+
/**
|
|
7
|
+
* Assemble the `agy -p …` argv.
|
|
8
|
+
*/
|
|
9
|
+
function buildAgyPrintArgs(prompt, opts) {
|
|
10
|
+
const args = [
|
|
11
|
+
"-p",
|
|
12
|
+
prompt,
|
|
13
|
+
"--model",
|
|
14
|
+
opts.model,
|
|
15
|
+
"--print-timeout",
|
|
16
|
+
`${opts.printTimeoutSec}s`
|
|
17
|
+
];
|
|
18
|
+
if (opts.skipPermissions) args.push("--dangerously-skip-permissions");
|
|
19
|
+
for (const dir of opts.addDirs ?? []) args.push("--add-dir", dir);
|
|
20
|
+
return args;
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/registry.ts
|
|
24
|
+
const AGY_CANONICAL_TO_NATIVE = {
|
|
25
|
+
"google/gemini-3-6-flash-high": "Gemini 3.6 Flash (High)",
|
|
26
|
+
"google/gemini-3-6-flash-medium": "Gemini 3.6 Flash (Medium)",
|
|
27
|
+
"google/gemini-3-6-flash-low": "Gemini 3.6 Flash (Low)",
|
|
28
|
+
"google/gemini-3-5-flash-high": "Gemini 3.5 Flash (High)",
|
|
29
|
+
"google/gemini-3-5-flash-low": "Gemini 3.5 Flash (Low)",
|
|
30
|
+
"google/gemini-3-5-pro-high": "Gemini 3.5 Pro (High)"
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/agyQuota.ts
|
|
34
|
+
/**
|
|
35
|
+
* agy quota via the Google Cloud Code API, reusing agy's OWN cached OAuth
|
|
36
|
+
* token — no separate login. Mechanism learned from
|
|
37
|
+
* github.com/skainguyen1412/antigravity-usage (reimplemented, not vendored):
|
|
38
|
+
*
|
|
39
|
+
* 1. Read `~/.gemini/antigravity-cli/antigravity-oauth-token`
|
|
40
|
+
* ({ token: { access_token, refresh_token, expiry } }) — agy refreshes
|
|
41
|
+
* this file itself whenever it runs. If expired, refresh in-memory via
|
|
42
|
+
* Google's token endpoint with Antigravity's installed-app client
|
|
43
|
+
* (public by design for installed apps); we NEVER write agy's file.
|
|
44
|
+
* 2. POST cloudcode-pa.googleapis.com/v1internal:loadCodeAssist
|
|
45
|
+
* (metadata ideType ANTIGRAVITY / pluginType GEMINI) → project id.
|
|
46
|
+
* 3. POST /v1internal:fetchAvailableModels { project } — the
|
|
47
|
+
* `User-Agent: antigravity` header is MANDATORY (403 without it).
|
|
48
|
+
* → models keyed by id, each with quotaInfo.remainingFraction (0..1)
|
|
49
|
+
* and quotaInfo.resetTime (ISO timestamp).
|
|
50
|
+
*
|
|
51
|
+
* Model `label`s match the names agy uses (e.g. "Gemini 3.5 Flash (Low)").
|
|
52
|
+
*/
|
|
53
|
+
const CLOUDCODE_BASE = "https://cloudcode-pa.googleapis.com";
|
|
54
|
+
const TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
|
|
55
|
+
const OAUTH_CLIENT_ID = process.env.ANTIGRAVITY_OAUTH_CLIENT_ID ?? "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
|
|
56
|
+
const OAUTH_CLIENT_SECRET = process.env.ANTIGRAVITY_OAUTH_CLIENT_SECRET ?? "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";
|
|
57
|
+
function parseQuotaGroups(groups) {
|
|
58
|
+
return groups.map((g) => ({
|
|
59
|
+
displayName: g.displayName ?? "?",
|
|
60
|
+
description: g.description,
|
|
61
|
+
buckets: (g.buckets ?? []).map((b) => ({
|
|
62
|
+
bucketId: b.bucketId ?? "?",
|
|
63
|
+
displayName: b.displayName ?? b.window ?? "?",
|
|
64
|
+
window: b.window ?? "?",
|
|
65
|
+
remainingFraction: typeof b.remainingFraction === "number" ? b.remainingFraction : 0,
|
|
66
|
+
resetTime: typeof b.resetTime === "string" ? b.resetTime : void 0
|
|
67
|
+
}))
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
function agyTokenPath() {
|
|
71
|
+
return process.env.AGY_OAUTH_TOKEN_PATH ?? join(homedir(), ".gemini", "antigravity-cli", "antigravity-oauth-token");
|
|
72
|
+
}
|
|
73
|
+
async function getAccessToken() {
|
|
74
|
+
const raw = readFileSync(agyTokenPath(), "utf8");
|
|
75
|
+
const parsed = JSON.parse(raw);
|
|
76
|
+
const access = parsed.token?.access_token;
|
|
77
|
+
const refresh = parsed.token?.refresh_token;
|
|
78
|
+
const expiry = parsed.token?.expiry;
|
|
79
|
+
if (!access) throw new Error("agy token file has no access_token");
|
|
80
|
+
if (!(expiry ? new Date(expiry).getTime() - Date.now() < 6e4 : false)) return access;
|
|
81
|
+
if (!refresh) throw new Error("agy token expired and no refresh_token present");
|
|
82
|
+
const res = await fetch(TOKEN_ENDPOINT, {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
85
|
+
body: new URLSearchParams({
|
|
86
|
+
refresh_token: refresh,
|
|
87
|
+
client_id: OAUTH_CLIENT_ID,
|
|
88
|
+
client_secret: OAUTH_CLIENT_SECRET,
|
|
89
|
+
grant_type: "refresh_token"
|
|
90
|
+
})
|
|
91
|
+
});
|
|
92
|
+
if (!res.ok) throw new Error(`agy token refresh failed: HTTP ${res.status}`);
|
|
93
|
+
const data = await res.json();
|
|
94
|
+
if (!data.access_token) throw new Error("agy token refresh returned no access_token");
|
|
95
|
+
return data.access_token;
|
|
96
|
+
}
|
|
97
|
+
async function cloudcode(access, endpoint, body) {
|
|
98
|
+
const res = await fetch(`${CLOUDCODE_BASE}/v1internal:${endpoint}`, {
|
|
99
|
+
method: "POST",
|
|
100
|
+
headers: {
|
|
101
|
+
Authorization: `Bearer ${access}`,
|
|
102
|
+
"Content-Type": "application/json",
|
|
103
|
+
"User-Agent": "antigravity"
|
|
104
|
+
},
|
|
105
|
+
body: JSON.stringify(body)
|
|
106
|
+
});
|
|
107
|
+
if (!res.ok) throw new Error(`cloudcode ${endpoint} failed: HTTP ${res.status}`);
|
|
108
|
+
return res.json();
|
|
109
|
+
}
|
|
110
|
+
function isRelevantModel(modelId, m) {
|
|
111
|
+
if (modelId.startsWith("chat_") || modelId.startsWith("tab_") || modelId.startsWith("rev")) return false;
|
|
112
|
+
if (modelId.includes("image") || modelId.includes("mquery")) return false;
|
|
113
|
+
return m.quotaInfo !== void 0;
|
|
114
|
+
}
|
|
115
|
+
function parseModels(modelsById) {
|
|
116
|
+
const out = [];
|
|
117
|
+
for (const [modelId, m] of Object.entries(modelsById)) {
|
|
118
|
+
if (!isRelevantModel(modelId, m)) continue;
|
|
119
|
+
const qi = m.quotaInfo;
|
|
120
|
+
const remainingFraction = typeof qi?.remainingFraction === "number" ? qi.remainingFraction : 0;
|
|
121
|
+
out.push({
|
|
122
|
+
modelId,
|
|
123
|
+
label: m.displayName ?? m.label ?? modelId,
|
|
124
|
+
remainingFraction,
|
|
125
|
+
exhausted: qi?.isExhausted ?? remainingFraction === 0,
|
|
126
|
+
resetTime: typeof qi?.resetTime === "string" ? qi.resetTime : void 0
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
out.sort((a, b) => a.label.localeCompare(b.label) || a.modelId.localeCompare(b.modelId));
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
let cache = null;
|
|
133
|
+
const CACHE_TTL_MS = 6e4;
|
|
134
|
+
async function fetchAgyQuota() {
|
|
135
|
+
if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache.snapshot;
|
|
136
|
+
const access = await getAccessToken();
|
|
137
|
+
const proj = (await cloudcode(access, "loadCodeAssist", { metadata: {
|
|
138
|
+
ideType: "ANTIGRAVITY",
|
|
139
|
+
platform: "PLATFORM_UNSPECIFIED",
|
|
140
|
+
pluginType: "GEMINI"
|
|
141
|
+
} })).cloudaicompanionProject;
|
|
142
|
+
const projectId = typeof proj === "string" ? proj : proj?.id;
|
|
143
|
+
const [modelsRes, summaryRes] = await Promise.all([cloudcode(access, "fetchAvailableModels", projectId ? { project: projectId } : {}), cloudcode(access, "retrieveUserQuotaSummary", projectId ? { project: projectId } : {}).catch(() => ({}))]);
|
|
144
|
+
const snapshot = {
|
|
145
|
+
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
146
|
+
groups: parseQuotaGroups(summaryRes.groups ?? []),
|
|
147
|
+
models: parseModels(modelsRes.models ?? {})
|
|
148
|
+
};
|
|
149
|
+
cache = {
|
|
150
|
+
at: Date.now(),
|
|
151
|
+
snapshot
|
|
152
|
+
};
|
|
153
|
+
return snapshot;
|
|
154
|
+
}
|
|
155
|
+
function findModelQuota(snapshot, labelOrId) {
|
|
156
|
+
const nativeLabel = AGY_CANONICAL_TO_NATIVE[labelOrId] ?? labelOrId;
|
|
157
|
+
const matches = snapshot.models.filter((m) => m.label === labelOrId || m.modelId === labelOrId || m.label === nativeLabel || m.modelId === nativeLabel);
|
|
158
|
+
if (matches.length === 0) return void 0;
|
|
159
|
+
return matches.find((m) => m.exhausted) ?? matches[0];
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/probe.ts
|
|
163
|
+
const INSTALL_HINT$1 = "Install the Antigravity CLI and sign in.";
|
|
164
|
+
async function probe(run = runCaptured) {
|
|
165
|
+
try {
|
|
166
|
+
const res = await run("agy", ["--version"], { timeoutMs: 1e4 });
|
|
167
|
+
if (res.timedOut) return {
|
|
168
|
+
ok: false,
|
|
169
|
+
error: "aibridge: \"agy\" timed out probing version."
|
|
170
|
+
};
|
|
171
|
+
const line = (res.stdout || res.stderr).split("\n")[0]?.trim();
|
|
172
|
+
if (line && line.length > 0) return {
|
|
173
|
+
ok: true,
|
|
174
|
+
version: line
|
|
175
|
+
};
|
|
176
|
+
return {
|
|
177
|
+
ok: false,
|
|
178
|
+
error: `aibridge: "agy" returned no version output. ${INSTALL_HINT$1}`
|
|
179
|
+
};
|
|
180
|
+
} catch (err) {
|
|
181
|
+
if (isNotFound(err)) return {
|
|
182
|
+
ok: false,
|
|
183
|
+
error: `aibridge: "agy" not found on PATH. ${INSTALL_HINT$1}`
|
|
184
|
+
};
|
|
185
|
+
return {
|
|
186
|
+
ok: false,
|
|
187
|
+
error: `aibridge: failed to probe agy: ${err.message}`
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region src/run.ts
|
|
193
|
+
const NOISE_RE = /^Shell cwd was reset[^\n]*$/gm;
|
|
194
|
+
const INSTALL_HINT = "Install the Antigravity CLI and sign in.";
|
|
195
|
+
function clean(s) {
|
|
196
|
+
return stripAnsi(s).replace(NOISE_RE, "").trim();
|
|
197
|
+
}
|
|
198
|
+
async function run(task, exec = runCaptured) {
|
|
199
|
+
let tempDir;
|
|
200
|
+
let answerPath;
|
|
201
|
+
let taskPrompt = task.prompt;
|
|
202
|
+
const addDirs = [];
|
|
203
|
+
if (task.tools) {
|
|
204
|
+
tempDir = mkdtempSync(join(tmpdir(), "aibridge-agy-"));
|
|
205
|
+
answerPath = join(tempDir, "answer.md");
|
|
206
|
+
taskPrompt = `${task.prompt}\n\nYou are working in the repository rooted at ${task.cwd}; make ALL file edits there (any relative paths in the task are relative to that root). When the task is complete, write ONLY your final answer (the exact text you would otherwise print as your response, with no narration of your steps) to the file ${answerPath} — nothing else in that file. This is how your answer is captured; do not mention the file in the answer.`;
|
|
207
|
+
addDirs.push(task.cwd, tempDir);
|
|
208
|
+
}
|
|
209
|
+
const modelId = task.backendModel ?? "";
|
|
210
|
+
const args = buildAgyPrintArgs(taskPrompt, {
|
|
211
|
+
model: modelId,
|
|
212
|
+
printTimeoutSec: task.timeoutSec,
|
|
213
|
+
skipPermissions: task.tools,
|
|
214
|
+
addDirs: addDirs.length > 0 ? addDirs : void 0
|
|
215
|
+
});
|
|
216
|
+
try {
|
|
217
|
+
let result;
|
|
218
|
+
try {
|
|
219
|
+
result = await exec("agy", args, {
|
|
220
|
+
cwd: task.cwd,
|
|
221
|
+
timeoutMs: (task.timeoutSec + 20) * 1e3,
|
|
222
|
+
onStdout: task.onStdout,
|
|
223
|
+
onStderr: task.onStderr,
|
|
224
|
+
onSpawn: task.onSpawn
|
|
225
|
+
});
|
|
226
|
+
} catch (err) {
|
|
227
|
+
if (isNotFound(err)) return {
|
|
228
|
+
ok: false,
|
|
229
|
+
kind: "not-found",
|
|
230
|
+
message: `aibridge: "agy" not found on PATH. ${INSTALL_HINT}`,
|
|
231
|
+
exitCode: null
|
|
232
|
+
};
|
|
233
|
+
return {
|
|
234
|
+
ok: false,
|
|
235
|
+
kind: "spawn",
|
|
236
|
+
message: `aibridge: failed to run agy: ${err.message}`,
|
|
237
|
+
exitCode: null
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
if (result.timedOut) return {
|
|
241
|
+
ok: false,
|
|
242
|
+
kind: "timeout",
|
|
243
|
+
message: `aibridge: agy timed out after ~${task.timeoutSec + 20}s; raise --timeout.`,
|
|
244
|
+
exitCode: result.code
|
|
245
|
+
};
|
|
246
|
+
let response = "";
|
|
247
|
+
if (answerPath && existsSync(answerPath)) {
|
|
248
|
+
response = clean(readFileSync(answerPath, "utf8"));
|
|
249
|
+
if (response.length > 0) task.onStdout?.(`\n--- final answer ---\n${response}\n`);
|
|
250
|
+
}
|
|
251
|
+
if (response.length === 0) response = clean(result.stdout);
|
|
252
|
+
if (result.code !== 0 || response.length === 0) return {
|
|
253
|
+
ok: false,
|
|
254
|
+
kind: "no-answer",
|
|
255
|
+
message: `aibridge: agy returned no usable answer (${clean(result.stderr) || `exit code ${result.code}`}).`,
|
|
256
|
+
exitCode: result.code
|
|
257
|
+
};
|
|
258
|
+
return {
|
|
259
|
+
ok: true,
|
|
260
|
+
response,
|
|
261
|
+
exitCode: result.code ?? 0
|
|
262
|
+
};
|
|
263
|
+
} finally {
|
|
264
|
+
if (tempDir) rmSync(tempDir, {
|
|
265
|
+
recursive: true,
|
|
266
|
+
force: true
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
//#endregion
|
|
271
|
+
export { AGY_CANONICAL_TO_NATIVE, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, parseModels, parseQuotaGroups, probe, run };
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@aibridge/driver-agy",
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Antigravity (agy) CLI driver for aibridge",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=24.11"
|
|
9
|
+
},
|
|
10
|
+
"keywords": [
|
|
11
|
+
"aibridge",
|
|
12
|
+
"antigravity",
|
|
13
|
+
"agy"
|
|
14
|
+
],
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/ycmjason/aibridge.git",
|
|
18
|
+
"directory": "packages/driver-agy"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/ycmjason/aibridge#readme",
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/ycmjason/aibridge/issues"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.mts",
|
|
27
|
+
"import": "./dist/index.mjs"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"src"
|
|
33
|
+
],
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@aibridge/proc": "0.0.2"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"tsdown": "0.22.14"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsdown"
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/agy.test.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { buildAgyPrintArgs } from './agy.ts';
|
|
3
|
+
|
|
4
|
+
describe('buildAgyPrintArgs', () => {
|
|
5
|
+
it('assembles default agy args', () => {
|
|
6
|
+
const args = buildAgyPrintArgs('test prompt', {
|
|
7
|
+
model: 'gemini-3.6-flash-high',
|
|
8
|
+
printTimeoutSec: 600,
|
|
9
|
+
});
|
|
10
|
+
expect(args).toEqual([
|
|
11
|
+
'-p',
|
|
12
|
+
'test prompt',
|
|
13
|
+
'--model',
|
|
14
|
+
'gemini-3.6-flash-high',
|
|
15
|
+
'--print-timeout',
|
|
16
|
+
'600s',
|
|
17
|
+
]);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('preserves order of skipPermissions and addDirs', () => {
|
|
21
|
+
const args = buildAgyPrintArgs('test prompt', {
|
|
22
|
+
model: 'gemini-3.6-flash-high',
|
|
23
|
+
printTimeoutSec: 600,
|
|
24
|
+
skipPermissions: true,
|
|
25
|
+
addDirs: ['/work/repo', '/tmp/answer-dir'],
|
|
26
|
+
});
|
|
27
|
+
expect(args).toEqual([
|
|
28
|
+
'-p',
|
|
29
|
+
'test prompt',
|
|
30
|
+
'--model',
|
|
31
|
+
'gemini-3.6-flash-high',
|
|
32
|
+
'--print-timeout',
|
|
33
|
+
'600s',
|
|
34
|
+
'--dangerously-skip-permissions',
|
|
35
|
+
'--add-dir',
|
|
36
|
+
'/work/repo',
|
|
37
|
+
'--add-dir',
|
|
38
|
+
'/tmp/answer-dir',
|
|
39
|
+
]);
|
|
40
|
+
});
|
|
41
|
+
});
|
package/src/agy.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helper for building Antigravity CLI (`agy`) print arguments.
|
|
3
|
+
*
|
|
4
|
+
* agy resets its own working directory (it emits "Shell cwd was reset …") and
|
|
5
|
+
* treats its --add-dir workspace as "the current directory", ignoring the cwd
|
|
6
|
+
* it was spawned with. So to let the delegate edit the CALLER's repo we must
|
|
7
|
+
* pass that dir explicitly as the FIRST --add-dir (its primary workspace) and
|
|
8
|
+
* anchor the prompt to it — otherwise file edits land in a throwaway dir and
|
|
9
|
+
* never reach the codebase.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export interface AgyPrintArgs {
|
|
13
|
+
readonly model: string; // full id including effort for gemini
|
|
14
|
+
readonly printTimeoutSec: number;
|
|
15
|
+
readonly skipPermissions?: boolean;
|
|
16
|
+
readonly addDirs?: readonly string[]; // order preserved
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Assemble the `agy -p …` argv.
|
|
21
|
+
*/
|
|
22
|
+
export function buildAgyPrintArgs(prompt: string, opts: AgyPrintArgs): string[] {
|
|
23
|
+
const args = ['-p', prompt, '--model', opts.model, '--print-timeout', `${opts.printTimeoutSec}s`];
|
|
24
|
+
|
|
25
|
+
if (opts.skipPermissions) {
|
|
26
|
+
args.push('--dangerously-skip-permissions');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
for (const dir of opts.addDirs ?? []) {
|
|
30
|
+
args.push('--add-dir', dir);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return args;
|
|
34
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { test } from 'vitest';
|
|
3
|
+
import { findModelQuota, parseModels, parseQuotaGroups } from './agyQuota.ts';
|
|
4
|
+
|
|
5
|
+
test('parseQuotaGroups preserves fractions or defaults to 0 if absent', () => {
|
|
6
|
+
const groups = [
|
|
7
|
+
{
|
|
8
|
+
displayName: 'Group 1',
|
|
9
|
+
description: 'Desc 1',
|
|
10
|
+
buckets: [
|
|
11
|
+
{
|
|
12
|
+
bucketId: 'b1',
|
|
13
|
+
displayName: 'Bucket 1',
|
|
14
|
+
window: '5h',
|
|
15
|
+
remainingFraction: 0.75,
|
|
16
|
+
resetTime: '2026-07-04T12:00:00Z',
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
bucketId: 'b2',
|
|
20
|
+
displayName: 'Bucket 2',
|
|
21
|
+
window: 'weekly',
|
|
22
|
+
// remainingFraction absent (exhausted)
|
|
23
|
+
resetTime: '2026-07-10T12:00:00Z',
|
|
24
|
+
},
|
|
25
|
+
],
|
|
26
|
+
},
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
const parsed = parseQuotaGroups(groups);
|
|
30
|
+
assert.deepEqual(parsed, [
|
|
31
|
+
{
|
|
32
|
+
displayName: 'Group 1',
|
|
33
|
+
description: 'Desc 1',
|
|
34
|
+
buckets: [
|
|
35
|
+
{
|
|
36
|
+
bucketId: 'b1',
|
|
37
|
+
displayName: 'Bucket 1',
|
|
38
|
+
window: '5h',
|
|
39
|
+
remainingFraction: 0.75,
|
|
40
|
+
resetTime: '2026-07-04T12:00:00Z',
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
bucketId: 'b2',
|
|
44
|
+
displayName: 'Bucket 2',
|
|
45
|
+
window: 'weekly',
|
|
46
|
+
remainingFraction: 0,
|
|
47
|
+
resetTime: '2026-07-10T12:00:00Z',
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
},
|
|
51
|
+
]);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('parseQuotaGroups with empty input returns empty output', () => {
|
|
55
|
+
assert.deepEqual(parseQuotaGroups([]), []);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('parseModels filters models and parses quota info correctly', () => {
|
|
59
|
+
const models = {
|
|
60
|
+
// Relevant model, normal
|
|
61
|
+
'gemini-3.5-flash-low': {
|
|
62
|
+
displayName: 'Gemini 3.5 Flash (Low)',
|
|
63
|
+
quotaInfo: {
|
|
64
|
+
remainingFraction: 0.8,
|
|
65
|
+
isExhausted: false,
|
|
66
|
+
resetTime: '2026-07-04T13:00:00Z',
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
// Relevant model, exhausted (remainingFraction omitted)
|
|
70
|
+
'gemini-3.5-pro-high': {
|
|
71
|
+
displayName: 'Gemini 3.5 Pro (High)',
|
|
72
|
+
quotaInfo: {
|
|
73
|
+
isExhausted: true,
|
|
74
|
+
resetTime: '2026-07-04T14:00:00Z',
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
// Irrelevant model (starts with chat_)
|
|
78
|
+
'chat_gemini-3.5': {
|
|
79
|
+
displayName: 'Chat Gemini',
|
|
80
|
+
quotaInfo: {
|
|
81
|
+
remainingFraction: 0.5,
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
// Irrelevant model (no quotaInfo)
|
|
85
|
+
'gemini-3.5-no-quota': {
|
|
86
|
+
displayName: 'Gemini No Quota',
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const parsed = parseModels(models);
|
|
91
|
+
assert.deepEqual(parsed, [
|
|
92
|
+
{
|
|
93
|
+
modelId: 'gemini-3.5-flash-low',
|
|
94
|
+
label: 'Gemini 3.5 Flash (Low)',
|
|
95
|
+
remainingFraction: 0.8,
|
|
96
|
+
exhausted: false,
|
|
97
|
+
resetTime: '2026-07-04T13:00:00Z',
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
modelId: 'gemini-3.5-pro-high',
|
|
101
|
+
label: 'Gemini 3.5 Pro (High)',
|
|
102
|
+
remainingFraction: 0,
|
|
103
|
+
exhausted: true,
|
|
104
|
+
resetTime: '2026-07-04T14:00:00Z',
|
|
105
|
+
},
|
|
106
|
+
]);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test('findModelQuota hits modelId id-form', () => {
|
|
110
|
+
const snapshot = {
|
|
111
|
+
fetchedAt: '2026-07-24T00:00:00Z',
|
|
112
|
+
groups: [],
|
|
113
|
+
models: [
|
|
114
|
+
{
|
|
115
|
+
modelId: 'gemini-3.6-flash-high',
|
|
116
|
+
label: 'Gemini 3.6 Flash (High)',
|
|
117
|
+
remainingFraction: 0.9,
|
|
118
|
+
exhausted: false,
|
|
119
|
+
resetTime: undefined,
|
|
120
|
+
},
|
|
121
|
+
],
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const found = findModelQuota(snapshot, 'gemini-3.6-flash-high');
|
|
125
|
+
assert.equal(found?.modelId, 'gemini-3.6-flash-high');
|
|
126
|
+
});
|
package/src/agyQuota.ts
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agy quota via the Google Cloud Code API, reusing agy's OWN cached OAuth
|
|
3
|
+
* token — no separate login. Mechanism learned from
|
|
4
|
+
* github.com/skainguyen1412/antigravity-usage (reimplemented, not vendored):
|
|
5
|
+
*
|
|
6
|
+
* 1. Read `~/.gemini/antigravity-cli/antigravity-oauth-token`
|
|
7
|
+
* ({ token: { access_token, refresh_token, expiry } }) — agy refreshes
|
|
8
|
+
* this file itself whenever it runs. If expired, refresh in-memory via
|
|
9
|
+
* Google's token endpoint with Antigravity's installed-app client
|
|
10
|
+
* (public by design for installed apps); we NEVER write agy's file.
|
|
11
|
+
* 2. POST cloudcode-pa.googleapis.com/v1internal:loadCodeAssist
|
|
12
|
+
* (metadata ideType ANTIGRAVITY / pluginType GEMINI) → project id.
|
|
13
|
+
* 3. POST /v1internal:fetchAvailableModels { project } — the
|
|
14
|
+
* `User-Agent: antigravity` header is MANDATORY (403 without it).
|
|
15
|
+
* → models keyed by id, each with quotaInfo.remainingFraction (0..1)
|
|
16
|
+
* and quotaInfo.resetTime (ISO timestamp).
|
|
17
|
+
*
|
|
18
|
+
* Model `label`s match the names agy uses (e.g. "Gemini 3.5 Flash (Low)").
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { readFileSync } from 'node:fs';
|
|
22
|
+
import { homedir } from 'node:os';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { AGY_CANONICAL_TO_NATIVE } from './registry.ts';
|
|
25
|
+
|
|
26
|
+
const CLOUDCODE_BASE = 'https://cloudcode-pa.googleapis.com';
|
|
27
|
+
const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';
|
|
28
|
+
const OAUTH_CLIENT_ID =
|
|
29
|
+
process.env.ANTIGRAVITY_OAUTH_CLIENT_ID ??
|
|
30
|
+
'1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com';
|
|
31
|
+
const OAUTH_CLIENT_SECRET =
|
|
32
|
+
process.env.ANTIGRAVITY_OAUTH_CLIENT_SECRET ?? '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';
|
|
33
|
+
|
|
34
|
+
export interface AgyModelQuota {
|
|
35
|
+
readonly modelId: string;
|
|
36
|
+
readonly label: string;
|
|
37
|
+
readonly remainingFraction: number | undefined;
|
|
38
|
+
readonly exhausted: boolean;
|
|
39
|
+
readonly resetTime: string | undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface AgyQuotaSnapshot {
|
|
43
|
+
readonly fetchedAt: string;
|
|
44
|
+
readonly groups: readonly AgyQuotaGroup[];
|
|
45
|
+
readonly models: readonly AgyModelQuota[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface AgyQuotaBucket {
|
|
49
|
+
readonly bucketId: string;
|
|
50
|
+
readonly displayName: string;
|
|
51
|
+
readonly window: string;
|
|
52
|
+
readonly remainingFraction: number;
|
|
53
|
+
readonly resetTime: string | undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface AgyQuotaGroup {
|
|
57
|
+
readonly displayName: string;
|
|
58
|
+
readonly description: string | undefined;
|
|
59
|
+
readonly buckets: readonly AgyQuotaBucket[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface RawBucket {
|
|
63
|
+
bucketId?: string;
|
|
64
|
+
displayName?: string;
|
|
65
|
+
window?: string;
|
|
66
|
+
remainingFraction?: number;
|
|
67
|
+
resetTime?: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function parseQuotaGroups(
|
|
71
|
+
groups: readonly { displayName?: string; description?: string; buckets?: RawBucket[] }[],
|
|
72
|
+
): AgyQuotaGroup[] {
|
|
73
|
+
return groups.map(g => ({
|
|
74
|
+
displayName: g.displayName ?? '?',
|
|
75
|
+
description: g.description,
|
|
76
|
+
buckets: (g.buckets ?? []).map(b => ({
|
|
77
|
+
bucketId: b.bucketId ?? '?',
|
|
78
|
+
displayName: b.displayName ?? b.window ?? '?',
|
|
79
|
+
window: b.window ?? '?',
|
|
80
|
+
remainingFraction: typeof b.remainingFraction === 'number' ? b.remainingFraction : 0,
|
|
81
|
+
resetTime: typeof b.resetTime === 'string' ? b.resetTime : undefined,
|
|
82
|
+
})),
|
|
83
|
+
}));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function agyTokenPath(): string {
|
|
87
|
+
return (
|
|
88
|
+
process.env.AGY_OAUTH_TOKEN_PATH ??
|
|
89
|
+
join(homedir(), '.gemini', 'antigravity-cli', 'antigravity-oauth-token')
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface AgyTokenFile {
|
|
94
|
+
token?: { access_token?: string; refresh_token?: string; expiry?: string };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function getAccessToken(): Promise<string> {
|
|
98
|
+
const raw = readFileSync(agyTokenPath(), 'utf8');
|
|
99
|
+
const parsed = JSON.parse(raw) as AgyTokenFile;
|
|
100
|
+
const access = parsed.token?.access_token;
|
|
101
|
+
const refresh = parsed.token?.refresh_token;
|
|
102
|
+
const expiry = parsed.token?.expiry;
|
|
103
|
+
if (!access) throw new Error('agy token file has no access_token');
|
|
104
|
+
|
|
105
|
+
const isExpired = expiry ? new Date(expiry).getTime() - Date.now() < 60_000 : false;
|
|
106
|
+
if (!isExpired) return access;
|
|
107
|
+
if (!refresh) throw new Error('agy token expired and no refresh_token present');
|
|
108
|
+
|
|
109
|
+
const res = await fetch(TOKEN_ENDPOINT, {
|
|
110
|
+
method: 'POST',
|
|
111
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
112
|
+
body: new URLSearchParams({
|
|
113
|
+
refresh_token: refresh,
|
|
114
|
+
client_id: OAUTH_CLIENT_ID,
|
|
115
|
+
client_secret: OAUTH_CLIENT_SECRET,
|
|
116
|
+
grant_type: 'refresh_token',
|
|
117
|
+
}),
|
|
118
|
+
});
|
|
119
|
+
if (!res.ok) {
|
|
120
|
+
throw new Error(`agy token refresh failed: HTTP ${res.status}`);
|
|
121
|
+
}
|
|
122
|
+
const data = (await res.json()) as { access_token?: string };
|
|
123
|
+
if (!data.access_token) throw new Error('agy token refresh returned no access_token');
|
|
124
|
+
return data.access_token;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function cloudcode(access: string, endpoint: string, body: unknown): Promise<unknown> {
|
|
128
|
+
const res = await fetch(`${CLOUDCODE_BASE}/v1internal:${endpoint}`, {
|
|
129
|
+
method: 'POST',
|
|
130
|
+
headers: {
|
|
131
|
+
Authorization: `Bearer ${access}`,
|
|
132
|
+
'Content-Type': 'application/json',
|
|
133
|
+
'User-Agent': 'antigravity',
|
|
134
|
+
},
|
|
135
|
+
body: JSON.stringify(body),
|
|
136
|
+
});
|
|
137
|
+
if (!res.ok) {
|
|
138
|
+
throw new Error(`cloudcode ${endpoint} failed: HTTP ${res.status}`);
|
|
139
|
+
}
|
|
140
|
+
return res.json();
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
interface RawModelInfo {
|
|
144
|
+
displayName?: string;
|
|
145
|
+
label?: string;
|
|
146
|
+
quotaInfo?: { remainingFraction?: number; isExhausted?: boolean; resetTime?: string };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function isRelevantModel(modelId: string, m: RawModelInfo): boolean {
|
|
150
|
+
if (modelId.startsWith('chat_') || modelId.startsWith('tab_') || modelId.startsWith('rev')) {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
if (modelId.includes('image') || modelId.includes('mquery')) return false;
|
|
154
|
+
return m.quotaInfo !== undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function parseModels(modelsById: Record<string, RawModelInfo>): AgyModelQuota[] {
|
|
158
|
+
const out: AgyModelQuota[] = [];
|
|
159
|
+
for (const [modelId, m] of Object.entries(modelsById)) {
|
|
160
|
+
if (!isRelevantModel(modelId, m)) continue;
|
|
161
|
+
const qi = m.quotaInfo;
|
|
162
|
+
const remainingFraction = typeof qi?.remainingFraction === 'number' ? qi.remainingFraction : 0;
|
|
163
|
+
out.push({
|
|
164
|
+
modelId,
|
|
165
|
+
label: m.displayName ?? m.label ?? modelId,
|
|
166
|
+
remainingFraction,
|
|
167
|
+
exhausted: qi?.isExhausted ?? remainingFraction === 0,
|
|
168
|
+
resetTime: typeof qi?.resetTime === 'string' ? qi.resetTime : undefined,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
out.sort((a, b) => a.label.localeCompare(b.label) || a.modelId.localeCompare(b.modelId));
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
let cache: { at: number; snapshot: AgyQuotaSnapshot } | null = null;
|
|
176
|
+
const CACHE_TTL_MS = 60_000;
|
|
177
|
+
|
|
178
|
+
export async function fetchAgyQuota(): Promise<AgyQuotaSnapshot> {
|
|
179
|
+
if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache.snapshot;
|
|
180
|
+
|
|
181
|
+
const access = await getAccessToken();
|
|
182
|
+
const load = (await cloudcode(access, 'loadCodeAssist', {
|
|
183
|
+
metadata: { ideType: 'ANTIGRAVITY', platform: 'PLATFORM_UNSPECIFIED', pluginType: 'GEMINI' },
|
|
184
|
+
})) as { cloudaicompanionProject?: string | { id?: string } };
|
|
185
|
+
|
|
186
|
+
const proj = load.cloudaicompanionProject;
|
|
187
|
+
const projectId = typeof proj === 'string' ? proj : proj?.id;
|
|
188
|
+
const [modelsRes, summaryRes] = await Promise.all([
|
|
189
|
+
cloudcode(access, 'fetchAvailableModels', projectId ? { project: projectId } : {}) as Promise<{
|
|
190
|
+
models?: Record<string, RawModelInfo>;
|
|
191
|
+
}>,
|
|
192
|
+
cloudcode(access, 'retrieveUserQuotaSummary', projectId ? { project: projectId } : {}).catch(
|
|
193
|
+
() => ({}),
|
|
194
|
+
) as Promise<{
|
|
195
|
+
groups?: { displayName?: string; description?: string; buckets?: [] }[];
|
|
196
|
+
}>,
|
|
197
|
+
]);
|
|
198
|
+
|
|
199
|
+
const snapshot: AgyQuotaSnapshot = {
|
|
200
|
+
fetchedAt: new Date().toISOString(),
|
|
201
|
+
groups: parseQuotaGroups(summaryRes.groups ?? []),
|
|
202
|
+
models: parseModels(modelsRes.models ?? {}),
|
|
203
|
+
};
|
|
204
|
+
cache = { at: Date.now(), snapshot };
|
|
205
|
+
return snapshot;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function findModelQuota(
|
|
209
|
+
snapshot: AgyQuotaSnapshot,
|
|
210
|
+
labelOrId: string,
|
|
211
|
+
): AgyModelQuota | undefined {
|
|
212
|
+
const nativeLabel = AGY_CANONICAL_TO_NATIVE[labelOrId] ?? labelOrId;
|
|
213
|
+
const matches = snapshot.models.filter(
|
|
214
|
+
m =>
|
|
215
|
+
m.label === labelOrId ||
|
|
216
|
+
m.modelId === labelOrId ||
|
|
217
|
+
m.label === nativeLabel ||
|
|
218
|
+
m.modelId === nativeLabel,
|
|
219
|
+
);
|
|
220
|
+
if (matches.length === 0) return undefined;
|
|
221
|
+
return matches.find(m => m.exhausted) ?? matches[0];
|
|
222
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { type AgyPrintArgs, buildAgyPrintArgs } from './agy.ts';
|
|
2
|
+
export {
|
|
3
|
+
type AgyModelQuota,
|
|
4
|
+
type AgyQuotaBucket,
|
|
5
|
+
type AgyQuotaGroup,
|
|
6
|
+
type AgyQuotaSnapshot,
|
|
7
|
+
agyTokenPath,
|
|
8
|
+
fetchAgyQuota,
|
|
9
|
+
findModelQuota,
|
|
10
|
+
parseModels,
|
|
11
|
+
parseQuotaGroups,
|
|
12
|
+
} from './agyQuota.ts';
|
|
13
|
+
export { type Availability, probe } from './probe.ts';
|
|
14
|
+
export { AGY_CANONICAL_TO_NATIVE } from './registry.ts';
|
|
15
|
+
export { type DelegationResult, type DelegationTask, run } from './run.ts';
|
package/src/probe.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { isNotFound, runCaptured } from '@aibridge/proc';
|
|
2
|
+
|
|
3
|
+
export type Availability =
|
|
4
|
+
| { readonly ok: true; readonly version: string }
|
|
5
|
+
| { readonly ok: false; readonly error: string };
|
|
6
|
+
|
|
7
|
+
const INSTALL_HINT = 'Install the Antigravity CLI and sign in.';
|
|
8
|
+
|
|
9
|
+
export async function probe(run: typeof runCaptured = runCaptured): Promise<Availability> {
|
|
10
|
+
try {
|
|
11
|
+
const res = await run('agy', ['--version'], { timeoutMs: 10_000 });
|
|
12
|
+
if (res.timedOut) {
|
|
13
|
+
return { ok: false, error: 'aibridge: "agy" timed out probing version.' };
|
|
14
|
+
}
|
|
15
|
+
const line = (res.stdout || res.stderr).split('\n')[0]?.trim();
|
|
16
|
+
if (line && line.length > 0) {
|
|
17
|
+
return { ok: true, version: line };
|
|
18
|
+
}
|
|
19
|
+
return { ok: false, error: `aibridge: "agy" returned no version output. ${INSTALL_HINT}` };
|
|
20
|
+
} catch (err) {
|
|
21
|
+
if (isNotFound(err)) {
|
|
22
|
+
return { ok: false, error: `aibridge: "agy" not found on PATH. ${INSTALL_HINT}` };
|
|
23
|
+
}
|
|
24
|
+
return { ok: false, error: `aibridge: failed to probe agy: ${(err as Error).message}` };
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/registry.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const AGY_CANONICAL_TO_NATIVE: Record<string, string> = {
|
|
2
|
+
'google/gemini-3-6-flash-high': 'Gemini 3.6 Flash (High)',
|
|
3
|
+
'google/gemini-3-6-flash-medium': 'Gemini 3.6 Flash (Medium)',
|
|
4
|
+
'google/gemini-3-6-flash-low': 'Gemini 3.6 Flash (Low)',
|
|
5
|
+
'google/gemini-3-5-flash-high': 'Gemini 3.5 Flash (High)',
|
|
6
|
+
'google/gemini-3-5-flash-low': 'Gemini 3.5 Flash (Low)',
|
|
7
|
+
'google/gemini-3-5-pro-high': 'Gemini 3.5 Pro (High)',
|
|
8
|
+
};
|
package/src/run.test.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { writeFileSync } from 'node:fs';
|
|
2
|
+
import type { RunOptions, RunResult } from '@aibridge/proc';
|
|
3
|
+
import { describe, expect, it } from 'vitest';
|
|
4
|
+
import { run } from './run.ts';
|
|
5
|
+
|
|
6
|
+
describe('agy driver run()', () => {
|
|
7
|
+
it('builds args without tools and handles successful execution', async () => {
|
|
8
|
+
let capturedCmd = '';
|
|
9
|
+
let capturedArgs: readonly string[] = [];
|
|
10
|
+
|
|
11
|
+
const fakeExec = async (
|
|
12
|
+
cmd: string,
|
|
13
|
+
args: readonly string[],
|
|
14
|
+
_opts: RunOptions = {},
|
|
15
|
+
): Promise<RunResult> => {
|
|
16
|
+
capturedCmd = cmd;
|
|
17
|
+
capturedArgs = args;
|
|
18
|
+
return { code: 0, signal: null, stdout: 'Hello world', stderr: '', timedOut: false };
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const res = await run(
|
|
22
|
+
{
|
|
23
|
+
prompt: 'do something',
|
|
24
|
+
tools: false,
|
|
25
|
+
timeoutSec: 60,
|
|
26
|
+
cwd: '/test/cwd',
|
|
27
|
+
backendModel: 'gemini-3.6-flash-high',
|
|
28
|
+
},
|
|
29
|
+
fakeExec,
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
expect(capturedCmd).toEqual('agy');
|
|
33
|
+
expect(capturedArgs).toEqual([
|
|
34
|
+
'-p',
|
|
35
|
+
'do something',
|
|
36
|
+
'--model',
|
|
37
|
+
'gemini-3.6-flash-high',
|
|
38
|
+
'--print-timeout',
|
|
39
|
+
'60s',
|
|
40
|
+
]);
|
|
41
|
+
expect(res).toEqual({ ok: true, response: 'Hello world', exitCode: 0 });
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('uses answer file protocol when tools=true', async () => {
|
|
45
|
+
let capturedArgs: readonly string[] = [];
|
|
46
|
+
|
|
47
|
+
const fakeExec = async (
|
|
48
|
+
_cmd: string,
|
|
49
|
+
args: readonly string[],
|
|
50
|
+
_opts: RunOptions = {},
|
|
51
|
+
): Promise<RunResult> => {
|
|
52
|
+
capturedArgs = args;
|
|
53
|
+
// find answer path from prompt in args
|
|
54
|
+
const prompt = args[1] ?? '';
|
|
55
|
+
const match = prompt.match(/file (\/.*answer\.md)/);
|
|
56
|
+
if (match?.[1]) {
|
|
57
|
+
writeFileSync(match[1], 'Written answer from file');
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
code: 0,
|
|
61
|
+
signal: null,
|
|
62
|
+
stdout: 'Shell cwd was reset to /foo\n',
|
|
63
|
+
stderr: '',
|
|
64
|
+
timedOut: false,
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const res = await run(
|
|
69
|
+
{
|
|
70
|
+
prompt: 'do tool task',
|
|
71
|
+
tools: true,
|
|
72
|
+
timeoutSec: 100,
|
|
73
|
+
cwd: '/repo/root',
|
|
74
|
+
backendModel: 'gemini-3.6-flash-high',
|
|
75
|
+
},
|
|
76
|
+
fakeExec,
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
expect(capturedArgs).toContain('--dangerously-skip-permissions');
|
|
80
|
+
expect(capturedArgs).toContain('/repo/root');
|
|
81
|
+
expect(res).toEqual({ ok: true, response: 'Written answer from file', exitCode: 0 });
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('maps ENOENT spawn error to not-found', async () => {
|
|
85
|
+
const fakeExec = async (): Promise<RunResult> => {
|
|
86
|
+
const err = new Error('spawn agy ENOENT') as Error & { code?: string };
|
|
87
|
+
err.code = 'ENOENT';
|
|
88
|
+
throw err;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const res = await run(
|
|
92
|
+
{
|
|
93
|
+
prompt: 'test',
|
|
94
|
+
tools: false,
|
|
95
|
+
timeoutSec: 30,
|
|
96
|
+
cwd: '/test/cwd',
|
|
97
|
+
backendModel: 'gemini-3.6-flash-high',
|
|
98
|
+
},
|
|
99
|
+
fakeExec,
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
expect(res.ok).toBe(false);
|
|
103
|
+
if (!res.ok) {
|
|
104
|
+
expect(res.kind).toBe('not-found');
|
|
105
|
+
expect(res.exitCode).toBeNull();
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('maps timeout correctly', async () => {
|
|
110
|
+
const fakeExec = async (): Promise<RunResult> => {
|
|
111
|
+
return { code: null, signal: 'SIGTERM', stdout: '', stderr: '', timedOut: true };
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const res = await run(
|
|
115
|
+
{
|
|
116
|
+
prompt: 'test',
|
|
117
|
+
tools: false,
|
|
118
|
+
timeoutSec: 10,
|
|
119
|
+
cwd: '/test/cwd',
|
|
120
|
+
backendModel: 'gemini-3.6-flash-high',
|
|
121
|
+
},
|
|
122
|
+
fakeExec,
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
expect(res.ok).toBe(false);
|
|
126
|
+
if (!res.ok) {
|
|
127
|
+
expect(res.kind).toBe('timeout');
|
|
128
|
+
expect(res.exitCode).toBeNull();
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('maps no-answer when stdout is empty and no answer file', async () => {
|
|
133
|
+
const fakeExec = async (): Promise<RunResult> => {
|
|
134
|
+
return { code: 0, signal: null, stdout: '', stderr: 'error details', timedOut: false };
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const res = await run(
|
|
138
|
+
{
|
|
139
|
+
prompt: 'test',
|
|
140
|
+
tools: false,
|
|
141
|
+
timeoutSec: 10,
|
|
142
|
+
cwd: '/test/cwd',
|
|
143
|
+
backendModel: 'gemini-3.6-flash-high',
|
|
144
|
+
},
|
|
145
|
+
fakeExec,
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
expect(res.ok).toBe(false);
|
|
149
|
+
if (!res.ok) {
|
|
150
|
+
expect(res.kind).toBe('no-answer');
|
|
151
|
+
expect(res.exitCode).toBe(0);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
});
|
package/src/run.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { isNotFound, type RunResult, runCaptured, stripAnsi } from '@aibridge/proc';
|
|
5
|
+
import { buildAgyPrintArgs } from './agy.ts';
|
|
6
|
+
|
|
7
|
+
export interface DelegationTask {
|
|
8
|
+
readonly prompt: string;
|
|
9
|
+
readonly tools: boolean;
|
|
10
|
+
readonly timeoutSec: number;
|
|
11
|
+
readonly cwd: string;
|
|
12
|
+
readonly backendModel: string | undefined;
|
|
13
|
+
readonly effort?: string | undefined;
|
|
14
|
+
readonly onStdout?: (chunk: string) => void;
|
|
15
|
+
readonly onStderr?: (chunk: string) => void;
|
|
16
|
+
readonly onSpawn?: (pid: number) => void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type DelegationResult =
|
|
20
|
+
| { readonly ok: true; readonly response: string; readonly exitCode: number }
|
|
21
|
+
| {
|
|
22
|
+
readonly ok: false;
|
|
23
|
+
readonly kind: 'not-found' | 'spawn' | 'timeout' | 'no-answer';
|
|
24
|
+
readonly message: string;
|
|
25
|
+
readonly exitCode: number | null;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const NOISE_RE = /^Shell cwd was reset[^\n]*$/gm;
|
|
29
|
+
const INSTALL_HINT = 'Install the Antigravity CLI and sign in.';
|
|
30
|
+
|
|
31
|
+
function clean(s: string): string {
|
|
32
|
+
return stripAnsi(s).replace(NOISE_RE, '').trim();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function run(
|
|
36
|
+
task: DelegationTask,
|
|
37
|
+
exec: typeof runCaptured = runCaptured,
|
|
38
|
+
): Promise<DelegationResult> {
|
|
39
|
+
let tempDir: string | undefined;
|
|
40
|
+
let answerPath: string | undefined;
|
|
41
|
+
|
|
42
|
+
let taskPrompt = task.prompt;
|
|
43
|
+
const addDirs: string[] = [];
|
|
44
|
+
|
|
45
|
+
if (task.tools) {
|
|
46
|
+
tempDir = mkdtempSync(join(tmpdir(), 'aibridge-agy-'));
|
|
47
|
+
answerPath = join(tempDir, 'answer.md');
|
|
48
|
+
taskPrompt =
|
|
49
|
+
`${task.prompt}\n\nYou are working in the repository rooted at ${task.cwd}; make ALL file ` +
|
|
50
|
+
`edits there (any relative paths in the task are relative to that root). When the task ` +
|
|
51
|
+
`is complete, write ONLY your final answer (the exact text you would otherwise print as ` +
|
|
52
|
+
`your response, with no narration of your steps) to the file ${answerPath} — nothing else ` +
|
|
53
|
+
`in that file. This is how your answer is captured; do not mention the file in the answer.`;
|
|
54
|
+
addDirs.push(task.cwd, tempDir);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const modelId = task.backendModel ?? '';
|
|
58
|
+
const args = buildAgyPrintArgs(taskPrompt, {
|
|
59
|
+
model: modelId,
|
|
60
|
+
printTimeoutSec: task.timeoutSec,
|
|
61
|
+
skipPermissions: task.tools,
|
|
62
|
+
addDirs: addDirs.length > 0 ? addDirs : undefined,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
let result: RunResult;
|
|
67
|
+
try {
|
|
68
|
+
result = await exec('agy', args, {
|
|
69
|
+
cwd: task.cwd,
|
|
70
|
+
timeoutMs: (task.timeoutSec + 20) * 1000,
|
|
71
|
+
onStdout: task.onStdout,
|
|
72
|
+
onStderr: task.onStderr,
|
|
73
|
+
onSpawn: task.onSpawn,
|
|
74
|
+
});
|
|
75
|
+
} catch (err) {
|
|
76
|
+
if (isNotFound(err)) {
|
|
77
|
+
return {
|
|
78
|
+
ok: false,
|
|
79
|
+
kind: 'not-found',
|
|
80
|
+
message: `aibridge: "agy" not found on PATH. ${INSTALL_HINT}`,
|
|
81
|
+
exitCode: null,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
ok: false,
|
|
86
|
+
kind: 'spawn',
|
|
87
|
+
message: `aibridge: failed to run agy: ${(err as Error).message}`,
|
|
88
|
+
exitCode: null,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (result.timedOut) {
|
|
93
|
+
return {
|
|
94
|
+
ok: false,
|
|
95
|
+
kind: 'timeout',
|
|
96
|
+
message: `aibridge: agy timed out after ~${task.timeoutSec + 20}s; raise --timeout.`,
|
|
97
|
+
exitCode: result.code,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
let response = '';
|
|
102
|
+
if (answerPath && existsSync(answerPath)) {
|
|
103
|
+
response = clean(readFileSync(answerPath, 'utf8'));
|
|
104
|
+
if (response.length > 0) {
|
|
105
|
+
task.onStdout?.(`\n--- final answer ---\n${response}\n`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (response.length === 0) {
|
|
109
|
+
response = clean(result.stdout);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (result.code !== 0 || response.length === 0) {
|
|
113
|
+
const detail = clean(result.stderr) || `exit code ${result.code}`;
|
|
114
|
+
return {
|
|
115
|
+
ok: false,
|
|
116
|
+
kind: 'no-answer',
|
|
117
|
+
message: `aibridge: agy returned no usable answer (${detail}).`,
|
|
118
|
+
exitCode: result.code,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return { ok: true, response, exitCode: result.code ?? 0 };
|
|
123
|
+
} finally {
|
|
124
|
+
if (tempDir) rmSync(tempDir, { recursive: true, force: true });
|
|
125
|
+
}
|
|
126
|
+
}
|