dsh-cliproxyapi-pro 1.11.0 → 1.12.1

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.
@@ -0,0 +1,119 @@
1
+ // System-prompt sanitizing: the `system-prompt/assemble` waterfall hook that
2
+ // removes text some upstreams reject before a request leaves DSH — the brand
3
+ // phrase (replaced) and known trigger sentences (removed).
4
+
5
+ /**
6
+ * Default text substituted for every "DeepSeek Harness" phrase, used when the
7
+ * account leaves its replacement blank. The phrase is used as a proper noun
8
+ * throughout the prompt ("powered by ___.", "the ___ implementation
9
+ * checkout", "the ___ Web GUI"), so the default is an article-free proper
10
+ * noun that reads grammatically in every position and is free of the brand
11
+ * words the upstream blocks.
12
+ */
13
+ export const DEFAULT_SANITIZE_REPLACEMENT = "Custom Harness";
14
+
15
+ /**
16
+ * The phrase some upstream gateways refuse in the system prompt. Antigravity
17
+ * Gemini accounts reject requests whose system text contains "DeepSeek
18
+ * Harness" (any letter case, across whitespace) with an unexplained 429, so
19
+ * every occurrence is replaced as one whole phrase — wherever it appears,
20
+ * including inside the fixed identity opener.
21
+ */
22
+ export const PROMPT_PHRASE_PATTERN = /deepseek\s+harness/gi;
23
+
24
+ /**
25
+ * The replacement text one account configured: its trimmed value, or the
26
+ * default when blank/missing.
27
+ */
28
+ export function sanitizeReplacement(configured) {
29
+ return typeof configured === "string" && configured.trim() !== ""
30
+ ? configured.trim()
31
+ : DEFAULT_SANITIZE_REPLACEMENT;
32
+ }
33
+
34
+ /**
35
+ * Build a sentence matcher that tolerates any whitespace between words, in
36
+ * any letter case, and also consumes the horizontal whitespace around it.
37
+ */
38
+ function sentencePattern(sentence) {
39
+ const words = sentence.trim().split(/\s+/).map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
40
+ return new RegExp(`[ \\t]*${words.join("\\s+")}[ \\t]*`, "gi");
41
+ }
42
+
43
+ /**
44
+ * Whole sentences removed from the prompt because upstream content screening
45
+ * rejects them in context. Google is not a plain keyword filter here: this
46
+ * sentence of DSH's Web GUI orientation (`app:web-surface`, also in its
47
+ * frozen legacy paragraph) passes on its own but 429s together with its
48
+ * neighbours ("…they mean this GUI. … The client-plugin…"); the full prompt
49
+ * passes once it is removed. Losing it only drops the hint that the browser
50
+ * supplies no implicit page context.
51
+ */
52
+ export const PROMPT_SENTENCE_REMOVALS = [
53
+ sentencePattern("The browser provides no implicit DOM, route, or screenshot context."),
54
+ ];
55
+
56
+ /**
57
+ * Drop one matched sentence, keeping a single space only where it sat between
58
+ * two pieces of text on the same line (no doubled or dangling spaces).
59
+ */
60
+ function removeSentence(match, offset, whole) {
61
+ const before = whole[offset - 1];
62
+ const after = whole[offset + match.length];
63
+ const textBefore = before !== undefined && before !== "\n" && before !== "\r";
64
+ const textAfter = after !== undefined && after !== "\n" && after !== "\r";
65
+ return textBefore && textAfter ? " " : "";
66
+ }
67
+
68
+ /**
69
+ * Sanitize one string: remove every known trigger sentence, then replace each
70
+ * "DeepSeek Harness" phrase with `replacement`, verbatim — a function replacer
71
+ * keeps `$`-sequences in custom text literal. Returns the input when nothing
72
+ * matched.
73
+ */
74
+ export function sanitizePromptText(text, replacement = DEFAULT_SANITIZE_REPLACEMENT) {
75
+ const target = sanitizeReplacement(replacement);
76
+ let out = text;
77
+ for (const pattern of PROMPT_SENTENCE_REMOVALS) {
78
+ pattern.lastIndex = 0;
79
+ out = out.replace(pattern, removeSentence);
80
+ }
81
+ PROMPT_PHRASE_PATTERN.lastIndex = 0;
82
+ return out.replace(PROMPT_PHRASE_PATTERN, () => target);
83
+ }
84
+
85
+ /**
86
+ * Rewrite every text value the assembled prompt contributes to the request:
87
+ * ordered sections, dynamic runtime contexts and interpolation variables.
88
+ * Section/context objects are shallow-copied; the input assembly is never
89
+ * mutated. Returns the original assembly reference when nothing matched, so
90
+ * listeners downstream see one identical value.
91
+ */
92
+ export function sanitizeAssembly(assembly, replacement = DEFAULT_SANITIZE_REPLACEMENT) {
93
+ if (assembly === null || typeof assembly !== "object") return assembly;
94
+ let changed = false;
95
+ const mapText = (entry) => {
96
+ if (entry === null || typeof entry !== "object" || typeof entry.text !== "string") return entry;
97
+ const text = sanitizePromptText(entry.text, replacement);
98
+ if (text === entry.text) return entry;
99
+ changed = true;
100
+ return { ...entry, text };
101
+ };
102
+ const sections = Array.isArray(assembly.sections) ? assembly.sections.map(mapText) : assembly.sections;
103
+ const contexts = Array.isArray(assembly.contexts) ? assembly.contexts.map(mapText) : assembly.contexts;
104
+ let variables = assembly.variables;
105
+ if (variables !== null && typeof variables === "object") {
106
+ const next = {};
107
+ let varsChanged = false;
108
+ for (const [name, value] of Object.entries(variables)) {
109
+ const rewritten = typeof value === "string" ? sanitizePromptText(value, replacement) : value;
110
+ if (rewritten !== value) varsChanged = true;
111
+ next[name] = rewritten;
112
+ }
113
+ if (varsChanged) {
114
+ variables = next;
115
+ changed = true;
116
+ }
117
+ }
118
+ return changed ? { ...assembly, sections, contexts, variables } : assembly;
119
+ }
@@ -1,28 +1,34 @@
1
1
  // Native wire protocols, model overrides and managed llm-pi-ai route profiles.
2
2
 
3
- import { REASONING_LEVELS, PROTOCOLS, PROTOCOL_ROUTES } from "./config.js";
3
+ import { REASONING_LEVELS, PROTOCOLS, PROTOCOL_ROUTES, GOOGLE_THINKING_LEVELS } from "./config.js";
4
4
  import { filterModels, sortModelsNewestFirst } from "./models.js";
5
5
 
6
6
  /**
7
7
  * Pick the wire protocol that reaches a model with the fewest translations.
8
8
  *
9
- * CLIProxyAPI serves every model on OpenAI Chat, OpenAI Responses and
10
- * Anthropic Messages and translates between them and the upstream channel.
11
- * Speaking the upstream's own protocol skips that translation:
9
+ * CLIProxyAPI serves every model on OpenAI Chat, OpenAI Responses, Anthropic
10
+ * Messages and Gemini generateContent and translates between them and the
11
+ * upstream channel. Speaking the upstream's own protocol skips that translation:
12
12
  * - Claude family -> Anthropic Messages (`/v1/messages`)
13
13
  * - OpenAI / Codex / Grok -> OpenAI Responses (`/v1/responses`)
14
- * - everything else, including Gemini -> OpenAI Chat Completions; DSH
15
- * cannot speak Gemini generateContent on a custom route.
14
+ * - unprefixed `gemini-*` ids -> Gemini generateContent (`/v1beta/models/…`).
15
+ * Prefixed ids (`team/gemini-…`) stay on Chat: pi-ai keys Gemini tool-call
16
+ * ids and multimodal tool results on an id that starts with `gemini-`.
17
+ * - everything else -> OpenAI Chat Completions.
16
18
  * `owned_by` from the CPA listing names the family; the id is the fallback.
19
+ * The Gemini route needs an API key; {@link buildPiAiRoutes} falls back to
20
+ * Chat for keyless accounts.
17
21
  * @param model - parsed catalog model.
18
22
  * @returns one of {@link PROTOCOLS}.
19
23
  */
20
24
  export function nativeProtocol(model) {
21
25
  const owner = String(model.ownedBy ?? "").toLowerCase();
22
- const bare = String(model.id ?? "").toLowerCase().split("/").pop() ?? "";
26
+ const id = String(model.id ?? "").toLowerCase();
27
+ const bare = id.split("/").pop() ?? "";
23
28
  if (owner === "anthropic" || /^claude/.test(bare)) return "anthropic-messages";
24
29
  if (owner === "openai" || owner === "xai") return "openai-responses";
25
30
  if (/^(gpt|o\d|codex|grok)/.test(bare) && !/^gpt-oss/.test(bare)) return "openai-responses";
31
+ if (/^gemini-/.test(id)) return "google-generative-ai";
26
32
  return "openai-completions";
27
33
  }
28
34
 
@@ -38,8 +44,11 @@ export function routeKeyFor(provider, protocol) {
38
44
  return `${provider}${PROTOCOL_ROUTES[protocol].suffix}`;
39
45
  }
40
46
 
47
+ /** Route base URL; pi-ai's Gemini client expects the API version in it. */
41
48
  export function routeBaseURL(rootURL, protocol) {
42
- return protocol === "anthropic-messages" ? rootURL : `${rootURL}/v1`;
49
+ if (protocol === "anthropic-messages") return rootURL;
50
+ if (protocol === "google-generative-ai") return `${rootURL}/v1beta`;
51
+ return `${rootURL}/v1`;
43
52
  }
44
53
 
45
54
  export function supportedReasoning(model) {
@@ -56,6 +65,29 @@ export function supportedReasoning(model) {
56
65
  return Object.keys(result).length === 0 ? undefined : result;
57
66
  }
58
67
 
68
+ /**
69
+ * Narrow reasoning efforts to what pi-ai's Gemini adapter can send: it maps a
70
+ * wire value to `thinkingLevel` / a budget and throws for anything outside
71
+ * {@link GOOGLE_THINKING_LEVELS}, so `xhigh` / `max` are dropped. `off` is
72
+ * kept only when the catalog declares it: Gemini sends it as
73
+ * `thinkingBudget: 0`, which thinking-level models may reject. A model that
74
+ * declared only levels above `high` keeps `high`.
75
+ */
76
+ export function googleReasoning(model, efforts) {
77
+ if (efforts === undefined) return undefined;
78
+ const declared = new Set(model.reasoningLevels);
79
+ const result = {};
80
+ for (const [level, wire] of Object.entries(efforts)) {
81
+ if (level === "off") {
82
+ if (declared.has("off")) result.off = null;
83
+ } else if (GOOGLE_THINKING_LEVELS.includes(wire)) {
84
+ result[level] = wire;
85
+ }
86
+ }
87
+ if (!Object.keys(result).some((level) => level !== "off")) result.high = "high";
88
+ return result;
89
+ }
90
+
59
91
  /**
60
92
  * Claude models that take adaptive thinking with an `effort` value rather
61
93
  * than a token budget: Opus/Sonnet 4.6+, Haiku 5+, Fable and every 5.x.
@@ -100,7 +132,8 @@ export function protocolCompat(model, protocol, hasReasoning) {
100
132
  }
101
133
 
102
134
  export function toPiAiModelProfile(model, protocol) {
103
- const reasoningEfforts = supportedReasoning(model);
135
+ const supported = supportedReasoning(model);
136
+ const reasoningEfforts = protocol === "google-generative-ai" ? googleReasoning(model, supported) : supported;
104
137
  const compat = protocolCompat(model, protocol, reasoningEfforts !== undefined);
105
138
  return {
106
139
  id: model.id,
@@ -116,8 +149,10 @@ export function toPiAiModelProfile(model, protocol) {
116
149
  /**
117
150
  * Build one llm-pi-ai route per protocol the selected models need.
118
151
  * The base route key (e.g. `cli-proxy`) always carries OpenAI Chat so that
119
- * existing sessions and the default-model setting keep resolving; Responses
120
- * and Messages models get `<key>-responses` / `<key>-messages` siblings.
152
+ * existing sessions and the default-model setting keep resolving; Responses,
153
+ * Messages and Gemini models get `<key>-responses` / `<key>-messages` /
154
+ * `<key>-gemini` siblings. pi-ai's Gemini adapter refuses to send a request
155
+ * without an API key, so a keyless account keeps Gemini models on Chat.
121
156
  * @returns `{ allModels, orderedModels, routes }` where `routes` maps each
122
157
  * route key to its profile, in protocol order, and every ordered model
123
158
  * carries its `protocol` and `route`.
@@ -133,7 +168,8 @@ export function buildPiAiRoutes(config, discovery, hasApiKey) {
133
168
  const chatOrdered = allOrdered.filter(isChatModel);
134
169
  const filtered = filterModels(chatOrdered, config).map((model) => {
135
170
  const effective = applyModelOverride(model, config.modelOverrides?.[model.id]);
136
- const protocol = modelProtocol(model, config);
171
+ const wanted = modelProtocol(model, config);
172
+ const protocol = wanted === "google-generative-ai" && !hasApiKey ? "openai-completions" : wanted;
137
173
  return { ...effective, protocol, route: routeKeyFor(config.provider, protocol) };
138
174
  });
139
175
  if (filtered.length === 0) {
package/lib/index.js CHANGED
@@ -18,6 +18,7 @@ export { filterModels, modelFamily, sortModelsNewestFirst } from "./host/models.
18
18
  export { recommendModels, planRecommendations, selectionSuggestions } from "./host/recommend.js";
19
19
  export { nativeProtocol, modelProtocol, routeKeyFor, applyModelOverride, isChatModel, buildPiAiRoutes, managedRouteKeys } from "./host/routes.js";
20
20
  export { CpaRuntime } from "./host/runtime.js";
21
+ export { DEFAULT_SANITIZE_REPLACEMENT, PROMPT_PHRASE_PATTERN, PROMPT_SENTENCE_REMOVALS, sanitizeReplacement, sanitizePromptText, sanitizeAssembly } from "./host/prompt-sanitize.js";
21
22
  export { resolveStateFilePath, loadPersistedState, savePersistedState } from "./host/state-store.js";
22
23
  export { renderQuotaText, renderStatusText } from "./host/status-text.js";
23
24
 
@@ -13,17 +13,20 @@ export const UPSTREAM = {
13
13
  claudeUsage: "https://api.anthropic.com/api/oauth/usage",
14
14
  googleLoad: "https://daily-cloudcode-pa.googleapis.com/v1internal:loadCodeAssist",
15
15
  googleQuota: "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota",
16
- // cloudcode-pa still serves the Gemini group; the daily/sandbox hosts may
17
- // return only "Claude and GPT models". Summary hosts first, then the
18
- // per-model fallbacks.
16
+ // Same order as CPA's management center: CPA serves Antigravity through the
17
+ // daily host, whose numbers are the ones that move; the production host's
18
+ // Gemini group can read 100% regardless of use, so it comes last. A summary
19
+ // may carry only the "Claude and GPT models" group (5h and weekly buckets);
20
+ // Gemini then comes from the per-model list.
19
21
  antigravityQuota: [
20
- "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
21
22
  "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
22
23
  "https://daily-cloudcode-pa.sandbox.googleapis.com/v1internal:retrieveUserQuotaSummary",
24
+ "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
23
25
  ],
24
26
  antigravityModels: [
25
- "https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels",
26
27
  "https://daily-cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels",
28
+ "https://daily-cloudcode-pa.sandbox.googleapis.com/v1internal:fetchAvailableModels",
29
+ "https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels",
27
30
  ],
28
31
  kimiUsage: "https://api.kimi.com/coding/v1/usages",
29
32
  // Kimi International (kimi.ai) accounts use the same API on another host.
@@ -50,12 +53,17 @@ export const DEVIN_METADATA = {
50
53
 
51
54
  export const AG_META = { ideType: "ANTIGRAVITY", platform: "PLATFORM_UNSPECIFIED", pluginType: "GEMINI" };
52
55
  export const GEMINI_META = { ideType: "IDE_UNSPECIFIED", platform: "PLATFORM_UNSPECIFIED", pluginType: "GEMINI" };
53
- export const AG_SUMMARY_UA = "antigravity/cli/1.0.13 (aidev_client; os_type=darwin; arch=arm64)";
54
- export const AG_MODELS_UA = "antigravity/1.11.5 windows/amd64";
56
+ // The Antigravity Hub identity CPA itself sends (internal/misc/antigravity_version.go,
57
+ // mirrored by its management center): Cloud Code omits groups and newer models
58
+ // for clients below 2.23.0, so every Antigravity quota request uses it.
59
+ export const AG_UA = "antigravity/hub/2.23.0 darwin/arm64";
55
60
  export const CODEX_UA = "codex_cli_rs/0.76.0 (Debian 13.0.0; x86_64) WindowsTerminal";
56
61
 
57
62
  export const GROUP_CLAUDE_GPT = "Claude and GPT models";
58
63
  export const GROUP_GEMINI = "Gemini models";
64
+ // Gemini Argon models: some plans (e.g. Google AI Pro) give them a quota of
65
+ // their own, separate from the other Gemini models.
66
+ export const GROUP_ARGON = "Gemini Argon models";
59
67
  export const GROUP_OTHER = "Other models";
60
68
 
61
69
  export const W5H = 5 * 60 * 60;
@@ -25,8 +25,6 @@ export function createQuotaController(deps) {
25
25
  const root = new AbortController();
26
26
  const pool = createLimiter(concurrency);
27
27
  const states = new Map();
28
- /** management origin → Antigravity endpoint that last returned usable rows. */
29
- const agPreferred = new Map();
30
28
  let disposed = false;
31
29
 
32
30
  // Consecutive management 401/403 counts survive reloads through
@@ -119,7 +117,7 @@ export function createQuotaController(deps) {
119
117
  // --- Provider quota probes: each returns { windows, plan? } or throws QuotaError ---
120
118
  const PROBES = {
121
119
  ...createOAuthProbes({ apiCall, now }),
122
- ...createGoogleProbes({ apiCall, now, agPreferred }),
120
+ ...createGoogleProbes({ apiCall, now }),
123
121
  ...createBillingProbes({ apiCall, management, now }),
124
122
  };
125
123
  PROBES.gemini = PROBES["gemini-cli"];
@@ -51,8 +51,13 @@ function servesFamily(credential, family) {
51
51
  case "gemini-api":
52
52
  case "aistudio": return family === "gemini";
53
53
  case "vertex": return family === "gemini" || family === "claude";
54
- // Antigravity serves Gemini, and Claude/GPT only when its quota groups say so.
55
- case "antigravity": return family === "gemini" || ((family === "claude" || family === "gpt") && windowsMention(credential, family));
54
+ // Antigravity serves Gemini, and Claude/GPT only when its quota groups say
55
+ // so. Those groups name whole families ("Claude and GPT models") while
56
+ // Antigravity offers only a few such models, so a disabled credential
57
+ // (whose model list CPA no longer reports) never claims Claude/GPT ids
58
+ // from them alone.
59
+ case "antigravity": return family === "gemini"
60
+ || ((family === "claude" || family === "gpt") && credential.status !== "disabled" && windowsMention(credential, family));
56
61
  case "kimi":
57
62
  case "xai":
58
63
  case "qwen":
@@ -65,6 +70,23 @@ function servesFamily(credential, family) {
65
70
 
66
71
  const listHas = (credential, idLower) => Array.isArray(credential.models) && credential.models.some((m) => text(m).toLowerCase() === idLower);
67
72
 
73
+ /**
74
+ * Lower-cased union of the model lists of the other Antigravity credentials
75
+ * with the same prefix, or null when none reports one. A credential whose own
76
+ * list is unknown (CPA reports none while it is disabled) serves what its
77
+ * siblings serve; that is far narrower than the family heuristics.
78
+ */
79
+ function antigravitySiblingModels(credentials, credential) {
80
+ let union = null;
81
+ for (const other of credentials) {
82
+ if (other === credential || !Array.isArray(other.models) || text(other.provider).toLowerCase() !== "antigravity") continue;
83
+ if (prefixOf(other) !== prefixOf(credential)) continue;
84
+ union ??= new Set();
85
+ for (const m of other.models) union.add(text(m).toLowerCase());
86
+ }
87
+ return union;
88
+ }
89
+
68
90
  function finishMatch(list, matchedBy) {
69
91
  const seen = new Set();
70
92
  const unique = list.filter((c) => (seen.has(c.id) ? false : (seen.add(c.id), true)));
@@ -109,7 +131,14 @@ export function matchCredentials(accountEntry, modelId) {
109
131
  const hint = picker.find((m) => isObj(m) && text(m.id).toLowerCase() === id && text(m.ownedBy) !== "");
110
132
  if (hint !== undefined) family = ownedByFamily(hint.ownedBy);
111
133
  }
112
- const familyHits = family === "" ? [] : unprefixed.filter((c) => !Array.isArray(c.models) && servesFamily(c, family));
134
+ const familyHits = unprefixed.filter((c) => {
135
+ if (Array.isArray(c.models)) return false;
136
+ if (text(c.provider).toLowerCase() === "antigravity") {
137
+ const siblings = antigravitySiblingModels(credentials, c);
138
+ if (siblings !== null) return siblings.has(id);
139
+ }
140
+ return family !== "" && servesFamily(c, family);
141
+ });
113
142
 
114
143
  const listHits = [...plainHits, ...prefixedHits];
115
144
  if (listHits.length > 0) return finishMatch([...listHits, ...familyHits], "model-list");
@@ -1,5 +1,5 @@
1
1
  // Converts provider quota payloads into safe windows and plan labels.
2
- import { GROUP_CLAUDE_GPT, GROUP_GEMINI, GROUP_OTHER, PLAN_LABELS } from "./constants.js";
2
+ import { GROUP_CLAUDE_GPT, GROUP_GEMINI, GROUP_ARGON, GROUP_OTHER, PLAN_LABELS } from "./constants.js";
3
3
  import { QuotaError, isObj, text, firstText, numberOrNull, flagOf, clampPct, roundPct, getPath, fractionPercent, kindFromText, kindFromSeconds, durationSeconds, kindFromReset, isoFromUnix, isoFromString, isoFromRelative, makeWindow, dedupeWindows, extractPlan } from "./helpers.js";
4
4
 
5
5
  //#region Upstream Parsers
@@ -101,17 +101,44 @@ function claudeProfilePlan(profile) {
101
101
  return extractPlan(profile);
102
102
  }
103
103
 
104
- function groupPrefixes(groupText) {
105
- const s = groupText.toLowerCase();
106
- if (s.includes("claude") || s.includes("gpt")) return ["claude", "gpt"];
107
- if (s.includes("gemini")) return ["gemini", "gemma"];
104
+ /** Model family a quota group/bucket/model text names: "claude-gpt", "argon", "gemini" or "". */
105
+ function textFamily(value) {
106
+ const s = text(value).toLowerCase();
107
+ if (s === "") return "";
108
+ // Antigravity labels its Claude/GPT ("third-party") buckets 3p-*.
109
+ if (/claude|gpt|third[\s_-]?party|(?:^|[^a-z0-9])3p(?:[^a-z0-9]|$)/.test(s)) return "claude-gpt";
110
+ if (/argon/.test(s)) return "argon";
111
+ if (/gemini|gemma/.test(s)) return "gemini";
112
+ return "";
113
+ }
114
+
115
+ /**
116
+ * Prefixes for Argon windows: "argon" plus every "gemini-<version>-argon"
117
+ * the text names (e.g. "Gemini 4 Argon" / "gemini-4-argon-high" →
118
+ * "gemini-4-argon"), so model ids match by prefix without hard-coding a
119
+ * version; "gemini-4-argon" when the text names none.
120
+ */
121
+ function argonPrefixes(...values) {
122
+ const found = new Set(["argon"]);
123
+ for (const value of values) {
124
+ for (const m of text(value).toLowerCase().matchAll(/gemini[\s_-]+([0-9][0-9.]*)[\s_-]+argon/g)) found.add(`gemini-${m[1]}-argon`);
125
+ }
126
+ if (found.size === 1) found.add("gemini-4-argon");
127
+ return [...found];
128
+ }
129
+
130
+ function familyPrefixes(family, ...values) {
131
+ if (family === "claude-gpt") return ["claude", "gpt"];
132
+ if (family === "argon") return argonPrefixes(...values);
133
+ if (family === "gemini") return ["gemini", "gemma"];
108
134
  return undefined;
109
135
  }
110
136
 
111
137
  function groupForModel(modelId, label) {
112
- const s = `${text(modelId)} ${text(label)}`.toLowerCase();
113
- if (s.includes("claude") || s.includes("gpt")) return GROUP_CLAUDE_GPT;
114
- if (s.includes("gemini") || s.includes("gemma")) return GROUP_GEMINI;
138
+ const family = textFamily(modelId) || textFamily(label);
139
+ if (family === "claude-gpt") return GROUP_CLAUDE_GPT;
140
+ if (family === "argon") return GROUP_ARGON;
141
+ if (family === "gemini") return GROUP_GEMINI;
115
142
  return GROUP_OTHER;
116
143
  }
117
144
 
@@ -133,19 +160,26 @@ function groupedQuotaWindows(body, idPrefix) {
133
160
  if (!isObj(group)) return;
134
161
  const groupLabel = firstText(group.displayName, group.display_name, group.name, `Quota Group ${groupIndex + 1}`);
135
162
  const groupId = text(group.id) || groupLabel.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || `group-${groupIndex + 1}`;
136
- const prefixes = groupPrefixes(`${groupLabel} ${text(group.description)}`);
163
+ // The group's own name decides its family; its description (a model list
164
+ // that may mention Argon among the Gemini models) only when the name says nothing.
165
+ const groupFamily = textFamily(groupLabel) || textFamily(group.description);
137
166
  const buckets = Array.isArray(group.buckets) ? group.buckets : [];
138
167
  buckets.forEach((bucket, bucketIndex) => {
139
168
  if (!isObj(bucket)) return;
140
169
  const remaining = fractionPercent(bucket.remainingFraction ?? bucket.remaining_fraction);
141
170
  const resetAt = isoFromString(firstText(bucket.resetTime, bucket.reset_time));
142
171
  if (remaining === null && resetAt === null) return;
143
- const label = firstText(bucket.displayName, bucket.display_name, bucket.label, bucket.description, bucket.window);
144
- const kind = kindFromText(bucket.window, bucket.windowType, bucket.window_type, label)
172
+ const bucketId = firstText(bucket.bucketId, bucket.bucket_id);
173
+ const label = firstText(bucket.displayName, bucket.display_name, bucket.label, bucket.description, bucket.window, bucketId);
174
+ const kind = kindFromText(bucket.window, bucket.windowType, bucket.window_type, label, bucketId)
145
175
  || kindFromSeconds(bucket.windowSeconds ?? bucket.window_seconds ?? bucket.limitWindowSeconds ?? bucket.limit_window_seconds)
146
176
  || "other";
177
+ // An Argon bucket (e.g. an Argon weekly limit inside the Gemini group)
178
+ // covers only the Argon models; any other bucket covers its group.
179
+ const argonBucket = textFamily(`${bucketId} ${label}`) === "argon";
180
+ const prefixes = argonBucket ? argonPrefixes(bucketId, label, groupLabel) : familyPrefixes(groupFamily, groupLabel);
147
181
  rows.push(makeWindow({
148
- id: `${idPrefix}:${groupId}:${firstText(bucket.bucketId, bucket.bucket_id, `${kind}-${bucketIndex + 1}`)}`,
182
+ id: `${idPrefix}:${groupId}:${firstText(bucketId, `${kind}-${bucketIndex + 1}`)}`,
149
183
  kind,
150
184
  label,
151
185
  group: groupLabel,
@@ -158,31 +192,63 @@ function groupedQuotaWindows(body, idPrefix) {
158
192
  return rows;
159
193
  }
160
194
 
195
+ const FAMILY_OF_GROUP = { [GROUP_CLAUDE_GPT]: "claude-gpt", [GROUP_ARGON]: "argon", [GROUP_GEMINI]: "gemini" };
196
+
197
+ /**
198
+ * Antigravity `fetchAvailableModels`: per-model quotaInfo keyed by the public
199
+ * model id (`modelId` there is an internal placeholder). Models of one family
200
+ * (Claude/GPT, Gemini Argon, other Gemini) that report the same quota share
201
+ * one pool: that pool becomes a single family window matched by prefix, so
202
+ * models the list omits (CPA serves more Gemini ids than Antigravity lists)
203
+ * still find it. Families with diverging values keep one window per pool,
204
+ * matched by exact id. Internal tab/chat completion models are skipped.
205
+ */
161
206
  function antigravityModelWindows(body, nowMs) {
162
207
  const models = body.models;
163
208
  if (models === null || typeof models !== "object") return [];
164
209
  const entries = Array.isArray(models) ? models.map((raw, i) => [String(i), raw]) : Object.entries(models);
165
- const rows = [];
210
+ const families = new Map();
166
211
  for (const [key, raw] of entries) {
167
- if (!isObj(raw)) continue;
168
- const modelId = firstText(raw.modelId, raw.model_id, raw.id, raw.model, Array.isArray(models) ? "" : key, raw.name);
169
- if (modelId === "") continue;
212
+ if (!isObj(raw) || flagOf(raw.isInternal ?? raw.is_internal) === true) continue;
213
+ const modelId = Array.isArray(models)
214
+ ? firstText(raw.id, raw.model_id, raw.modelId, raw.model, raw.name)
215
+ : firstText(key, raw.id, raw.model_id, raw.modelId, raw.model, raw.name);
216
+ if (modelId === "" || /^(?:chat|tab)_/i.test(modelId)) continue;
170
217
  const quota = isObj(raw.quotaInfo) ? raw.quotaInfo : isObj(raw.quota_info) ? raw.quota_info : raw;
171
218
  let remaining = fractionPercent(quota.remainingFraction ?? quota.remaining_fraction ?? quota.remaining);
172
219
  const amount = numberOrNull(quota.remainingAmount ?? quota.remaining_amount);
173
220
  const resetAt = isoFromString(firstText(quota.resetTime, quota.reset_time, raw.resetTime, raw.reset_time));
174
221
  if (remaining === null && amount !== null && amount <= 0) remaining = 0;
175
222
  if (remaining === null && resetAt === null) continue;
176
- const label = firstText(raw.displayName, raw.display_name, raw.name);
177
- rows.push(makeWindow({
178
- id: `ag-model:${modelId}`,
179
- kind: kindFromReset(resetAt, nowMs),
180
- label,
181
- group: groupForModel(modelId, label),
182
- remainingPercent: remaining,
183
- resetAt,
184
- modelIds: [modelId],
185
- }));
223
+ const label = firstText(raw.displayName, raw.display_name);
224
+ const group = groupForModel(modelId, label);
225
+ if (group === GROUP_OTHER && label === "") continue;
226
+ const kind = kindFromReset(resetAt, nowMs);
227
+ const pct = roundPct(remaining);
228
+ if (!families.has(group)) families.set(group, new Map());
229
+ const pools = families.get(group);
230
+ const poolKey = `${kind}|${pct}|${resetAt ?? ""}`;
231
+ const pool = pools.get(poolKey);
232
+ if (pool === undefined) pools.set(poolKey, { kind, pct, resetAt, label, modelIds: [modelId] });
233
+ else if (!pool.modelIds.includes(modelId)) pool.modelIds.push(modelId);
234
+ }
235
+ const rows = [];
236
+ for (const [group, pools] of families) {
237
+ const list = [...pools.values()];
238
+ const prefixes = familyPrefixes(FAMILY_OF_GROUP[group], ...list.flatMap((pool) => pool.modelIds));
239
+ const familyKey = group.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
240
+ list.forEach((pool, index) => {
241
+ const shared = list.length === 1 && prefixes !== undefined;
242
+ rows.push(makeWindow({
243
+ id: shared ? `ag-model:${familyKey}` : `ag-model:${familyKey}:${index + 1}`,
244
+ kind: pool.kind,
245
+ label: shared || pool.modelIds.length > 1 ? "" : pool.label,
246
+ group,
247
+ remainingPercent: pool.pct,
248
+ resetAt: pool.resetAt,
249
+ ...(shared ? { modelPrefixes: prefixes } : { modelIds: pool.modelIds }),
250
+ }));
251
+ });
186
252
  }
187
253
  return rows;
188
254
  }
@@ -194,7 +260,7 @@ function googleBucketWindows(body, nowMs, idPrefix) {
194
260
  for (const bucket of buckets) {
195
261
  if (!isObj(bucket)) continue;
196
262
  const modelId = firstText(bucket.modelId, bucket.model_id).replace(/_vertex$/, "");
197
- if (!/^(?:gemini|gemma)/i.test(modelId)) continue;
263
+ if (!/^(?:gemini|gemma|argon)/i.test(modelId)) continue;
198
264
  const remaining = fractionPercent(bucket.remainingFraction ?? bucket.remaining_fraction ?? bucket.remaining);
199
265
  const resetAt = isoFromString(firstText(bucket.resetTime, bucket.reset_time));
200
266
  if (remaining === null && resetAt === null) continue;