@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.
@@ -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
- constructor(kind: StreamErrorKind, message: string, status?: number | undefined, details?: ToolStreamDiagnostics | undefined);
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
- constructor(kind, message, status, details) {
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({ context: input.context, model: input.model, options: input.generationOptions, project: input.projectId, requestId: input.requestId }, selection, (diagnostics) => { replayDiagnostics = diagnostics; });
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
- const response = await abortable(input.fetch(ENDPOINT, { method: "POST", redirect: "error", headers, body: JSON.stringify(payload), signal }), signal);
186
- await responseHook(input, response, signal);
187
- responseBody = response.body;
188
- if (!response.ok)
189
- throw await httpError(response, signal);
190
- if (!response.body || !isSse(response.headers.get("content-type"))) {
191
- await boundedBody(response.body, signal);
192
- throw streamError("response", "Antigravity did not return an SSE response.");
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
- await consume(response.body, signal, input.onSemantic, inactivityTimeout(input), responsePolicy(original, selection));
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
- for (const name of Object.keys(input.headers ?? {}))
290
- if (PROTECTED_HEADERS.has(name.toLowerCase()))
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
- ...input.headers,
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.body, signal);
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(body, signal) {
347
- if (!body)
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)
@@ -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>) => string | undefined;
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 {};