dsh-cliproxyapi-pro 1.10.1 → 1.12.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.
@@ -16,6 +16,10 @@ export function pickAccount(resolved) {
16
16
  protocolMode: resolved.protocolMode,
17
17
  includePrefix: resolved.includePrefix,
18
18
  excludePrefix: resolved.excludePrefix,
19
+ sanitizePrompt: resolved.sanitizePrompt,
20
+ ...(resolved.sanitizePromptReplacement === undefined
21
+ ? {}
22
+ : { sanitizePromptReplacement: resolved.sanitizePromptReplacement }),
19
23
  ...(resolved.selectedModels === undefined ? {} : { selectedModels: resolved.selectedModels }),
20
24
  modelOverrides: resolved.modelOverrides,
21
25
  };
@@ -34,8 +38,8 @@ export function plainObject(value) {
34
38
 
35
39
  /**
36
40
  * Normalize the state file into `{ version, refreshIntervalSeconds,
37
- * probeTimeoutMs, onlineModelInfo, accounts[] }` (a file without
38
- * `onlineModelInfo` reads as on). A legacy single-account file (flat fields,
41
+ * probeTimeoutMs, onlineModelInfo, sidebarQuota, accounts[] }` (a file
42
+ * without `onlineModelInfo` / `sidebarQuota` reads as on). A legacy single-account file (flat fields,
39
43
  * no `accounts` array) becomes one account with id `default`, so its
40
44
  * provider route, key reference and model selection carry over unchanged.
41
45
  * Invalid or duplicate account ids are replaced with generated ones.
@@ -64,6 +68,7 @@ export function normalizeState(raw = {}) {
64
68
  refreshIntervalSeconds: globals.refreshIntervalSeconds,
65
69
  probeTimeoutMs: globals.probeTimeoutMs,
66
70
  onlineModelInfo: globals.onlineModelInfo,
71
+ sidebarQuota: globals.sidebarQuota,
67
72
  accounts,
68
73
  };
69
74
  }
@@ -7,6 +7,7 @@ import { outsideHmrTransaction } from "../apply-utils.js";
7
7
  import { toCredentialRef, getEnvValue } from "../config.js";
8
8
  import { createCpaController } from "../controller.js";
9
9
  import { createModelInfo } from "../model-info.js";
10
+ import { sanitizeAssembly } from "../prompt-sanitize.js";
10
11
 
11
12
  export function createController(shared) {
12
13
  const { ctx, readExistingPiAiRoute, readDefaultModel, readState, writeState, updateDirectory } = shared;
@@ -117,5 +118,28 @@ export function createController(shared) {
117
118
  onGlobalsChanged: () => reschedule(),
118
119
  });
119
120
 
121
+ // Some upstreams (Antigravity-backed Gemini accounts) return an unexplained
122
+ // 429 whenever the system prompt contains the exact phrase "DeepSeek
123
+ // Harness", and CPA cools the whole account down over that one rejection.
124
+ // The assemble waterfall is the last point where the prompt text is still
125
+ // editable; matching steps get a copy with the phrase rewritten. This fires
126
+ // once per model step, so the per-request work stays a regex over already
127
+ // built strings — a sanitizing failure degrades to the unsanitized prompt.
128
+ ctx.on("system-prompt/assemble", (assembly, context, next) => {
129
+ const provider = context?.modelSelection?.provider;
130
+ const replacement = typeof provider === "string" ? controller.sanitizePromptRoutes().get(provider) : undefined;
131
+ if (replacement === undefined) return next();
132
+ return next().then((resolved) => {
133
+ try {
134
+ return sanitizeAssembly(resolved, replacement);
135
+ } catch (error) {
136
+ ctx.logger?.warn?.(
137
+ `dsh-cliproxyapi: prompt sanitizing failed, sending the prompt unchanged: ${error instanceof Error ? error.message : String(error)}`
138
+ );
139
+ return resolved;
140
+ }
141
+ });
142
+ });
143
+
120
144
  return { resolveApiKey, describeApiKey, reschedule, mediaSettingsPath, readMedia, controller, modelInfo };
121
145
  }
@@ -5,7 +5,7 @@ import { dirname, join } from "node:path";
5
5
  import { createQuotaController } from "../../quota/index.js";
6
6
 
7
7
  export function createQuotaService(shared) {
8
- const { ctx, resolveApiKey, describeApiKey, controller, updateDirectory } = shared;
8
+ const { ctx, resolveApiKey, describeApiKey, controller, updateDirectory, readState } = shared;
9
9
  // Quota ("额度" tab + composer badge): management keys live in the
10
10
  // credentials service under their own refs, never in account state.
11
11
  // Consecutive management-key rejections per account (never the key itself),
@@ -22,6 +22,7 @@ export function createQuotaService(shared) {
22
22
  },
23
23
  },
24
24
  listAccounts: () => controller.quotaAccounts(),
25
+ sidebar: () => readState().sidebarQuota !== false,
25
26
  resolveKey: (ref) => resolveApiKey(ref),
26
27
  describeKey: (ref) => describeApiKey(ref),
27
28
  setKey: async (ref, value) => {
@@ -28,6 +28,8 @@ export function accountPatchFromInput(input) {
28
28
  if (typeof input[field] === "string") patch[field] = input[field];
29
29
  }
30
30
  if (typeof input.enabled === "boolean") patch.enabled = input.enabled;
31
+ if (typeof input.sanitizePrompt === "boolean") patch.sanitizePrompt = input.sanitizePrompt;
32
+ if (typeof input.sanitizePromptReplacement === "string") patch.sanitizePromptReplacement = input.sanitizePromptReplacement;
31
33
  if (Array.isArray(input.selectedModels)) patch.selectedModels = input.selectedModels;
32
34
  if (plainObject(input.modelOverrides) !== undefined) patch.modelOverrides = input.modelOverrides;
33
35
  if (typeof input.apiKey === "string" && input.apiKey.trim() !== "") patch.apiKey = input.apiKey.trim();
@@ -25,12 +25,15 @@ export const ACCOUNT_FIELDS = [
25
25
  "excludePrefix",
26
26
  "selectedModels",
27
27
  "modelOverrides",
28
+ "sanitizePrompt",
29
+ "sanitizePromptReplacement",
28
30
  ];
29
31
  /**
30
32
  * All-account settings. `onlineModelInfo` (default on) lets recommendations
31
33
  * use public model catalogs (lib/host/model-info.js); download only.
34
+ * `sidebarQuota` (default on) shows the quota entry in the DSH sidebar footer.
32
35
  */
33
- export const GLOBAL_FIELDS = ["refreshIntervalSeconds", "probeTimeoutMs", "onlineModelInfo"];
36
+ export const GLOBAL_FIELDS = ["refreshIntervalSeconds", "probeTimeoutMs", "onlineModelInfo", "sidebarQuota"];
34
37
  export const DEFAULT_REFRESH_INTERVAL_SECONDS = 300;
35
38
  export const DEFAULT_PROBE_TIMEOUT_MS = 5000;
36
39
 
@@ -197,8 +200,16 @@ export function resolveConfig(rawConfig = {}) {
197
200
  refreshIntervalSeconds,
198
201
  probeTimeoutMs,
199
202
  onlineModelInfo: readVolatile(rawConfig?.onlineModelInfo, true) !== false,
203
+ sidebarQuota: readVolatile(rawConfig?.sidebarQuota, true) !== false,
200
204
  includePrefix,
201
205
  excludePrefix,
206
+ // On by default: rewrite upstream-triggering brand phrases in the assembled
207
+ // system prompt for this account's routes (see lib/host/prompt-sanitize.js).
208
+ sanitizePrompt: readVolatile(rawConfig?.sanitizePrompt, true) === true,
209
+ // Optional custom text substituted for the phrase; omitted when unset.
210
+ ...(String(readVolatile(rawConfig?.sanitizePromptReplacement, "")).trim() !== ""
211
+ ? { sanitizePromptReplacement: String(readVolatile(rawConfig?.sanitizePromptReplacement, "")).trim() }
212
+ : {}),
202
213
  ...(selectedModels === undefined ? {} : { selectedModels }),
203
214
  modelOverrides,
204
215
  };
@@ -5,6 +5,7 @@ import { DEFAULT_API_KEY_ENV, GLOBAL_FIELDS, toCredentialRef, resolveConfig } fr
5
5
  import { planRecommendations, selectionSuggestions } from "./recommend.js";
6
6
  import { isChatModel, managedRouteKeys } from "./routes.js";
7
7
  import { pickFields, normalizeState, accountConflicts, assertNoConflicts, newAccountDefaults, patchAccount } from "./accounts.js";
8
+ import { sanitizeReplacement } from "./prompt-sanitize.js";
8
9
  import { normalizeCpaRoot, discoverCpa } from "./discovery.js";
9
10
  import { CpaRuntime } from "./runtime.js";
10
11
 
@@ -204,6 +205,7 @@ export function createCpaController(deps) {
204
205
  refreshIntervalSeconds: state.refreshIntervalSeconds,
205
206
  probeTimeoutMs: state.probeTimeoutMs,
206
207
  onlineModelInfo: state.onlineModelInfo !== false,
208
+ sidebarQuota: state.sidebarQuota !== false,
207
209
  ...(deps.modelInfo === undefined ? {} : { modelInfo: deps.modelInfo.status() }),
208
210
  },
209
211
  accounts,
@@ -239,6 +241,23 @@ export function createCpaController(deps) {
239
241
  statusPayload,
240
242
  findAccount: (ref) => findAccount(deps.readState(), ref),
241
243
 
244
+ /**
245
+ * Route keys whose requests get a sanitized system prompt, mapped to the
246
+ * phrase replacement each account configured: every managed route of each
247
+ * account that switched the workaround on (its base route plus
248
+ * `-responses` / `-messages` siblings). A blank configured value resolves
249
+ * to the default in lib/host/prompt-sanitize.js.
250
+ */
251
+ sanitizePromptRoutes() {
252
+ const routes = new Map();
253
+ for (const account of deps.readState().accounts) {
254
+ if (account.sanitizePrompt !== true) continue;
255
+ const replacement = sanitizeReplacement(account.sanitizePromptReplacement);
256
+ for (const key of managedRouteKeys(account.provider)) routes.set(key, replacement);
257
+ }
258
+ return routes;
259
+ },
260
+
242
261
  /** Refresh every account (no catalog probe for disabled ones). */
243
262
  async refreshAll(options = {}) {
244
263
  const state = deps.readState();
@@ -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
+ }
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"];
@@ -339,6 +337,8 @@ export function createQuotaController(deps) {
339
337
  return {
340
338
  generatedAt: new Date(now()).toISOString(),
341
339
  refreshing: out.some((a) => a.refreshing),
340
+ // The global sidebar switch, so the page learns it from the same read.
341
+ sidebar: deps.sidebar?.() !== false,
342
342
  accounts: out,
343
343
  };
344
344
  }
@@ -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;