@heyhuynhgiabuu/pi-oauth-antigravity 0.2.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -7,6 +7,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.3.0] - 2026-11-19
11
+
12
+ ### Added
13
+
14
+ - **Gemini 4 Neon** (`gemini-4-neon-{low,medium,high,xhigh}`, launched 2026-11-18, the
15
+ Antigravity default model). `gemini-4-neon-xhigh` matches CLIProxyAPI's registry entry
16
+ (2026-11-19); the other wire ids follow the family pattern and are UNVERIFIED against a
17
+ live listing. Falls back to Hydrogen tier-for-tier. Context and cost follow the
18
+ registry/AI Studio figures (1M window; $3 / $15 per 1M), though Antigravity's own doc
19
+ says 512K.
20
+
21
+ - **Agent-name scrub for harness-authored text.** Google fingerprints third-party agent
22
+ identity in request content and answers 429 RESOURCE_EXHAUSTED (verified 2026-11-19:
23
+ a minimal request whose system text contains the harness name is blocked while the
24
+ identical text without it passes; path/identifier forms like `/.pi/`, `pi-oauth`,
25
+ `pi-task` are not flagged). `buildRequest` now removes the standalone harness name from
26
+ system instructions and tool descriptions — never from message text, so file paths and
27
+ identifiers in the conversation survive. Note: on accounts whose lane enforces a small
28
+ input budget the full default pi system prompt can still trip Google's broader
29
+ fingerprint even scrubbed — use `ANTIGRAVITY_COMPACT_PROMPT` (below) in that case.
30
+
31
+ - **`ANTIGRAVITY_COMPACT_PROMPT` for small-input-budget accounts.** On a g1-pro-tier
32
+ account served the shared consumer lane, Google enforced ~500-750 input tokens per
33
+ request (tightening after 429 bursts), so Pi's ~4k-token default system prompt could
34
+ never fit — through this extension or through a proxy. Set `ANTIGRAVITY_COMPACT_PROMPT=1`
35
+ to swap the preamble for a bundled ~1.9KB compact one (working style, verification
36
+ discipline, communication rules) and drop the `<docs>`/`<tools>`/`<rules>` sections,
37
+ mirroring what Pi sends for a `--system-prompt` run. `<project_context>` (AGENTS.md),
38
+ `<skills>`, and `<cwd>` are preserved, and skills keep working (the listing is a system
39
+ section; reading a skill's SKILL.md is a runtime read-tool call). The variable also
40
+ accepts a file path for a custom preamble.
41
+
42
+ ### Fixed
43
+
44
+ - **A transient 429 now falls back to the next model instead of failing the turn.**
45
+ Previously, after the in-place retries ran out, the throttled runtime model (for example
46
+ `gemini-4-hydrogen-medium`, "Resource has been exhausted") ended the request even though a
47
+ fallback model (`gemini-4-carbon-medium`) was lined up. Plan quota ("Individual quota
48
+ reached") still fails fast.
49
+ - **Retry hints are also read from the 429 body, and exhausted-plan reasons fail fast**
50
+ (mirrors CLIProxyAPI's 429 handling, issue #7565). The wait now comes from the
51
+ `Retry-After` header, the body's `RetryInfo.retryDelay`, `ErrorInfo
52
+ metadata.quotaResetDelay`, or a "retry after 33s" message — whichever is present. A 429
53
+ whose `error.details` carries reason `QUOTA_EXHAUSTED` or
54
+ `INSUFFICIENT_G1_CREDITS_BALANCE` is treated as plan quota and fails fast instead of
55
+ burning retries.
56
+
10
57
  ## [0.2.0] - 2026-11-15
11
58
 
12
59
  ### Added
package/README.md CHANGED
@@ -23,6 +23,7 @@ Google Antigravity OAuth provider extension for [Pi](https://pi.dev). Connects P
23
23
 
24
24
  | Public Model ID | Backend Wire ID | Max Output | Context Window |
25
25
  | :--- | :--- | :--- | :--- |
26
+ | `antigravity/gemini-4-neon` | `gemini-4-neon-{low,medium,high,xhigh}`† | 65,536 | 1,048,576 |
26
27
  | `antigravity/gemini-4-hydrogen` | `gemini-4-hydrogen-{low,medium,high,xhigh}`† | 65,536† | 1,048,576† |
27
28
  | `antigravity/gemini-4-carbon` | `gemini-4-carbon-{low,medium,high}`† | 65,536† | 1,048,576† |
28
29
  | `antigravity/gemini-4-argon` | `gemini-4-argon-{low,medium,high}` | 65,536† | 1,048,576† |
@@ -38,10 +39,15 @@ Google Antigravity OAuth provider extension for [Pi](https://pi.dev). Connects P
38
39
  | `antigravity/claude-sonnet-5-5-medium` | `claude-sonnet-5-5-medium` | 64,000* | 200,000* |
39
40
  | `antigravity/claude-sonnet-5-5-high` | `claude-sonnet-5-5-high` | 64,000* | 200,000* |
40
41
 
41
- Hydrogen (2026-11-12) is the first model with an `-xhigh` effort tier; Carbon (2026-11-10)
42
- and Argon (2026-10-13) top out at High. Argon/Carbon/Hydrogen are entitlement-gated
43
- (Ultra / Enterprise / paid Pro); a rejected request falls back through the Gemini 4
44
- family to Gemini 3.8 Flash.
42
+ Neon (2026-11-18, Antigravity's default model) and Hydrogen (2026-11-12) have an `-xhigh`
43
+ effort tier; Carbon (2026-11-10) and Argon (2026-10-13) top out at High. The Gemini 4
44
+ models are entitlement-gated (Ultra / Enterprise / paid Pro); a rejected or throttled
45
+ request falls back through the Gemini 4 family (Neon → Hydrogen → Carbon → Argon) to
46
+ Gemini 3.8 Flash. A transient 429 honors the server's wait hint from the `Retry-After`
47
+ header or the body's `RetryInfo` detail before moving to the fallback model; an explicit
48
+ `QUOTA_EXHAUSTED` reason fails fast like plan quota. Neon's wire id matches
49
+ CLIProxyAPI's registry; its listed context (1M) comes from the same registry —
50
+ Antigravity's own doc says 512K, untested either way.
45
51
 
46
52
  `claude-opus-4-6-thinking`, `claude-sonnet-4-6` and `gpt-oss-120b-medium` were removed by
47
53
  Google on **2026-11-18** and are no longer selectable; pinned overrides to their wire ids
@@ -50,6 +56,23 @@ surfaced as errors instead of assistant text.
50
56
 
51
57
  ### Third-party OAuth is a ToS risk
52
58
 
59
+ Google also fingerprints third-party clients by request content: requests whose system
60
+ text or tool descriptions carry the harness name are answered with 429
61
+ RESOURCE_EXHAUSTED before quota is even considered. The extension scrubs its name from
62
+ system instructions and tool descriptions it authors (message text is left untouched).
63
+ On lanes that enforce a small per-request input budget, set `ANTIGRAVITY_COMPACT_PROMPT=1`
64
+ to run with a bundled compact preamble — see the changelog for the verified scope.
65
+
66
+ On accounts whose requests are limited to a small input budget (observed ~500-750 input
67
+ tokens per request on the shared consumer lane, tightening after 429 bursts), the full
68
+ default Pi system prompt (~4k tokens) cannot fit at all. Set
69
+ `ANTIGRAVITY_COMPACT_PROMPT=1` to swap the prompt preamble for a bundled ~1.9KB compact
70
+ one and drop the fingerprint-heavy `<docs>`/`<tools>`/`<rules>` sections — Pi's
71
+ `<project_context>` (AGENTS.md), `<skills>`, and `<cwd>` sections are preserved, so
72
+ AGENTS.md rules and skills keep working. Point the variable at a file path to supply
73
+ your own preamble instead. Skills keep working normally: listing them is a system
74
+ section, and reading a skill's SKILL.md is a runtime read-tool call.
75
+
53
76
  Google's enforcement against third-party Antigravity OAuth clients is active: appeal forms
54
77
  name "using third party software to access Antigravity", and 403 `PERMISSION_DENIED /
55
78
  TOS_VIOLATION` reports against third-party clients exist (oh-my-pi paused its provider on
@@ -13,6 +13,11 @@ export declare const PROVIDER_NAME = "Antigravity";
13
13
  * - Gemini 4 Carbon (Low / Medium / High) — launched 2026-11-10 (changelog v2.31.0);
14
14
  * CCA wire IDs follow the family pattern but are UNVERIFIED against a live listing,
15
15
  * so requests fall back through Argon to Gemini 3.8 Flash when rejected.
16
+ * - Gemini 4 Neon (Low / Medium / High / xHigh) — launched 2026-11-18 as the Antigravity
17
+ * default model, positioned between Hydrogen and Carbon. The four tiers and the
18
+ * `gemini-4-neon-xhigh` CLI form come from the Antigravity models doc; the other wire IDs
19
+ * follow the family pattern and are UNVERIFIED against a live listing. Falls back to
20
+ * Hydrogen at the same tier (both advertise -xhigh).
16
21
  * - Gemini 4 Hydrogen (Low / Medium / High / xHigh) — launched 2026-11-12; the four
17
22
  * SKUs incl. the new `-xhigh` tier were observed in live discovery (oh-my-pi 7c74c203,
18
23
  * opencodex #8644 2026-11-13). Falls back through Carbon → Argon → 3.8 Flash.
@@ -12,6 +12,11 @@ export const PROVIDER_NAME = "Antigravity";
12
12
  * - Gemini 4 Carbon (Low / Medium / High) — launched 2026-11-10 (changelog v2.31.0);
13
13
  * CCA wire IDs follow the family pattern but are UNVERIFIED against a live listing,
14
14
  * so requests fall back through Argon to Gemini 3.8 Flash when rejected.
15
+ * - Gemini 4 Neon (Low / Medium / High / xHigh) — launched 2026-11-18 as the Antigravity
16
+ * default model, positioned between Hydrogen and Carbon. The four tiers and the
17
+ * `gemini-4-neon-xhigh` CLI form come from the Antigravity models doc; the other wire IDs
18
+ * follow the family pattern and are UNVERIFIED against a live listing. Falls back to
19
+ * Hydrogen at the same tier (both advertise -xhigh).
15
20
  * - Gemini 4 Hydrogen (Low / Medium / High / xHigh) — launched 2026-11-12; the four
16
21
  * SKUs incl. the new `-xhigh` tier were observed in live discovery (oh-my-pi 7c74c203,
17
22
  * opencodex #8644 2026-11-13). Falls back through Carbon → Argon → 3.8 Flash.
@@ -30,6 +35,17 @@ export const PROVIDER_NAME = "Antigravity";
30
35
  * old wire IDs keep working until the backend drops them.
31
36
  */
32
37
  export const ANTIGRAVITY_ROUTING = {
38
+ "gemini-4-neon": {
39
+ off: "gemini-4-neon-low",
40
+ routing: {
41
+ minimal: "gemini-4-neon-low",
42
+ low: "gemini-4-neon-low",
43
+ medium: "gemini-4-neon-medium",
44
+ high: "gemini-4-neon-high",
45
+ xhigh: "gemini-4-neon-xhigh",
46
+ },
47
+ defaultRequestId: "gemini-4-neon-low",
48
+ },
33
49
  "gemini-4-hydrogen": {
34
50
  off: "gemini-4-hydrogen-low",
35
51
  routing: {
@@ -178,6 +194,12 @@ export const RUNTIME_MAX_OUTPUT_TOKENS = {
178
194
  "gemini-4-carbon-low": 65536,
179
195
  "gemini-4-carbon-medium": 65536,
180
196
  "gemini-4-carbon-high": 65536,
197
+ // Neon: 65,536 sync max output per the AI Studio model page.
198
+ "gemini-4-neon": 65536,
199
+ "gemini-4-neon-low": 65536,
200
+ "gemini-4-neon-medium": 65536,
201
+ "gemini-4-neon-high": 65536,
202
+ "gemini-4-neon-xhigh": 65536,
181
203
  "gemini-4-hydrogen": 65536,
182
204
  "gemini-4-hydrogen-low": 65536,
183
205
  "gemini-4-hydrogen-medium": 65536,
@@ -235,6 +257,9 @@ export function getMaxOutputTokens(modelId, runtimeModel) {
235
257
  }
236
258
  const geminiFlashCost = { input: 0.1, output: 0.4, cacheRead: 0.025, cacheWrite: 0.1 };
237
259
  const geminiProCost = { input: 1.25, output: 5.0, cacheRead: 0.3125, cacheWrite: 1.25 };
260
+ // Neon input/output are Google's published $3 / $15 per 1M; cache rates are unpublished
261
+ // and reuse the Pro-tier ratios (read 25%, write 100% of input).
262
+ const geminiNeonCost = { input: 3.0, output: 15.0, cacheRead: 0.75, cacheWrite: 3.0 };
238
263
  const claudeSonnetCost = { input: 3.0, output: 15.0, cacheRead: 0.3, cacheWrite: 3.75 };
239
264
  const claudeOpusCost = { input: 15.0, output: 75.0, cacheRead: 1.5, cacheWrite: 18.75 };
240
265
  // A null entry is intentionally hidden by Pi. Do not collapse levels that happen to
@@ -350,6 +375,19 @@ export const ANTIGRAVITY_MODELS = [
350
375
  contextWindow: 1048576,
351
376
  maxTokens: 65536,
352
377
  },
378
+ {
379
+ // Launched 2026-11-18; wire id `gemini-4-neon-xhigh` matches CLIProxyAPI's registry
380
+ // entry (2026-11-19), which lists the family's 1M context. Antigravity's models doc
381
+ // says 512K — untested either way; the 1M figure matches the other Gemini 4 rows.
382
+ id: "gemini-4-neon",
383
+ name: "Gemini 4 Neon (Antigravity)",
384
+ reasoning: true,
385
+ thinkingLevelMap: thinkingLevelMaps.lowMediumHighXhigh,
386
+ input: ["text", "image"],
387
+ cost: geminiNeonCost,
388
+ contextWindow: 1048576,
389
+ maxTokens: 65536,
390
+ },
353
391
  {
354
392
  // Launched 2026-11-12 with the backend's first -xhigh tier. Hydrogen-specific
355
393
  // cost/context/output are unverified; values reuse the Gemini 4 family estimates.
@@ -435,7 +473,14 @@ export function getAntigravityRequestModelId(modelId, effort) {
435
473
  * provide a fallback runtime model ID (e.g. Gemini 3.6 Flash) to maintain availability.
436
474
  */
437
475
  export function getFallbackRuntimeModel(runtimeModel, effort) {
438
- // Only Hydrogen advertises an -xhigh wire id; Carbon and Argon top out at -high,
476
+ // Neon and Hydrogen share the same four tiers, so Neon falls back tier-for-tier.
477
+ if (runtimeModel === "gemini-4-neon") {
478
+ return "gemini-4-hydrogen-low";
479
+ }
480
+ if (runtimeModel.startsWith("gemini-4-neon-")) {
481
+ return runtimeModel.replace("gemini-4-neon-", "gemini-4-hydrogen-");
482
+ }
483
+ // Only Neon and Hydrogen advertise an -xhigh wire id; Carbon and Argon top out at -high,
439
484
  // so a Hydrogen xHigh fallback must downgrade the tier when it crosses families.
440
485
  const carbonTarget = runtimeModel.startsWith("gemini-4-hydrogen-")
441
486
  ? runtimeModel.replace("gemini-4-hydrogen-", "gemini-4-carbon-").replace(/-xhigh$/, "-high")
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Compact preamble for accounts whose requests are limited to a small input budget
3
+ * (measured 2026-11-19 on a g1-pro-tier account served the shared consumer lane:
4
+ * ~500-750 input tokens per request, tightened further by 429 bursts). It keeps the
5
+ * working style, verification discipline, and communication rules and lets Pi append
6
+ * its own sections (<tools>, <rules>, <project_context>, <skills>, <cwd>) after it.
7
+ */
8
+ export declare const COMPACT_SYSTEM_PROMPT = "You are a senior software engineer working as a coding agent in the user's terminal.\n\n## Working style\n\n- Resolve the repository root once and use absolute paths under it.\n- Understand the design (flow, boundaries, invariants) before editing; make the smallest change that fits the existing architecture and style.\n- Read the code before changing it. Fix causes, not symptoms. Match the surrounding conventions exactly \u2014 no shortened names, no compressed formatting, no changes outside the request's scope.\n- Reuse existing repo logic and helpers before writing anything new. Avoid speculative abstraction and premature configuration.\n- Every changed line must trace to the request. When a request is a review or a question, do not modify code.\n\n## Verification\n\n- Keep verification proportional to risk; run the narrowest deterministic check on touched code (typecheck, lint, targeted tests).\n- Read errors fully before fixing. After two failed attempts on the same approach, stop and escalate with what you learned.\n- Before claiming done, re-read the final diff yourself. State what was verified, what was not, and any assumptions made.\n\n## Communication\n\n- Answer in the user's language. Lead with the main point; calibrate confidence in the first sentence.\n- Match length to the question: simple gets direct answers, multi-part gets structure. Never cut necessary caveats to look brief.\n- Rank findings by severity with evidence. Bring a recommendation next to any request for a decision, so approval is one line.\n- Show file paths for anything touched. Skip narration of routine steps, but never skip the final summary.\n- When a decision materially changes scope, cost, or reversibility, ask; otherwise proceed and state the assumption.\n\n## Output discipline\n\n- No filler openers, no restating the task, no decorated separators in shell output.\n- Treat the final answer as the first thing the user reads: plain words, no internal shorthand.\n";
9
+ /**
10
+ * Resolve ANTIGRAVITY_COMPACT_PROMPT:
11
+ * - unset/empty -> undefined (default Pi system prompt, scrubbed)
12
+ * - 1/true/on/yes -> the bundled compact preamble
13
+ * - a file path -> that file's contents (falls back to the bundled preamble on error)
14
+ */
15
+ export declare function compactSystemPromptOverride(): string | undefined;
16
+ /**
17
+ * Replace only the preamble of a rendered system prompt: everything before the first
18
+ * XML section tag stays out, and Pi's own sections (<tools>, <rules>,
19
+ * <project_context>, <skills>, <cwd>) are preserved so AGENTS.md rules and skill
20
+ * listings keep working. Prompts without sections are replaced entirely.
21
+ */
22
+ export declare function replaceSystemPreamble(systemPrompt: string, preamble: string): string;
23
+ /** Swap the preamble and drop the heavy sections; tidies the joins afterwards. */
24
+ export declare function applyCompactSystemPrompt(systemPrompt: string): string;
@@ -0,0 +1,87 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { antigravityEnv } from "../utils/util.js";
3
+ /**
4
+ * Compact preamble for accounts whose requests are limited to a small input budget
5
+ * (measured 2026-11-19 on a g1-pro-tier account served the shared consumer lane:
6
+ * ~500-750 input tokens per request, tightened further by 429 bursts). It keeps the
7
+ * working style, verification discipline, and communication rules and lets Pi append
8
+ * its own sections (<tools>, <rules>, <project_context>, <skills>, <cwd>) after it.
9
+ */
10
+ export const COMPACT_SYSTEM_PROMPT = `You are a senior software engineer working as a coding agent in the user's terminal.
11
+
12
+ ## Working style
13
+
14
+ - Resolve the repository root once and use absolute paths under it.
15
+ - Understand the design (flow, boundaries, invariants) before editing; make the smallest change that fits the existing architecture and style.
16
+ - Read the code before changing it. Fix causes, not symptoms. Match the surrounding conventions exactly — no shortened names, no compressed formatting, no changes outside the request's scope.
17
+ - Reuse existing repo logic and helpers before writing anything new. Avoid speculative abstraction and premature configuration.
18
+ - Every changed line must trace to the request. When a request is a review or a question, do not modify code.
19
+
20
+ ## Verification
21
+
22
+ - Keep verification proportional to risk; run the narrowest deterministic check on touched code (typecheck, lint, targeted tests).
23
+ - Read errors fully before fixing. After two failed attempts on the same approach, stop and escalate with what you learned.
24
+ - Before claiming done, re-read the final diff yourself. State what was verified, what was not, and any assumptions made.
25
+
26
+ ## Communication
27
+
28
+ - Answer in the user's language. Lead with the main point; calibrate confidence in the first sentence.
29
+ - Match length to the question: simple gets direct answers, multi-part gets structure. Never cut necessary caveats to look brief.
30
+ - Rank findings by severity with evidence. Bring a recommendation next to any request for a decision, so approval is one line.
31
+ - Show file paths for anything touched. Skip narration of routine steps, but never skip the final summary.
32
+ - When a decision materially changes scope, cost, or reversibility, ask; otherwise proceed and state the assumption.
33
+
34
+ ## Output discipline
35
+
36
+ - No filler openers, no restating the task, no decorated separators in shell output.
37
+ - Treat the final answer as the first thing the user reads: plain words, no internal shorthand.
38
+ `;
39
+ /**
40
+ * Resolve ANTIGRAVITY_COMPACT_PROMPT:
41
+ * - unset/empty -> undefined (default Pi system prompt, scrubbed)
42
+ * - 1/true/on/yes -> the bundled compact preamble
43
+ * - a file path -> that file's contents (falls back to the bundled preamble on error)
44
+ */
45
+ export function compactSystemPromptOverride() {
46
+ const setting = antigravityEnv("COMPACT_PROMPT")?.trim();
47
+ if (!setting)
48
+ return undefined;
49
+ if (/^(1|true|on|yes)$/i.test(setting))
50
+ return COMPACT_SYSTEM_PROMPT;
51
+ if (existsSync(setting)) {
52
+ try {
53
+ const content = readFileSync(setting, "utf8").trim();
54
+ if (content)
55
+ return content;
56
+ }
57
+ catch {
58
+ // fall through to the bundled preamble
59
+ }
60
+ }
61
+ return COMPACT_SYSTEM_PROMPT;
62
+ }
63
+ /**
64
+ * Replace only the preamble of a rendered system prompt: everything before the first
65
+ * XML section tag stays out, and Pi's own sections (<tools>, <rules>,
66
+ * <project_context>, <skills>, <cwd>) are preserved so AGENTS.md rules and skill
67
+ * listings keep working. Prompts without sections are replaced entirely.
68
+ */
69
+ export function replaceSystemPreamble(systemPrompt, preamble) {
70
+ const sectionStart = systemPrompt.search(/^</m);
71
+ return sectionStart === -1 ? preamble : `${preamble}\n\n${systemPrompt.slice(sectionStart)}`;
72
+ }
73
+ /**
74
+ * Sections dropped in compact mode, mirroring what Pi sends for a `--system-prompt` run
75
+ * (preamble + <project_context> + <skills> + <cwd> — no docs, tool list, or rules
76
+ * sections). The <docs> block is the fingerprint-heavy one: it names the harness, its
77
+ * SDK docs, and pi-coding-agent paths throughout.
78
+ */
79
+ const COMPACT_DROP_SECTIONS = ["docs", "tools", "rules"];
80
+ /** Swap the preamble and drop the heavy sections; tidies the joins afterwards. */
81
+ export function applyCompactSystemPrompt(systemPrompt) {
82
+ let out = replaceSystemPreamble(systemPrompt, COMPACT_SYSTEM_PROMPT);
83
+ for (const name of COMPACT_DROP_SECTIONS) {
84
+ out = out.replace(new RegExp(`\\n*<${name}>[\\s\\S]*?</${name}>`, "g"), "");
85
+ }
86
+ return out.replace(/\n{3,}/g, "\n\n").trim();
87
+ }
@@ -0,0 +1 @@
1
+ export { COMPACT_SYSTEM_PROMPT, compactSystemPromptOverride, replaceSystemPreamble, } from "./compact.js";
@@ -0,0 +1 @@
1
+ export { COMPACT_SYSTEM_PROMPT, compactSystemPromptOverride, replaceSystemPreamble, } from "./compact.js";
@@ -12,6 +12,16 @@ export declare function isPlanQuotaError(status: number | undefined, text: strin
12
12
  */
13
13
  export declare const THROTTLE_RETRY_AFTER_CAP_SECONDS = 60;
14
14
  export declare function parseRetryAfterSeconds(raw: string | null | undefined): number | undefined;
15
+ /** Parse a Google RPC duration ("33s", "1.5m", "500ms", "2h") into whole seconds. */
16
+ export declare function parseGoogleDurationSeconds(raw: string): number | undefined;
17
+ /**
18
+ * Google also puts the wait inside the 429 body: a RetryInfo detail carries
19
+ * `retryDelay` ("33s"), an ErrorInfo detail may carry `metadata.quotaResetDelay`, and
20
+ * some messages embed "retry after 33s". CLIProxyAPI reads all of these (issue #7565)
21
+ * because the Retry-After header is often absent when the body carries the hint.
22
+ * A zero delay is kept: Antigravity uses it to mean "retry immediately".
23
+ */
24
+ export declare function parseRetryAfterFromBody(body: string): number | undefined;
15
25
  /** Exported for unit tests. */
16
26
  export declare function convertMessages(model: Model<Api>, context: TranscriptContext, runtimeModel: string): GeminiContent[];
17
27
  /**
@@ -25,6 +35,8 @@ export declare function convertTools(tools: Tool[] | undefined, useLegacyParamet
25
35
  /** Exported for unit tests. */
26
36
  export declare function buildRequest(model: Model<Api>, context: TranscriptContext, projectId: string, options: AntigravityStreamOptions, runtimeModel: string, sessionState?: AntigravitySessionState): AntigravityGenerateRequest;
27
37
  /** Exported for unit tests. */
38
+ export declare function scrubAgentName(text: string): string;
39
+ /** Exported for unit tests. */
28
40
  export declare function mapStopReason(reason: string | undefined): StopReason;
29
41
  /**
30
42
  * Google blocks an entire account — not one model — with 403 VALIDATION_REQUIRED until
@@ -1,6 +1,7 @@
1
1
  import { calculateCost, createAssistantMessageEventStream, } from "@earendil-works/pi-ai";
2
2
  import { getJsonSchemaToolParameters, requiresToolCallId, resolveJsonSchemaStrictSampling, } from "./provider-helpers.js";
3
3
  import { getCurrentSystemPrompt, getCurrentTools } from "./transcript.js";
4
+ import { applyCompactSystemPrompt, compactSystemPromptOverride } from "../prompt/compact.js";
4
5
  import { antigravityHeaders, DEFAULT_ENDPOINT, endpointCandidates, fetchAvailableRuntimeModel, formatRequestDiagnostics, jsonOrTextError, loadCodeAssist, parseApiKey, resolveProjectId, } from "../client/client.js";
5
6
  import { getCurrentEndpoint, runWithDiagnostics, setLastEndpoint, setLastError, setLastLatencyMs, setLastProjectId, setLastResolvedRuntimeModel, setLastStatus, } from "../diagnostics/diagnostics.js";
6
7
  import { AntigravityRequestType, AntigravityUserAgent, GeminiRole, GeminiToolCallingMode, StopReason, ToolChoice, } from "../types/enums.js";
@@ -47,7 +48,13 @@ function sleep(ms, signal) {
47
48
  }
48
49
  /** Plan quota is deterministic; everything else on a 429 is a transient throttle. */
49
50
  export function isPlanQuotaError(status, text) {
50
- return status === 429 && /Individual quota reached/i.test(text);
51
+ if (status !== 429)
52
+ return false;
53
+ // CLIProxyAPI classifies these ErrorInfo reasons as exhausted plan quota; the
54
+ // plain-text "Individual quota reached" form is the older shape of the same verdict.
55
+ if (/"reason"\s*:\s*"(?:QUOTA_EXHAUSTED|INSUFFICIENT_G1_CREDITS_BALANCE)"/i.test(text))
56
+ return true;
57
+ return /Individual quota reached/i.test(text);
51
58
  }
52
59
  /**
53
60
  * Transient 429s may carry a server-provided Retry-After (seconds or HTTP-date, CPA
@@ -71,6 +78,52 @@ export function parseRetryAfterSeconds(raw) {
71
78
  const seconds = Math.round((date - Date.now()) / 1000);
72
79
  return seconds >= 0 ? seconds : 0;
73
80
  }
81
+ /** Parse a Google RPC duration ("33s", "1.5m", "500ms", "2h") into whole seconds. */
82
+ export function parseGoogleDurationSeconds(raw) {
83
+ const match = raw.trim().match(/^(\d+(?:\.\d+)?)(ms|s|m|h)$/);
84
+ if (!match)
85
+ return undefined;
86
+ const value = Number(match[1]);
87
+ if (!Number.isFinite(value))
88
+ return undefined;
89
+ const unitSeconds = { ms: 0.001, s: 1, m: 60, h: 3600 }[match[2]];
90
+ const seconds = Math.round(value * unitSeconds);
91
+ return seconds >= 0 ? seconds : undefined;
92
+ }
93
+ /**
94
+ * Google also puts the wait inside the 429 body: a RetryInfo detail carries
95
+ * `retryDelay` ("33s"), an ErrorInfo detail may carry `metadata.quotaResetDelay`, and
96
+ * some messages embed "retry after 33s". CLIProxyAPI reads all of these (issue #7565)
97
+ * because the Retry-After header is often absent when the body carries the hint.
98
+ * A zero delay is kept: Antigravity uses it to mean "retry immediately".
99
+ */
100
+ export function parseRetryAfterFromBody(body) {
101
+ try {
102
+ const details = JSON.parse(body)?.error?.details;
103
+ if (Array.isArray(details)) {
104
+ for (const detail of details) {
105
+ if (typeof detail?.retryDelay === "string") {
106
+ const seconds = parseGoogleDurationSeconds(detail.retryDelay);
107
+ if (seconds !== undefined)
108
+ return seconds;
109
+ }
110
+ const resetDelay = detail?.metadata?.quotaResetDelay;
111
+ if (typeof resetDelay === "string") {
112
+ const seconds = parseGoogleDurationSeconds(resetDelay);
113
+ if (seconds !== undefined)
114
+ return seconds;
115
+ }
116
+ }
117
+ }
118
+ }
119
+ catch {
120
+ // Not JSON — the message scan below still applies.
121
+ }
122
+ const match = body.match(/\b(?:after|retry\s+in)\s+(\d+(?:\.\d+)?(?:h|ms|m|s))\b/i);
123
+ if (!match)
124
+ return undefined;
125
+ return parseGoogleDurationSeconds(match[1]);
126
+ }
74
127
  /**
75
128
  * pi chooses auto-retry by matching the error text (`isRetryableAssistantError`) and
76
129
  * checks account-limit phrases like "quota exceeded" BEFORE retryable ones. Google's
@@ -451,7 +504,11 @@ function mapToolChoiceMode(toolChoice) {
451
504
  }
452
505
  /** Exported for unit tests. */
453
506
  export function buildRequest(model, context, projectId, options, runtimeModel, sessionState) {
454
- const systemPrompt = getCurrentSystemPrompt(context);
507
+ const systemPromptSource = getCurrentSystemPrompt(context);
508
+ // Compact-prompt opt-in: swap the preamble, keep Pi's own sections (tools, rules,
509
+ // project context, skills, cwd) so AGENTS.md rules and skill listings survive.
510
+ const compact = compactSystemPromptOverride();
511
+ const systemPrompt = compact ? applyCompactSystemPrompt(systemPromptSource) : systemPromptSource;
455
512
  const request = {
456
513
  contents: convertMessages(model, context, runtimeModel),
457
514
  systemInstruction: {
@@ -500,6 +557,7 @@ export function buildRequest(model, context, projectId, options, runtimeModel, s
500
557
  const envelope = antigravityRequestEnvelope(runtimeModel, isClaude, state);
501
558
  request.sessionId = envelope.sessionId;
502
559
  request.labels = envelope.labels;
560
+ scrubRequestAgentName(request);
503
561
  return {
504
562
  project: projectId,
505
563
  model: runtimeModel,
@@ -509,6 +567,34 @@ export function buildRequest(model, context, projectId, options, runtimeModel, s
509
567
  requestId: envelope.requestId,
510
568
  };
511
569
  }
570
+ /**
571
+ * Google fingerprints third-party agent names in request content and soft-blocks them
572
+ * with 429 RESOURCE_EXHAUSTED (verified 2026-11-19 on a free-tier account: a system
573
+ * prompt containing the standalone word for this harness gets 429 while the identical
574
+ * text with the word removed passes, and path or identifier forms like "/.pi/",
575
+ * "pi-oauth", "pi-task" are not flagged). Harness-authored text is scrubbed — system
576
+ * instructions and tool descriptions — while message text is left untouched so file
577
+ * paths and identifiers in the conversation survive.
578
+ */
579
+ const AGENT_NAME_PATTERN = /(?<![\w.-])pi(?![\w-])/gi;
580
+ /** Exported for unit tests. */
581
+ export function scrubAgentName(text) {
582
+ return text
583
+ .replace(AGENT_NAME_PATTERN, "")
584
+ .replace(/\s+,/g, ",")
585
+ .replace(/ {2,}/g, " ");
586
+ }
587
+ function scrubRequestAgentName(request) {
588
+ for (const part of request.systemInstruction?.parts ?? []) {
589
+ if (typeof part.text === "string")
590
+ part.text = scrubAgentName(part.text);
591
+ }
592
+ for (const declaration of request.tools?.[0]?.functionDeclarations ?? []) {
593
+ if (typeof declaration.description === "string") {
594
+ declaration.description = scrubAgentName(declaration.description);
595
+ }
596
+ }
597
+ }
512
598
  /** Exported for unit tests. */
513
599
  export function mapStopReason(reason) {
514
600
  if (reason === "STOP")
@@ -1029,7 +1115,8 @@ export function streamAntigravity(model, context, options) {
1029
1115
  // instead of hopping regions, which multiplies load on a throttled account.
1030
1116
  // Honor a server Retry-After when it is short; a longer one is a cooldown
1031
1117
  // that will not clear inside this loop, so burn no attempts on it.
1032
- const retryAfterSeconds = parseRetryAfterSeconds(response.headers.get("retry-after"));
1118
+ const retryAfterSeconds = parseRetryAfterSeconds(response.headers.get("retry-after")) ??
1119
+ parseRetryAfterFromBody(lastText);
1033
1120
  const retryable = response.status === 429 &&
1034
1121
  throttleAttempt < THROTTLE_MAX_RETRIES &&
1035
1122
  (retryAfterSeconds === undefined ||
@@ -1056,6 +1143,15 @@ export function streamAntigravity(model, context, options) {
1056
1143
  }
1057
1144
  if (response?.ok)
1058
1145
  break;
1146
+ // Throttles are tracked per model, and freshly launched models (Gemini 4
1147
+ // Hydrogen) hit them hardest. Once the in-place retries are spent, a transient
1148
+ // 429 moves on to the fallback model instead of failing the turn. Plan quota
1149
+ // still fails fast: its message tells the user to wait or switch on purpose.
1150
+ if (response?.status === 429 &&
1151
+ !isPlanQuotaError(response.status, lastText) &&
1152
+ candIdx + 1 < runtimeCandidates.length) {
1153
+ continue;
1154
+ }
1059
1155
  if (response?.status === 404) {
1060
1156
  if (candIdx + 1 < runtimeCandidates.length) {
1061
1157
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heyhuynhgiabuu/pi-oauth-antigravity",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
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",