@heyhuynhgiabuu/pi-oauth-antigravity 0.1.9 → 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,102 @@ 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
+
57
+ ## [0.2.0] - 2026-11-15
58
+
59
+ ### Added
60
+
61
+ - **Gemini 4 Carbon** (`gemini-4-carbon-{low,medium,high}`, launched 2026-11-10) and
62
+ **Gemini 4 Hydrogen** (`gemini-4-hydrogen-{low,medium,high,xhigh}`, launched 2026-11-12 —
63
+ the backend's first `-xhigh` effort tier). Carbon/Hydrogen wire ids follow the family
64
+ pattern and are UNVERIFIED against a live listing; rejected requests fall back through
65
+ the Gemini 4 family (Hydrogen → Carbon → Argon → 3.8 Flash), with an xHigh tier
66
+ downgrade at each family boundary since only Hydrogen advertises `-xhigh`.
67
+ - Fresh `x-cloudaicompanion-trace-id` / `X-Aicode-Request-Id` headers on every request.
68
+ - **403 `TOS_VIOLATION` is recognized and surfaces account-risk advice** instead of the
69
+ generic "try another model, re-login" line. Google is actively enforcing third-party
70
+ OAuth use (the appeal copy names "third party software"); the reason lives in
71
+ `error.details`, which the old message path dropped, so a flagged account now gets told
72
+ that retries and re-login will not clear it and that further use risks suspension.
73
+ - **Server `Retry-After` is honored on transient 429s** (seconds or HTTP-date form,
74
+ capped at 60s). A longer `Retry-After` is a cooldown that cannot clear inside the
75
+ retry loop (CPA issue #6646), so no attempts are burned on it and the backend's own
76
+ reset note is surfaced. Without the header the 2s/4s backoff is unchanged.
77
+ - Claude Opus 5.5 / Sonnet 5.5 are documented as officially served (2026-11 models doc,
78
+ live discovery since 2026-10-03); the listed output/context figures remain same-family
79
+ estimates until Google publishes 5.5-specific numbers.
80
+
81
+ ### Added
82
+
83
+ - **Gemini 4 Carbon** (`gemini-4-carbon-{low,medium,high}`, launched 2026-11-10) and
84
+ **Gemini 4 Hydrogen** (`gemini-4-hydrogen-{low,medium,high,xhigh}`, launched 2026-11-12 —
85
+ the backend's first `-xhigh` effort tier). Carbon/Hydrogen wire ids follow the family
86
+ pattern and are UNVERIFIED against a live listing; rejected requests fall back through
87
+ the Gemini 4 family (Hydrogen → Carbon → Argon → 3.8 Flash), with an xHigh tier
88
+ downgrade at each family boundary since only Hydrogen advertises `-xhigh`.
89
+ - Fresh `x-cloudaicompanion-trace-id` / `X-Aicode-Request-Id` headers on every request.
90
+
91
+ ### Changed
92
+
93
+ - **`claude-opus-4-6-thinking`, `claude-sonnet-4-6` and `gpt-oss-120b-medium` leave the
94
+ selectable catalog** — Google removes them on 2026-11-18. Pinned overrides to their wire
95
+ ids still resolve (routing + output-token entries retained), and the retirement-notice
96
+ detector now covers their plain-text notices instead of rendering them as assistant text;
97
+ the surfaced error names retirement generically and points at `/antigravity.models`.
98
+ - **Request identity tracks the shipping client** (`antigravity/hub/2.32.1`, was 2.23.0).
99
+ A stale identity silently receives a REDUCED model catalog from discovery, without an
100
+ error (codex2api e3d59f9; oh-my-pi pinned 2.32.1 on 2026-11-14 for the same reason).
101
+ - Gemini 4 Argon is no longer provisional: launched 2026-10-13, wire ids verified against
102
+ live `fetchAvailableModels` (opencodex 2026-10-14, codex2api 2026-10-16). Catalog table
103
+ and README reflect the 2026-11 models doc; README carries a ToS-risk warning for
104
+ third-party OAuth use.
105
+
10
106
  ## [0.1.9] - 2026-10-26
11
107
 
12
108
  ### Added
package/README.md CHANGED
@@ -23,25 +23,71 @@ 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-argon` | `gemini-4-argon-{low,medium,high}`† | 65,536† | 1,048,576† |
26
+ | `antigravity/gemini-4-neon` | `gemini-4-neon-{low,medium,high,xhigh}`† | 65,536 | 1,048,576 |
27
+ | `antigravity/gemini-4-hydrogen` | `gemini-4-hydrogen-{low,medium,high,xhigh}`† | 65,536† | 1,048,576† |
28
+ | `antigravity/gemini-4-carbon` | `gemini-4-carbon-{low,medium,high}`† | 65,536† | 1,048,576† |
29
+ | `antigravity/gemini-4-argon` | `gemini-4-argon-{low,medium,high}` | 65,536† | 1,048,576† |
27
30
  | `antigravity/gemini-3.8-flash` | `gemini-3.8-flash-{low,medium,high}` | 65,536 | 1,048,576 |
28
31
  | `antigravity/gemini-3.7-flash` | `gemini-3.7-flash-{low,medium,high}` | 65,536 | 1,048,576 |
29
32
  | `antigravity/gemini-3.7-flash-thinking` | `gemini-3.7-flash-thinking` | 65,536 | 1,048,576 |
30
33
  | `antigravity/gemini-3.6-flash` | `gemini-3.6-flash-{low,medium,high}` | 65,536 | 1,048,576 |
31
34
  | `antigravity/gemini-3.1-pro` | `gemini-3.1-pro` | 65,536 | 1,048,576 |
32
- | `antigravity/claude-opus-4-6` | `claude-opus-4-6` | 64,000 | 200,000 |
33
35
  | `antigravity/claude-opus-5-5-low` | `claude-opus-5-5-low` | 64,000* | 250,000* |
34
36
  | `antigravity/claude-opus-5-5-medium` | `claude-opus-5-5-medium` | 64,000* | 250,000* |
35
37
  | `antigravity/claude-opus-5-5-high` | `claude-opus-5-5-high` | 64,000* | 250,000* |
36
- | `antigravity/claude-sonnet-4-6` | `claude-sonnet-4-6` | 64,000 | 200,000 |
37
38
  | `antigravity/claude-sonnet-5-5-low` | `claude-sonnet-5-5-low` | 64,000* | 200,000* |
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
- | `antigravity/gpt-oss-120b` | `gpt-oss-120b` | 8,192 | 131,072 |
41
41
 
42
- † Inferred from runtime ids referenced by Antigravity IDE 2.23.0, not yet confirmed against a live model listing; limits and pricing are provisional, and requests fall back to Gemini 3.8 Flash if the backend rejects the model.
43
-
44
- \* Provisional same-family estimates only; Claude 5.5 backend output/context limits have not been verified.
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.
51
+
52
+ `claude-opus-4-6-thinking`, `claude-sonnet-4-6` and `gpt-oss-120b-medium` were removed by
53
+ Google on **2026-11-18** and are no longer selectable; pinned overrides to their wire ids
54
+ still resolve until the backend drops them, and their retirement notices are detected and
55
+ surfaced as errors instead of assistant text.
56
+
57
+ ### Third-party OAuth is a ToS risk
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
+
76
+ Google's enforcement against third-party Antigravity OAuth clients is active: appeal forms
77
+ name "using third party software to access Antigravity", and 403 `PERMISSION_DENIED /
78
+ TOS_VIOLATION` reports against third-party clients exist (oh-my-pi paused its provider on
79
+ 2026-11-14 for this reason). Using this extension may put your Google account at risk —
80
+ prefer the official Antigravity IDE/CLI when possible, and don't say you weren't warned.
81
+
82
+ † Gemini 4 family: Argon wire ids verified against live discovery (2026-10-14); Carbon/Hydrogen wire ids follow the family pattern but are UNVERIFIED against a live listing. Limits and pricing are same-family estimates; a rejected request falls back to the previous Gemini 4 model, then Gemini 3.8 Flash.
83
+
84
+ \* Claude Opus 5.5 / Sonnet 5.5 are officially served (2026-11 models doc, live discovery
85
+ since 2026-10-03); the listed output/context figures stay same-family estimates until
86
+ Google publishes 5.5-specific numbers.
87
+
88
+ The request identity tracks the shipping client (`antigravity/hub/2.32.1`) and every call
89
+ sends fresh `x-cloudaicompanion-trace-id` / `X-Aicode-Request-Id` headers — a stale client
90
+ identity silently receives a REDUCED model catalog from discovery, without an error.
45
91
 
46
92
  ## Installation
47
93
 
@@ -1,4 +1,4 @@
1
- import { createHash } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import { Platform } from "../types/enums.js";
3
3
  import { getCurrentAvailableModels, getCurrentEndpoint, getCurrentMatchedModelDebug, setLastAvailableModels, setLastEndpoint, setLastError, setLastMatchedModelDebug, setLastStatus, } from "../diagnostics/diagnostics.js";
4
4
  import { assertSafeApiBaseUrl, safeError } from "../utils/security.js";
@@ -45,8 +45,11 @@ export function endpointCandidates(preferredEndpoint) {
45
45
  }
46
46
  return ENDPOINT_FALLBACKS;
47
47
  }
48
- // Cloud Code rejects newer models (e.g. Gemini 4 Argon) for clients below 2.23.0.
49
- const DEFAULT_ANTIGRAVITY_VERSION = "2.23.0";
48
+ // Cloud Code rejects newer models (e.g. Gemini 4 Argon) for clients below 2.23.0, and a
49
+ // stale identity silently gets a REDUCED catalog from discovery (no error): control-plane
50
+ // requests sent as antigravity/1.11.3 returned fewer models (codex2api e3d59f9). Track the
51
+ // shipping client — oh-my-pi pinned 2.32.1 on 2026-11-14 for the same reason.
52
+ const DEFAULT_ANTIGRAVITY_VERSION = "2.32.1";
50
53
  const DEFAULT_ANTIGRAVITY_CL = "963137146";
51
54
  function defaultUserAgent() {
52
55
  const version = antigravityEnv("HUB_VERSION") || DEFAULT_ANTIGRAVITY_VERSION;
@@ -67,6 +70,10 @@ export function antigravityHeaders(token) {
67
70
  Accept: "text/event-stream",
68
71
  "User-Agent": antigravityEnv("USER_AGENT") || defaultUserAgent(),
69
72
  "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
73
+ // Per-request trace/request ids match the shipping client (oh-my-pi #19279,
74
+ // 2026-11-14): requests without them were served the reduced catalog.
75
+ "x-cloudaicompanion-trace-id": randomUUID(),
76
+ "X-Aicode-Request-Id": randomUUID(),
70
77
  "Client-Metadata": JSON.stringify({
71
78
  ideType: "ANTIGRAVITY",
72
79
  platform,
@@ -5,27 +5,35 @@ export declare const PROVIDER_NAME = "Antigravity";
5
5
  /**
6
6
  * Public selectable model IDs → backend request model IDs by thinking effort.
7
7
  *
8
- * Catalog mirrors `agy models` (Antigravity CLI), which currently advertises:
9
- * - Gemini 4 Argon (Low / Medium / High) — provisional, see below
8
+ * Catalog mirrors `agy models` (Antigravity CLI) and the 2026-11 models doc, which advertises:
9
+ * - Gemini 4 Argon (Low / Medium / High) — CONFIRMED: launched 2026-10-13; wire IDs
10
+ * `gemini-4-argon-{low,medium,high}` verified against live `fetchAvailableModels`
11
+ * (opencodex 2026-10-14, codex2api 2026-10-16). Entitlement-gated (Ultra / Enterprise /
12
+ * paid Pro); requests fall back to Gemini 3.8 Flash when the backend rejects it.
13
+ * - Gemini 4 Carbon (Low / Medium / High) — launched 2026-11-10 (changelog v2.31.0);
14
+ * CCA wire IDs follow the family pattern but are UNVERIFIED against a live listing,
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).
21
+ * - Gemini 4 Hydrogen (Low / Medium / High / xHigh) — launched 2026-11-12; the four
22
+ * SKUs incl. the new `-xhigh` tier were observed in live discovery (oh-my-pi 7c74c203,
23
+ * opencodex #8644 2026-11-13). Falls back through Carbon → Argon → 3.8 Flash.
10
24
  * - Gemini 3.8 Flash (Low / Medium / High)
11
- * - Gemini 3.7 Flash (Low / Medium / High)
12
- * - Gemini 3.6 Flash (Low / Medium / High)
25
+ * - Gemini 3.7 Flash (Low / Medium / High) — still served, single `gemini-3.7-flash-tiered`
26
+ * wire id on newer discovery payloads; Enterprise-only per the 2026-11 models doc.
27
+ * - Gemini 3.6 Flash (Low / Medium / High) — Enterprise-only; effectively absent from CCA
28
+ * for non-Enterprise accounts since 3.7 shipped, but kept selectable for entitled ones.
13
29
  * - Gemini 3.1 Pro (Low / High)
14
- * - Claude Sonnet 4.6 (Thinking)
15
- * - Claude Opus 4.6 (Thinking)
16
30
  * - Claude Opus 5.5 (Low / Medium / High)
17
31
  * - Claude Sonnet 5.5 (Low / Medium / High)
18
- * - GPT-OSS 120B (Medium)
19
32
  *
20
- * Gemini 4 Argon is inferred from runtime ids referenced by Antigravity IDE 2.23.0
21
- * (`gemini-4-argon-{low,medium,high}`); it is not yet confirmed against a live
22
- * `fetchAvailableModels` or `agy models` listing, so its limits and pricing are
23
- * provisional and requests fall back to Gemini 3.8 Flash when the backend rejects it.
24
- *
25
- * Gemini 3.5 Flash is intentionally omitted from the selectable catalog; the
26
- * stream handler recognizes the reported retirement notice for old model IDs.
27
- * Pi exposes the remaining models as public IDs and surfaces the exact thinking
28
- * levels advertised by the backend for each model.
33
+ * Removed 2026-11-18 per Google's models doc: `claude-opus-4-6-thinking`,
34
+ * `claude-sonnet-4-6`, `gpt-oss-120b-medium`. They are no longer selectable; the stream
35
+ * handler still recognizes their retirement notices, and pinned runtime overrides to the
36
+ * old wire IDs keep working until the backend drops them.
29
37
  */
30
38
  export declare const ANTIGRAVITY_ROUTING: Record<string, AntigravityRouting>;
31
39
  /**
@@ -4,29 +4,70 @@ export const PROVIDER_NAME = "Antigravity";
4
4
  /**
5
5
  * Public selectable model IDs → backend request model IDs by thinking effort.
6
6
  *
7
- * Catalog mirrors `agy models` (Antigravity CLI), which currently advertises:
8
- * - Gemini 4 Argon (Low / Medium / High) — provisional, see below
7
+ * Catalog mirrors `agy models` (Antigravity CLI) and the 2026-11 models doc, which advertises:
8
+ * - Gemini 4 Argon (Low / Medium / High) — CONFIRMED: launched 2026-10-13; wire IDs
9
+ * `gemini-4-argon-{low,medium,high}` verified against live `fetchAvailableModels`
10
+ * (opencodex 2026-10-14, codex2api 2026-10-16). Entitlement-gated (Ultra / Enterprise /
11
+ * paid Pro); requests fall back to Gemini 3.8 Flash when the backend rejects it.
12
+ * - Gemini 4 Carbon (Low / Medium / High) — launched 2026-11-10 (changelog v2.31.0);
13
+ * CCA wire IDs follow the family pattern but are UNVERIFIED against a live listing,
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).
20
+ * - Gemini 4 Hydrogen (Low / Medium / High / xHigh) — launched 2026-11-12; the four
21
+ * SKUs incl. the new `-xhigh` tier were observed in live discovery (oh-my-pi 7c74c203,
22
+ * opencodex #8644 2026-11-13). Falls back through Carbon → Argon → 3.8 Flash.
9
23
  * - Gemini 3.8 Flash (Low / Medium / High)
10
- * - Gemini 3.7 Flash (Low / Medium / High)
11
- * - Gemini 3.6 Flash (Low / Medium / High)
24
+ * - Gemini 3.7 Flash (Low / Medium / High) — still served, single `gemini-3.7-flash-tiered`
25
+ * wire id on newer discovery payloads; Enterprise-only per the 2026-11 models doc.
26
+ * - Gemini 3.6 Flash (Low / Medium / High) — Enterprise-only; effectively absent from CCA
27
+ * for non-Enterprise accounts since 3.7 shipped, but kept selectable for entitled ones.
12
28
  * - Gemini 3.1 Pro (Low / High)
13
- * - Claude Sonnet 4.6 (Thinking)
14
- * - Claude Opus 4.6 (Thinking)
15
29
  * - Claude Opus 5.5 (Low / Medium / High)
16
30
  * - Claude Sonnet 5.5 (Low / Medium / High)
17
- * - GPT-OSS 120B (Medium)
18
31
  *
19
- * Gemini 4 Argon is inferred from runtime ids referenced by Antigravity IDE 2.23.0
20
- * (`gemini-4-argon-{low,medium,high}`); it is not yet confirmed against a live
21
- * `fetchAvailableModels` or `agy models` listing, so its limits and pricing are
22
- * provisional and requests fall back to Gemini 3.8 Flash when the backend rejects it.
23
- *
24
- * Gemini 3.5 Flash is intentionally omitted from the selectable catalog; the
25
- * stream handler recognizes the reported retirement notice for old model IDs.
26
- * Pi exposes the remaining models as public IDs and surfaces the exact thinking
27
- * levels advertised by the backend for each model.
32
+ * Removed 2026-11-18 per Google's models doc: `claude-opus-4-6-thinking`,
33
+ * `claude-sonnet-4-6`, `gpt-oss-120b-medium`. They are no longer selectable; the stream
34
+ * handler still recognizes their retirement notices, and pinned runtime overrides to the
35
+ * old wire IDs keep working until the backend drops them.
28
36
  */
29
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
+ },
49
+ "gemini-4-hydrogen": {
50
+ off: "gemini-4-hydrogen-low",
51
+ routing: {
52
+ minimal: "gemini-4-hydrogen-low",
53
+ low: "gemini-4-hydrogen-low",
54
+ medium: "gemini-4-hydrogen-medium",
55
+ high: "gemini-4-hydrogen-high",
56
+ xhigh: "gemini-4-hydrogen-xhigh",
57
+ },
58
+ defaultRequestId: "gemini-4-hydrogen-low",
59
+ },
60
+ "gemini-4-carbon": {
61
+ off: "gemini-4-carbon-low",
62
+ routing: {
63
+ minimal: "gemini-4-carbon-low",
64
+ low: "gemini-4-carbon-low",
65
+ medium: "gemini-4-carbon-medium",
66
+ high: "gemini-4-carbon-high",
67
+ xhigh: "gemini-4-carbon-high",
68
+ },
69
+ defaultRequestId: "gemini-4-carbon-low",
70
+ },
30
71
  "gemini-4-argon": {
31
72
  off: "gemini-4-argon-low",
32
73
  routing: {
@@ -130,6 +171,8 @@ export const ANTIGRAVITY_ROUTING = {
130
171
  },
131
172
  defaultRequestId: "gemini-3.6-flash-low",
132
173
  },
174
+ // Removed-from-catalog IDs keep their routing so a pinned frontend override still
175
+ // resolves to the right wire id until the backend drops the model (2026-11-18).
133
176
  "gpt-oss-120b": {
134
177
  off: "gpt-oss-120b-medium",
135
178
  routing: {
@@ -146,6 +189,22 @@ export const ANTIGRAVITY_ROUTING = {
146
189
  * Requesting more than these limits returns a 400 Bad Request from the API.
147
190
  */
148
191
  export const RUNTIME_MAX_OUTPUT_TOKENS = {
192
+ // Gemini 4 family: 3.8-tier value as provisional estimate; no verified 4-family limit.
193
+ "gemini-4-carbon": 65536,
194
+ "gemini-4-carbon-low": 65536,
195
+ "gemini-4-carbon-medium": 65536,
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,
203
+ "gemini-4-hydrogen": 65536,
204
+ "gemini-4-hydrogen-low": 65536,
205
+ "gemini-4-hydrogen-medium": 65536,
206
+ "gemini-4-hydrogen-high": 65536,
207
+ "gemini-4-hydrogen-xhigh": 65536,
149
208
  // Provisional: family fallback, not a verified Gemini 4 limit.
150
209
  "gemini-4-argon": 65536,
151
210
  "gemini-4-argon-low": 65536,
@@ -198,9 +257,11 @@ export function getMaxOutputTokens(modelId, runtimeModel) {
198
257
  }
199
258
  const geminiFlashCost = { input: 0.1, output: 0.4, cacheRead: 0.025, cacheWrite: 0.1 };
200
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 };
201
263
  const claudeSonnetCost = { input: 3.0, output: 15.0, cacheRead: 0.3, cacheWrite: 3.75 };
202
264
  const claudeOpusCost = { input: 15.0, output: 75.0, cacheRead: 1.5, cacheWrite: 18.75 };
203
- const gptOssCost = { input: 0.6, output: 2.4, cacheRead: 0.15, cacheWrite: 0.6 };
204
265
  // A null entry is intentionally hidden by Pi. Do not collapse levels that happen to
205
266
  // route to the same runtime ID: the UI must reflect the levels the backend advertises.
206
267
  const thinkingLevelMaps = {
@@ -213,6 +274,15 @@ const thinkingLevelMaps = {
213
274
  xhigh: null,
214
275
  max: null,
215
276
  },
277
+ lowMediumHighXhigh: {
278
+ off: null,
279
+ minimal: null,
280
+ low: "low",
281
+ medium: "medium",
282
+ high: "high",
283
+ xhigh: "xhigh",
284
+ max: null,
285
+ },
216
286
  lowHigh: {
217
287
  off: null,
218
288
  minimal: null,
@@ -256,8 +326,10 @@ const claude55ThinkingLevelMaps = {
256
326
  high: thinkingLevelMaps.thinking,
257
327
  };
258
328
  /**
259
- * Use existing same-family values as provisional estimates only; 5.5-specific
260
- * cost, context-window, and output-token metadata has not been verified.
329
+ * Claude Opus 5.5 and Sonnet 5.5 are officially served by Antigravity (confirmed in the
330
+ * 2026-11 models doc and observed in live discovery since 2026-10-03). The per-tier cost,
331
+ * context window, and output caps below remain same-family estimates — Google does not
332
+ * publish 5.5-specific numbers — but the models themselves are first-class.
261
333
  */
262
334
  function claude55Models(family) {
263
335
  const familyName = family === "opus" ? "Opus" : "Sonnet";
@@ -280,7 +352,8 @@ function claude55Models(family) {
280
352
  /** Selectable provider models; effort variants share public IDs where routing supports them. */
281
353
  export const ANTIGRAVITY_MODELS = [
282
354
  {
283
- // Provisional: cost (Pro-tier estimate), context window, and max output are unverified.
355
+ // Wire IDs verified against live discovery (2026-10-14); cost/context are
356
+ // Pro-tier estimates and the output cap is the 3.8-tier value.
284
357
  id: "gemini-4-argon",
285
358
  name: "Gemini 4 Argon (Antigravity)",
286
359
  reasoning: true,
@@ -290,6 +363,43 @@ export const ANTIGRAVITY_MODELS = [
290
363
  contextWindow: 1048576,
291
364
  maxTokens: 65536,
292
365
  },
366
+ {
367
+ // Launched 2026-11-10. Carbon-specific cost/context/output are unverified;
368
+ // values reuse the Gemini 4 family estimates.
369
+ id: "gemini-4-carbon",
370
+ name: "Gemini 4 Carbon (Antigravity)",
371
+ reasoning: true,
372
+ thinkingLevelMap: thinkingLevelMaps.lowMediumHigh,
373
+ input: ["text", "image"],
374
+ cost: geminiProCost,
375
+ contextWindow: 1048576,
376
+ maxTokens: 65536,
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
+ },
391
+ {
392
+ // Launched 2026-11-12 with the backend's first -xhigh tier. Hydrogen-specific
393
+ // cost/context/output are unverified; values reuse the Gemini 4 family estimates.
394
+ id: "gemini-4-hydrogen",
395
+ name: "Gemini 4 Hydrogen (Antigravity)",
396
+ reasoning: true,
397
+ thinkingLevelMap: thinkingLevelMaps.lowMediumHighXhigh,
398
+ input: ["text", "image"],
399
+ cost: geminiProCost,
400
+ contextWindow: 1048576,
401
+ maxTokens: 65536,
402
+ },
293
403
  {
294
404
  id: "gemini-3.8-flash",
295
405
  name: "Gemini 3.8 Flash (Antigravity)",
@@ -320,28 +430,8 @@ export const ANTIGRAVITY_MODELS = [
320
430
  contextWindow: 1048576,
321
431
  maxTokens: 65536,
322
432
  },
323
- {
324
- id: "claude-opus-4-6",
325
- name: "Claude Opus 4.6 (Antigravity)",
326
- reasoning: true,
327
- thinkingLevelMap: thinkingLevelMaps.thinking,
328
- input: ["text", "image"],
329
- cost: claudeOpusCost,
330
- contextWindow: 250000,
331
- maxTokens: 64000,
332
- },
333
433
  ...claude55Models("opus"),
334
434
  ...claude55Models("sonnet"),
335
- {
336
- id: "claude-sonnet-4-6",
337
- name: "Claude Sonnet 4.6 (Antigravity)",
338
- reasoning: true,
339
- thinkingLevelMap: thinkingLevelMaps.thinking,
340
- input: ["text", "image"],
341
- cost: claudeSonnetCost,
342
- contextWindow: 200000,
343
- maxTokens: 64000,
344
- },
345
435
  {
346
436
  id: "gemini-3.1-pro",
347
437
  name: "Gemini 3.1 Pro (Antigravity)",
@@ -352,16 +442,6 @@ export const ANTIGRAVITY_MODELS = [
352
442
  contextWindow: 1048576,
353
443
  maxTokens: 65535,
354
444
  },
355
- {
356
- id: "gpt-oss-120b",
357
- name: "GPT-OSS 120B (Antigravity)",
358
- reasoning: true,
359
- thinkingLevelMap: thinkingLevelMaps.medium,
360
- input: ["text"],
361
- cost: gptOssCost,
362
- contextWindow: 131072,
363
- maxTokens: 32768,
364
- },
365
445
  ];
366
446
  /** Resolve public model id + thinking effort to Antigravity runtime model id. */
367
447
  export function getAntigravityRequestModelId(modelId, effort) {
@@ -393,6 +473,29 @@ export function getAntigravityRequestModelId(modelId, effort) {
393
473
  * provide a fallback runtime model ID (e.g. Gemini 3.6 Flash) to maintain availability.
394
474
  */
395
475
  export function getFallbackRuntimeModel(runtimeModel, effort) {
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,
484
+ // so a Hydrogen xHigh fallback must downgrade the tier when it crosses families.
485
+ const carbonTarget = runtimeModel.startsWith("gemini-4-hydrogen-")
486
+ ? runtimeModel.replace("gemini-4-hydrogen-", "gemini-4-carbon-").replace(/-xhigh$/, "-high")
487
+ : undefined;
488
+ if (runtimeModel === "gemini-4-hydrogen") {
489
+ return "gemini-4-carbon-low";
490
+ }
491
+ if (carbonTarget)
492
+ return carbonTarget;
493
+ if (runtimeModel === "gemini-4-carbon") {
494
+ return "gemini-4-argon-low";
495
+ }
496
+ if (runtimeModel.startsWith("gemini-4-carbon-")) {
497
+ return runtimeModel.replace("gemini-4-carbon-", "gemini-4-argon-").replace(/-xhigh$/, "-high");
498
+ }
396
499
  if (runtimeModel === "gemini-4-argon") {
397
500
  return "gemini-3.8-flash-low";
398
501
  }
@@ -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";
@@ -5,6 +5,23 @@ import { type AntigravitySessionState } from "../utils/util.js";
5
5
  export { ANTIGRAVITY_API };
6
6
  /** Plan quota is deterministic; everything else on a 429 is a transient throttle. */
7
7
  export declare function isPlanQuotaError(status: number | undefined, text: string): boolean;
8
+ /**
9
+ * Transient 429s may carry a server-provided Retry-After (seconds or HTTP-date, CPA
10
+ * issue #6646). Trust it over the local backoff when it is short enough to be worth a
11
+ * retry; a longer value is a cooldown that will not clear inside this loop.
12
+ */
13
+ export declare const THROTTLE_RETRY_AFTER_CAP_SECONDS = 60;
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;
8
25
  /** Exported for unit tests. */
9
26
  export declare function convertMessages(model: Model<Api>, context: TranscriptContext, runtimeModel: string): GeminiContent[];
10
27
  /**
@@ -18,6 +35,8 @@ export declare function convertTools(tools: Tool[] | undefined, useLegacyParamet
18
35
  /** Exported for unit tests. */
19
36
  export declare function buildRequest(model: Model<Api>, context: TranscriptContext, projectId: string, options: AntigravityStreamOptions, runtimeModel: string, sessionState?: AntigravitySessionState): AntigravityGenerateRequest;
20
37
  /** Exported for unit tests. */
38
+ export declare function scrubAgentName(text: string): string;
39
+ /** Exported for unit tests. */
21
40
  export declare function mapStopReason(reason: string | undefined): StopReason;
22
41
  /**
23
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,81 @@ 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);
58
+ }
59
+ /**
60
+ * Transient 429s may carry a server-provided Retry-After (seconds or HTTP-date, CPA
61
+ * issue #6646). Trust it over the local backoff when it is short enough to be worth a
62
+ * retry; a longer value is a cooldown that will not clear inside this loop.
63
+ */
64
+ export const THROTTLE_RETRY_AFTER_CAP_SECONDS = 60;
65
+ export function parseRetryAfterSeconds(raw) {
66
+ if (!raw)
67
+ return undefined;
68
+ const trimmed = raw.trim();
69
+ if (!trimmed)
70
+ return undefined;
71
+ if (/^\d+$/.test(trimmed)) {
72
+ const seconds = Number(trimmed);
73
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;
74
+ }
75
+ const date = Date.parse(trimmed);
76
+ if (Number.isNaN(date))
77
+ return undefined;
78
+ const seconds = Math.round((date - Date.now()) / 1000);
79
+ return seconds >= 0 ? seconds : 0;
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]);
51
126
  }
52
127
  /**
53
128
  * pi chooses auto-retry by matching the error text (`isRetryableAssistantError`) and
@@ -429,7 +504,11 @@ function mapToolChoiceMode(toolChoice) {
429
504
  }
430
505
  /** Exported for unit tests. */
431
506
  export function buildRequest(model, context, projectId, options, runtimeModel, sessionState) {
432
- 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;
433
512
  const request = {
434
513
  contents: convertMessages(model, context, runtimeModel),
435
514
  systemInstruction: {
@@ -478,6 +557,7 @@ export function buildRequest(model, context, projectId, options, runtimeModel, s
478
557
  const envelope = antigravityRequestEnvelope(runtimeModel, isClaude, state);
479
558
  request.sessionId = envelope.sessionId;
480
559
  request.labels = envelope.labels;
560
+ scrubRequestAgentName(request);
481
561
  return {
482
562
  project: projectId,
483
563
  model: runtimeModel,
@@ -487,6 +567,34 @@ export function buildRequest(model, context, projectId, options, runtimeModel, s
487
567
  requestId: envelope.requestId,
488
568
  };
489
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
+ }
490
598
  /** Exported for unit tests. */
491
599
  export function mapStopReason(reason) {
492
600
  if (reason === "STOP")
@@ -495,16 +603,30 @@ export function mapStopReason(reason) {
495
603
  return StopReason.Length;
496
604
  return reason ? StopReason.Error : StopReason.Stop;
497
605
  }
498
- const RETIRED_GEMINI_35_NOTICE_PREFIX = "gemini 3.5 flash is no longer available. please switch to";
499
- function isRetiredGemini35Runtime(runtimeModel) {
500
- return /^(?:gemini-3\.5-flash(?:-|$)|gemini-3-flash-agent$)/i.test(runtimeModel);
606
+ /**
607
+ * Backends answer retired models with a plain text notice instead of an error. The 3.5
608
+ * wording is the observed template; the 2026-11-18 removals (Claude 4.6, Sonnet 4.6,
609
+ * GPT-OSS 120B) are expected to reuse it. Match on the model name prefix, not the full
610
+ * sentence, so wording drift on the suffix stays harmless.
611
+ */
612
+ const RETIRED_NOTICE_PREFIXES = [
613
+ "gemini 3.5 flash is no longer available. please switch to",
614
+ "claude-opus-4-6 is no longer available",
615
+ "claude-sonnet-4-6 is no longer available",
616
+ "gpt-oss-120b is no longer available",
617
+ ];
618
+ const RETIRED_RUNTIME_PATTERN = /^(?:gemini-3\.5-flash(?:-|$)|gemini-3-flash-agent$|claude-opus-4-6|claude-sonnet-4-6|gpt-oss-120b)/i;
619
+ function isRetiredRuntime(runtimeModel) {
620
+ return RETIRED_RUNTIME_PATTERN.test(runtimeModel);
501
621
  }
502
622
  function retiredNoticePrefixState(text) {
503
623
  const normalized = text.trimStart().replace(/\s+/g, " ").toLowerCase();
504
- if (normalized.startsWith(RETIRED_GEMINI_35_NOTICE_PREFIX))
505
- return "match";
506
- if (RETIRED_GEMINI_35_NOTICE_PREFIX.startsWith(normalized))
507
- return "possible";
624
+ for (const prefix of RETIRED_NOTICE_PREFIXES) {
625
+ if (normalized.startsWith(prefix))
626
+ return "match";
627
+ if (prefix.startsWith(normalized) && normalized.length > 0)
628
+ return "possible";
629
+ }
508
630
  return "no-match";
509
631
  }
510
632
  /**
@@ -600,6 +722,16 @@ export function friendlyAntigravityError(status, text) {
600
722
  if (/verify your account|VALIDATION_REQUIRED/i.test(msg)) {
601
723
  return formatAccountValidation({ message: msg });
602
724
  }
725
+ // Google is actively enforcing third-party OAuth use (403 PERMISSION_DENIED,
726
+ // reason TOS_VIOLATION; the appeal copy names "third party software"). The reason
727
+ // lives in error.details, which jsonOrTextError drops — match the raw body. Retries,
728
+ // re-login and model switches do not clear it, and the account itself is at risk.
729
+ if (/TOS_VIOLATION|third[- ]party (software|tools|services|clients?)/i.test(text)) {
730
+ return ("Antigravity flagged this account for third-party access (TOS_VIOLATION). " +
731
+ "Retries and re-login will not clear it; further use may get the account suspended. " +
732
+ "Next: stop using third-party clients on this account and appeal through Google support. " +
733
+ `Backend said: ${msg}`);
734
+ }
603
735
  if (/permission|forbidden|access/i.test(msg)) {
604
736
  return "Antigravity access was denied for this account or project. Next: try another model, re-login, or use an account with access.";
605
737
  }
@@ -816,8 +948,8 @@ export async function streamResponse(response, stream, output, model, sessionSta
816
948
  // The response is being discarded; cancellation is best-effort.
817
949
  }
818
950
  reader.releaseLock();
819
- throw new Error("Antigravity reports that Gemini 3.5 Flash is no longer available. " +
820
- "Next: switch to gemini-3.8-flash, gemini-3.7-flash, or another catalog model.");
951
+ throw new Error("Antigravity reports that this model has been retired and is no longer available. " +
952
+ "Next: switch to a current catalog model (see /antigravity.models).");
821
953
  }
822
954
  if (noticeState !== "possible")
823
955
  flushPendingRetiredNoticeParts();
@@ -981,8 +1113,19 @@ export function streamAntigravity(model, context, options) {
981
1113
  break;
982
1114
  // Every other 429 is a transient throttle. Back off on the same endpoint
983
1115
  // instead of hopping regions, which multiplies load on a throttled account.
984
- if (response.status === 429 && throttleAttempt < THROTTLE_MAX_RETRIES) {
985
- await sleep(throttleBaseDelayMs() * 2 ** throttleAttempt, opts.signal);
1116
+ // Honor a server Retry-After when it is short; a longer one is a cooldown
1117
+ // that will not clear inside this loop, so burn no attempts on it.
1118
+ const retryAfterSeconds = parseRetryAfterSeconds(response.headers.get("retry-after")) ??
1119
+ parseRetryAfterFromBody(lastText);
1120
+ const retryable = response.status === 429 &&
1121
+ throttleAttempt < THROTTLE_MAX_RETRIES &&
1122
+ (retryAfterSeconds === undefined ||
1123
+ retryAfterSeconds <= THROTTLE_RETRY_AFTER_CAP_SECONDS);
1124
+ if (retryable) {
1125
+ const delayMs = retryAfterSeconds !== undefined
1126
+ ? retryAfterSeconds * 1000
1127
+ : throttleBaseDelayMs() * 2 ** throttleAttempt;
1128
+ await sleep(delayMs, opts.signal);
986
1129
  throttleAttempt += 1;
987
1130
  continue;
988
1131
  }
@@ -1000,6 +1143,15 @@ export function streamAntigravity(model, context, options) {
1000
1143
  }
1001
1144
  if (response?.ok)
1002
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
+ }
1003
1155
  if (response?.status === 404) {
1004
1156
  if (candIdx + 1 < runtimeCandidates.length) {
1005
1157
  continue;
@@ -1057,7 +1209,7 @@ export function streamAntigravity(model, context, options) {
1057
1209
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1058
1210
  };
1059
1211
  output.stopReason = "stop";
1060
- received = await streamResponse(response, stream, output, model, sessionState, isRetiredGemini35Runtime(runtimeModel));
1212
+ received = await streamResponse(response, stream, output, model, sessionState, isRetiredRuntime(runtimeModel));
1061
1213
  if (received)
1062
1214
  break;
1063
1215
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heyhuynhgiabuu/pi-oauth-antigravity",
3
- "version": "0.1.9",
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",
@@ -59,8 +59,8 @@
59
59
  "undici": "^8.10.0"
60
60
  },
61
61
  "devDependencies": {
62
- "@earendil-works/pi-ai": "1.3.0",
63
- "@earendil-works/pi-coding-agent": "1.3.0",
62
+ "@earendil-works/pi-ai": "1.2.0",
63
+ "@earendil-works/pi-coding-agent": "1.2.0",
64
64
  "@types/node": "^22.20.1",
65
65
  "pi-usage-core": "^0.1.0",
66
66
  "tsx": "^4.20.6",