@benjamolina/pi-antigravity-guard 0.5.1 → 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 +181 -20
- 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 +40 -14
- package/dist/tool-schema.d.ts +2 -0
- package/dist/tool-schema.js +20 -26
- package/package.json +2 -2
package/dist/response.d.ts
CHANGED
|
@@ -49,6 +49,12 @@ export declare class ResponseSemantics {
|
|
|
49
49
|
private readonly ids;
|
|
50
50
|
private pendingFinish;
|
|
51
51
|
private usage;
|
|
52
|
+
private groundingSources;
|
|
53
|
+
private groundingSourceUrls;
|
|
54
|
+
private groundingQueries;
|
|
55
|
+
private groundingQuerySet;
|
|
56
|
+
private groundingUrls;
|
|
57
|
+
private groundingUrlSet;
|
|
52
58
|
constructor(policy?: ToolResponsePolicy);
|
|
53
59
|
push(record: string): ResponseSemantic[];
|
|
54
60
|
finish(): FinishSemantic;
|
|
@@ -59,4 +65,6 @@ export declare class ResponseSemantics {
|
|
|
59
65
|
hasId(id: string): boolean;
|
|
60
66
|
addId(id: string): void;
|
|
61
67
|
callIndex(): number;
|
|
68
|
+
recordGrounding(groundingMetadata: unknown, urlContextMetadata: unknown): void;
|
|
69
|
+
consumeGroundingFooter(): string | undefined;
|
|
62
70
|
}
|
package/dist/response.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { formatGroundingFooter, parseCandidateGrounding, } from "@benjamolina/antigravity-guard-core";
|
|
1
2
|
import { canonicalJson } from "./tool-contract.js";
|
|
2
3
|
export class ResponseSemanticError extends Error {
|
|
3
4
|
}
|
|
@@ -10,6 +11,12 @@ export class ResponseSemantics {
|
|
|
10
11
|
ids = new Set();
|
|
11
12
|
pendingFinish;
|
|
12
13
|
usage = { prompt: 0, cacheRead: 0, output: 0, reasoning: 0 };
|
|
14
|
+
groundingSources = [];
|
|
15
|
+
groundingSourceUrls = new Set();
|
|
16
|
+
groundingQueries = [];
|
|
17
|
+
groundingQuerySet = new Set();
|
|
18
|
+
groundingUrls = [];
|
|
19
|
+
groundingUrlSet = new Set();
|
|
13
20
|
constructor(policy = { kind: "reject" }) {
|
|
14
21
|
this.policy = policy;
|
|
15
22
|
}
|
|
@@ -65,6 +72,47 @@ export class ResponseSemantics {
|
|
|
65
72
|
hasId(id) { return this.ids.has(id); }
|
|
66
73
|
addId(id) { this.ids.add(id); }
|
|
67
74
|
callIndex() { return this.calls; }
|
|
75
|
+
recordGrounding(groundingMetadata, urlContextMetadata) {
|
|
76
|
+
if (groundingMetadata !== undefined && (typeof groundingMetadata !== "object" || groundingMetadata === null || Array.isArray(groundingMetadata))) {
|
|
77
|
+
throw new ResponseSemanticError("Antigravity returned invalid grounding metadata.");
|
|
78
|
+
}
|
|
79
|
+
if (urlContextMetadata !== undefined && (typeof urlContextMetadata !== "object" || urlContextMetadata === null || Array.isArray(urlContextMetadata))) {
|
|
80
|
+
throw new ResponseSemanticError("Antigravity returned invalid URL context metadata.");
|
|
81
|
+
}
|
|
82
|
+
const parsed = parseCandidateGrounding({
|
|
83
|
+
groundingMetadata: groundingMetadata,
|
|
84
|
+
urlContextMetadata: urlContextMetadata,
|
|
85
|
+
});
|
|
86
|
+
for (const src of parsed.sources) {
|
|
87
|
+
if (!this.groundingSourceUrls.has(src.url)) {
|
|
88
|
+
this.groundingSourceUrls.add(src.url);
|
|
89
|
+
this.groundingSources.push(src);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const q of parsed.searchQueries) {
|
|
93
|
+
if (!this.groundingQuerySet.has(q)) {
|
|
94
|
+
this.groundingQuerySet.add(q);
|
|
95
|
+
this.groundingQueries.push(q);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
for (const u of parsed.urlsRetrieved) {
|
|
99
|
+
const key = `${u.status}:${u.url}`;
|
|
100
|
+
if (!this.groundingUrlSet.has(key)) {
|
|
101
|
+
this.groundingUrlSet.add(key);
|
|
102
|
+
this.groundingUrls.push(u);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
consumeGroundingFooter() {
|
|
107
|
+
const footer = formatGroundingFooter({
|
|
108
|
+
sources: this.groundingSources,
|
|
109
|
+
searchQueries: this.groundingQueries,
|
|
110
|
+
urlsRetrieved: this.groundingUrls,
|
|
111
|
+
});
|
|
112
|
+
if (!footer)
|
|
113
|
+
return undefined;
|
|
114
|
+
return `\n\n${footer}`;
|
|
115
|
+
}
|
|
68
116
|
}
|
|
69
117
|
function candidate(value, events, semantics) {
|
|
70
118
|
if (!Array.isArray(value) || value.length !== 1)
|
|
@@ -108,12 +156,23 @@ function candidate(value, events, semantics) {
|
|
|
108
156
|
}
|
|
109
157
|
}
|
|
110
158
|
}
|
|
159
|
+
const groundingMetadata = field(item, "groundingMetadata");
|
|
160
|
+
const urlContextMetadata = field(item, "urlContextMetadata");
|
|
161
|
+
if (groundingMetadata !== undefined || urlContextMetadata !== undefined) {
|
|
162
|
+
semantics.recordGrounding(groundingMetadata, urlContextMetadata);
|
|
163
|
+
}
|
|
111
164
|
const finishReason = field(item, "finishReason");
|
|
112
165
|
if (finishReason !== undefined) {
|
|
113
166
|
const hasCalls = semantics.callIndex() + callCount > 0;
|
|
114
167
|
const reason = hasCalls ? "toolUse" : finishReason === "STOP" ? "stop" : finishReason === "MAX_TOKENS" ? "length" : undefined;
|
|
115
168
|
if (!reason)
|
|
116
169
|
throw new ResponseSemanticError("Antigravity returned an unsupported finish reason.");
|
|
170
|
+
if (!hasCalls) {
|
|
171
|
+
const footer = semantics.consumeGroundingFooter();
|
|
172
|
+
if (footer) {
|
|
173
|
+
local.push({ type: "text", text: footer });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
117
176
|
semantics.setFinish(reason);
|
|
118
177
|
}
|
|
119
178
|
for (const id of ids)
|
package/dist/stream.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Context, Model, SimpleStreamOptions } from "@earendil-works/pi-ai";
|
|
2
|
+
import { MAX_CAPACITY_RETRIES_PER_ENDPOINT, type SessionSignatureCache } from "@benjamolina/antigravity-guard-core";
|
|
2
3
|
import { type GenerationSelection } from "./catalog.ts";
|
|
3
4
|
import { type ToolReplayMode } from "./tool-context.ts";
|
|
4
5
|
import type { ResponseSemantic } from "./response.ts";
|
|
@@ -31,24 +32,33 @@ export declare class StreamTransportError extends Error {
|
|
|
31
32
|
readonly kind: StreamErrorKind;
|
|
32
33
|
readonly status?: number | undefined;
|
|
33
34
|
readonly details?: ToolStreamDiagnostics | undefined;
|
|
34
|
-
|
|
35
|
+
readonly responseBody?: string | undefined;
|
|
36
|
+
readonly responseHeaders?: Record<string, string> | undefined;
|
|
37
|
+
constructor(kind: StreamErrorKind, message: string, status?: number | undefined, details?: ToolStreamDiagnostics | undefined, responseBody?: string | undefined, responseHeaders?: Record<string, string> | undefined);
|
|
35
38
|
}
|
|
36
39
|
export interface StreamTransportInput {
|
|
37
40
|
accessToken: string;
|
|
41
|
+
allowSentinelFallback?: boolean;
|
|
38
42
|
context: Context;
|
|
43
|
+
endpoints?: readonly string[];
|
|
39
44
|
fetch: typeof globalThis.fetch;
|
|
40
45
|
generationOptions?: SimpleStreamOptions;
|
|
41
46
|
headers?: Record<string, string>;
|
|
42
47
|
inactivityTimeoutMs?: number;
|
|
48
|
+
maxCapacityRetriesPerEndpoint?: number;
|
|
43
49
|
model: Model<string>;
|
|
44
50
|
projectId: string;
|
|
45
51
|
now: () => number;
|
|
46
52
|
onSemantic: (semantic: StreamSemantic) => void | Promise<void>;
|
|
47
53
|
platform: string;
|
|
48
54
|
requestId: string;
|
|
55
|
+
requestJitterMaxMs?: number;
|
|
49
56
|
selection?: GenerationSelection;
|
|
50
57
|
signal?: AbortSignal;
|
|
58
|
+
signatureCache?: SessionSignatureCache;
|
|
59
|
+
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
51
60
|
timeoutMs?: number;
|
|
61
|
+
userAgent?: string;
|
|
52
62
|
}
|
|
53
63
|
export interface PiStreamLifecycleInput {
|
|
54
64
|
model: Model<string>;
|
|
@@ -61,4 +71,25 @@ export interface PiStreamLifecycleInput {
|
|
|
61
71
|
}
|
|
62
72
|
export declare function createPiLifecycleStream(input: PiStreamLifecycleInput): import("@earendil-works/pi-ai").AssistantMessageEventStream;
|
|
63
73
|
export declare function executeStreamTransport(input: StreamTransportInput): Promise<void>;
|
|
64
|
-
export {
|
|
74
|
+
export type PoolUnavailableErrorDescriptor = {
|
|
75
|
+
reason: "soft-quota";
|
|
76
|
+
accountCount: number;
|
|
77
|
+
thresholdPercent: number;
|
|
78
|
+
family: "claude" | "gemini";
|
|
79
|
+
waitMs: number | null;
|
|
80
|
+
} | {
|
|
81
|
+
reason: "rate-limited";
|
|
82
|
+
accountCount: number;
|
|
83
|
+
family: "claude" | "gemini";
|
|
84
|
+
waitMs: number;
|
|
85
|
+
} | {
|
|
86
|
+
reason: "pool-unavailable";
|
|
87
|
+
accountCount: number;
|
|
88
|
+
waitMs?: number | null;
|
|
89
|
+
} | {
|
|
90
|
+
reason: "no-enabled-accounts";
|
|
91
|
+
} | {
|
|
92
|
+
reason: "no-accounts";
|
|
93
|
+
};
|
|
94
|
+
export declare function createPoolUnavailableError(descriptor: PoolUnavailableErrorDescriptor): StreamTransportError;
|
|
95
|
+
export { MAX_CAPACITY_RETRIES_PER_ENDPOINT };
|
package/dist/stream.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { calculateCost, createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
2
|
-
import { ANTIGRAVITY_ENDPOINTS, formatAntigravityHubUserAgent } from "@benjamolina/antigravity-guard-core";
|
|
2
|
+
import { ANTIGRAVITY_ENDPOINTS, MAX_CAPACITY_RETRIES_PER_ENDPOINT, abortableSleep, calculateCapacityBackoffMs, extractRateLimitTextInfo, formatAntigravityHubUserAgent, formatWaitTime, isGemini3Or4SignatureModel, parseRateLimitReason, } from "@benjamolina/antigravity-guard-core";
|
|
3
3
|
import { getCatalogEntry, resolveGenerationSelection } from "./catalog.js";
|
|
4
|
-
import { ContextSerializationError, serializeContext } from "./context.js";
|
|
4
|
+
import { ContextSerializationError, resolvePiSignatureSessionKey, serializeContext, } from "./context.js";
|
|
5
5
|
import { ToolPreflightError } from "./tool-contract.js";
|
|
6
6
|
import { hasToolContext } from "./tool-context.js";
|
|
7
7
|
import { ResponseSemanticError, ResponseSemantics } from "./response.js";
|
|
@@ -18,11 +18,15 @@ export class StreamTransportError extends Error {
|
|
|
18
18
|
kind;
|
|
19
19
|
status;
|
|
20
20
|
details;
|
|
21
|
-
|
|
21
|
+
responseBody;
|
|
22
|
+
responseHeaders;
|
|
23
|
+
constructor(kind, message, status, details, responseBody, responseHeaders) {
|
|
22
24
|
super(message);
|
|
23
25
|
this.kind = kind;
|
|
24
26
|
this.status = status;
|
|
25
27
|
this.details = details;
|
|
28
|
+
this.responseBody = responseBody;
|
|
29
|
+
this.responseHeaders = responseHeaders;
|
|
26
30
|
}
|
|
27
31
|
}
|
|
28
32
|
export function createPiLifecycleStream(input) {
|
|
@@ -172,26 +176,119 @@ export async function executeStreamTransport(input) {
|
|
|
172
176
|
validateInput(input);
|
|
173
177
|
const signal = totalSignal(input);
|
|
174
178
|
const headers = requestHeaders(input);
|
|
179
|
+
const endpointRoots = input.endpoints && input.endpoints.length > 0
|
|
180
|
+
? input.endpoints
|
|
181
|
+
: [ANTIGRAVITY_ENDPOINTS.daily];
|
|
182
|
+
const maxCapacityRetries = Math.max(0, input.maxCapacityRetriesPerEndpoint ?? 0);
|
|
183
|
+
const sleepFn = input.sleep ?? ((ms, sig) => abortableSleep(ms, sig));
|
|
175
184
|
let responseBody = null;
|
|
176
185
|
let selection;
|
|
177
186
|
let replayDiagnostics = emptyReplayDiagnostics();
|
|
178
187
|
try {
|
|
179
188
|
const entry = getCatalogEntry(input.model.id);
|
|
180
189
|
selection = input.selection ?? resolveGenerationSelection(entry, input.generationOptions?.reasoning);
|
|
181
|
-
const original = serializeContext({
|
|
190
|
+
const original = serializeContext({
|
|
191
|
+
context: input.context,
|
|
192
|
+
model: input.model,
|
|
193
|
+
options: input.generationOptions,
|
|
194
|
+
project: input.projectId,
|
|
195
|
+
requestId: input.requestId,
|
|
196
|
+
signatureCache: input.signatureCache,
|
|
197
|
+
allowSentinelFallback: input.allowSentinelFallback,
|
|
198
|
+
}, selection, (diagnostics) => { replayDiagnostics = diagnostics; });
|
|
182
199
|
if (hasToolContext(input.context))
|
|
183
200
|
await deliver(input.onSemantic, { type: "toolDiagnostics", details: toolDiagnostics(entry.publicId, selection, replayDiagnostics, "accepted") });
|
|
184
201
|
const payload = await payloadHook(input, original, signal);
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
202
|
+
await applyRequestJitter(input.requestJitterMaxMs, signal);
|
|
203
|
+
const requestBody = JSON.stringify(payload);
|
|
204
|
+
let lastPreStreamError;
|
|
205
|
+
for (let epIndex = 0; epIndex < endpointRoots.length; epIndex += 1) {
|
|
206
|
+
const endpointRoot = endpointRoots[epIndex].replace(/\/+$/, "");
|
|
207
|
+
const targetUrl = endpointRoot === ANTIGRAVITY_ENDPOINTS.daily
|
|
208
|
+
? ENDPOINT
|
|
209
|
+
: `${endpointRoot}/v1internal:streamGenerateContent?alt=sse`;
|
|
210
|
+
const hasMoreEndpoints = epIndex + 1 < endpointRoots.length;
|
|
211
|
+
let capacityRetries = 0;
|
|
212
|
+
while (true) {
|
|
213
|
+
let response;
|
|
214
|
+
try {
|
|
215
|
+
response = await abortable(input.fetch(targetUrl, {
|
|
216
|
+
method: "POST",
|
|
217
|
+
redirect: "error",
|
|
218
|
+
headers,
|
|
219
|
+
body: requestBody,
|
|
220
|
+
signal,
|
|
221
|
+
}), signal);
|
|
222
|
+
}
|
|
223
|
+
catch (fetchErr) {
|
|
224
|
+
if (isLocalStreamError(fetchErr)) {
|
|
225
|
+
if (fetchErr.kind === "aborted" || !hasMoreEndpoints)
|
|
226
|
+
throw fetchErr;
|
|
227
|
+
lastPreStreamError = fetchErr;
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
if (signal.aborted)
|
|
231
|
+
throw streamError("aborted", "Generation was cancelled.");
|
|
232
|
+
const transportErr = streamError("transport", "Antigravity generation request failed.");
|
|
233
|
+
if (!hasMoreEndpoints)
|
|
234
|
+
throw transportErr;
|
|
235
|
+
lastPreStreamError = transportErr;
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
await responseHook(input, response, signal);
|
|
239
|
+
responseBody = response.body;
|
|
240
|
+
if (!response.ok) {
|
|
241
|
+
const err = await httpError(response, signal);
|
|
242
|
+
responseBody = null;
|
|
243
|
+
if (err.status === 429 || err.status === 503 || err.status === 529) {
|
|
244
|
+
const parsedInfo = extractRateLimitTextInfo(err.responseBody ?? "");
|
|
245
|
+
const reason = parseRateLimitReason(parsedInfo.reason, parsedInfo.message ?? err.responseBody, err.status);
|
|
246
|
+
const isTransientCapacity = reason === "MODEL_CAPACITY_EXHAUSTED" || reason === "SERVER_ERROR";
|
|
247
|
+
if (isTransientCapacity) {
|
|
248
|
+
if (capacityRetries < maxCapacityRetries) {
|
|
249
|
+
capacityRetries += 1;
|
|
250
|
+
const waitMs = calculateCapacityBackoffMs(capacityRetries - 1);
|
|
251
|
+
await abortable(sleepFn(waitMs, signal), signal);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (hasMoreEndpoints) {
|
|
255
|
+
lastPreStreamError = err;
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
throw err;
|
|
260
|
+
}
|
|
261
|
+
const isValidation403 = err.status === 403 &&
|
|
262
|
+
Boolean(err.responseBody?.includes("VALIDATION_REQUIRED") || err.responseBody?.includes("validation_required"));
|
|
263
|
+
const canAdvanceEndpoint = hasMoreEndpoints &&
|
|
264
|
+
!isValidation403 &&
|
|
265
|
+
(err.status === 403 || err.status === 404 || (typeof err.status === "number" && err.status >= 500));
|
|
266
|
+
if (canAdvanceEndpoint) {
|
|
267
|
+
lastPreStreamError = err;
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
throw err;
|
|
271
|
+
}
|
|
272
|
+
if (!response.body || !isSse(response.headers.get("content-type"))) {
|
|
273
|
+
await boundedBody(response, signal);
|
|
274
|
+
responseBody = null;
|
|
275
|
+
throw streamError("response", "Antigravity did not return an SSE response.");
|
|
276
|
+
}
|
|
277
|
+
const signatureSessionKey = input.signatureCache && shouldCacheModelSignatures(selection.route.wireModel)
|
|
278
|
+
? resolvePiSignatureSessionKey({
|
|
279
|
+
context: input.context,
|
|
280
|
+
wireModel: selection.route.wireModel,
|
|
281
|
+
projectId: input.projectId,
|
|
282
|
+
})
|
|
283
|
+
: undefined;
|
|
284
|
+
const wrappedOnSemantic = signatureSessionKey && input.signatureCache
|
|
285
|
+
? createSignatureCachingSemanticSink(signatureSessionKey, input.signatureCache, input.onSemantic)
|
|
286
|
+
: input.onSemantic;
|
|
287
|
+
await consume(response.body, signal, wrappedOnSemantic, inactivityTimeout(input), responsePolicy(original, selection));
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
193
290
|
}
|
|
194
|
-
|
|
291
|
+
throw lastPreStreamError ?? streamError("transport", "Antigravity generation request failed.");
|
|
195
292
|
}
|
|
196
293
|
catch (error) {
|
|
197
294
|
void responseBody?.cancel().catch(() => undefined);
|
|
@@ -211,6 +308,53 @@ export async function executeStreamTransport(input) {
|
|
|
211
308
|
throw streamError("transport", "Antigravity generation request failed.");
|
|
212
309
|
}
|
|
213
310
|
}
|
|
311
|
+
function shouldCacheModelSignatures(wireModel) {
|
|
312
|
+
const lower = wireModel.toLowerCase();
|
|
313
|
+
return lower.includes("claude") || isGemini3Or4SignatureModel(wireModel);
|
|
314
|
+
}
|
|
315
|
+
function createSignatureCachingSemanticSink(sessionKey, signatureCache, onSemantic) {
|
|
316
|
+
let activeThinking;
|
|
317
|
+
const flushThinking = (fallbackSignature) => {
|
|
318
|
+
if (!activeThinking)
|
|
319
|
+
return;
|
|
320
|
+
const sig = activeThinking.signature ?? fallbackSignature;
|
|
321
|
+
if (activeThinking.text && sig) {
|
|
322
|
+
signatureCache.cacheSignature(sessionKey, activeThinking.text, sig);
|
|
323
|
+
}
|
|
324
|
+
activeThinking = undefined;
|
|
325
|
+
};
|
|
326
|
+
return async (semantic) => {
|
|
327
|
+
if (semantic.type === "thinking") {
|
|
328
|
+
if (activeThinking && (activeThinking.closedByText || (activeThinking.signature && !semantic.signature))) {
|
|
329
|
+
flushThinking();
|
|
330
|
+
}
|
|
331
|
+
if (!activeThinking) {
|
|
332
|
+
activeThinking = { text: semantic.thinking, signature: semantic.signature };
|
|
333
|
+
}
|
|
334
|
+
else {
|
|
335
|
+
activeThinking.text += semantic.thinking;
|
|
336
|
+
if (semantic.signature) {
|
|
337
|
+
activeThinking.signature = semantic.signature;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
else if (semantic.type === "toolCall") {
|
|
342
|
+
flushThinking(activeThinking?.closedByText ? undefined : semantic.signature);
|
|
343
|
+
}
|
|
344
|
+
else if (semantic.type === "text") {
|
|
345
|
+
if (activeThinking?.signature || semantic.signature) {
|
|
346
|
+
flushThinking(semantic.signature);
|
|
347
|
+
}
|
|
348
|
+
else if (activeThinking) {
|
|
349
|
+
activeThinking.closedByText = true;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
else if (semantic.type === "finish") {
|
|
353
|
+
flushThinking();
|
|
354
|
+
}
|
|
355
|
+
await onSemantic(semantic);
|
|
356
|
+
};
|
|
357
|
+
}
|
|
214
358
|
function validateInput(input) {
|
|
215
359
|
if (!getCatalogEntry(input.model.id) || input.model.api !== API)
|
|
216
360
|
throw streamError("response", "The selected Antigravity model or API is unsupported.");
|
|
@@ -285,18 +429,45 @@ async function responseHook(input, response, signal) {
|
|
|
285
429
|
throw streamError("callback", "Response handling failed.");
|
|
286
430
|
}
|
|
287
431
|
}
|
|
432
|
+
const OVERRIDDEN_HEADERS = new Set(["accept", "user-agent"]);
|
|
288
433
|
function requestHeaders(input) {
|
|
289
|
-
|
|
290
|
-
|
|
434
|
+
const callerHeaders = {};
|
|
435
|
+
for (const [name, value] of Object.entries(input.headers ?? {})) {
|
|
436
|
+
const lower = name.toLowerCase();
|
|
437
|
+
if (PROTECTED_HEADERS.has(lower))
|
|
291
438
|
throw streamError("response", "Custom headers cannot replace protected request headers.");
|
|
439
|
+
if (OVERRIDDEN_HEADERS.has(lower))
|
|
440
|
+
continue;
|
|
441
|
+
callerHeaders[name] = value;
|
|
442
|
+
}
|
|
292
443
|
return {
|
|
293
|
-
...
|
|
444
|
+
...callerHeaders,
|
|
294
445
|
Authorization: `Bearer ${input.accessToken}`,
|
|
295
446
|
Accept: "text/event-stream",
|
|
296
447
|
"Content-Type": "application/json",
|
|
297
|
-
"User-Agent": ANTIGRAVITY_USER_AGENT,
|
|
448
|
+
"User-Agent": input.userAgent ?? ANTIGRAVITY_USER_AGENT,
|
|
298
449
|
};
|
|
299
450
|
}
|
|
451
|
+
async function applyRequestJitter(maxMs, signal) {
|
|
452
|
+
if (!maxMs || maxMs <= 0)
|
|
453
|
+
return;
|
|
454
|
+
if (signal.aborted)
|
|
455
|
+
throw streamError("aborted", "Generation was cancelled.");
|
|
456
|
+
const delayMs = Math.floor(Math.random() * maxMs);
|
|
457
|
+
if (delayMs <= 0)
|
|
458
|
+
return;
|
|
459
|
+
await new Promise((resolve, reject) => {
|
|
460
|
+
const onAbort = () => {
|
|
461
|
+
clearTimeout(timer);
|
|
462
|
+
reject(streamError("aborted", "Generation was cancelled."));
|
|
463
|
+
};
|
|
464
|
+
const timer = setTimeout(() => {
|
|
465
|
+
signal.removeEventListener("abort", onAbort);
|
|
466
|
+
resolve();
|
|
467
|
+
}, delayMs);
|
|
468
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
469
|
+
});
|
|
470
|
+
}
|
|
300
471
|
async function consume(body, signal, onSemantic, inactivityMs, policy) {
|
|
301
472
|
const reader = body.getReader();
|
|
302
473
|
const framer = new SseFramer();
|
|
@@ -332,19 +503,22 @@ async function deliver(callback, semantic) {
|
|
|
332
503
|
}
|
|
333
504
|
}
|
|
334
505
|
async function httpError(response, signal) {
|
|
335
|
-
const body = await boundedBody(response
|
|
506
|
+
const body = await boundedBody(response, signal);
|
|
507
|
+
const headers = {};
|
|
508
|
+
response.headers.forEach((value, key) => { headers[key] = value; });
|
|
336
509
|
if (response.status === 401)
|
|
337
|
-
return streamError("access", "Authentication expired. Run /login antigravity-guard.", 401);
|
|
510
|
+
return streamError("access", "Authentication expired. Run /login antigravity-guard.", 401, undefined, body, headers);
|
|
338
511
|
if (response.status === 403)
|
|
339
|
-
return streamError("access", "Antigravity access was denied. Check your entitlement.", 403);
|
|
512
|
+
return streamError("access", "Antigravity access was denied. Check your entitlement.", 403, undefined, body, headers);
|
|
340
513
|
if (response.status === 404)
|
|
341
|
-
return streamError("model", "The requested Antigravity model is unavailable.", 404);
|
|
514
|
+
return streamError("model", "The requested Antigravity model is unavailable.", 404, undefined, body, headers);
|
|
342
515
|
if (response.status === 429 || body.includes("RESOURCE_EXHAUSTED"))
|
|
343
|
-
return streamError("quota", "Antigravity quota or rate limit was reached.", response.status);
|
|
344
|
-
return streamError("response", "Antigravity generation request was rejected.", response.status);
|
|
516
|
+
return streamError("quota", "Antigravity quota or rate limit was reached.", response.status, undefined, body, headers);
|
|
517
|
+
return streamError("response", "Antigravity generation request was rejected.", response.status, undefined, body, headers);
|
|
345
518
|
}
|
|
346
|
-
async function boundedBody(
|
|
347
|
-
|
|
519
|
+
async function boundedBody(response, signal) {
|
|
520
|
+
const body = response.body;
|
|
521
|
+
if (!body || response.bodyUsed || body.locked)
|
|
348
522
|
return "";
|
|
349
523
|
const reader = body.getReader();
|
|
350
524
|
const chunks = [];
|
|
@@ -395,11 +569,46 @@ function diagnosticFailure(error) {
|
|
|
395
569
|
function isStreamErrorKind(value) {
|
|
396
570
|
return value === "aborted" || value === "access" || value === "capability" || value === "model" || value === "quota" || value === "preflight" || value === "response" || value === "transport" || value === "callback";
|
|
397
571
|
}
|
|
398
|
-
function streamError(kind, message, status, details) {
|
|
399
|
-
const error = new StreamTransportError(kind, message, status, details);
|
|
572
|
+
function streamError(kind, message, status, details, responseBody, responseHeaders) {
|
|
573
|
+
const error = new StreamTransportError(kind, message, status, details, responseBody, responseHeaders);
|
|
400
574
|
LOCAL_ERRORS.add(error);
|
|
401
575
|
return error;
|
|
402
576
|
}
|
|
577
|
+
export function createPoolUnavailableError(descriptor) {
|
|
578
|
+
if (descriptor.reason === "soft-quota") {
|
|
579
|
+
const safeCount = Math.max(0, Math.trunc(descriptor.accountCount));
|
|
580
|
+
const safeThreshold = Math.max(0, Math.min(100, Math.trunc(descriptor.thresholdPercent)));
|
|
581
|
+
const safeFamily = descriptor.family === "claude" ? "claude" : "gemini";
|
|
582
|
+
const waitText = typeof descriptor.waitMs === "number" &&
|
|
583
|
+
Number.isFinite(descriptor.waitMs) &&
|
|
584
|
+
descriptor.waitMs > 0
|
|
585
|
+
? formatWaitTime(descriptor.waitMs)
|
|
586
|
+
: "unknown";
|
|
587
|
+
return streamError("quota", `[Antigravity Error] Quota protection: All ${safeCount} account(s) are over ${safeThreshold}% usage for ${safeFamily}. Quota resets in ${waitText}. Add more accounts with /login antigravity-guard, wait for quota reset, or set soft_quota_threshold_percent: 100 in antigravity.json.`, 429);
|
|
588
|
+
}
|
|
589
|
+
if (descriptor.reason === "rate-limited") {
|
|
590
|
+
const safeCount = Math.max(0, Math.trunc(descriptor.accountCount));
|
|
591
|
+
const safeFamily = descriptor.family === "claude" ? "claude" : "gemini";
|
|
592
|
+
const waitText = typeof descriptor.waitMs === "number" &&
|
|
593
|
+
Number.isFinite(descriptor.waitMs) &&
|
|
594
|
+
descriptor.waitMs > 0
|
|
595
|
+
? formatWaitTime(descriptor.waitMs)
|
|
596
|
+
: "unknown";
|
|
597
|
+
return streamError("quota", `All ${safeCount} Antigravity Guard account(s) are rate-limited for ${safeFamily}. Quota resets in ${waitText}.`, 429);
|
|
598
|
+
}
|
|
599
|
+
if (descriptor.reason === "no-enabled-accounts") {
|
|
600
|
+
return streamError("access", "No enabled Antigravity Guard accounts in the shared pool. Run /antigravity-accounts or /login antigravity-guard.", 401);
|
|
601
|
+
}
|
|
602
|
+
if (descriptor.reason === "pool-unavailable") {
|
|
603
|
+
const safeCount = Math.max(0, Math.trunc(descriptor.accountCount));
|
|
604
|
+
const suffix = typeof descriptor.waitMs === "number" && Number.isFinite(descriptor.waitMs) && descriptor.waitMs > 0
|
|
605
|
+
? ` Retry in ${formatWaitTime(descriptor.waitMs)}.`
|
|
606
|
+
: "";
|
|
607
|
+
return streamError("transport", `No available Antigravity Guard accounts across ${safeCount} enabled account(s) in the shared pool.${suffix} Run /antigravity-accounts for status.`, 503);
|
|
608
|
+
}
|
|
609
|
+
return streamError("access", "Antigravity credentials are invalid. Run /login antigravity-guard.", 401);
|
|
610
|
+
}
|
|
611
|
+
export { MAX_CAPACITY_RETRIES_PER_ENDPOINT };
|
|
403
612
|
function isLocalStreamError(error) { return error instanceof StreamTransportError && LOCAL_ERRORS.has(error); }
|
|
404
613
|
function abortable(promise, signal) {
|
|
405
614
|
if (signal.aborted)
|
package/dist/tool-context.d.ts
CHANGED
|
@@ -24,8 +24,9 @@ export declare function sanitizeToolCallId(id: string, fallbackName?: string): s
|
|
|
24
24
|
export interface ToolReplayPolicy {
|
|
25
25
|
readonly requireSignedToolCalls: boolean;
|
|
26
26
|
readonly isSameModel: (message: Record<string, unknown>) => boolean;
|
|
27
|
-
readonly toolCallSignature: (part: Record<string, unknown>, message: Record<string, unknown
|
|
27
|
+
readonly toolCallSignature: (part: Record<string, unknown>, message: Record<string, unknown>, callIndex: number, contentIndex: number) => string | undefined;
|
|
28
28
|
readonly includeToolCallId?: boolean;
|
|
29
|
+
readonly allowMultimodal?: boolean;
|
|
29
30
|
}
|
|
30
31
|
export declare function replayToolHistory(messages: unknown[], serializePart: (part: Record<string, unknown>, message: Record<string, unknown>) => WirePart, onDiagnostics?: (diagnostics: ToolReplayDiagnostics) => void, policy?: ToolReplayPolicy, declaredToolCount?: number): WireContent[];
|
|
31
32
|
export {};
|
package/dist/tool-context.js
CHANGED
|
@@ -128,33 +128,58 @@ export function replayToolHistory(messages, serializePart, onDiagnostics, policy
|
|
|
128
128
|
if (value(current, "addedToolNames") !== undefined && dense(value(current, "addedToolNames")).length)
|
|
129
129
|
history("PI_TOOL_CALL_INVALID");
|
|
130
130
|
const textParts = [];
|
|
131
|
-
const
|
|
131
|
+
const mediaParts = [];
|
|
132
132
|
for (const item of dense(value(current, "content"))) {
|
|
133
133
|
const part = record(item);
|
|
134
|
-
|
|
134
|
+
const partType = value(part, "type");
|
|
135
|
+
if (partType === "text" && typeof value(part, "text") === "string") {
|
|
135
136
|
textParts.push(value(part, "text"));
|
|
136
137
|
}
|
|
137
|
-
else if (
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const rawMime = value(part, "mimeType") ?? (isRecord(value(part, "source")) ? value(record(value(part, "source")), "media_type") : undefined);
|
|
141
|
-
const mimeType = typeof rawMime === "string" && rawMime ? rawMime : "image/jpeg";
|
|
142
|
-
const cleanedData = rawData.replace(/^data:[^;]+;base64,/s, "").trim();
|
|
143
|
-
imageParts.push({ inlineData: { mimeType, data: cleanedData } });
|
|
138
|
+
else if (partType === "image" || partType === "document" || partType === "file") {
|
|
139
|
+
if (policy?.allowMultimodal === false) {
|
|
140
|
+
history("PI_TOOL_RESULT_MEDIA_UNSUPPORTED");
|
|
144
141
|
}
|
|
142
|
+
const source = isRecord(value(part, "source")) ? record(value(part, "source")) : undefined;
|
|
143
|
+
const rawData = value(part, "data") ?? (source ? value(source, "data") : undefined);
|
|
144
|
+
if (typeof rawData !== "string" || !rawData) {
|
|
145
|
+
history("PI_TOOL_RESULT_MEDIA_UNSUPPORTED");
|
|
146
|
+
}
|
|
147
|
+
const dataUriMatch = /^data:([^;,]+);base64,/is.exec(rawData);
|
|
148
|
+
const rawMime = value(part, "mimeType") ?? (source ? value(source, "media_type") ?? value(source, "mimeType") : undefined) ?? dataUriMatch?.[1];
|
|
149
|
+
const defaultMime = partType === "image" ? "image/jpeg" : "application/pdf";
|
|
150
|
+
const mimeType = typeof rawMime === "string" && rawMime.trim() ? rawMime.trim() : defaultMime;
|
|
151
|
+
const lowerMime = mimeType.toLowerCase();
|
|
152
|
+
const isPdf = lowerMime === "application/pdf";
|
|
153
|
+
const isImage = lowerMime.startsWith("image/");
|
|
154
|
+
if (!isPdf && !isImage) {
|
|
155
|
+
history("PI_TOOL_RESULT_MEDIA_UNSUPPORTED");
|
|
156
|
+
}
|
|
157
|
+
if ((partType === "document" || partType === "file") && !isPdf) {
|
|
158
|
+
history("PI_TOOL_RESULT_MEDIA_UNSUPPORTED");
|
|
159
|
+
}
|
|
160
|
+
const cleanedData = rawData.replace(/^data:[^;]+;base64,/is, "").replace(/\s+/g, "");
|
|
161
|
+
if (!cleanedData || cleanedData.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(cleanedData)) {
|
|
162
|
+
history("PI_TOOL_RESULT_MEDIA_UNSUPPORTED");
|
|
163
|
+
}
|
|
164
|
+
mediaParts.push({ inlineData: { mimeType, data: cleanedData } });
|
|
145
165
|
}
|
|
146
166
|
else {
|
|
147
167
|
history("PI_TOOL_RESULT_MEDIA_UNSUPPORTED");
|
|
148
168
|
}
|
|
149
169
|
}
|
|
150
170
|
const text = textParts.join("\n\n");
|
|
151
|
-
const
|
|
171
|
+
const fallbackMediaLabel = mediaParts.length > 0
|
|
172
|
+
? mediaParts.every((p) => p.inlineData.mimeType.toLowerCase() === "application/pdf")
|
|
173
|
+
? "[PDF content]"
|
|
174
|
+
: "[Image content]"
|
|
175
|
+
: "";
|
|
176
|
+
const outputText = text || fallbackMediaLabel;
|
|
152
177
|
const response = value(current, "isError") === true ? { error: outputText } : { output: outputText };
|
|
153
178
|
pending.results.set(id, pending.observations ? observation(call, outputText) : { functionResponse: { ...(policy?.includeToolCallId ? { id: sanitizeToolCallId(call.id, call.name) } : {}), name: call.name, response } });
|
|
154
|
-
if (
|
|
179
|
+
if (mediaParts.length > 0) {
|
|
155
180
|
if (!pending.extraParts)
|
|
156
181
|
pending.extraParts = [];
|
|
157
|
-
pending.extraParts.push(...
|
|
182
|
+
pending.extraParts.push(...mediaParts);
|
|
158
183
|
}
|
|
159
184
|
results.add(id);
|
|
160
185
|
continue;
|
|
@@ -183,7 +208,7 @@ export function replayToolHistory(messages, serializePart, onDiagnostics, policy
|
|
|
183
208
|
if (value(current, "stopReason") !== "toolUse")
|
|
184
209
|
history("PI_TOOL_CALL_INVALID");
|
|
185
210
|
const group = [];
|
|
186
|
-
const parts = content.flatMap((item) => {
|
|
211
|
+
const parts = content.flatMap((item, contentIndex) => {
|
|
187
212
|
const part = record(item);
|
|
188
213
|
if (value(part, "type") !== "toolCall") {
|
|
189
214
|
if (isEmptyUnsignedText(part))
|
|
@@ -199,9 +224,10 @@ export function replayToolHistory(messages, serializePart, onDiagnostics, policy
|
|
|
199
224
|
if (typeof args !== "object" || Array.isArray(args) || args === null)
|
|
200
225
|
history("PI_TOOL_CALL_INVALID");
|
|
201
226
|
calls.add(id);
|
|
227
|
+
const callIndex = group.length;
|
|
202
228
|
const call = { id, name, args };
|
|
203
229
|
group.push(call);
|
|
204
|
-
return [{ call, signature: policy?.toolCallSignature(part, current), signaturePresent: value(part, "thoughtSignature") !== undefined }];
|
|
230
|
+
return [{ call, signature: policy?.toolCallSignature(part, current, callIndex, contentIndex), signaturePresent: value(part, "thoughtSignature") !== undefined, callIndex }];
|
|
205
231
|
});
|
|
206
232
|
const toolParts = parts.filter((part) => "call" in part);
|
|
207
233
|
const callsAreSigned = policy?.requireSignedToolCalls === true && policy.isSameModel(current) && Boolean(toolParts[0]?.signature) && toolParts.every((part) => !part.signaturePresent || Boolean(part.signature));
|
package/dist/tool-schema.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { cleanJSONSchemaForAntigravity, toGeminiSchema } from "@benjamolina/antigravity-guard-core";
|
|
1
2
|
import { type JsonObject } from "./tool-contract.ts";
|
|
3
|
+
export { cleanJSONSchemaForAntigravity, toGeminiSchema };
|
|
2
4
|
export interface ToolDeclaration {
|
|
3
5
|
readonly name: string;
|
|
4
6
|
readonly description: string;
|