-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathtypes.ts
More file actions
715 lines (639 loc) · 18.9 KB
/
Copy pathtypes.ts
File metadata and controls
715 lines (639 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/**
* Type definitions for opencode-quota plugin
*/
import type { QuotaFormatStyle } from "./quota-format-style.js";
import { DEFAULT_QUOTA_FORMAT_STYLE } from "./quota-format-style.js";
// =============================================================================
// Configuration Types
// =============================================================================
/** Google model identifiers */
export type GoogleModelId = "G3PRO" | "G3FLASH" | "CLAUDE" | "G3IMAGE" | "GPTOSS";
export type GeminiCliAuthSourceKey =
| "google-gemini-cli"
| "gemini-cli"
| "opencode-gemini-auth"
| "gemini"
| "google";
export type CursorQuotaPlan = "none" | "pro" | "pro-plus" | "ultra";
export type PricingSnapshotSource = "auto" | "bundled" | "runtime";
export type PercentDisplayMode = "remaining" | "used";
export type OpenCodeGoWindowKey = "rolling" | "weekly" | "monthly";
export interface PricingSnapshotConfig {
source: PricingSnapshotSource;
autoRefresh: number;
}
export interface TuiSidebarPanelConfig {
enabled: boolean;
}
export interface TuiCompactStatusConfig {
enabled: boolean;
homeBottom: boolean;
sessionPrompt: boolean;
suppressWhenNativeProviderQuota: boolean;
maxWidth: number;
}
export interface MaintainerAnnouncementsConfig {
enabled: boolean;
home: boolean;
}
/** Request timeout in milliseconds */
export const REQUEST_TIMEOUT_MS = 5000;
/** Plugin configuration from opencode-quota/quota-toast.json or legacy experimental.quotaToast. */
export interface QuotaToastConfig {
enabled: boolean;
/** If false, never show popup toasts (commands/tools still work). */
enableToast: boolean;
/**
* Shared quota-row formatting style for popup toasts and the TUI sidebar.
*
* Canonical values:
* - "singleWindow": collapse each provider to a single displayable quota window
* - "allWindows": render all quota windows
*
* Legacy aliases "classic" and "grouped" remain accepted for backward compatibility.
*/
formatStyle: QuotaFormatStyle;
/** Shared percent meaning for popup toasts and the TUI sidebar. */
percentDisplayMode: PercentDisplayMode;
minIntervalMs: number;
/** Request timeout in milliseconds for remote provider API calls. */
requestTimeoutMs: number;
/**
* Debug mode for troubleshooting.
*
* When enabled, the plugin appends a short debug footer to the toast.
* If the plugin would normally show no toast (e.g. enabledProviders empty),
* it will show a debug-only toast explaining why.
*/
debug: boolean;
/**
* Provider ids to query.
*
* Keep this list short and user-friendly; each provider advertises a stable id.
* Example: ["copilot", "google-antigravity"].
*
* When set to "auto" (or left unconfigured), the plugin will auto-enable
* all providers whose `isAvailable()` returns true at runtime.
*/
enabledProviders: string[] | "auto";
/** Path or command name for the local Claude CLI used by Anthropic probing. */
anthropicBinaryPath: string;
googleModels: GoogleModelId[];
alibabaCodingPlanTier: AlibabaCodingPlanTier;
cursorPlan: CursorQuotaPlan;
/**
* Which OpenCode Go usage windows to display.
* Defaults to ["rolling", "weekly", "monthly"].
*/
opencodeGoWindows: OpenCodeGoWindowKey[];
cursorIncludedApiUsd?: number;
cursorBillingCycleStartDay?: number;
pricingSnapshot: PricingSnapshotConfig;
showOnIdle: boolean;
showOnQuestion: boolean;
showOnCompact: boolean;
showOnBothFail: boolean;
/** Toast duration in milliseconds */
toastDurationMs: number;
/** If true, only show quota for current model */
onlyCurrentModel: boolean;
/**
* If true, show the Session input/output tokens section in quota displays when session token data is available.
* "allWindows" keeps per-model rows on toast + sidebar; "singleWindow"
* uses a one-line total summary.
* The `/quota` command keeps its detailed per-model rendering.
*/
showSessionTokens: boolean;
/** TUI sidebar panel visibility when the TUI plugin is installed. */
tuiSidebarPanel: TuiSidebarPanelConfig;
/** Opt-in compact quota/status text for TUI prompt/home surfaces. */
tuiCompactStatus: TuiCompactStatusConfig;
/** Bundled-only maintainer announcement surfaces. */
maintainerAnnouncements: MaintainerAnnouncementsConfig;
/** Responsive toast layout breakpoints (not used by the fixed-width TUI sidebar). */
layout: {
/** Default max width target for toast formatting */
maxWidth: number;
/** If toast max width is <= this, use compact layout */
narrowAt: number;
/** If toast max width is <= this, use ultra-compact layout */
tinyAt: number;
};
}
/** Default configuration values */
export const DEFAULT_CONFIG: QuotaToastConfig = {
enabled: true,
enableToast: true,
formatStyle: DEFAULT_QUOTA_FORMAT_STYLE,
percentDisplayMode: "remaining",
minIntervalMs: 300000, // 5 minutes
requestTimeoutMs: REQUEST_TIMEOUT_MS,
debug: false,
// Providers are auto-detected by default; set to explicit list to opt-in manually.
enabledProviders: "auto" as const,
anthropicBinaryPath: "claude",
// If Google Antigravity is enabled, default to Claude only.
googleModels: ["CLAUDE"],
alibabaCodingPlanTier: "lite",
cursorPlan: "none",
opencodeGoWindows: ["rolling", "weekly", "monthly"],
pricingSnapshot: {
source: "auto",
autoRefresh: 7,
},
showOnIdle: true,
showOnQuestion: true,
showOnCompact: true,
showOnBothFail: true,
toastDurationMs: 9000,
onlyCurrentModel: false,
showSessionTokens: true,
tuiSidebarPanel: {
enabled: true,
},
tuiCompactStatus: {
enabled: false,
homeBottom: true,
sessionPrompt: true,
suppressWhenNativeProviderQuota: true,
maxWidth: 96,
},
maintainerAnnouncements: {
enabled: true,
home: true,
},
layout: {
maxWidth: 50,
narrowAt: 42,
tinyAt: 32,
},
};
// =============================================================================
// Auth Data Types (from ~/.local/share/opencode/auth.json)
// =============================================================================
/** GitHub Copilot authentication data */
export interface CopilotAuthData {
type: string;
refresh?: string;
access?: string;
expires?: number;
}
export type AlibabaCodingPlanTier = "lite" | "pro";
export interface QwenOAuthAuthData {
type: string;
access?: string;
refresh?: string;
expires?: number;
plan?: string;
tier?: string;
[key: string]: unknown;
}
export interface CursorOAuthAuthData {
type: string;
access?: string;
refresh?: string;
expires?: number;
[key: string]: unknown;
}
export interface OpenAIOAuthData {
type: string;
access?: string;
refresh?: string;
expires?: number;
accountId?: string;
[key: string]: unknown;
}
export interface GeminiCliOAuthAuthData {
type: string;
access?: string;
refresh?: string;
expires?: number;
projectId?: string;
/** Legacy spelling used by some companion/runtime variants */
projectID?: string;
managedProjectId?: string;
quotaProjectId?: string;
email?: string;
accountEmail?: string;
login?: string;
[key: string]: unknown;
}
export interface AlibabaAuthData {
type: string;
key?: string;
access?: string;
tier?: string;
plan?: string;
[key: string]: unknown;
}
export interface NanoGptAuthData {
type: "api";
key: string;
}
export interface DeepSeekAuthData {
type: "api";
key: string;
}
export interface SyntheticAuthData {
type: "api";
key: string;
}
export interface MiniMaxAuthData {
type: string;
key?: string;
access?: string;
}
/**
* Copilot subscription tier.
* See: https://docs.github.com/en/copilot/about-github-copilot/subscription-plans-for-github-copilot
*/
export type CopilotTier = "free" | "pro" | "pro+" | "business" | "enterprise";
/**
* Copilot quota token configuration.
*
* Stored locally in:
* - OpenCode runtime config candidate directories as
* `.../opencode/copilot-quota-token.json`
* (for example `$XDG_CONFIG_HOME/opencode` or `~/.config/opencode`)
*
* Users can create a fine-grained PAT with "Plan" read permission
* to enable quota checking via GitHub's public billing API.
*/
export interface CopilotQuotaConfig {
/** Fine-grained PAT with GitHub billing-report access */
token: string;
/** Optional user login override for user-scoped reports or org user filtering */
username?: string;
/**
* Optional organization slug.
*
* In business mode, this selects
* `/organizations/{org}/settings/billing/premium_request/usage`.
*
* In enterprise mode with an explicit `enterprise` slug, this becomes the
* optional `organization` query filter on the enterprise usage report.
*/
organization?: string;
/**
* Optional enterprise slug for enterprise-scoped premium request reports.
*
* When present, the plugin queries
* `/enterprises/{enterprise}/settings/billing/premium_request/usage`.
*/
enterprise?: string;
/** Copilot subscription tier (used for personal-tier fallback quota math) */
tier: CopilotTier;
}
/** Full auth.json structure (partial - only what we need) */
export interface AuthData {
"github-copilot"?: CopilotAuthData;
copilot?: CopilotAuthData;
"copilot-chat"?: CopilotAuthData;
"github-copilot-chat"?: CopilotAuthData;
// Provider id used by opencode-gemini-auth.
google?: GeminiCliOAuthAuthData;
// Canonical and compatibility keys for Gemini CLI auth snapshots.
"google-gemini-cli"?: GeminiCliOAuthAuthData;
"gemini-cli"?: GeminiCliOAuthAuthData;
"opencode-gemini-auth"?: GeminiCliOAuthAuthData;
gemini?: GeminiCliOAuthAuthData;
openai?: OpenAIOAuthData;
// Some OpenCode installs store ChatGPT auth under "codex".
codex?: OpenAIOAuthData;
// Some OpenCode installs store ChatGPT auth under "chatgpt".
chatgpt?: OpenAIOAuthData;
// Some OpenCode installs store OpenAI auth under "opencode".
opencode?: OpenAIOAuthData;
synthetic?: SyntheticAuthData;
chutes?: {
type: string;
key?: string;
};
nanogpt?: NanoGptAuthData;
"nano-gpt"?: NanoGptAuthData;
deepseek?: DeepSeekAuthData;
cursor?: CursorOAuthAuthData;
// Canonical OpenCode provider id used by the Qwen auth plugin.
"qwen-code"?: QwenOAuthAuthData;
// Legacy package-name key kept for backward compatibility with older installs.
"opencode-qwencode-auth"?: QwenOAuthAuthData;
alibaba?: AlibabaAuthData;
"alibaba-coding-plan"?: AlibabaAuthData;
"zai-coding-plan"?: {
type: "api";
key: string;
};
"zhipu-coding-plan"?: {
type: "api";
key: string;
};
"minimax-coding-plan"?: MiniMaxAuthData;
"minimax-china-coding-plan"?: MiniMaxAuthData;
"minimax-cn-coding-plan"?: MiniMaxAuthData;
"kimi-code"?: KimiAuthData;
kimi?: KimiAuthData;
}
// =============================================================================
// Antigravity Account Types (from ~/.config/opencode/antigravity-accounts.json)
// =============================================================================
/** Single Antigravity account from opencode-antigravity-auth storage */
export interface AntigravityAccount {
email?: string;
refreshToken: string;
projectId?: string;
/** Legacy spelling used by some plugin versions */
projectID?: string;
managedProjectId?: string;
addedAt: number;
lastUsed: number;
rateLimitResetTimes?: Record<string, number>;
}
/** Antigravity accounts file structure */
export interface AntigravityAccountsFile {
version: number;
accounts: AntigravityAccount[];
activeIndex?: number;
activeIndexByFamily?: {
claude?: number;
gemini?: number;
};
}
// =============================================================================
// Google Antigravity Types
// =============================================================================
/** Google quota API response */
export interface GoogleQuotaResponse {
models: Record<
string,
{
quotaInfo?: {
remainingFraction?: number;
resetTime?: string;
};
}
>;
}
// =============================================================================
// Kimi Types
// =============================================================================
/** Kimi auth entry in auth.json */
export interface KimiAuthData {
type: "api";
key: string;
}
/** Kimi quota window */
export interface KimiQuotaWindow {
label: string;
used: number;
limit: number;
percentRemaining: number;
resetTimeIso?: string;
}
/** Result from fetching Kimi quota */
export interface KimiQuotaResult {
success: true;
label: string;
windows: KimiQuotaWindow[];
}
export type KimiResult = KimiQuotaResult | QuotaError | null;
// =============================================================================
// Z.ai Types
// =============================================================================
/** Z.ai auth entry in auth.json */
export interface ZaiAuthData {
type: "api";
key: string;
}
/** Z.ai quota limit entry from API */
export interface ZaiQuotaLimit {
type: string;
unit: number;
number: number;
usage: number;
currentValue?: number;
remaining?: number;
percentage: number;
nextResetTime?: number;
usageDetails?: Array<{
modelCode: string;
usage: number;
}>;
}
/** Z.ai API response */
export interface ZaiQuotaResponse {
code: number;
msg: string;
data: {
limits: ZaiQuotaLimit[];
level: string;
};
success: boolean;
}
/** Result from fetching Z.ai quota */
export interface ZaiQuotaResult {
success: true;
label: string;
windows: {
fiveHour?: { percentRemaining: number; resetTimeIso?: string };
weekly?: { percentRemaining: number; resetTimeIso?: string };
mcp?: { percentRemaining: number; resetTimeIso?: string };
};
}
// =============================================================================
// Quota Result Types
// =============================================================================
/** Result from fetching per-user Copilot quota */
export interface CopilotQuotaResult {
success: true;
mode: "user_quota";
used: number;
total: number;
percentRemaining: number;
unlimited?: boolean;
resetTimeIso?: string;
}
/** Result from fetching organization-scoped Copilot premium usage */
export interface CopilotOrganizationUsageResult {
success: true;
mode: "organization_usage";
organization: string;
username?: string;
period: {
year: number;
month: number;
};
used: number;
resetTimeIso?: string;
}
/** Result from fetching enterprise-scoped Copilot premium usage */
export interface CopilotEnterpriseUsageResult {
success: true;
mode: "enterprise_usage";
enterprise: string;
organization?: string;
username?: string;
period: {
year: number;
month: number;
};
used: number;
resetTimeIso?: string;
}
/** Result from fetching Google quota for a single model */
export interface GoogleModelQuota {
modelId: GoogleModelId;
displayName: string;
percentRemaining: number;
resetTimeIso?: string;
accountEmail?: string;
}
/** Error for a single account */
export interface GoogleAccountError {
email: string;
error: string;
}
export interface GeminiCliQuotaBucket {
modelId: string;
displayName: string;
percentRemaining: number;
resetTimeIso?: string;
remainingAmount?: string;
tokenType?: string;
accountEmail?: string;
sourceKey?: GeminiCliAuthSourceKey;
}
export interface GeminiCliQuotaResult {
success: true;
buckets: GeminiCliQuotaBucket[];
errors?: GoogleAccountError[];
}
/** Result from fetching Google quota */
export interface GoogleQuotaResult {
success: true;
models: GoogleModelQuota[];
errors?: GoogleAccountError[];
}
/** Error result */
export interface QuotaError {
success: false;
error: string;
}
/** Combined quota result */
export type CopilotResult =
| CopilotQuotaResult
| CopilotOrganizationUsageResult
| CopilotEnterpriseUsageResult
| QuotaError
| null;
export type GoogleResult = GoogleQuotaResult | QuotaError | null;
export type GeminiCliResult = GeminiCliQuotaResult | QuotaError | null;
export type ZaiResult = ZaiQuotaResult | QuotaError | null;
/** Single entry in a MiniMax quota result */
export interface MiniMaxResultEntry {
window: "five_hour" | "weekly";
name: string;
group?: string;
label?: string;
right?: string;
percentRemaining: number;
resetTimeIso?: string;
}
export type MiniMaxResult =
| {
success: true;
entries: MiniMaxResultEntry[];
}
| QuotaError;
export type ChutesResult =
| {
success: true;
percentRemaining: number;
resetTimeIso?: string;
}
| QuotaError
| null;
export type CrofResult =
| {
success: true;
credits: number;
requestsPlan: number;
usableRequests: number;
percentRemaining: number;
}
| QuotaError
| null;
export interface SyntheticQuotaWindow {
limit: number;
used: number;
percentRemaining: number;
resetTimeIso?: string;
}
export type SyntheticResult =
| {
success: true;
windows: {
fiveHour: SyntheticQuotaWindow;
weekly: SyntheticQuotaWindow;
};
}
| QuotaError
| null;
/** Single usage window from OpenCode Go dashboard */
export interface OpenCodeGoWindow {
/** Usage percentage [0..100] */
usagePercent: number;
/** Seconds until usage resets */
resetInSec: number;
/** Remaining percentage [0..100] */
percentRemaining: number;
/** ISO reset timestamp */
resetTimeIso: string;
}
/** Result from scraping OpenCode Go dashboard usage */
export type OpenCodeGoResult =
| {
success: true;
/** Rolling (~5h) usage window, when present in the dashboard payload */
rolling?: OpenCodeGoWindow;
/** Weekly usage window, when present in the dashboard payload */
weekly?: OpenCodeGoWindow;
/** Monthly usage window, when present in the dashboard payload */
monthly?: OpenCodeGoWindow;
}
| QuotaError
| null;
/** Cached toast data */
export interface CachedToast {
message: string;
timestamp: number;
}
// =============================================================================
// Constants
// =============================================================================
/** Model key mapping for Google API */
export const GOOGLE_MODEL_KEYS: Record<
GoogleModelId,
{ key: string; altKey?: string; display: string }
> = {
G3PRO: {
key: "gemini-3.1-pro",
altKey: "gemini-3.1-pro-high|gemini-3.1-pro-low|gemini-3-pro-high|gemini-3-pro-low|gemini-3.5-pro-high|gemini-3.5-pro-low",
display: "G3Pro",
},
G3FLASH: {
key: "gemini-3-flash",
altKey: "gemini-3-flash-medium|gemini-3-flash-high|gemini-3-flash-low|gemini-3-5-flash-medium|gemini-3-5-flash-high|gemini-3-5-flash-low|gemini-3.5-flash-medium|gemini-3.5-flash-high|gemini-3.5-flash-low",
display: "G3Flash",
},
CLAUDE: {
key: "claude-opus-4-6-thinking",
altKey: "claude-opus-4-5-thinking|claude-opus-4-5|claude-sonnet-4-6|claude-sonnet-4-6-thinking|claude-opus-4-6|gemini-claude-sonnet-4-6|gemini-claude-opus-4-6-thinking",
display: "Claude",
},
G3IMAGE: { key: "gemini-3-pro-image", display: "G3Image" },
GPTOSS: {
key: "gpt-oss-120b-medium",
altKey: "gpt-oss-120b-high|gpt-oss-120b-low|gpt-oss-120b",
display: "GPT-OSS",
},
};