@benjamolina/pi-antigravity-guard 0.5.0 → 0.6.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/README.md +30 -14
- package/dist/accounts.d.ts +94 -0
- package/dist/accounts.js +953 -0
- package/dist/auth-http.d.ts +2 -1
- package/dist/auth-http.js +4 -2
- package/dist/catalog.d.ts +268 -0
- package/dist/catalog.js +265 -1
- package/dist/commands.d.ts +13 -0
- package/dist/commands.js +97 -0
- package/dist/context.d.ts +12 -2
- package/dist/context.js +291 -34
- package/dist/extension.d.ts +2 -2
- package/dist/extension.js +3 -3
- package/dist/project.d.ts +1 -0
- package/dist/project.js +1 -1
- package/dist/provider.d.ts +26 -1
- package/dist/provider.js +621 -23
- package/dist/response.d.ts +8 -0
- package/dist/response.js +59 -0
- package/dist/stream.d.ts +33 -2
- package/dist/stream.js +236 -27
- package/dist/tool-context.d.ts +2 -1
- package/dist/tool-context.js +79 -19
- package/dist/tool-schema.d.ts +2 -0
- package/dist/tool-schema.js +29 -27
- package/package.json +2 -2
package/dist/provider.js
CHANGED
|
@@ -1,28 +1,152 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { Type } from "@earendil-works/pi-ai";
|
|
2
|
+
import { ANTIGRAVITY_DEFAULT_PROJECT_ID, ANTIGRAVITY_ENDPOINTS, ANTIGRAVITY_ENDPOINT_FALLBACKS, DEFAULT_SHARED_GUARD_CONFIG, MAX_CAPACITY_RETRIES_PER_ENDPOINT, SEARCH_MODEL, abortableSleep, createAntigravityVersionState, createSessionFingerprintStore, createSessionSignatureCache, createSignatureCache, executeAntigravitySearchDetailed, fetchAntigravityHubVersion, fetchAvailableModels, loadAccountsFromPath, loadSharedGuardConfig, parseRefreshParts, resolveSharedGuardPaths, } from "@benjamolina/antigravity-guard-core";
|
|
3
|
+
import { SHARED_POOL_PLACEHOLDER_ACCESS, createPiAccountPool, readPiAuthEntry, resolvePiAuthJsonPath, } from "./accounts.js";
|
|
4
|
+
import { refreshCredentials } from "./auth-http.js";
|
|
5
|
+
import { listCatalogEntries, registerDiscoveredCatalogEntries, toPiModelDescriptor, } from "./catalog.js";
|
|
6
|
+
import { registerPiGuardCommands } from "./commands.js";
|
|
3
7
|
import { createPiOAuthLifecycle } from "./oauth.js";
|
|
4
|
-
import {
|
|
8
|
+
import { resolveLoginProject } from "./project.js";
|
|
9
|
+
import { StreamTransportError, createPiLifecycleStream, createPoolUnavailableError, executeStreamTransport, } from "./stream.js";
|
|
5
10
|
const PROVIDER = "antigravity-guard";
|
|
6
11
|
const API = "antigravity-guard-sse";
|
|
7
12
|
const INVALID_CREDENTIALS = "Antigravity credentials are invalid. Run /login antigravity-guard.";
|
|
8
|
-
export function
|
|
9
|
-
const
|
|
13
|
+
export function createPiGuardRuntime(options = {}) {
|
|
14
|
+
const versionState = createAntigravityVersionState();
|
|
15
|
+
const fingerprintStore = createSessionFingerprintStore({
|
|
16
|
+
getVersion: () => versionState.getVersion(),
|
|
17
|
+
});
|
|
18
|
+
const hasExplicitConfigScope = options.cwd !== undefined || options.homeDir !== undefined || options.env !== undefined;
|
|
19
|
+
let config = hasExplicitConfigScope
|
|
20
|
+
? loadSharedGuardConfig(options)
|
|
21
|
+
: {
|
|
22
|
+
...DEFAULT_SHARED_GUARD_CONFIG,
|
|
23
|
+
model_discovery: { ...DEFAULT_SHARED_GUARD_CONFIG.model_discovery },
|
|
24
|
+
signature_cache: { ...DEFAULT_SHARED_GUARD_CONFIG.signature_cache },
|
|
25
|
+
};
|
|
26
|
+
const signatureCache = createSessionSignatureCache({
|
|
27
|
+
memoryTtlMs: config.signature_cache.memory_ttl_seconds * 1_000,
|
|
28
|
+
now: options.now,
|
|
29
|
+
});
|
|
30
|
+
const syncDiskSignatureCache = (cwd) => {
|
|
31
|
+
signatureCache.setMemoryTtlMs(config.signature_cache.memory_ttl_seconds * 1_000);
|
|
32
|
+
signatureCache.setDiskCache(null, { shutdownPrevious: true });
|
|
33
|
+
const paths = resolveSharedGuardPaths({
|
|
34
|
+
...options,
|
|
35
|
+
cwd: cwd ?? options.cwd,
|
|
36
|
+
});
|
|
37
|
+
const diskCache = createSignatureCache(config.signature_cache, {
|
|
38
|
+
cacheFilePath: paths.signatureCachePath,
|
|
39
|
+
now: options.now,
|
|
40
|
+
});
|
|
41
|
+
signatureCache.setDiskCache(diskCache);
|
|
42
|
+
};
|
|
43
|
+
if (hasExplicitConfigScope) {
|
|
44
|
+
syncDiskSignatureCache(options.cwd);
|
|
45
|
+
}
|
|
46
|
+
const accountPool = createPiAccountPool({
|
|
47
|
+
...options,
|
|
48
|
+
getVersion: () => versionState.getVersion(),
|
|
49
|
+
getConfig: () => config,
|
|
50
|
+
});
|
|
51
|
+
return {
|
|
52
|
+
getVersion() {
|
|
53
|
+
return versionState.getVersion();
|
|
54
|
+
},
|
|
55
|
+
getUserAgent() {
|
|
56
|
+
return fingerprintStore.get().userAgent;
|
|
57
|
+
},
|
|
58
|
+
getConfig() {
|
|
59
|
+
return config;
|
|
60
|
+
},
|
|
61
|
+
getAccountPool() {
|
|
62
|
+
return accountPool;
|
|
63
|
+
},
|
|
64
|
+
getSignatureCache() {
|
|
65
|
+
return signatureCache;
|
|
66
|
+
},
|
|
67
|
+
async refreshSession(cwd) {
|
|
68
|
+
config = loadSharedGuardConfig({
|
|
69
|
+
...options,
|
|
70
|
+
cwd: cwd ?? options.cwd,
|
|
71
|
+
});
|
|
72
|
+
syncDiskSignatureCache(cwd);
|
|
73
|
+
const env = options.env ?? process.env;
|
|
74
|
+
if (!/^(1|true|yes)$/i.test(env.PI_OFFLINE ?? "")) {
|
|
75
|
+
const liveVersion = await fetchAntigravityHubVersion({
|
|
76
|
+
fetch: options.fetch ?? globalThis.fetch,
|
|
77
|
+
});
|
|
78
|
+
if (liveVersion && versionState.setVersion(liveVersion)) {
|
|
79
|
+
fingerprintStore.syncVersion(versionState.getVersion());
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
await accountPool.loadOrRefresh(cwd ?? options.cwd);
|
|
83
|
+
},
|
|
84
|
+
shutdown() {
|
|
85
|
+
accountPool.stopBackgroundRefresh();
|
|
86
|
+
signatureCache.shutdown();
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
export function registerAntigravityProvider(pi, options) {
|
|
91
|
+
const runtime = createPiGuardRuntime(options);
|
|
92
|
+
const hasExplicitScope = options?.cwd !== undefined || options?.homeDir !== undefined || options?.env !== undefined;
|
|
93
|
+
let activeSessionCwd = options?.cwd;
|
|
94
|
+
const oauth = createPiOAuthLifecycle({
|
|
95
|
+
fetch: options?.fetch ?? globalThis.fetch,
|
|
96
|
+
now: options?.now ?? Date.now,
|
|
97
|
+
project: (projectOptions) => resolveLoginProject({
|
|
98
|
+
...projectOptions,
|
|
99
|
+
userAgent: runtime.getUserAgent(),
|
|
100
|
+
}),
|
|
101
|
+
});
|
|
102
|
+
pi.on?.("session_start", async (_event, ctx) => {
|
|
103
|
+
activeSessionCwd = ctx?.cwd ?? options?.cwd;
|
|
104
|
+
await runtime.refreshSession(ctx?.cwd);
|
|
105
|
+
});
|
|
106
|
+
pi.on?.("session_shutdown", () => {
|
|
107
|
+
runtime.shutdown();
|
|
108
|
+
});
|
|
109
|
+
registerPiGuardCommands(pi, {
|
|
110
|
+
pool: runtime.getAccountPool(),
|
|
111
|
+
getConfig: () => runtime.getConfig(),
|
|
112
|
+
now: options?.now,
|
|
113
|
+
});
|
|
114
|
+
registerPiGoogleSearchTool(pi, runtime, options, () => activeSessionCwd);
|
|
10
115
|
pi.registerProvider(PROVIDER, {
|
|
11
116
|
name: "Antigravity Guard",
|
|
12
117
|
baseUrl: ANTIGRAVITY_ENDPOINTS.daily,
|
|
13
118
|
api: API,
|
|
14
119
|
models: listCatalogEntries().map(toPiModelDescriptor),
|
|
120
|
+
async refreshModels(refreshCtx) {
|
|
121
|
+
return refreshDiscoveredModels(refreshCtx, runtime, options, activeSessionCwd);
|
|
122
|
+
},
|
|
15
123
|
oauth: {
|
|
16
124
|
name: "Antigravity Guard",
|
|
17
125
|
isSubscription: true,
|
|
18
|
-
login
|
|
126
|
+
async login(callbacks) {
|
|
127
|
+
const credentials = await oauth.login(callbacks);
|
|
128
|
+
// Persist newly logged-in accounts into the shared pool only when a session or explicit scope is active,
|
|
129
|
+
// keeping un-scoped unit tests hermetic with zero real host filesystem writes.
|
|
130
|
+
if (hasExplicitScope || runtime.getAccountPool().getManager() !== null) {
|
|
131
|
+
const extras = credentials;
|
|
132
|
+
await runtime.getAccountPool().recordLoginAccount({
|
|
133
|
+
refreshToken: credentials.refresh,
|
|
134
|
+
access: credentials.access,
|
|
135
|
+
expires: credentials.expires,
|
|
136
|
+
projectId: extras.projectId,
|
|
137
|
+
email: extras.email,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return credentials;
|
|
141
|
+
},
|
|
19
142
|
refreshToken: oauth.refreshToken,
|
|
20
143
|
getApiKey: oauth.getApiKey,
|
|
21
144
|
},
|
|
22
|
-
streamSimple(model, context,
|
|
23
|
-
return streamText(model, context, options);
|
|
145
|
+
streamSimple(model, context, streamOptions) {
|
|
146
|
+
return streamText(model, context, streamOptions, runtime, options);
|
|
24
147
|
},
|
|
25
148
|
});
|
|
149
|
+
return runtime;
|
|
26
150
|
}
|
|
27
151
|
export function parseProviderApiKey(value) {
|
|
28
152
|
let parsed;
|
|
@@ -32,44 +156,518 @@ export function parseProviderApiKey(value) {
|
|
|
32
156
|
catch {
|
|
33
157
|
throw new Error(INVALID_CREDENTIALS);
|
|
34
158
|
}
|
|
35
|
-
if (!
|
|
159
|
+
if (!isCredentialPayload(parsed)) {
|
|
36
160
|
throw new Error(INVALID_CREDENTIALS);
|
|
37
161
|
}
|
|
38
162
|
return { token: parsed.token, projectId: parsed.projectId };
|
|
39
163
|
}
|
|
40
|
-
function
|
|
164
|
+
function normalizeProviderHeaders(headers) {
|
|
165
|
+
if (!headers)
|
|
166
|
+
return undefined;
|
|
167
|
+
const out = {};
|
|
168
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
169
|
+
if (typeof value === "string") {
|
|
170
|
+
out[key] = value;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
function streamText(model, context, options, runtime, runtimeOptions) {
|
|
41
176
|
return createPiLifecycleStream({
|
|
42
177
|
model,
|
|
43
|
-
now: Date.now,
|
|
178
|
+
now: runtimeOptions?.now ?? Date.now,
|
|
44
179
|
signal: options?.signal,
|
|
45
|
-
runTransport: ({ onSemantic, signal }) => {
|
|
180
|
+
runTransport: async ({ onSemantic, signal }) => {
|
|
181
|
+
const fetchFn = (options?.fetch ??
|
|
182
|
+
runtimeOptions?.fetch ??
|
|
183
|
+
globalThis.fetch);
|
|
184
|
+
const guardConfig = runtime.getConfig();
|
|
185
|
+
const pool = runtime.getAccountPool();
|
|
186
|
+
const activeManager = pool.getManager();
|
|
187
|
+
if (activeManager && pool.hasManagedPoolHistory()) {
|
|
188
|
+
if (activeManager.getTotalAccountCount() === 0) {
|
|
189
|
+
throw createPoolUnavailableError({ reason: "no-accounts" });
|
|
190
|
+
}
|
|
191
|
+
const excludedRefreshTokens = new Set();
|
|
192
|
+
let lastError;
|
|
193
|
+
let waitedForSoftQuota = false;
|
|
194
|
+
let waitedForRateLimit = false;
|
|
195
|
+
while (true) {
|
|
196
|
+
const selected = await pool.acquireCredentials({
|
|
197
|
+
modelId: model.id,
|
|
198
|
+
fetch: fetchFn,
|
|
199
|
+
signal,
|
|
200
|
+
excludeRefreshTokens: excludedRefreshTokens,
|
|
201
|
+
});
|
|
202
|
+
if (!selected) {
|
|
203
|
+
if (lastError)
|
|
204
|
+
throw lastError;
|
|
205
|
+
const unavailable = await pool.resolvePoolUnavailableOutcome({
|
|
206
|
+
modelId: model.id,
|
|
207
|
+
fetch: fetchFn,
|
|
208
|
+
signal,
|
|
209
|
+
alreadyWaitedForSoftQuota: waitedForSoftQuota,
|
|
210
|
+
alreadyWaitedForRateLimit: waitedForRateLimit,
|
|
211
|
+
});
|
|
212
|
+
if (unavailable.action === "wait-and-retry") {
|
|
213
|
+
if (unavailable.kind === "soft-quota") {
|
|
214
|
+
waitedForSoftQuota = true;
|
|
215
|
+
await (runtimeOptions?.sleep ?? abortableSleep)(unavailable.waitMs, signal);
|
|
216
|
+
await pool.refreshQuotasLive({ fetch: fetchFn, signal });
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
waitedForRateLimit = true;
|
|
220
|
+
await (runtimeOptions?.sleep ?? abortableSleep)(unavailable.waitMs, signal);
|
|
221
|
+
}
|
|
222
|
+
excludedRefreshTokens.clear();
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
throw unavailable.error;
|
|
226
|
+
}
|
|
227
|
+
excludedRefreshTokens.add(selected.account.parts.refreshToken);
|
|
228
|
+
let emittedOutput = false;
|
|
229
|
+
try {
|
|
230
|
+
await executeStreamTransport({
|
|
231
|
+
accessToken: selected.accessToken,
|
|
232
|
+
projectId: selected.projectId,
|
|
233
|
+
context,
|
|
234
|
+
endpoints: ANTIGRAVITY_ENDPOINT_FALLBACKS,
|
|
235
|
+
fetch: fetchFn,
|
|
236
|
+
generationOptions: options,
|
|
237
|
+
headers: normalizeProviderHeaders(options?.headers),
|
|
238
|
+
maxCapacityRetriesPerEndpoint: MAX_CAPACITY_RETRIES_PER_ENDPOINT,
|
|
239
|
+
model,
|
|
240
|
+
now: runtimeOptions?.now ?? Date.now,
|
|
241
|
+
onSemantic: async (semantic) => {
|
|
242
|
+
if (semantic.type !== "toolDiagnostics") {
|
|
243
|
+
emittedOutput = true;
|
|
244
|
+
}
|
|
245
|
+
await onSemantic(semantic);
|
|
246
|
+
},
|
|
247
|
+
platform: process.platform,
|
|
248
|
+
requestId: `agent-${crypto.randomUUID()}`,
|
|
249
|
+
requestJitterMaxMs: guardConfig.request_jitter_max_ms,
|
|
250
|
+
signal,
|
|
251
|
+
signatureCache: runtime.getSignatureCache(),
|
|
252
|
+
sleep: runtimeOptions?.sleep,
|
|
253
|
+
timeoutMs: options?.timeoutMs,
|
|
254
|
+
userAgent: selected.userAgent,
|
|
255
|
+
});
|
|
256
|
+
await pool.recordSuccess(selected.account, fetchFn);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
lastError = error;
|
|
261
|
+
if (emittedOutput || signal.aborted || !(error instanceof StreamTransportError)) {
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
const outcome = await pool.recordHttpFailure({
|
|
265
|
+
account: selected.account,
|
|
266
|
+
modelId: model.id,
|
|
267
|
+
status: error.status,
|
|
268
|
+
body: error.responseBody,
|
|
269
|
+
headers: error.responseHeaders,
|
|
270
|
+
message: error.message,
|
|
271
|
+
tokenConsumed: selected.tokenConsumed,
|
|
272
|
+
});
|
|
273
|
+
if (!outcome.rotated) {
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
46
279
|
const credentials = parseProviderApiKey(options?.apiKey ?? "");
|
|
47
280
|
return executeStreamTransport({
|
|
48
281
|
accessToken: credentials.token,
|
|
49
282
|
projectId: credentials.projectId,
|
|
50
283
|
context,
|
|
51
|
-
fetch:
|
|
284
|
+
fetch: fetchFn,
|
|
52
285
|
generationOptions: options,
|
|
53
|
-
headers:
|
|
286
|
+
headers: normalizeProviderHeaders(options?.headers),
|
|
54
287
|
model,
|
|
55
|
-
now: Date.now,
|
|
288
|
+
now: runtimeOptions?.now ?? Date.now,
|
|
56
289
|
onSemantic,
|
|
57
290
|
platform: process.platform,
|
|
58
291
|
requestId: `agent-${crypto.randomUUID()}`,
|
|
292
|
+
requestJitterMaxMs: guardConfig.request_jitter_max_ms,
|
|
59
293
|
signal,
|
|
294
|
+
signatureCache: runtime.getSignatureCache(),
|
|
295
|
+
sleep: runtimeOptions?.sleep,
|
|
60
296
|
timeoutMs: options?.timeoutMs,
|
|
297
|
+
userAgent: runtime.getUserAgent(),
|
|
61
298
|
});
|
|
62
299
|
},
|
|
63
300
|
});
|
|
64
301
|
}
|
|
65
|
-
function
|
|
66
|
-
if (!
|
|
67
|
-
return
|
|
68
|
-
|
|
302
|
+
function isCredentialPayload(value) {
|
|
303
|
+
if (!value || typeof value !== "object")
|
|
304
|
+
return false;
|
|
305
|
+
const candidate = value;
|
|
306
|
+
return (Object.keys(candidate).length === 2 &&
|
|
307
|
+
typeof candidate.token === "string" &&
|
|
308
|
+
candidate.token.trim().length > 0 &&
|
|
309
|
+
candidate.token.trim() !== SHARED_POOL_PLACEHOLDER_ACCESS &&
|
|
310
|
+
typeof candidate.projectId === "string" &&
|
|
311
|
+
candidate.projectId.trim().length > 0);
|
|
69
312
|
}
|
|
70
|
-
|
|
71
|
-
|
|
313
|
+
const googleSearchParameters = Type.Object({
|
|
314
|
+
query: Type.String({
|
|
315
|
+
description: "The search query or question to answer using web search",
|
|
316
|
+
}),
|
|
317
|
+
urls: Type.Optional(Type.Array(Type.String(), {
|
|
318
|
+
description: "List of specific URLs to fetch and analyze. Extract and include any URLs mentioned by the user.",
|
|
319
|
+
})),
|
|
320
|
+
thinking: Type.Optional(Type.Boolean({
|
|
321
|
+
description: "Enable deep thinking for more thorough analysis (default: true)",
|
|
322
|
+
})),
|
|
323
|
+
});
|
|
324
|
+
function registerPiGoogleSearchTool(pi, runtime, runtimeOptions, getSessionCwd) {
|
|
325
|
+
if (typeof pi.registerTool !== "function")
|
|
326
|
+
return;
|
|
327
|
+
pi.registerTool({
|
|
328
|
+
name: "google_search",
|
|
329
|
+
label: "Google Search",
|
|
330
|
+
description: "Search the web using Google Search and analyze URLs. Returns real-time information from the internet with source citations.",
|
|
331
|
+
parameters: googleSearchParameters,
|
|
332
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
333
|
+
const effectiveSignal = signal ?? new AbortController().signal;
|
|
334
|
+
effectiveSignal.throwIfAborted();
|
|
335
|
+
const fetchFn = runtimeOptions?.fetch ?? globalThis.fetch;
|
|
336
|
+
const nowFn = runtimeOptions?.now ?? Date.now;
|
|
337
|
+
const pool = runtime.getAccountPool();
|
|
338
|
+
const cwd = ctx?.cwd ?? getSessionCwd?.() ?? runtimeOptions?.cwd;
|
|
339
|
+
const allowDiskScope = runtimeOptions === undefined ||
|
|
340
|
+
cwd !== undefined ||
|
|
341
|
+
runtimeOptions.homeDir !== undefined ||
|
|
342
|
+
runtimeOptions.env !== undefined ||
|
|
343
|
+
pool.getManager() !== null;
|
|
344
|
+
if (allowDiskScope) {
|
|
345
|
+
await pool.loadOrRefresh(cwd);
|
|
346
|
+
}
|
|
347
|
+
const activeManager = pool.getManager();
|
|
348
|
+
if (activeManager && pool.hasManagedPoolHistory()) {
|
|
349
|
+
if (activeManager.getTotalAccountCount() === 0) {
|
|
350
|
+
const noAccErr = createPoolUnavailableError({ reason: "no-accounts" });
|
|
351
|
+
return {
|
|
352
|
+
content: [{ type: "text", text: `## Search Error\n\n${noAccErr.message}` }],
|
|
353
|
+
details: { error: true },
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
const excludedRefreshTokens = new Set();
|
|
357
|
+
const retriedStaleAuthByToken = new Set();
|
|
358
|
+
let lastFailureText;
|
|
359
|
+
let waitedForSoftQuota = false;
|
|
360
|
+
let waitedForRateLimit = false;
|
|
361
|
+
while (true) {
|
|
362
|
+
const selected = await pool.acquireCredentials({
|
|
363
|
+
modelId: SEARCH_MODEL,
|
|
364
|
+
fetch: fetchFn,
|
|
365
|
+
signal: effectiveSignal,
|
|
366
|
+
excludeRefreshTokens: excludedRefreshTokens,
|
|
367
|
+
});
|
|
368
|
+
if (!selected) {
|
|
369
|
+
if (lastFailureText) {
|
|
370
|
+
return {
|
|
371
|
+
content: [{ type: "text", text: lastFailureText }],
|
|
372
|
+
details: { error: true },
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
const unavailable = await pool.resolvePoolUnavailableOutcome({
|
|
376
|
+
modelId: SEARCH_MODEL,
|
|
377
|
+
fetch: fetchFn,
|
|
378
|
+
signal: effectiveSignal,
|
|
379
|
+
alreadyWaitedForSoftQuota: waitedForSoftQuota,
|
|
380
|
+
alreadyWaitedForRateLimit: waitedForRateLimit,
|
|
381
|
+
});
|
|
382
|
+
if (unavailable.action === "wait-and-retry") {
|
|
383
|
+
if (unavailable.kind === "soft-quota") {
|
|
384
|
+
waitedForSoftQuota = true;
|
|
385
|
+
await (runtimeOptions?.sleep ?? abortableSleep)(unavailable.waitMs, effectiveSignal);
|
|
386
|
+
await pool.refreshQuotasLive({ fetch: fetchFn, signal: effectiveSignal });
|
|
387
|
+
}
|
|
388
|
+
else {
|
|
389
|
+
waitedForRateLimit = true;
|
|
390
|
+
await (runtimeOptions?.sleep ?? abortableSleep)(unavailable.waitMs, effectiveSignal);
|
|
391
|
+
}
|
|
392
|
+
excludedRefreshTokens.clear();
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
return {
|
|
396
|
+
content: [{ type: "text", text: `## Search Error\n\n${unavailable.error.message}` }],
|
|
397
|
+
details: { error: true },
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
const tokenKey = selected.account.parts.refreshToken;
|
|
401
|
+
const searchOutcome = await executeAntigravitySearchDetailed({
|
|
402
|
+
query: params.query,
|
|
403
|
+
urls: params.urls,
|
|
404
|
+
thinking: params.thinking,
|
|
405
|
+
}, selected.accessToken, selected.projectId, {
|
|
406
|
+
abortSignal: effectiveSignal,
|
|
407
|
+
endpoints: ANTIGRAVITY_ENDPOINT_FALLBACKS,
|
|
408
|
+
fetch: fetchFn,
|
|
409
|
+
userAgent: selected.userAgent,
|
|
410
|
+
});
|
|
411
|
+
if (searchOutcome.ok) {
|
|
412
|
+
await pool.recordSuccess(selected.account, fetchFn);
|
|
413
|
+
return {
|
|
414
|
+
content: [{ type: "text", text: searchOutcome.formatted }],
|
|
415
|
+
details: { query: params.query, urlCount: params.urls?.length ?? 0 },
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
lastFailureText = searchOutcome.formatted;
|
|
419
|
+
if (effectiveSignal.aborted || searchOutcome.status === undefined) {
|
|
420
|
+
return {
|
|
421
|
+
content: [{ type: "text", text: searchOutcome.formatted }],
|
|
422
|
+
details: { error: true },
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
const failureOutcome = await pool.recordHttpFailure({
|
|
426
|
+
account: selected.account,
|
|
427
|
+
modelId: SEARCH_MODEL,
|
|
428
|
+
status: searchOutcome.status,
|
|
429
|
+
body: searchOutcome.errorBody,
|
|
430
|
+
headers: searchOutcome.headers,
|
|
431
|
+
message: searchOutcome.statusText,
|
|
432
|
+
tokenConsumed: selected.tokenConsumed,
|
|
433
|
+
});
|
|
434
|
+
// If a cached access token returned HTTP 401 and recordHttpFailure cleared it, allow one immediate re-acquire on this account
|
|
435
|
+
if (searchOutcome.status === 401 && !retriedStaleAuthByToken.has(tokenKey)) {
|
|
436
|
+
retriedStaleAuthByToken.add(tokenKey);
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
excludedRefreshTokens.add(tokenKey);
|
|
440
|
+
if (!failureOutcome.rotated) {
|
|
441
|
+
return {
|
|
442
|
+
content: [{ type: "text", text: searchOutcome.formatted }],
|
|
443
|
+
details: { error: true },
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
if (allowDiskScope) {
|
|
449
|
+
const authPath = resolvePiAuthJsonPath({
|
|
450
|
+
...runtimeOptions,
|
|
451
|
+
cwd,
|
|
452
|
+
});
|
|
453
|
+
const authEntry = readPiAuthEntry(authPath);
|
|
454
|
+
if (authEntry) {
|
|
455
|
+
let accessToken = authEntry.access;
|
|
456
|
+
if (!accessToken || accessToken === SHARED_POOL_PLACEHOLDER_ACCESS || authEntry.expires <= nowFn() + 60_000) {
|
|
457
|
+
try {
|
|
458
|
+
const refreshToken = parseRefreshParts(authEntry.refresh).refreshToken;
|
|
459
|
+
const refreshed = await refreshCredentials({
|
|
460
|
+
credentials: {
|
|
461
|
+
refresh: refreshToken,
|
|
462
|
+
access: authEntry.access,
|
|
463
|
+
expires: authEntry.expires,
|
|
464
|
+
projectId: authEntry.projectId || ANTIGRAVITY_DEFAULT_PROJECT_ID,
|
|
465
|
+
email: authEntry.email,
|
|
466
|
+
},
|
|
467
|
+
fetch: fetchFn,
|
|
468
|
+
now: nowFn,
|
|
469
|
+
signal: effectiveSignal,
|
|
470
|
+
deadlineMs: nowFn() + 30_000,
|
|
471
|
+
});
|
|
472
|
+
accessToken = refreshed.access;
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
476
|
+
return {
|
|
477
|
+
content: [
|
|
478
|
+
{
|
|
479
|
+
type: "text",
|
|
480
|
+
text: `Error: Failed to refresh access token: ${message}`,
|
|
481
|
+
},
|
|
482
|
+
],
|
|
483
|
+
details: { error: true },
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (accessToken) {
|
|
488
|
+
const projectId = authEntry.projectId || ANTIGRAVITY_DEFAULT_PROJECT_ID;
|
|
489
|
+
const searchOutcome = await executeAntigravitySearchDetailed({
|
|
490
|
+
query: params.query,
|
|
491
|
+
urls: params.urls,
|
|
492
|
+
thinking: params.thinking,
|
|
493
|
+
}, accessToken, projectId, {
|
|
494
|
+
abortSignal: effectiveSignal,
|
|
495
|
+
endpoints: ANTIGRAVITY_ENDPOINT_FALLBACKS,
|
|
496
|
+
fetch: fetchFn,
|
|
497
|
+
userAgent: runtime.getUserAgent(),
|
|
498
|
+
});
|
|
499
|
+
return {
|
|
500
|
+
content: [{ type: "text", text: searchOutcome.formatted }],
|
|
501
|
+
details: { query: params.query, urlCount: params.urls?.length ?? 0 },
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return {
|
|
507
|
+
content: [
|
|
508
|
+
{
|
|
509
|
+
type: "text",
|
|
510
|
+
text: "Error: Not authenticated with Antigravity. Run `/login antigravity-guard` to authenticate.",
|
|
511
|
+
},
|
|
512
|
+
],
|
|
513
|
+
details: { error: true },
|
|
514
|
+
};
|
|
515
|
+
},
|
|
516
|
+
});
|
|
72
517
|
}
|
|
73
|
-
function
|
|
74
|
-
|
|
518
|
+
async function resolveDiscoveryCredentials(refreshCtx, runtime, runtimeOptions, allowDiskFallback = false, effectiveCwd) {
|
|
519
|
+
const fetchFn = runtimeOptions?.fetch ?? globalThis.fetch;
|
|
520
|
+
const nowFn = runtimeOptions?.now ?? Date.now;
|
|
521
|
+
const nowMs = nowFn();
|
|
522
|
+
const refreshInMemory = async (rawRefresh, fallbackProjectId) => {
|
|
523
|
+
const parts = parseRefreshParts(rawRefresh);
|
|
524
|
+
if (!parts.refreshToken)
|
|
525
|
+
return null;
|
|
526
|
+
const projectId = parts.managedProjectId ??
|
|
527
|
+
parts.projectId ??
|
|
528
|
+
(fallbackProjectId && fallbackProjectId.trim() ? fallbackProjectId.trim() : undefined) ??
|
|
529
|
+
ANTIGRAVITY_DEFAULT_PROJECT_ID;
|
|
530
|
+
try {
|
|
531
|
+
const refreshed = await refreshCredentials({
|
|
532
|
+
credentials: {
|
|
533
|
+
refresh: parts.refreshToken,
|
|
534
|
+
access: "",
|
|
535
|
+
expires: 0,
|
|
536
|
+
projectId,
|
|
537
|
+
},
|
|
538
|
+
fetch: fetchFn,
|
|
539
|
+
now: nowFn,
|
|
540
|
+
signal: refreshCtx.signal,
|
|
541
|
+
deadlineMs: nowMs + 15_000,
|
|
542
|
+
});
|
|
543
|
+
if (refreshed.access) {
|
|
544
|
+
return { token: refreshed.access, projectId };
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
catch {
|
|
548
|
+
// Ignore refresh failure on candidate and try next fallback
|
|
549
|
+
}
|
|
550
|
+
return null;
|
|
551
|
+
};
|
|
552
|
+
const credential = refreshCtx.credential;
|
|
553
|
+
if (credential && credential.type === "oauth") {
|
|
554
|
+
const extras = credential;
|
|
555
|
+
const credProjectId = typeof extras.projectId === "string" && extras.projectId.trim()
|
|
556
|
+
? extras.projectId.trim()
|
|
557
|
+
: undefined;
|
|
558
|
+
const isUnexpired = typeof credential.expires !== "number" || credential.expires > nowMs;
|
|
559
|
+
const rawAccess = typeof credential.access === "string" ? credential.access.trim() : "";
|
|
560
|
+
if (rawAccess && rawAccess !== SHARED_POOL_PLACEHOLDER_ACCESS && isUnexpired) {
|
|
561
|
+
try {
|
|
562
|
+
return parseProviderApiKey(rawAccess);
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
return {
|
|
566
|
+
token: rawAccess,
|
|
567
|
+
projectId: credProjectId ?? ANTIGRAVITY_DEFAULT_PROJECT_ID,
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (typeof credential.refresh === "string" && credential.refresh.trim()) {
|
|
572
|
+
const refreshed = await refreshInMemory(credential.refresh, credProjectId);
|
|
573
|
+
if (refreshed)
|
|
574
|
+
return refreshed;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
const manager = runtime.getAccountPool().getManager();
|
|
578
|
+
if (manager) {
|
|
579
|
+
for (const acc of manager.getEnabledAccounts()) {
|
|
580
|
+
if (acc.access &&
|
|
581
|
+
acc.access !== SHARED_POOL_PLACEHOLDER_ACCESS &&
|
|
582
|
+
typeof acc.expires === "number" &&
|
|
583
|
+
acc.expires > nowMs) {
|
|
584
|
+
return {
|
|
585
|
+
token: acc.access,
|
|
586
|
+
projectId: acc.parts.managedProjectId ??
|
|
587
|
+
acc.parts.projectId ??
|
|
588
|
+
ANTIGRAVITY_DEFAULT_PROJECT_ID,
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
for (const acc of manager.getEnabledAccounts()) {
|
|
593
|
+
const refreshed = await refreshInMemory(acc.parts.refreshToken, acc.parts.managedProjectId ?? acc.parts.projectId);
|
|
594
|
+
if (refreshed)
|
|
595
|
+
return refreshed;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
if (allowDiskFallback) {
|
|
599
|
+
const scopedOptions = {
|
|
600
|
+
...runtimeOptions,
|
|
601
|
+
cwd: effectiveCwd ?? runtimeOptions?.cwd,
|
|
602
|
+
};
|
|
603
|
+
// Read-only disk fallback when refreshModels runs before session_start (zero mutations to AccountManager or disk)
|
|
604
|
+
const paths = resolveSharedGuardPaths(scopedOptions);
|
|
605
|
+
const storedPool = await loadAccountsFromPath(paths.accountsPath);
|
|
606
|
+
if (storedPool?.accounts?.length) {
|
|
607
|
+
for (const acc of storedPool.accounts) {
|
|
608
|
+
if (acc.enabled === false)
|
|
609
|
+
continue;
|
|
610
|
+
const refreshed = await refreshInMemory(acc.refreshToken, acc.managedProjectId ?? acc.projectId);
|
|
611
|
+
if (refreshed)
|
|
612
|
+
return refreshed;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
const authEntry = readPiAuthEntry(resolvePiAuthJsonPath(scopedOptions));
|
|
616
|
+
if (authEntry) {
|
|
617
|
+
if (authEntry.access &&
|
|
618
|
+
authEntry.access !== SHARED_POOL_PLACEHOLDER_ACCESS &&
|
|
619
|
+
authEntry.expires > nowMs) {
|
|
620
|
+
return {
|
|
621
|
+
token: authEntry.access,
|
|
622
|
+
projectId: authEntry.projectId || ANTIGRAVITY_DEFAULT_PROJECT_ID,
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
const refreshed = await refreshInMemory(authEntry.refresh, authEntry.projectId);
|
|
626
|
+
if (refreshed)
|
|
627
|
+
return refreshed;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
async function refreshDiscoveredModels(refreshCtx, runtime, runtimeOptions, sessionCwd) {
|
|
633
|
+
const staticModels = listCatalogEntries().map(toPiModelDescriptor);
|
|
634
|
+
const env = runtimeOptions?.env ?? process.env;
|
|
635
|
+
const offline = /^(1|true|yes)$/i.test(env.PI_OFFLINE ?? "");
|
|
636
|
+
if (!refreshCtx.allowNetwork || offline || refreshCtx.signal.aborted) {
|
|
637
|
+
return staticModels;
|
|
638
|
+
}
|
|
639
|
+
const effectiveCwd = sessionCwd ?? runtimeOptions?.cwd;
|
|
640
|
+
const allowDiskScope = runtimeOptions === undefined ||
|
|
641
|
+
effectiveCwd !== undefined ||
|
|
642
|
+
runtimeOptions.homeDir !== undefined ||
|
|
643
|
+
runtimeOptions.env !== undefined ||
|
|
644
|
+
runtime.getAccountPool().getManager() !== null;
|
|
645
|
+
const config = allowDiskScope
|
|
646
|
+
? loadSharedGuardConfig({
|
|
647
|
+
...runtimeOptions,
|
|
648
|
+
cwd: effectiveCwd,
|
|
649
|
+
})
|
|
650
|
+
: runtime.getConfig();
|
|
651
|
+
if (!config.model_discovery.enabled || !config.model_discovery.antigravity) {
|
|
652
|
+
return staticModels;
|
|
653
|
+
}
|
|
654
|
+
const creds = await resolveDiscoveryCredentials(refreshCtx, runtime, runtimeOptions, allowDiskScope, effectiveCwd);
|
|
655
|
+
if (!creds) {
|
|
656
|
+
return staticModels;
|
|
657
|
+
}
|
|
658
|
+
try {
|
|
659
|
+
const response = await fetchAvailableModels(creds.token, creds.projectId, {
|
|
660
|
+
fetch: runtimeOptions?.fetch ?? globalThis.fetch,
|
|
661
|
+
signal: refreshCtx.signal,
|
|
662
|
+
userAgent: runtime.getUserAgent(),
|
|
663
|
+
});
|
|
664
|
+
if (!response.models || Object.keys(response.models).length === 0) {
|
|
665
|
+
return staticModels;
|
|
666
|
+
}
|
|
667
|
+
const mergedEntries = registerDiscoveredCatalogEntries(response.models);
|
|
668
|
+
return mergedEntries.map(toPiModelDescriptor);
|
|
669
|
+
}
|
|
670
|
+
catch {
|
|
671
|
+
return staticModels;
|
|
672
|
+
}
|
|
75
673
|
}
|