@heyhuynhgiabuu/pi-oauth-antigravity 0.1.0 → 0.1.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/CHANGELOG.md CHANGED
@@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.1.2] - 2026-09-20
9
+
10
+ ### Changed
11
+ - Updated the Pi dependencies to 0.86.0 and migrated the provider to normalized `TranscriptContext` prompts and tool declarations.
12
+
13
+ ### Fixed
14
+ - **Gemini 3 tool schemas now use Pi's strict-prefer contract** before `VALIDATED` tool calling, preserving nullable optional arguments and rejecting unknown properties at the model boundary.
15
+ - **Gemini 3 tool-call replay now preserves matching sanitized IDs** in both function calls and function responses, reducing malformed or unexpected function-call failures.
16
+
17
+ ## [0.1.1] - 2026-09-15
18
+
19
+ ### Fixed
20
+ - **Transient throttles are no longer reported as quota exhaustion.** Only `Individual quota reached` (plan quota) maps to "Quota reached"; shared-capacity smoothing, per-minute rate limits, and generic `RESOURCE_EXHAUSTED` now report a transient throttle with the HTTP status and backend message preserved, so the host's retry classifier can retry them instead of failing the turn. Account-limit phrases inside the quoted backend text (e.g. `quota exceeded`) are neutralized so a transient throttle is not misclassified as non-retryable.
21
+ - **Transient 429s retry in place with backoff.** A throttled request is retried up to twice on the same endpoint (2s, then 4s; override via `ANTIGRAVITY_THROTTLE_BASE_DELAY_MS`) instead of hopping to the sandbox/production endpoints, which multiplied load on an already-throttled account.
22
+ - **Plan-quota 429s fail fast** without retrying or hopping endpoints, since the limit cannot clear before its reset time.
23
+ - **Backoff is abort-aware**: cancelling a turn stops the retry immediately.
24
+
8
25
  ## [0.1.0] - 2026-09-02
9
26
 
10
27
  ### Added
package/README.md CHANGED
@@ -72,7 +72,7 @@ pi -e /path/to/pi-oauth-antigravity/dist/index.js
72
72
  # Install dependencies
73
73
  npm install
74
74
 
75
- # Run unit tests (42 tests)
75
+ # Run unit tests (50 tests)
76
76
  npm test
77
77
 
78
78
  # Typecheck
@@ -1,24 +1,26 @@
1
- import { type Api, type AssistantMessage, type AssistantMessageEventStream, type Context, type Model, type Tool } from "@earendil-works/pi-ai";
1
+ import { type Api, type AssistantMessage, type AssistantMessageEventStream, type Model, type TranscriptContext, type Tool } from "@earendil-works/pi-ai";
2
2
  import { StopReason } from "../types/enums.js";
3
3
  import { ANTIGRAVITY_API, type AntigravityGenerateRequest, type AntigravityStreamOptions, type GeminiContent, type GeminiFunctionDeclaration } from "../types/types.js";
4
4
  import { type AntigravitySessionState } from "../utils/util.js";
5
5
  export { ANTIGRAVITY_API };
6
+ /** Plan quota is deterministic; everything else on a 429 is a transient throttle. */
7
+ export declare function isPlanQuotaError(status: number | undefined, text: string): boolean;
6
8
  /** Exported for unit tests. */
7
- export declare function convertMessages(model: Model<Api>, context: Context, runtimeModel: string): GeminiContent[];
9
+ export declare function convertMessages(model: Model<Api>, context: TranscriptContext, runtimeModel: string): GeminiContent[];
8
10
  /**
9
11
  * Gemini accepts JSON Schema through parametersJsonSchema. Claude and GPT-OSS
10
12
  * use Cloud Code Assist's custom-tool bridge, which requires a compatible
11
13
  * Draft 2020-12 subset in the legacy parameters field.
12
14
  */
13
- export declare function convertTools(tools: Tool[] | undefined, useLegacyParameters?: boolean): {
15
+ export declare function convertTools(tools: Tool[] | undefined, useLegacyParameters?: boolean, supportsStrictMode?: boolean): {
14
16
  functionDeclarations: GeminiFunctionDeclaration[];
15
17
  }[] | undefined;
16
18
  /** Exported for unit tests. */
17
- export declare function buildRequest(model: Model<Api>, context: Context, projectId: string, options: AntigravityStreamOptions, runtimeModel: string, sessionState?: AntigravitySessionState): AntigravityGenerateRequest;
19
+ export declare function buildRequest(model: Model<Api>, context: TranscriptContext, projectId: string, options: AntigravityStreamOptions, runtimeModel: string, sessionState?: AntigravitySessionState): AntigravityGenerateRequest;
18
20
  /** Exported for unit tests. */
19
21
  export declare function mapStopReason(reason: string | undefined): StopReason;
20
22
  /** Exported for unit tests. */
21
23
  export declare function friendlyAntigravityError(status: number | undefined, text: string): string;
22
24
  /** Exported for unit tests. */
23
25
  export declare function streamResponse(response: Response, stream: AssistantMessageEventStream, output: AssistantMessage, model?: Model<Api>, sessionState?: AntigravitySessionState): Promise<boolean>;
24
- export declare function streamAntigravity(model: Model<Api>, context: Context, options?: AntigravityStreamOptions): AssistantMessageEventStream;
26
+ export declare function streamAntigravity(model: Model<Api>, context: TranscriptContext, options?: AntigravityStreamOptions): AssistantMessageEventStream;
@@ -1,4 +1,7 @@
1
1
  import { calculateCost, createAssistantMessageEventStream, } from "@earendil-works/pi-ai";
2
+ import { getJsonSchemaToolParameters, resolveJsonSchemaStrictSampling } from "@earendil-works/pi-ai/api/constrained-sampling";
3
+ import { requiresToolCallId, supportsGoogleStrictToolSampling } from "@earendil-works/pi-ai/api/google-shared";
4
+ import { getCurrentSystemPrompt, getCurrentTools } from "@earendil-works/pi-ai/utils/transcript";
2
5
  import { antigravityHeaders, endpointCandidates, fetchAvailableRuntimeModel, formatRequestDiagnostics, jsonOrTextError, loadCodeAssist, parseApiKey, resolveProjectId, } from "../client/client.js";
3
6
  import { getCurrentEndpoint, runWithDiagnostics, setLastEndpoint, setLastError, setLastLatencyMs, setLastProjectId, setLastResolvedRuntimeModel, setLastStatus, } from "../diagnostics/diagnostics.js";
4
7
  import { AntigravityRequestType, AntigravityUserAgent, GeminiRole, GeminiToolCallingMode, StopReason, ToolChoice, } from "../types/enums.js";
@@ -12,16 +15,58 @@ const ANTIGRAVITY_SYSTEM_INSTRUCTION = "You are Antigravity, a powerful agentic
12
15
  "You are pair programming with a user to solve coding tasks. Be concise, practical, and tool-aware.";
13
16
  const ANTIGRAVITY_NO_PREAMBLE_INSTRUCTION = 'CRITICAL: NEVER output rule checks, formatting guidelines, constraint checklists (e.g. "No emdashes"), or your thinking/personality preambles in the final response. Output only the final response.';
14
17
  let toolCallCounter = 0;
18
+ /**
19
+ * Transient 429s (shared-capacity smoothing, per-minute rate limits, generic
20
+ * RESOURCE_EXHAUSTED) are retried on the same endpoint with backoff. Only
21
+ * "Individual quota reached" is plan quota, which cannot clear before its reset time
22
+ * and therefore fails fast instead of burning the host's retry budget.
23
+ */
24
+ const THROTTLE_MAX_RETRIES = 2;
25
+ const DEFAULT_THROTTLE_BASE_DELAY_MS = 2000;
26
+ /** Override the 429 backoff via ANTIGRAVITY_THROTTLE_BASE_DELAY_MS (ops/tests). */
27
+ function throttleBaseDelayMs() {
28
+ const raw = Number(antigravityEnv("THROTTLE_BASE_DELAY_MS"));
29
+ return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_THROTTLE_BASE_DELAY_MS;
30
+ }
31
+ /** Abort-aware sleep so a cancelled turn never waits out a backoff. */
32
+ function sleep(ms, signal) {
33
+ return new Promise((resolve, reject) => {
34
+ if (signal?.aborted) {
35
+ reject(new Error("Request was aborted"));
36
+ return;
37
+ }
38
+ const timer = setTimeout(() => {
39
+ signal?.removeEventListener("abort", onAbort);
40
+ resolve();
41
+ }, ms);
42
+ function onAbort() {
43
+ clearTimeout(timer);
44
+ reject(new Error("Request was aborted"));
45
+ }
46
+ signal?.addEventListener("abort", onAbort, { once: true });
47
+ });
48
+ }
49
+ /** Plan quota is deterministic; everything else on a 429 is a transient throttle. */
50
+ export function isPlanQuotaError(status, text) {
51
+ return status === 429 && /Individual quota reached/i.test(text);
52
+ }
53
+ /**
54
+ * pi chooses auto-retry by matching the error text (`isRetryableAssistantError`) and
55
+ * checks account-limit phrases like "quota exceeded" BEFORE retryable ones. Google's
56
+ * transient per-minute 429 body starts with exactly that phrase, so quoting it verbatim
57
+ * would make the host skip retrying a throttle. Keep the quote readable but unmatchable.
58
+ */
59
+ const HOST_ACCOUNT_LIMIT_PHRASES = /\bquota[\s-]+exceeded\b/gi;
60
+ function quoteBackendMessage(text) {
61
+ return text.replace(HOST_ACCOUNT_LIMIT_PHRASES, "quota-limit hit");
62
+ }
15
63
  function sanitizeToolCallId(id, fallbackName) {
16
64
  const cleaned = id.replace(/[^a-zA-Z0-9_-]/g, "_");
17
65
  const capped = cleaned.slice(0, 64);
18
66
  return capped || `${fallbackName || "tool"}_${++toolCallCounter}`;
19
67
  }
20
68
  function toolCallIdNeeded(modelId, runtimeModel) {
21
- return (modelId.startsWith("claude-") ||
22
- modelId.startsWith("gpt-oss-") ||
23
- runtimeModel.startsWith("claude-") ||
24
- runtimeModel.startsWith("gpt-oss-"));
69
+ return requiresToolCallId(modelId) || requiresToolCallId(runtimeModel);
25
70
  }
26
71
  const base64SignaturePattern = /^[A-Za-z0-9+/]+={0,2}$/;
27
72
  function isValidThoughtSignature(signature) {
@@ -109,6 +154,7 @@ function appendTurn(contents, role, parts) {
109
154
  export function convertMessages(model, context, runtimeModel) {
110
155
  const contents = [];
111
156
  const requiresSig = geminiRequiresThoughtSignature(runtimeModel);
157
+ const includeToolCallId = toolCallIdNeeded(model.id, runtimeModel);
112
158
  const droppedToolCallIds = new Map();
113
159
  for (const msg of context.messages) {
114
160
  if (msg.role === "user") {
@@ -171,7 +217,7 @@ export function convertMessages(model, context, runtimeModel) {
171
217
  functionCall: {
172
218
  name: block.name,
173
219
  args: block.arguments ?? {},
174
- ...(toolCallIdNeeded(model.id, runtimeModel)
220
+ ...(includeToolCallId
175
221
  ? { id: sanitizeToolCallId(block.id || "", block.name) }
176
222
  : {}),
177
223
  },
@@ -190,9 +236,7 @@ export function convertMessages(model, context, runtimeModel) {
190
236
  const responseText = text || (msg.isError ? "Tool failed" : "");
191
237
  const imageParts = asImageParts(msg.content);
192
238
  const rawId = msg.toolCallId || "";
193
- const sanitizedId = toolCallIdNeeded(model.id, runtimeModel)
194
- ? sanitizeToolCallId(rawId, msg.toolName)
195
- : rawId;
239
+ const sanitizedId = includeToolCallId ? sanitizeToolCallId(rawId, msg.toolName) : rawId;
196
240
  const droppedArgs = requiresSig
197
241
  ? (droppedToolCallIds.get(rawId) ??
198
242
  droppedToolCallIds.get(sanitizedId) ??
@@ -210,7 +254,7 @@ export function convertMessages(model, context, runtimeModel) {
210
254
  functionResponse: {
211
255
  name: msg.toolName,
212
256
  response: msg.isError ? { error: responseText } : { output: responseText },
213
- ...(toolCallIdNeeded(model.id, runtimeModel)
257
+ ...(includeToolCallId
214
258
  ? { id: sanitizeToolCallId(msg.toolCallId || "", msg.toolName) }
215
259
  : {}),
216
260
  },
@@ -356,13 +400,14 @@ function normalizeCustomToolSchema(schema) {
356
400
  * use Cloud Code Assist's custom-tool bridge, which requires a compatible
357
401
  * Draft 2020-12 subset in the legacy parameters field.
358
402
  */
359
- export function convertTools(tools, useLegacyParameters = false) {
403
+ export function convertTools(tools, useLegacyParameters = false, supportsStrictMode = false) {
360
404
  if (!tools?.length)
361
405
  return undefined;
362
406
  return [
363
407
  {
364
408
  functionDeclarations: tools.map((tool) => {
365
- const dereferenced = dereferenceSchema(tool.parameters);
409
+ const parameters = getJsonSchemaToolParameters(tool, resolveJsonSchemaStrictSampling(tool, supportsStrictMode));
410
+ const dereferenced = dereferenceSchema(parameters);
366
411
  const rootObject = ensureRootObjectSchema(dereferenced);
367
412
  const schema = stripMetaSchema(rootObject);
368
413
  return {
@@ -385,12 +430,13 @@ function mapToolChoiceMode(toolChoice) {
385
430
  }
386
431
  /** Exported for unit tests. */
387
432
  export function buildRequest(model, context, projectId, options, runtimeModel, sessionState) {
433
+ const systemPrompt = getCurrentSystemPrompt(context.messages);
388
434
  const request = {
389
435
  contents: convertMessages(model, context, runtimeModel),
390
436
  systemInstruction: {
391
437
  role: GeminiRole.User,
392
- parts: context.systemPrompt
393
- ? [{ text: sanitizeText(context.systemPrompt) }]
438
+ parts: systemPrompt
439
+ ? [{ text: sanitizeText(systemPrompt) }]
394
440
  : [{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION }, { text: ANTIGRAVITY_NO_PREAMBLE_INSTRUCTION }],
395
441
  },
396
442
  };
@@ -410,7 +456,7 @@ export function buildRequest(model, context, projectId, options, runtimeModel, s
410
456
  if (Object.keys(generationConfig).length)
411
457
  request.generationConfig = generationConfig;
412
458
  const isClaude = model.id.startsWith("claude-") || runtimeModel.startsWith("claude-");
413
- const tools = convertTools(context.tools, isClaude || model.id.startsWith("gpt-oss-"));
459
+ const tools = convertTools(getCurrentTools(context.messages), isClaude || model.id.startsWith("gpt-oss-"), supportsGoogleStrictToolSampling(model.id));
414
460
  if (tools) {
415
461
  request.tools = tools;
416
462
  request.toolConfig = {
@@ -450,7 +496,8 @@ export function mapStopReason(reason) {
450
496
  }
451
497
  /** Exported for unit tests. */
452
498
  export function friendlyAntigravityError(status, text) {
453
- const msg = redactSecrets(jsonOrTextError(text)).slice(0, 500);
499
+ const full = redactSecrets(jsonOrTextError(text));
500
+ const msg = full.slice(0, 500);
454
501
  if (status === 400) {
455
502
  if (/API key not valid|API_KEY_INVALID/i.test(msg)) {
456
503
  return "Antigravity login expired or credentials are invalid. Next: run /login antigravity, then retry.";
@@ -485,13 +532,17 @@ export function friendlyAntigravityError(status, text) {
485
532
  }
486
533
  if (status === 429) {
487
534
  const wait = msg.match(/Resets? in ([^.\n]+)/i)?.[1]?.trim();
488
- if (/Individual quota reached/i.test(msg)) {
535
+ if (isPlanQuotaError(status, full)) {
489
536
  return `Quota reached. Please wait ${wait || "for reset"}. Next: switch models or try again after reset.`;
490
537
  }
538
+ // Only "Individual quota reached" is plan quota. Shared-capacity smoothing,
539
+ // per-minute rate limits, and generic RESOURCE_EXHAUSTED all contain "quota" too,
540
+ // so never tell the user their quota is gone on those.
541
+ const backendNote = msg ? ` Backend said: ${quoteBackendMessage(msg)}` : "";
491
542
  if (/quota/i.test(msg)) {
492
- return `Quota reached.${wait ? ` Please wait ${wait}.` : ""} Next: switch models or retry later.`;
543
+ return `Antigravity throttled this request (transient, not plan quota)${wait ? `; resets in ${wait}` : ""}.${backendNote}`;
493
544
  }
494
- return `Rate limited by Antigravity. Next: wait a bit and retry.${wait ? ` Reset: ${wait}.` : ""}`;
545
+ return `Rate limited by Antigravity. Next: wait a bit and retry.${wait ? ` Reset: ${wait}.` : ""}${backendNote}`;
495
546
  }
496
547
  if (status === 500) {
497
548
  return "Antigravity had an internal server error. Next: retry in a moment or switch models.";
@@ -757,7 +808,7 @@ export function streamAntigravity(model, context, options) {
757
808
  throw new Error("Request was aborted");
758
809
  if (emptyAttempt > 0) {
759
810
  const delay = 500 * 2 ** (emptyAttempt - 1);
760
- await new Promise((res) => setTimeout(res, delay));
811
+ await sleep(delay, opts.signal);
761
812
  }
762
813
  for (let candIdx = 0; candIdx < runtimeCandidates.length; candIdx++) {
763
814
  runtimeModel = runtimeCandidates[candIdx];
@@ -765,22 +816,39 @@ export function streamAntigravity(model, context, options) {
765
816
  const body = JSON.stringify(buildRequest(model, context, projectId, opts, runtimeModel, sessionState));
766
817
  for (const endpoint of endpointCandidates(sessionState.lastGoodEndpoint)) {
767
818
  setLastEndpoint(endpoint);
768
- response = await antigravityFetch(`${endpoint}/v1internal:streamGenerateContent?alt=sse`, {
769
- method: "POST",
770
- headers: requestHeaders,
771
- body,
772
- signal: opts.signal,
773
- });
774
- setLastStatus(response.status);
775
- if (response.ok) {
776
- sessionState.lastGoodEndpoint = endpoint;
777
- persistAntigravitySessions();
819
+ let throttleAttempt = 0;
820
+ for (;;) {
821
+ response = await antigravityFetch(`${endpoint}/v1internal:streamGenerateContent?alt=sse`, {
822
+ method: "POST",
823
+ headers: requestHeaders,
824
+ body,
825
+ signal: opts.signal,
826
+ });
827
+ setLastStatus(response.status);
828
+ if (response.ok) {
829
+ sessionState.lastGoodEndpoint = endpoint;
830
+ persistAntigravitySessions();
831
+ break;
832
+ }
833
+ lastText = await response.text();
834
+ // Plan quota cannot clear before its reset time: fail fast.
835
+ if (isPlanQuotaError(response.status, lastText))
836
+ break;
837
+ // Every other 429 is a transient throttle. Back off on the same endpoint
838
+ // instead of hopping regions, which multiplies load on a throttled account.
839
+ if (response.status === 429 && throttleAttempt < THROTTLE_MAX_RETRIES) {
840
+ await sleep(throttleBaseDelayMs() * 2 ** throttleAttempt, opts.signal);
841
+ throttleAttempt += 1;
842
+ continue;
843
+ }
778
844
  break;
779
845
  }
780
- lastText = await response.text();
781
- if (response.status === 429 && /Individual quota reached/i.test(lastText))
846
+ if (response.ok)
847
+ break;
848
+ // 429s were already retried above; every endpoint shares the same throttle.
849
+ if (response.status === 429)
782
850
  break;
783
- if (![403, 404, 429, 500, 502, 503, 504].includes(response.status))
851
+ if (![403, 404, 500, 502, 503, 504].includes(response.status))
784
852
  break;
785
853
  }
786
854
  if (response?.ok)
@@ -824,7 +892,10 @@ export function streamAntigravity(model, context, options) {
824
892
  }
825
893
  }
826
894
  const friendly = friendlyAntigravityError(response?.status, lastText);
827
- if (response?.status === 429 && /Quota reached\./i.test(friendly)) {
895
+ // Plan quota only clears at reset: keep the bare message so the host does not
896
+ // retry it. Transient throttles keep the status + backend text so they stay
897
+ // diagnosable and retryable.
898
+ if (isPlanQuotaError(response?.status, lastText)) {
828
899
  throw new Error(friendly);
829
900
  }
830
901
  throw new Error(`Antigravity API error (${response?.status ?? "no response"}, ${formatRequestDiagnostics({ projectId, runtimeModel })}): ${friendly}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heyhuynhgiabuu/pi-oauth-antigravity",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Google Antigravity OAuth provider extension for Pi with Gemini 3.8, prompt cache session affinity, and trajectory chaining.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -59,8 +59,9 @@
59
59
  "undici": "^8.10.0"
60
60
  },
61
61
  "devDependencies": {
62
- "@earendil-works/pi-ai": "^0.84.4",
63
- "@earendil-works/pi-coding-agent": "^0.84.4",
62
+ "@earendil-works/pi-ai": "^0.86.0",
63
+ "@earendil-works/pi-coding-agent": "^0.86.0",
64
+ "@earendil-works/pi-server": "^0.86.0",
64
65
  "@types/node": "^22.20.1",
65
66
  "tsx": "^4.20.6",
66
67
  "typescript": "^5.9.3"