opencode-ag-quota 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +54 -0
- package/dist/auth.d.ts +14 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +99 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/plugin.d.ts +4 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +263 -0
- package/package.json +59 -0
- package/src/auth.ts +151 -0
- package/src/index.ts +3 -0
- package/src/plugin.ts +311 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Philipp
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# opencode-ag-quota
|
|
2
|
+
|
|
3
|
+
Opencode plugin that shows your **Antigravity quota** inside the Opencode TUI.
|
|
4
|
+
|
|
5
|
+
## TL;DR
|
|
6
|
+
|
|
7
|
+
- Installs as an Opencode plugin (`"opencode-ag-quota"`).
|
|
8
|
+
- **Antigravity-only for now** (quota is shown only when the model ID contains `antigravity`).
|
|
9
|
+
- Cloud mode uses `opencode auth login` credentials (auth/API approach based on [`opencode-antigravity-auth`](https://github.com/NoeFabris/opencode-antigravity-auth)).
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
Add the plugin to your Opencode config (`opencode.json`):
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"plugin": ["opencode-ag-quota"]
|
|
18
|
+
}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Configuration
|
|
22
|
+
|
|
23
|
+
Zero-config by default. Customize via:
|
|
24
|
+
|
|
25
|
+
- Project: `.opencode/ag-quota.json`
|
|
26
|
+
- Global: `~/.config/opencode/ag-quota.json`
|
|
27
|
+
|
|
28
|
+
```json
|
|
29
|
+
{
|
|
30
|
+
"quotaSource": "auto",
|
|
31
|
+
"format": "{category}: {percent}% ({resetIn})",
|
|
32
|
+
"separator": " | ",
|
|
33
|
+
"displayMode": "all",
|
|
34
|
+
"alwaysAppend": true
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Options
|
|
39
|
+
|
|
40
|
+
| Option | Type | Default | Description |
|
|
41
|
+
|--------|------|---------|-------------|
|
|
42
|
+
| `quotaSource` | `"auto" \| "cloud" \| "local"` | `"auto"` | `auto` tries cloud first, falls back to local. |
|
|
43
|
+
| `format` | `string` | `"{category}: {percent}% ({resetIn})"` | Placeholders: `{category}`, `{percent}`, `{resetIn}`, `{resetAt}`, `{model}`. |
|
|
44
|
+
| `separator` | `string` | `" | "` | Separator when `displayMode` is `all`. |
|
|
45
|
+
| `displayMode` | `"all" \| "current"` | `"all"` | Show all quotas or only the current model's quota. |
|
|
46
|
+
| `alwaysAppend` | `boolean` | `true` | Show an "Unavailable" hint when quota can't be read. |
|
|
47
|
+
|
|
48
|
+
## Disclaimer
|
|
49
|
+
|
|
50
|
+
This is an independent, third-party plugin for Opencode. It is not affiliated with, endorsed by, or maintained by the Opencode developers.
|
|
51
|
+
|
|
52
|
+
## License
|
|
53
|
+
|
|
54
|
+
MIT
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface CloudAuthCredentials {
|
|
2
|
+
accessToken: string;
|
|
3
|
+
projectId?: string;
|
|
4
|
+
email: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Check if cloud credentials are available.
|
|
8
|
+
*/
|
|
9
|
+
export declare function hasCloudCredentials(): Promise<boolean>;
|
|
10
|
+
/**
|
|
11
|
+
* Get a valid access token and project ID from the stored accounts.
|
|
12
|
+
*/
|
|
13
|
+
export declare function getCloudCredentials(): Promise<CloudAuthCredentials>;
|
|
14
|
+
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAsCA,MAAM,WAAW,oBAAoB;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;CACjB;AAwCD;;GAEG;AACH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,OAAO,CAAC,CAO5D;AAqCD;;GAEG;AACH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,oBAAoB,CAAC,CAkBzE"}
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
// ============================================================================
|
|
5
|
+
// Constants
|
|
6
|
+
// ============================================================================
|
|
7
|
+
const ANTIGRAVITY_CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
|
|
8
|
+
const ANTIGRAVITY_CLIENT_SECRET = "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";
|
|
9
|
+
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// Account Loading
|
|
12
|
+
// ============================================================================
|
|
13
|
+
/**
|
|
14
|
+
* Get the path to the antigravity accounts file.
|
|
15
|
+
*/
|
|
16
|
+
function getAccountsFilePath() {
|
|
17
|
+
return join(homedir(), ".config", "opencode", "antigravity-accounts.json");
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Load accounts from the opencode-antigravity-auth plugin.
|
|
21
|
+
* @throws Error if no accounts file exists or no accounts are configured
|
|
22
|
+
*/
|
|
23
|
+
async function loadAccounts() {
|
|
24
|
+
const accountsPath = getAccountsFilePath();
|
|
25
|
+
try {
|
|
26
|
+
const content = await readFile(accountsPath, "utf-8");
|
|
27
|
+
const data = JSON.parse(content);
|
|
28
|
+
if (!data.accounts || data.accounts.length === 0) {
|
|
29
|
+
throw new Error("No accounts found in antigravity-accounts.json");
|
|
30
|
+
}
|
|
31
|
+
return data;
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error.code === "ENOENT") {
|
|
35
|
+
throw new Error(`Antigravity accounts file not found.\n` +
|
|
36
|
+
`Run 'opencode auth login' first to authenticate with Google.`);
|
|
37
|
+
}
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Check if cloud credentials are available.
|
|
43
|
+
*/
|
|
44
|
+
export async function hasCloudCredentials() {
|
|
45
|
+
try {
|
|
46
|
+
await loadAccounts();
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// ============================================================================
|
|
54
|
+
// Token Refresh
|
|
55
|
+
// ============================================================================
|
|
56
|
+
/**
|
|
57
|
+
* Exchange a refresh token for an access token.
|
|
58
|
+
*/
|
|
59
|
+
async function refreshAccessToken(refreshToken) {
|
|
60
|
+
const response = await fetch(TOKEN_URL, {
|
|
61
|
+
method: "POST",
|
|
62
|
+
headers: {
|
|
63
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
64
|
+
},
|
|
65
|
+
body: new URLSearchParams({
|
|
66
|
+
client_id: ANTIGRAVITY_CLIENT_ID,
|
|
67
|
+
client_secret: ANTIGRAVITY_CLIENT_SECRET,
|
|
68
|
+
refresh_token: refreshToken,
|
|
69
|
+
grant_type: "refresh_token",
|
|
70
|
+
}).toString(),
|
|
71
|
+
});
|
|
72
|
+
if (!response.ok) {
|
|
73
|
+
const errorText = await response.text();
|
|
74
|
+
if (errorText.toLowerCase().includes("invalid_grant")) {
|
|
75
|
+
throw new Error("Refresh token is invalid or expired. Run 'opencode auth login' to re-authenticate.");
|
|
76
|
+
}
|
|
77
|
+
throw new Error(`Token refresh failed: ${response.status} - ${errorText}`);
|
|
78
|
+
}
|
|
79
|
+
const data = (await response.json());
|
|
80
|
+
return data.access_token;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Get a valid access token and project ID from the stored accounts.
|
|
84
|
+
*/
|
|
85
|
+
export async function getCloudCredentials() {
|
|
86
|
+
// Load accounts
|
|
87
|
+
const accountsFile = await loadAccounts();
|
|
88
|
+
const activeAccount = accountsFile.accounts[accountsFile.activeIndex] ?? accountsFile.accounts[0];
|
|
89
|
+
if (!activeAccount) {
|
|
90
|
+
throw new Error("No active account found in antigravity-accounts.json");
|
|
91
|
+
}
|
|
92
|
+
// Get access token
|
|
93
|
+
const accessToken = await refreshAccessToken(activeAccount.refreshToken);
|
|
94
|
+
return {
|
|
95
|
+
accessToken,
|
|
96
|
+
projectId: activeAccount.projectId,
|
|
97
|
+
email: activeAccount.email,
|
|
98
|
+
};
|
|
99
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,MAAM,UAAU,CAAC;AAEnC,OAAO,EAAE,WAAW,EAAE,CAAC"}
|
package/dist/index.js
ADDED
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAYlD,eAAO,MAAM,WAAW,EAAE,MA+QzB,CAAC;AAEF,eAAe,WAAW,CAAC"}
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2026 Philipp
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
|
21
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
|
22
|
+
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
23
|
+
* DEALINGS IN THE SOFTWARE.
|
|
24
|
+
*/
|
|
25
|
+
import { fetchQuota, formatRelativeTime, formatAbsoluteTime, loadConfig, formatQuotaEntry, } from "ag-quota";
|
|
26
|
+
import { getCloudCredentials } from "./auth";
|
|
27
|
+
export const QuotaPlugin = async ({ client, directory, $ }) => {
|
|
28
|
+
// Load configuration (loadConfig always returns Required<QuotaConfig> with defaults)
|
|
29
|
+
const config = await loadConfig(directory);
|
|
30
|
+
// Use Bun's $ shell helper from opencode
|
|
31
|
+
const shellRunner = async (cmd) => {
|
|
32
|
+
try {
|
|
33
|
+
const result = await $ `sh -c ${cmd}`.quiet().text();
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return "";
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
let quotaState = {
|
|
41
|
+
data: null,
|
|
42
|
+
lastAlertLevel: 1.0,
|
|
43
|
+
isConnected: false,
|
|
44
|
+
currentSource: null,
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Check if a model ID is an Antigravity model (quota tracking applies).
|
|
48
|
+
*/
|
|
49
|
+
const isAntigravityModel = (modelID) => {
|
|
50
|
+
return modelID.toLowerCase().includes("antigravity");
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Get the last assistant message's model ID from a session
|
|
54
|
+
*/
|
|
55
|
+
const getLastAssistantModelID = async (sessionID) => {
|
|
56
|
+
try {
|
|
57
|
+
const response = await client.session.messages({
|
|
58
|
+
path: { id: sessionID },
|
|
59
|
+
query: { limit: 10 }, // Get recent messages, we just need the last assistant one
|
|
60
|
+
});
|
|
61
|
+
if (!response.data)
|
|
62
|
+
return null;
|
|
63
|
+
// Find the last assistant message (iterate in reverse)
|
|
64
|
+
for (let i = response.data.length - 1; i >= 0; i--) {
|
|
65
|
+
const msg = response.data[i];
|
|
66
|
+
if (msg.info.role === "assistant" && msg.info.modelID) {
|
|
67
|
+
return msg.info.modelID;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Get the indicator symbol for a given remaining fraction based on config.
|
|
78
|
+
*/
|
|
79
|
+
const getIndicatorSymbol = (fraction) => {
|
|
80
|
+
if (!config.indicators || config.indicators.length === 0)
|
|
81
|
+
return "";
|
|
82
|
+
// Sort by threshold ascending to find the most severe (lowest threshold met)
|
|
83
|
+
const sorted = [...config.indicators].sort((a, b) => a.threshold - b.threshold);
|
|
84
|
+
for (const indicator of sorted) {
|
|
85
|
+
if (fraction <= indicator.threshold) {
|
|
86
|
+
return ` ${indicator.symbol}`;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return "";
|
|
90
|
+
};
|
|
91
|
+
const buildQuotaSummary = (quotaResult, modelID, separator) => {
|
|
92
|
+
if (config.displayMode === "current" && modelID) {
|
|
93
|
+
// Find the model that matches the last used model
|
|
94
|
+
const currentModel = quotaResult.models.find((m) => m.modelName === modelID ||
|
|
95
|
+
modelID.includes(m.modelName) ||
|
|
96
|
+
(m.label && modelID.toLowerCase().includes(m.label.toLowerCase())) ||
|
|
97
|
+
(m.label && m.label.toLowerCase().includes(modelID.toLowerCase())));
|
|
98
|
+
if (currentModel?.quotaInfo) {
|
|
99
|
+
const fraction = currentModel.quotaInfo.remainingFraction;
|
|
100
|
+
const percent = (typeof fraction === "number" && Number.isFinite(fraction)
|
|
101
|
+
? fraction * 100
|
|
102
|
+
: 0).toFixed(1);
|
|
103
|
+
const resetDate = currentModel.quotaInfo.resetTime
|
|
104
|
+
? new Date(currentModel.quotaInfo.resetTime)
|
|
105
|
+
: null;
|
|
106
|
+
const displayPercent = `${percent}%${getIndicatorSymbol(fraction)}`;
|
|
107
|
+
return formatQuotaEntry(config.format, {
|
|
108
|
+
category: "Current",
|
|
109
|
+
percent: displayPercent,
|
|
110
|
+
resetIn: resetDate ? formatRelativeTime(resetDate) : null,
|
|
111
|
+
resetAt: resetDate ? formatAbsoluteTime(resetDate) : null,
|
|
112
|
+
model: currentModel.modelName,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const parts = [];
|
|
117
|
+
for (const cat of quotaResult.categories) {
|
|
118
|
+
const percent = (cat.remainingFraction * 100).toFixed(0);
|
|
119
|
+
const displayPercent = `${percent}%${getIndicatorSymbol(cat.remainingFraction)}`;
|
|
120
|
+
const formatted = formatQuotaEntry(config.format, {
|
|
121
|
+
category: cat.category,
|
|
122
|
+
percent: displayPercent,
|
|
123
|
+
resetIn: cat.resetTime ? formatRelativeTime(cat.resetTime) : null,
|
|
124
|
+
resetAt: cat.resetTime ? formatAbsoluteTime(cat.resetTime) : null,
|
|
125
|
+
model: modelID ?? "current",
|
|
126
|
+
});
|
|
127
|
+
parts.push(formatted);
|
|
128
|
+
}
|
|
129
|
+
return parts.join(separator ?? config.separator);
|
|
130
|
+
};
|
|
131
|
+
// Try to connect with the configured source
|
|
132
|
+
const tryConnect = async () => {
|
|
133
|
+
try {
|
|
134
|
+
let cloudAuth;
|
|
135
|
+
if (config.quotaSource !== "local") {
|
|
136
|
+
try {
|
|
137
|
+
cloudAuth = await getCloudCredentials();
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// If cloud auth fails but source is auto, we'll continue to local
|
|
141
|
+
if (config.quotaSource === "cloud")
|
|
142
|
+
throw new Error("Cloud auth failed");
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const result = await fetchQuota(config.quotaSource, shellRunner, cloudAuth);
|
|
146
|
+
quotaState.currentSource = result.source;
|
|
147
|
+
return result;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
/**
|
|
154
|
+
* Check if we need to alert the user about low quota
|
|
155
|
+
*/
|
|
156
|
+
const checkAlerts = () => {
|
|
157
|
+
if (!quotaState.data)
|
|
158
|
+
return;
|
|
159
|
+
// Find lowest category fraction
|
|
160
|
+
let minFraction = 1.0;
|
|
161
|
+
for (const cat of quotaState.data.categories) {
|
|
162
|
+
if (cat.remainingFraction < minFraction) {
|
|
163
|
+
minFraction = cat.remainingFraction;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
// Check against thresholds (ascending order).
|
|
167
|
+
// We want to show the most severe (lowest) warning once when crossing multiple levels.
|
|
168
|
+
const thresholds = [...config.alertThresholds].sort((a, b) => a - b);
|
|
169
|
+
for (const threshold of thresholds) {
|
|
170
|
+
// If we dropped below this threshold AND haven't alerted for it yet
|
|
171
|
+
if (minFraction <= threshold && quotaState.lastAlertLevel > threshold) {
|
|
172
|
+
// Use buildQuotaSummary for consistent formatting across all toasts
|
|
173
|
+
const summary = buildQuotaSummary(quotaState.data, undefined, "\n");
|
|
174
|
+
client.tui.showToast({
|
|
175
|
+
body: {
|
|
176
|
+
title: "Low Quota Warning",
|
|
177
|
+
message: `Below ${(threshold * 100).toFixed(0)}% threshold.\n\n${summary}`,
|
|
178
|
+
variant: "warning",
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
quotaState.lastAlertLevel = threshold;
|
|
182
|
+
break; // Only one alert per drop
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
// If quota went back up (reset), reset alert level
|
|
186
|
+
if (minFraction > quotaState.lastAlertLevel) {
|
|
187
|
+
quotaState.lastAlertLevel = 1.0;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
/**
|
|
191
|
+
* Start background polling loop
|
|
192
|
+
*/
|
|
193
|
+
const startPolling = async () => {
|
|
194
|
+
// Fetch quota
|
|
195
|
+
const result = await tryConnect();
|
|
196
|
+
if (result) {
|
|
197
|
+
if (!quotaState.isConnected) {
|
|
198
|
+
// Just became connected
|
|
199
|
+
quotaState.isConnected = true;
|
|
200
|
+
const sourceLabel = quotaState.currentSource === "cloud" ? "Cloud API" : "Language Server";
|
|
201
|
+
const summary = buildQuotaSummary(result, undefined, "\n") || "unknown";
|
|
202
|
+
client.tui.showToast({
|
|
203
|
+
body: {
|
|
204
|
+
title: "AG Quota",
|
|
205
|
+
message: `Connected via ${sourceLabel}.\n${summary}`,
|
|
206
|
+
variant: "success",
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
quotaState.data = result;
|
|
211
|
+
quotaState.currentSource = result.source;
|
|
212
|
+
checkAlerts();
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
if (quotaState.isConnected) {
|
|
216
|
+
// Just became disconnected
|
|
217
|
+
quotaState.isConnected = false;
|
|
218
|
+
quotaState.currentSource = null;
|
|
219
|
+
client.tui.showToast({
|
|
220
|
+
body: {
|
|
221
|
+
title: "Quota Disconnected",
|
|
222
|
+
message: "Quota connection lost",
|
|
223
|
+
variant: "warning",
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// Schedule next poll
|
|
229
|
+
setTimeout(startPolling, config.pollingInterval);
|
|
230
|
+
};
|
|
231
|
+
// Start polling immediately
|
|
232
|
+
startPolling();
|
|
233
|
+
return {
|
|
234
|
+
event: async ({ event }) => {
|
|
235
|
+
// On session.idle, show quota toast if an Antigravity model was used
|
|
236
|
+
if (event.type === "session.idle") {
|
|
237
|
+
const { sessionID } = event.properties;
|
|
238
|
+
// Get the last assistant message's model ID from the session
|
|
239
|
+
const lastModelID = await getLastAssistantModelID(sessionID);
|
|
240
|
+
// Only show quota for Antigravity models (model ID contains "antigravity")
|
|
241
|
+
if (!lastModelID || !isAntigravityModel(lastModelID)) {
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
// Check if we have quota data
|
|
245
|
+
if (!quotaState.isConnected || !quotaState.data) {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
// Build and show quota summary
|
|
249
|
+
const summary = buildQuotaSummary(quotaState.data, lastModelID, "\n");
|
|
250
|
+
if (summary) {
|
|
251
|
+
client.tui.showToast({
|
|
252
|
+
body: {
|
|
253
|
+
title: "AG Quota",
|
|
254
|
+
message: summary,
|
|
255
|
+
variant: "info",
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
};
|
|
263
|
+
export default QuotaPlugin;
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "opencode-ag-quota",
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Opencode plugin to display Antigravity/Windsurf quotas",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"src",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc",
|
|
22
|
+
"prepublishOnly": "bun run build",
|
|
23
|
+
"typecheck": "tsc --noEmit"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"opencode",
|
|
27
|
+
"plugin",
|
|
28
|
+
"antigravity",
|
|
29
|
+
"windsurf",
|
|
30
|
+
"quota",
|
|
31
|
+
"codeium"
|
|
32
|
+
],
|
|
33
|
+
"author": "Philipp",
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/phibkro/opencode-quota-display.git",
|
|
38
|
+
"directory": "packages/opencode-ag-quota"
|
|
39
|
+
},
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/phibkro/opencode-quota-display/issues"
|
|
42
|
+
},
|
|
43
|
+
"homepage": "https://github.com/phibkro/opencode-quota-display/tree/main/packages/opencode-ag-quota#readme",
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=18"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"ag-quota": "^0.0.2"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@opencode-ai/plugin": "^1.1.3",
|
|
52
|
+
"@opencode-ai/sdk": "^1.1.3",
|
|
53
|
+
"@types/node": "^22.0.0",
|
|
54
|
+
"typescript": "^5.9.3"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"@opencode-ai/plugin": "^1.0.0"
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
// ============================================================================
|
|
6
|
+
// Constants
|
|
7
|
+
// ============================================================================
|
|
8
|
+
|
|
9
|
+
const ANTIGRAVITY_CLIENT_ID =
|
|
10
|
+
"1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
|
|
11
|
+
const ANTIGRAVITY_CLIENT_SECRET = "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";
|
|
12
|
+
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
13
|
+
|
|
14
|
+
// ============================================================================
|
|
15
|
+
// Types
|
|
16
|
+
// ============================================================================
|
|
17
|
+
|
|
18
|
+
interface StoredAccount {
|
|
19
|
+
email: string;
|
|
20
|
+
refreshToken: string;
|
|
21
|
+
projectId?: string;
|
|
22
|
+
managedProjectId?: string;
|
|
23
|
+
addedAt: number;
|
|
24
|
+
lastUsed: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface AccountsFile {
|
|
28
|
+
version: number;
|
|
29
|
+
accounts: StoredAccount[];
|
|
30
|
+
activeIndex: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface TokenResponse {
|
|
34
|
+
access_token: string;
|
|
35
|
+
expires_in: number;
|
|
36
|
+
token_type: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface CloudAuthCredentials {
|
|
40
|
+
accessToken: string;
|
|
41
|
+
projectId?: string;
|
|
42
|
+
email: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ============================================================================
|
|
46
|
+
// Account Loading
|
|
47
|
+
// ============================================================================
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Get the path to the antigravity accounts file.
|
|
51
|
+
*/
|
|
52
|
+
function getAccountsFilePath(): string {
|
|
53
|
+
return join(homedir(), ".config", "opencode", "antigravity-accounts.json");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Load accounts from the opencode-antigravity-auth plugin.
|
|
58
|
+
* @throws Error if no accounts file exists or no accounts are configured
|
|
59
|
+
*/
|
|
60
|
+
async function loadAccounts(): Promise<AccountsFile> {
|
|
61
|
+
const accountsPath = getAccountsFilePath();
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
const content = await readFile(accountsPath, "utf-8");
|
|
65
|
+
const data = JSON.parse(content) as AccountsFile;
|
|
66
|
+
|
|
67
|
+
if (!data.accounts || data.accounts.length === 0) {
|
|
68
|
+
throw new Error("No accounts found in antigravity-accounts.json");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return data;
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Antigravity accounts file not found.\n` +
|
|
76
|
+
`Run 'opencode auth login' first to authenticate with Google.`,
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Check if cloud credentials are available.
|
|
85
|
+
*/
|
|
86
|
+
export async function hasCloudCredentials(): Promise<boolean> {
|
|
87
|
+
try {
|
|
88
|
+
await loadAccounts();
|
|
89
|
+
return true;
|
|
90
|
+
} catch {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ============================================================================
|
|
96
|
+
// Token Refresh
|
|
97
|
+
// ============================================================================
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Exchange a refresh token for an access token.
|
|
101
|
+
*/
|
|
102
|
+
async function refreshAccessToken(refreshToken: string): Promise<string> {
|
|
103
|
+
const response = await fetch(TOKEN_URL, {
|
|
104
|
+
method: "POST",
|
|
105
|
+
headers: {
|
|
106
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
107
|
+
},
|
|
108
|
+
body: new URLSearchParams({
|
|
109
|
+
client_id: ANTIGRAVITY_CLIENT_ID,
|
|
110
|
+
client_secret: ANTIGRAVITY_CLIENT_SECRET,
|
|
111
|
+
refresh_token: refreshToken,
|
|
112
|
+
grant_type: "refresh_token",
|
|
113
|
+
}).toString(),
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
if (!response.ok) {
|
|
117
|
+
const errorText = await response.text();
|
|
118
|
+
if (errorText.toLowerCase().includes("invalid_grant")) {
|
|
119
|
+
throw new Error(
|
|
120
|
+
"Refresh token is invalid or expired. Run 'opencode auth login' to re-authenticate.",
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
throw new Error(`Token refresh failed: ${response.status} - ${errorText}`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const data = (await response.json()) as TokenResponse;
|
|
127
|
+
return data.access_token;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Get a valid access token and project ID from the stored accounts.
|
|
132
|
+
*/
|
|
133
|
+
export async function getCloudCredentials(): Promise<CloudAuthCredentials> {
|
|
134
|
+
// Load accounts
|
|
135
|
+
const accountsFile = await loadAccounts();
|
|
136
|
+
const activeAccount =
|
|
137
|
+
accountsFile.accounts[accountsFile.activeIndex] ?? accountsFile.accounts[0];
|
|
138
|
+
|
|
139
|
+
if (!activeAccount) {
|
|
140
|
+
throw new Error("No active account found in antigravity-accounts.json");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Get access token
|
|
144
|
+
const accessToken = await refreshAccessToken(activeAccount.refreshToken);
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
accessToken,
|
|
148
|
+
projectId: activeAccount.projectId,
|
|
149
|
+
email: activeAccount.email,
|
|
150
|
+
};
|
|
151
|
+
}
|
package/src/index.ts
ADDED
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2026 Philipp
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
|
21
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
|
22
|
+
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
23
|
+
* DEALINGS IN THE SOFTWARE.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { type Plugin } from "@opencode-ai/plugin";
|
|
27
|
+
import {
|
|
28
|
+
fetchQuota,
|
|
29
|
+
formatRelativeTime,
|
|
30
|
+
formatAbsoluteTime,
|
|
31
|
+
loadConfig,
|
|
32
|
+
formatQuotaEntry,
|
|
33
|
+
type ShellRunner,
|
|
34
|
+
type UnifiedQuotaResult,
|
|
35
|
+
} from "ag-quota";
|
|
36
|
+
import { getCloudCredentials } from "./auth";
|
|
37
|
+
|
|
38
|
+
export const QuotaPlugin: Plugin = async ({ client, directory, $ }) => {
|
|
39
|
+
// Load configuration (loadConfig always returns Required<QuotaConfig> with defaults)
|
|
40
|
+
const config = await loadConfig(directory);
|
|
41
|
+
|
|
42
|
+
// Use Bun's $ shell helper from opencode
|
|
43
|
+
const shellRunner: ShellRunner = async (cmd: string) => {
|
|
44
|
+
try {
|
|
45
|
+
const result = await $`sh -c ${cmd}`.quiet().text();
|
|
46
|
+
return result;
|
|
47
|
+
} catch {
|
|
48
|
+
return "";
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Connection state
|
|
53
|
+
interface PluginState {
|
|
54
|
+
data: UnifiedQuotaResult | null;
|
|
55
|
+
lastAlertLevel: number; // Start at 1.0 (100%)
|
|
56
|
+
isConnected: boolean;
|
|
57
|
+
currentSource: "cloud" | "local" | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
let quotaState: PluginState = {
|
|
61
|
+
data: null,
|
|
62
|
+
lastAlertLevel: 1.0,
|
|
63
|
+
isConnected: false,
|
|
64
|
+
currentSource: null,
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Check if a model ID is an Antigravity model (quota tracking applies).
|
|
69
|
+
*/
|
|
70
|
+
const isAntigravityModel = (modelID: string): boolean => {
|
|
71
|
+
return modelID.toLowerCase().includes("antigravity");
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Get the last assistant message's model ID from a session
|
|
76
|
+
*/
|
|
77
|
+
const getLastAssistantModelID = async (sessionID: string): Promise<string | null> => {
|
|
78
|
+
try {
|
|
79
|
+
const response = await client.session.messages({
|
|
80
|
+
path: { id: sessionID },
|
|
81
|
+
query: { limit: 10 }, // Get recent messages, we just need the last assistant one
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
if (!response.data) return null;
|
|
85
|
+
|
|
86
|
+
// Find the last assistant message (iterate in reverse)
|
|
87
|
+
for (let i = response.data.length - 1; i >= 0; i--) {
|
|
88
|
+
const msg = response.data[i];
|
|
89
|
+
if (msg.info.role === "assistant" && msg.info.modelID) {
|
|
90
|
+
return msg.info.modelID;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return null;
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Get the indicator symbol for a given remaining fraction based on config.
|
|
102
|
+
*/
|
|
103
|
+
const getIndicatorSymbol = (fraction: number): string => {
|
|
104
|
+
if (!config.indicators || config.indicators.length === 0) return "";
|
|
105
|
+
// Sort by threshold ascending to find the most severe (lowest threshold met)
|
|
106
|
+
const sorted = [...config.indicators].sort((a, b) => a.threshold - b.threshold);
|
|
107
|
+
for (const indicator of sorted) {
|
|
108
|
+
if (fraction <= indicator.threshold) {
|
|
109
|
+
return ` ${indicator.symbol}`;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return "";
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const buildQuotaSummary = (quotaResult: UnifiedQuotaResult, modelID?: string, separator?: string): string => {
|
|
116
|
+
if (config.displayMode === "current" && modelID) {
|
|
117
|
+
// Find the model that matches the last used model
|
|
118
|
+
const currentModel = quotaResult.models.find(
|
|
119
|
+
(m) =>
|
|
120
|
+
m.modelName === modelID ||
|
|
121
|
+
modelID.includes(m.modelName) ||
|
|
122
|
+
(m.label && modelID.toLowerCase().includes(m.label.toLowerCase())) ||
|
|
123
|
+
(m.label && m.label.toLowerCase().includes(modelID.toLowerCase())),
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
if (currentModel?.quotaInfo) {
|
|
127
|
+
const fraction = currentModel.quotaInfo.remainingFraction;
|
|
128
|
+
const percent = (
|
|
129
|
+
typeof fraction === "number" && Number.isFinite(fraction)
|
|
130
|
+
? fraction * 100
|
|
131
|
+
: 0
|
|
132
|
+
).toFixed(1);
|
|
133
|
+
const resetDate = currentModel.quotaInfo.resetTime
|
|
134
|
+
? new Date(currentModel.quotaInfo.resetTime)
|
|
135
|
+
: null;
|
|
136
|
+
|
|
137
|
+
const displayPercent = `${percent}%${getIndicatorSymbol(fraction)}`;
|
|
138
|
+
|
|
139
|
+
return formatQuotaEntry(config.format, {
|
|
140
|
+
category: "Current",
|
|
141
|
+
percent: displayPercent,
|
|
142
|
+
resetIn: resetDate ? formatRelativeTime(resetDate) : null,
|
|
143
|
+
resetAt: resetDate ? formatAbsoluteTime(resetDate) : null,
|
|
144
|
+
model: currentModel.modelName,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const parts: string[] = [];
|
|
150
|
+
for (const cat of quotaResult.categories) {
|
|
151
|
+
const percent = (cat.remainingFraction * 100).toFixed(0);
|
|
152
|
+
const displayPercent = `${percent}%${getIndicatorSymbol(cat.remainingFraction)}`;
|
|
153
|
+
|
|
154
|
+
const formatted = formatQuotaEntry(config.format, {
|
|
155
|
+
category: cat.category,
|
|
156
|
+
percent: displayPercent,
|
|
157
|
+
resetIn: cat.resetTime ? formatRelativeTime(cat.resetTime) : null,
|
|
158
|
+
resetAt: cat.resetTime ? formatAbsoluteTime(cat.resetTime) : null,
|
|
159
|
+
model: modelID ?? "current",
|
|
160
|
+
});
|
|
161
|
+
parts.push(formatted);
|
|
162
|
+
}
|
|
163
|
+
return parts.join(separator ?? config.separator);
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
// Try to connect with the configured source
|
|
167
|
+
const tryConnect = async (): Promise<UnifiedQuotaResult | null> => {
|
|
168
|
+
try {
|
|
169
|
+
let cloudAuth;
|
|
170
|
+
if (config.quotaSource !== "local") {
|
|
171
|
+
try {
|
|
172
|
+
cloudAuth = await getCloudCredentials();
|
|
173
|
+
} catch {
|
|
174
|
+
// If cloud auth fails but source is auto, we'll continue to local
|
|
175
|
+
if (config.quotaSource === "cloud") throw new Error("Cloud auth failed");
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const result = await fetchQuota(config.quotaSource, shellRunner, cloudAuth);
|
|
180
|
+
quotaState.currentSource = result.source;
|
|
181
|
+
return result;
|
|
182
|
+
} catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Check if we need to alert the user about low quota
|
|
189
|
+
*/
|
|
190
|
+
const checkAlerts = () => {
|
|
191
|
+
if (!quotaState.data) return;
|
|
192
|
+
|
|
193
|
+
// Find lowest category fraction
|
|
194
|
+
let minFraction = 1.0;
|
|
195
|
+
for (const cat of quotaState.data.categories) {
|
|
196
|
+
if (cat.remainingFraction < minFraction) {
|
|
197
|
+
minFraction = cat.remainingFraction;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Check against thresholds (ascending order).
|
|
202
|
+
// We want to show the most severe (lowest) warning once when crossing multiple levels.
|
|
203
|
+
const thresholds = [...config.alertThresholds].sort((a, b) => a - b);
|
|
204
|
+
|
|
205
|
+
for (const threshold of thresholds) {
|
|
206
|
+
// If we dropped below this threshold AND haven't alerted for it yet
|
|
207
|
+
if (minFraction <= threshold && quotaState.lastAlertLevel > threshold) {
|
|
208
|
+
// Use buildQuotaSummary for consistent formatting across all toasts
|
|
209
|
+
const summary = buildQuotaSummary(quotaState.data, undefined, "\n");
|
|
210
|
+
|
|
211
|
+
client.tui.showToast({
|
|
212
|
+
body: {
|
|
213
|
+
title: "Low Quota Warning",
|
|
214
|
+
message: `Below ${(threshold * 100).toFixed(0)}% threshold.\n\n${summary}`,
|
|
215
|
+
variant: "warning",
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
quotaState.lastAlertLevel = threshold;
|
|
219
|
+
break; // Only one alert per drop
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// If quota went back up (reset), reset alert level
|
|
224
|
+
if (minFraction > quotaState.lastAlertLevel) {
|
|
225
|
+
quotaState.lastAlertLevel = 1.0;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Start background polling loop
|
|
231
|
+
*/
|
|
232
|
+
const startPolling = async () => {
|
|
233
|
+
// Fetch quota
|
|
234
|
+
const result = await tryConnect();
|
|
235
|
+
|
|
236
|
+
if (result) {
|
|
237
|
+
if (!quotaState.isConnected) {
|
|
238
|
+
// Just became connected
|
|
239
|
+
quotaState.isConnected = true;
|
|
240
|
+
const sourceLabel = quotaState.currentSource === "cloud" ? "Cloud API" : "Language Server";
|
|
241
|
+
const summary = buildQuotaSummary(result, undefined, "\n") || "unknown";
|
|
242
|
+
client.tui.showToast({
|
|
243
|
+
body: {
|
|
244
|
+
title: "AG Quota",
|
|
245
|
+
message: `Connected via ${sourceLabel}.\n${summary}`,
|
|
246
|
+
variant: "success",
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
quotaState.data = result;
|
|
252
|
+
quotaState.currentSource = result.source;
|
|
253
|
+
checkAlerts();
|
|
254
|
+
} else {
|
|
255
|
+
if (quotaState.isConnected) {
|
|
256
|
+
// Just became disconnected
|
|
257
|
+
quotaState.isConnected = false;
|
|
258
|
+
quotaState.currentSource = null;
|
|
259
|
+
client.tui.showToast({
|
|
260
|
+
body: {
|
|
261
|
+
title: "Quota Disconnected",
|
|
262
|
+
message: "Quota connection lost",
|
|
263
|
+
variant: "warning",
|
|
264
|
+
},
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// Schedule next poll
|
|
270
|
+
setTimeout(startPolling, config.pollingInterval);
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// Start polling immediately
|
|
274
|
+
startPolling();
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
event: async ({ event }) => {
|
|
278
|
+
// On session.idle, show quota toast if an Antigravity model was used
|
|
279
|
+
if (event.type === "session.idle") {
|
|
280
|
+
const { sessionID } = event.properties;
|
|
281
|
+
|
|
282
|
+
// Get the last assistant message's model ID from the session
|
|
283
|
+
const lastModelID = await getLastAssistantModelID(sessionID);
|
|
284
|
+
|
|
285
|
+
// Only show quota for Antigravity models (model ID contains "antigravity")
|
|
286
|
+
if (!lastModelID || !isAntigravityModel(lastModelID)) {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Check if we have quota data
|
|
291
|
+
if (!quotaState.isConnected || !quotaState.data) {
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Build and show quota summary
|
|
296
|
+
const summary = buildQuotaSummary(quotaState.data, lastModelID, "\n");
|
|
297
|
+
if (summary) {
|
|
298
|
+
client.tui.showToast({
|
|
299
|
+
body: {
|
|
300
|
+
title: "AG Quota",
|
|
301
|
+
message: summary,
|
|
302
|
+
variant: "info",
|
|
303
|
+
},
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
export default QuotaPlugin;
|