pi-usage-hub 1.0.9 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -3
- package/core/config.ts +76 -78
- package/core/registry.ts +79 -21
- package/index.ts +6 -0
- package/package.json +1 -1
- package/providers/codex.ts +152 -0
- package/providers/kimi-coding.ts +101 -0
- package/providers/xai.ts +8 -4
- package/providers/zai.ts +122 -0
- package/types.ts +39 -3
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
## Why
|
|
9
9
|
|
|
10
|
-
Checking separate dashboards for DeepSeek, NewAPI relays, xAI, Kiro, OpenCode Go, and ARK breaks flow. pi-usage-hub brings their quotas and balances into one TUI panel while keeping footer integration optional and pull-based.
|
|
10
|
+
Checking separate dashboards for DeepSeek, NewAPI relays, OpenAI Codex, xAI, Kiro, OpenCode Go, and ARK breaks flow. pi-usage-hub brings their quotas and balances into one TUI panel while keeping footer integration optional and pull-based.
|
|
11
11
|
|
|
12
12
|
## Install
|
|
13
13
|
|
|
@@ -59,7 +59,10 @@ Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel
|
|
|
59
59
|
"type": "xai",
|
|
60
60
|
"matchProviders": ["xai-auth", "xai", "grok-cli"]
|
|
61
61
|
},
|
|
62
|
-
{ "type": "kiro" }
|
|
62
|
+
{ "type": "kiro" },
|
|
63
|
+
{ "type": "kimi-coding" },
|
|
64
|
+
{ "type": "zai" },
|
|
65
|
+
{ "type": "codex" }
|
|
63
66
|
]
|
|
64
67
|
}
|
|
65
68
|
```
|
|
@@ -73,6 +76,7 @@ Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel
|
|
|
73
76
|
| `matchProviders` | no | Additional `model.provider` values mapped to this entry |
|
|
74
77
|
| `shortLabel` / `label` | no | Override the footer label or panel title |
|
|
75
78
|
| `hidden` | no | Exclude from panel and footer; `/usage-hub login` still works |
|
|
79
|
+
| `disabled` | no | Do not register at all; on untyped entries, refuses that provider's registration |
|
|
76
80
|
|
|
77
81
|
### Provider types
|
|
78
82
|
|
|
@@ -84,6 +88,9 @@ Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel
|
|
|
84
88
|
| `ark` | optional `cookie`, `csrfToken` | Uses the configured Cookie header or macOS Chrome | [火山引擎](https://console.volcengine.com/ark) |
|
|
85
89
|
| `xai` | — | Reads `auth.json` or `~/.grok/auth.json` | [x.ai/grok](https://x.ai/grok) |
|
|
86
90
|
| `kiro` | — | Reads the Kiro OAuth entry from `auth.json` | [kiro.dev](https://kiro.dev) |
|
|
91
|
+
| `kimi-coding` | optional `apiKey` | 5h rolling window + weekly quota; falls back to the `kimi-coding` entry in `auth.json` (Kimi Code key, not the open-platform key) | [kimi.com/code](https://www.kimi.com/code) |
|
|
92
|
+
| `zai` | optional `apiKey` | 5h window, weekly, and monthly search quota; falls back to the `zai` entry in `auth.json` | [z.ai](https://z.ai) |
|
|
93
|
+
| `codex` | — | Codex rolling and 7-day usage windows; reads the `openai-codex` OAuth entry in `auth.json` | [OpenAI Codex](https://openai.com/codex/) |
|
|
87
94
|
|
|
88
95
|
For NewAPI, `token` is the **system access token** (not a chat `sk-` token), and `userId` is sent as `New-Api-User`. See [Authentication](https://www.newapi.ai/en/docs/api/management/auth) and [Generate access token](https://www.newapi.ai/en/docs/api/management/user-management/user-token-get).
|
|
89
96
|
|
|
@@ -95,7 +102,6 @@ These are companion packages, not npm peer dependencies:
|
|
|
95
102
|
|
|
96
103
|
| Type | Companion | Purpose |
|
|
97
104
|
|------|-----------|---------|
|
|
98
|
-
| `xai` | [`pi-xai-oauth`](https://www.npmjs.com/package/pi-xai-oauth) | `/login xai-auth` writes the OAuth entry to `auth.json` |
|
|
99
105
|
| `kiro` | [`pi-provider-kiro-dev`](https://www.npmjs.com/package/pi-provider-kiro-dev) | Provides `/login kiro`, models, and the `auth.json` entry |
|
|
100
106
|
|
|
101
107
|
pi-usage-hub only reads those credentials; it does not run their OAuth flows.
|
|
@@ -112,6 +118,39 @@ pi.events.emit("pi-usage-hub:register", myProvider);
|
|
|
112
118
|
pi.events.emit("pi-usage-hub:unregister", { key: "my-relay" });
|
|
113
119
|
```
|
|
114
120
|
|
|
121
|
+
Re-registering the same key overwrites (registration is idempotent), so the ready-listener + emit combination above never duplicates a provider.
|
|
122
|
+
|
|
123
|
+
### Configure a custom provider from JSON
|
|
124
|
+
|
|
125
|
+
`providers` entries **without** `type` target an externally-registered provider by `name`. Meta fields override the provider's own values at register time; `disabled: true` refuses registration; all other fields pass through untouched to `hub.getProviderConfig(name)`, so the extension can read its credentials from JSON instead of env vars:
|
|
126
|
+
|
|
127
|
+
```json
|
|
128
|
+
{
|
|
129
|
+
"providers": [
|
|
130
|
+
{ "type": "kimi-coding" },
|
|
131
|
+
{
|
|
132
|
+
"name": "qianwen",
|
|
133
|
+
"shortLabel": "QW",
|
|
134
|
+
"hidden": false,
|
|
135
|
+
"cookie": "login_qianwenai_ticket=..."
|
|
136
|
+
}
|
|
137
|
+
]
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
pi.events.on("pi-usage-hub:ready", (hub) => {
|
|
143
|
+
const cfg = hub.getProviderConfig("qianwen"); // { shortLabel, hidden, cookie, ... }
|
|
144
|
+
const cookie = typeof cfg?.cookie === "string" ? cfg.cookie : undefined;
|
|
145
|
+
});
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Untyped entries do not affect built-in name allocation; two untyped entries with the same `name` resolve last-write-wins. An untyped entry whose `name` matches a built-in entry also applies to it, so `{ "name": "kimi-coding", "hidden": true }` hides the built-in without editing its own entry.
|
|
149
|
+
|
|
150
|
+
### Register a built-in from an extension
|
|
151
|
+
|
|
152
|
+
`hub.registerBuiltin(type, cfg?)` instantiates any built-in factory with your own parameters (e.g. credentials obtained at runtime) and registers it, allocating `type`, `type-2`, … on key clash. Returns the registered key, or `null` for unknown types or `disabled: true`.
|
|
153
|
+
|
|
115
154
|
## Pull API
|
|
116
155
|
|
|
117
156
|
The hub caches results for 60 seconds and deduplicates concurrent requests. It never pushes footer text: consumers start refreshes without blocking lifecycle events, read the cached summary, and re-render when notified.
|
package/core/config.ts
CHANGED
|
@@ -1,16 +1,33 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
import type {
|
|
4
|
+
import type {
|
|
5
|
+
BuiltinProviderConfig,
|
|
6
|
+
ExtensionProviderConfig,
|
|
7
|
+
ProviderConfig,
|
|
8
|
+
ProviderMeta,
|
|
9
|
+
ProviderType,
|
|
10
|
+
UsageHubConfig,
|
|
11
|
+
} from "../types";
|
|
12
|
+
|
|
13
|
+
interface BuiltinSchema {
|
|
14
|
+
/** Fields that must be non-empty strings, or the entry is skipped. */
|
|
15
|
+
required?: string[];
|
|
16
|
+
/** Extra string fields picked into the config when present. */
|
|
17
|
+
optional?: string[];
|
|
18
|
+
}
|
|
5
19
|
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"opencode-go",
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
]
|
|
20
|
+
const BUILTIN_SCHEMAS: Record<ProviderType, BuiltinSchema> = {
|
|
21
|
+
deepseek: { required: ["apiKey"] },
|
|
22
|
+
newapi: { required: ["host", "token", "userId"] },
|
|
23
|
+
ark: { optional: ["cookie", "csrfToken"] },
|
|
24
|
+
"opencode-go": { required: ["workspaceId"], optional: ["auth"] },
|
|
25
|
+
xai: {},
|
|
26
|
+
kiro: {},
|
|
27
|
+
"kimi-coding": { optional: ["apiKey"] },
|
|
28
|
+
zai: { optional: ["apiKey"] },
|
|
29
|
+
codex: {},
|
|
30
|
+
};
|
|
14
31
|
|
|
15
32
|
export function agentDir(): string {
|
|
16
33
|
return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
@@ -30,6 +47,16 @@ function asStringArray(value: unknown): string[] | undefined {
|
|
|
30
47
|
return items.length > 0 ? items : undefined;
|
|
31
48
|
}
|
|
32
49
|
|
|
50
|
+
function parseMeta(raw: Record<string, unknown>): ProviderMeta {
|
|
51
|
+
return {
|
|
52
|
+
matchProviders: asStringArray(raw.matchProviders),
|
|
53
|
+
shortLabel: typeof raw.shortLabel === "string" ? raw.shortLabel : undefined,
|
|
54
|
+
label: typeof raw.label === "string" ? raw.label : undefined,
|
|
55
|
+
hidden: typeof raw.hidden === "boolean" ? raw.hidden : undefined,
|
|
56
|
+
disabled: typeof raw.disabled === "boolean" ? raw.disabled : undefined,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
33
60
|
/** Prefer explicit name; otherwise type, then type-2, type-3, … */
|
|
34
61
|
function allocateName(type: ProviderType, preferred: string | undefined, seen: Set<string>): string {
|
|
35
62
|
const base = preferred?.trim() || type;
|
|
@@ -39,17 +66,12 @@ function allocateName(type: ProviderType, preferred: string | undefined, seen: S
|
|
|
39
66
|
return `${base}-${n}`;
|
|
40
67
|
}
|
|
41
68
|
|
|
42
|
-
function
|
|
43
|
-
raw: unknown
|
|
69
|
+
function parseBuiltinEntry(
|
|
70
|
+
raw: Record<string, unknown>,
|
|
44
71
|
index: number,
|
|
45
72
|
seen: Set<string>,
|
|
46
|
-
):
|
|
47
|
-
if (!
|
|
48
|
-
console.warn(`[pi-usage-hub] skip providers[${index}]: not an object`);
|
|
49
|
-
return null;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
if (typeof raw.type !== "string" || !TYPES.has(raw.type as ProviderType)) {
|
|
73
|
+
): BuiltinProviderConfig | null {
|
|
74
|
+
if (typeof raw.type !== "string" || !(raw.type in BUILTIN_SCHEMAS)) {
|
|
53
75
|
console.warn(`[pi-usage-hub] skip providers[${index}]: unknown or missing type`);
|
|
54
76
|
return null;
|
|
55
77
|
}
|
|
@@ -61,65 +83,43 @@ function parseProviderEntry(
|
|
|
61
83
|
console.warn(`[pi-usage-hub] providers[${index}] name "${preferred.trim()}" taken, using "${name}"`);
|
|
62
84
|
}
|
|
63
85
|
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
switch (type) {
|
|
72
|
-
case "deepseek": {
|
|
73
|
-
if (typeof raw.apiKey !== "string" || !raw.apiKey) {
|
|
74
|
-
console.warn(`[pi-usage-hub] skip providers[${index}]: deepseek requires apiKey`);
|
|
75
|
-
return null;
|
|
76
|
-
}
|
|
77
|
-
return { name, type: "deepseek", ...meta, apiKey: raw.apiKey };
|
|
78
|
-
}
|
|
79
|
-
case "newapi": {
|
|
80
|
-
if (
|
|
81
|
-
typeof raw.host !== "string" ||
|
|
82
|
-
typeof raw.token !== "string" ||
|
|
83
|
-
typeof raw.userId !== "string"
|
|
84
|
-
) {
|
|
85
|
-
console.warn(`[pi-usage-hub] skip providers[${index}]: newapi requires host, token, userId`);
|
|
86
|
-
return null;
|
|
87
|
-
}
|
|
88
|
-
return {
|
|
89
|
-
name,
|
|
90
|
-
type: "newapi",
|
|
91
|
-
...meta,
|
|
92
|
-
host: raw.host,
|
|
93
|
-
token: raw.token,
|
|
94
|
-
userId: raw.userId,
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
case "opencode-go": {
|
|
98
|
-
if (typeof raw.workspaceId !== "string" || !raw.workspaceId) {
|
|
99
|
-
console.warn(`[pi-usage-hub] skip providers[${index}]: opencode-go requires workspaceId`);
|
|
100
|
-
return null;
|
|
101
|
-
}
|
|
102
|
-
return {
|
|
103
|
-
name,
|
|
104
|
-
type: "opencode-go",
|
|
105
|
-
...meta,
|
|
106
|
-
workspaceId: raw.workspaceId,
|
|
107
|
-
auth: typeof raw.auth === "string" ? raw.auth : undefined,
|
|
108
|
-
};
|
|
86
|
+
const schema = BUILTIN_SCHEMAS[type];
|
|
87
|
+
const required = schema.required ?? [];
|
|
88
|
+
for (const field of required) {
|
|
89
|
+
if (typeof raw[field] !== "string" || !raw[field]) {
|
|
90
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: ${type} requires ${required.join(", ")}`);
|
|
91
|
+
return null;
|
|
109
92
|
}
|
|
110
|
-
case "ark":
|
|
111
|
-
return {
|
|
112
|
-
name,
|
|
113
|
-
type: "ark",
|
|
114
|
-
...meta,
|
|
115
|
-
cookie: typeof raw.cookie === "string" ? raw.cookie : undefined,
|
|
116
|
-
csrfToken: typeof raw.csrfToken === "string" ? raw.csrfToken : undefined,
|
|
117
|
-
};
|
|
118
|
-
case "xai":
|
|
119
|
-
return { name, type: "xai", ...meta };
|
|
120
|
-
case "kiro":
|
|
121
|
-
return { name, type: "kiro", ...meta };
|
|
122
93
|
}
|
|
94
|
+
|
|
95
|
+
const fields: Record<string, string> = {};
|
|
96
|
+
for (const field of [...required, ...(schema.optional ?? [])]) {
|
|
97
|
+
const value = raw[field];
|
|
98
|
+
if (typeof value === "string") fields[field] = value;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
seen.add(name);
|
|
102
|
+
return { name, type, ...parseMeta(raw), ...fields } as BuiltinProviderConfig;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function parseExtensionEntry(
|
|
106
|
+
raw: Record<string, unknown>,
|
|
107
|
+
index: number,
|
|
108
|
+
): ExtensionProviderConfig | null {
|
|
109
|
+
if (typeof raw.name !== "string" || !raw.name.trim()) {
|
|
110
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: entry without type requires a name`);
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
return { ...raw, ...parseMeta(raw), name: raw.name.trim() };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function parseProviderEntry(raw: unknown, index: number, seen: Set<string>): ProviderConfig | null {
|
|
117
|
+
if (!isObject(raw)) {
|
|
118
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: not an object`);
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
if (raw.type == null) return parseExtensionEntry(raw, index);
|
|
122
|
+
return parseBuiltinEntry(raw, index, seen);
|
|
123
123
|
}
|
|
124
124
|
|
|
125
125
|
export function loadConfig(): UsageHubConfig {
|
|
@@ -144,9 +144,7 @@ export function loadConfig(): UsageHubConfig {
|
|
|
144
144
|
|
|
145
145
|
for (let i = 0; i < raw.providers.length; i++) {
|
|
146
146
|
const parsed = parseProviderEntry(raw.providers[i], i, seen);
|
|
147
|
-
if (
|
|
148
|
-
seen.add(parsed.name);
|
|
149
|
-
providers.push(parsed);
|
|
147
|
+
if (parsed) providers.push(parsed);
|
|
150
148
|
}
|
|
151
149
|
|
|
152
150
|
return { providers };
|
package/core/registry.ts
CHANGED
|
@@ -1,16 +1,66 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
BuiltinProviderConfig,
|
|
3
|
+
ExtensionProviderConfig,
|
|
4
|
+
ProviderConfig,
|
|
5
|
+
ProviderMeta,
|
|
6
|
+
ProviderType,
|
|
7
|
+
UsageProvider,
|
|
8
|
+
} from "../types";
|
|
2
9
|
import { makeDeepseekProvider } from "../providers/deepseek";
|
|
3
10
|
import { makeNewApiProvider } from "../providers/newapi";
|
|
4
11
|
import { makeArkProvider } from "../providers/ark";
|
|
5
12
|
import { makeOpencodeGoProvider } from "../providers/opencode-go";
|
|
6
13
|
import { makeXaiProvider } from "../providers/xai";
|
|
7
14
|
import { makeKiroProvider } from "../providers/kiro";
|
|
15
|
+
import { makeKimiCodingProvider } from "../providers/kimi-coding";
|
|
16
|
+
import { makeZaiProvider } from "../providers/zai";
|
|
17
|
+
import { makeCodexProvider } from "../providers/codex";
|
|
18
|
+
|
|
19
|
+
const FACTORIES = {
|
|
20
|
+
deepseek: makeDeepseekProvider,
|
|
21
|
+
newapi: makeNewApiProvider,
|
|
22
|
+
ark: makeArkProvider,
|
|
23
|
+
"opencode-go": makeOpencodeGoProvider,
|
|
24
|
+
xai: makeXaiProvider,
|
|
25
|
+
kiro: makeKiroProvider,
|
|
26
|
+
"kimi-coding": makeKimiCodingProvider,
|
|
27
|
+
zai: makeZaiProvider,
|
|
28
|
+
} satisfies Record<Exclude<ProviderType, "codex">, (name: string, cfg: any) => UsageProvider>;
|
|
29
|
+
|
|
30
|
+
/** Config-entry meta wins over the provider's own values, per explicitly-set field. */
|
|
31
|
+
function applyMeta(p: UsageProvider, cfg: ExtensionProviderConfig): UsageProvider {
|
|
32
|
+
return {
|
|
33
|
+
...p,
|
|
34
|
+
matchProviders: cfg.matchProviders ?? p.matchProviders,
|
|
35
|
+
shortLabel: cfg.shortLabel ?? p.shortLabel,
|
|
36
|
+
label: cfg.label ?? p.label,
|
|
37
|
+
hidden: cfg.hidden ?? p.hidden,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function allocateName(base: string, taken: (name: string) => boolean): string {
|
|
42
|
+
if (!taken(base)) return base;
|
|
43
|
+
let n = 2;
|
|
44
|
+
while (taken(`${base}-${n}`)) n++;
|
|
45
|
+
return `${base}-${n}`;
|
|
46
|
+
}
|
|
8
47
|
|
|
9
48
|
export class ProviderRegistry {
|
|
10
49
|
private providers = new Map<string, UsageProvider>();
|
|
50
|
+
private extensionConfigs = new Map<string, ExtensionProviderConfig>();
|
|
51
|
+
|
|
52
|
+
private makeBuiltinProvider(cfg: BuiltinProviderConfig): UsageProvider {
|
|
53
|
+
if (cfg.type === "codex") {
|
|
54
|
+
return makeCodexProvider(cfg.name, cfg);
|
|
55
|
+
}
|
|
56
|
+
const factory = FACTORIES[cfg.type] as (name: string, config: unknown) => UsageProvider;
|
|
57
|
+
return factory(cfg.name, cfg);
|
|
58
|
+
}
|
|
11
59
|
|
|
12
60
|
register(provider: UsageProvider): void {
|
|
13
|
-
this.
|
|
61
|
+
const cfg = this.extensionConfigs.get(provider.key);
|
|
62
|
+
if (cfg?.disabled) return;
|
|
63
|
+
this.providers.set(provider.key, cfg ? applyMeta(provider, cfg) : provider);
|
|
14
64
|
}
|
|
15
65
|
|
|
16
66
|
unregister(key: string): void {
|
|
@@ -29,6 +79,25 @@ export class ProviderRegistry {
|
|
|
29
79
|
return this.providers.get(key);
|
|
30
80
|
}
|
|
31
81
|
|
|
82
|
+
getExtensionConfig(key: string): ExtensionProviderConfig | undefined {
|
|
83
|
+
return this.extensionConfigs.get(key);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
registerBuiltin(type: ProviderType, cfg: ProviderMeta & Record<string, unknown> = {}): string | null {
|
|
87
|
+
if (cfg.disabled) return null;
|
|
88
|
+
const preferred = typeof (cfg as { name?: unknown }).name === "string"
|
|
89
|
+
? (cfg as { name: string }).name.trim()
|
|
90
|
+
: "";
|
|
91
|
+
const name = allocateName(preferred || type, n => this.providers.has(n));
|
|
92
|
+
if (type === "codex") {
|
|
93
|
+
this.register(makeCodexProvider(name, cfg));
|
|
94
|
+
return name;
|
|
95
|
+
}
|
|
96
|
+
const factory = FACTORIES[type] as (name: string, config: unknown) => UsageProvider;
|
|
97
|
+
this.register(factory(name, cfg));
|
|
98
|
+
return name;
|
|
99
|
+
}
|
|
100
|
+
|
|
32
101
|
detectActive(): UsageProvider[] {
|
|
33
102
|
return this.list().filter(p => {
|
|
34
103
|
if (p.hidden) return false;
|
|
@@ -50,25 +119,14 @@ export class ProviderRegistry {
|
|
|
50
119
|
|
|
51
120
|
loadFromConfig(providers: ProviderConfig[]): void {
|
|
52
121
|
for (const cfg of providers) {
|
|
53
|
-
|
|
54
|
-
|
|
122
|
+
if (typeof (cfg as { type?: unknown }).type === "string") {
|
|
123
|
+
const builtin = cfg as BuiltinProviderConfig;
|
|
124
|
+
if (builtin.disabled) continue;
|
|
125
|
+
// Name pre-allocated by the config parser; register verbatim (last write wins).
|
|
126
|
+
this.register(this.makeBuiltinProvider(builtin));
|
|
127
|
+
} else {
|
|
128
|
+
this.extensionConfigs.set(cfg.name, cfg as ExtensionProviderConfig);
|
|
129
|
+
}
|
|
55
130
|
}
|
|
56
131
|
}
|
|
57
132
|
}
|
|
58
|
-
|
|
59
|
-
function makeProvider(cfg: ProviderConfig): UsageProvider | null {
|
|
60
|
-
switch (cfg.type) {
|
|
61
|
-
case "deepseek":
|
|
62
|
-
return makeDeepseekProvider(cfg.name, cfg);
|
|
63
|
-
case "newapi":
|
|
64
|
-
return makeNewApiProvider(cfg.name, cfg);
|
|
65
|
-
case "ark":
|
|
66
|
-
return makeArkProvider(cfg.name, cfg);
|
|
67
|
-
case "opencode-go":
|
|
68
|
-
return makeOpencodeGoProvider(cfg.name, cfg);
|
|
69
|
-
case "xai":
|
|
70
|
-
return makeXaiProvider(cfg.name, cfg);
|
|
71
|
-
case "kiro":
|
|
72
|
-
return makeKiroProvider(cfg.name, cfg);
|
|
73
|
-
}
|
|
74
|
-
}
|
package/index.ts
CHANGED
|
@@ -27,6 +27,12 @@ export default function register(pi: ExtensionAPI) {
|
|
|
27
27
|
registry.unregister(key);
|
|
28
28
|
cache.invalidate(key);
|
|
29
29
|
},
|
|
30
|
+
registerBuiltin(type, cfg) {
|
|
31
|
+
return registry.registerBuiltin(type, cfg);
|
|
32
|
+
},
|
|
33
|
+
getProviderConfig(key) {
|
|
34
|
+
return registry.getExtensionConfig(key);
|
|
35
|
+
},
|
|
30
36
|
list() {
|
|
31
37
|
return registry.list();
|
|
32
38
|
},
|
package/package.json
CHANGED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { CodexConfig, UsageData, UsageProvider, UsageReport } from "../types";
|
|
4
|
+
import { agentDir } from "../core/config";
|
|
5
|
+
import { formatDurationSeconds } from "../utils/duration";
|
|
6
|
+
|
|
7
|
+
const USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
8
|
+
const FETCH_TIMEOUT_MS = 15_000;
|
|
9
|
+
const WEEK_SECONDS = 7 * 24 * 60 * 60;
|
|
10
|
+
|
|
11
|
+
interface StoredCodexCredential {
|
|
12
|
+
type?: string;
|
|
13
|
+
access?: string;
|
|
14
|
+
accountId?: string;
|
|
15
|
+
account_id?: string;
|
|
16
|
+
expires?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface UsageWindow {
|
|
20
|
+
used_percent?: number | null;
|
|
21
|
+
reset_after_seconds?: number | null;
|
|
22
|
+
reset_at?: number | null;
|
|
23
|
+
limit_window_seconds?: number | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface UsagePayload {
|
|
27
|
+
rate_limit?: {
|
|
28
|
+
primary_window?: UsageWindow | null;
|
|
29
|
+
secondary_window?: UsageWindow | null;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface Credentials {
|
|
34
|
+
accessToken: string;
|
|
35
|
+
accountId: string;
|
|
36
|
+
expires?: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function readCredentials(): Credentials | null {
|
|
40
|
+
const path = join(agentDir(), "auth.json");
|
|
41
|
+
if (!existsSync(path)) return null;
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
const auth = JSON.parse(readFileSync(path, "utf-8")) as { "openai-codex"?: StoredCodexCredential };
|
|
45
|
+
const entry = auth["openai-codex"];
|
|
46
|
+
const accountId = entry?.accountId ?? entry?.account_id;
|
|
47
|
+
if (entry?.type !== "oauth" || typeof entry.access !== "string" || !entry.access || typeof accountId !== "string" || !accountId) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
return { accessToken: entry.access, accountId, expires: entry.expires };
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isFresh(credentials: Credentials): boolean {
|
|
57
|
+
return credentials.expires == null || Date.now() < credentials.expires;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function toUsageData(window: UsageWindow | null | undefined): UsageData | undefined {
|
|
61
|
+
if (!window || typeof window.used_percent !== "number" || !Number.isFinite(window.used_percent)) return undefined;
|
|
62
|
+
|
|
63
|
+
let resetSeconds: number | undefined;
|
|
64
|
+
if (typeof window.reset_after_seconds === "number" && Number.isFinite(window.reset_after_seconds)) {
|
|
65
|
+
resetSeconds = window.reset_after_seconds;
|
|
66
|
+
} else if (typeof window.reset_at === "number" && Number.isFinite(window.reset_at)) {
|
|
67
|
+
const resetAtMs = window.reset_at > 100_000_000_000 ? window.reset_at : window.reset_at * 1000;
|
|
68
|
+
resetSeconds = (resetAtMs - Date.now()) / 1000;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
pct: Math.min(100, Math.max(0, window.used_percent)),
|
|
73
|
+
resetsIn: resetSeconds != null && resetSeconds > 0 ? formatDurationSeconds(resetSeconds) : undefined,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function isRollingWindow(window: UsageWindow | null | undefined): boolean {
|
|
78
|
+
const seconds = window?.limit_window_seconds;
|
|
79
|
+
return typeof seconds === "number" && seconds > 0 && seconds < WEEK_SECONDS - 24 * 60 * 60;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function isWeeklyWindow(window: UsageWindow | null | undefined): boolean {
|
|
83
|
+
const seconds = window?.limit_window_seconds;
|
|
84
|
+
return typeof seconds === "number" && Math.abs(seconds - WEEK_SECONDS) <= 24 * 60 * 60;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function parseCodexUsage(payload: UsagePayload): UsageReport {
|
|
88
|
+
const rateLimit = payload.rate_limit;
|
|
89
|
+
const primary = rateLimit?.primary_window;
|
|
90
|
+
const secondary = rateLimit?.secondary_window;
|
|
91
|
+
|
|
92
|
+
let session = isRollingWindow(primary) ? toUsageData(primary) : undefined;
|
|
93
|
+
let weekly = isWeeklyWindow(primary) ? toUsageData(primary) : undefined;
|
|
94
|
+
|
|
95
|
+
if (!session && isRollingWindow(secondary)) session = toUsageData(secondary);
|
|
96
|
+
if (!weekly && isWeeklyWindow(secondary)) weekly = toUsageData(secondary);
|
|
97
|
+
|
|
98
|
+
// Old responses omit duration metadata. With two windows, their documented order is rolling then weekly.
|
|
99
|
+
if (!session && primary && secondary) session = toUsageData(primary);
|
|
100
|
+
if (!weekly && secondary) weekly = toUsageData(secondary);
|
|
101
|
+
// A single undifferentiated window is treated as weekly so the UI never invents a 5h allowance.
|
|
102
|
+
if (!session && !weekly && primary) weekly = toUsageData(primary);
|
|
103
|
+
|
|
104
|
+
if (!session && !weekly) return { error: "could not parse usage" };
|
|
105
|
+
return {
|
|
106
|
+
...(session ? { session } : {}),
|
|
107
|
+
...(weekly ? { weekly } : {}),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function makeCodexProvider(name: string, cfg: CodexConfig = {}): UsageProvider {
|
|
112
|
+
return {
|
|
113
|
+
key: name,
|
|
114
|
+
matchProviders: cfg.matchProviders ?? [name, "openai-codex"],
|
|
115
|
+
shortLabel: cfg.shortLabel ?? "Codex",
|
|
116
|
+
label: cfg.label ?? "OpenAI Codex",
|
|
117
|
+
hidden: cfg.hidden,
|
|
118
|
+
detect: () => readCredentials() !== null,
|
|
119
|
+
|
|
120
|
+
fetchUsage: async (): Promise<UsageReport> => {
|
|
121
|
+
const stored = readCredentials();
|
|
122
|
+
if (!stored) return { error: "not logged in — run /login openai-codex" };
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
if (!isFresh(stored)) return { error: "session expired — run /login openai-codex" };
|
|
126
|
+
const accessToken = stored.accessToken;
|
|
127
|
+
|
|
128
|
+
const controller = new AbortController();
|
|
129
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
130
|
+
try {
|
|
131
|
+
const res = await fetch(USAGE_URL, {
|
|
132
|
+
headers: {
|
|
133
|
+
accept: "application/json",
|
|
134
|
+
authorization: `Bearer ${accessToken}`,
|
|
135
|
+
"chatgpt-account-id": stored.accountId,
|
|
136
|
+
},
|
|
137
|
+
signal: controller.signal,
|
|
138
|
+
});
|
|
139
|
+
if (res.status === 401 || res.status === 403) return { error: "session expired — run /login openai-codex" };
|
|
140
|
+
if (!res.ok) return { error: `HTTP ${res.status}` };
|
|
141
|
+
return parseCodexUsage(await res.json() as UsagePayload);
|
|
142
|
+
} finally {
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
}
|
|
145
|
+
} catch (err: any) {
|
|
146
|
+
if (err?.name === "AbortError") return { error: "timeout" };
|
|
147
|
+
return { error: err?.message ?? String(err) };
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { KimiCodingConfig, UsageProvider, UsageData, UsageReport } from "../types";
|
|
4
|
+
import { agentDir } from "../core/config";
|
|
5
|
+
import { formatDurationSeconds } from "../utils/duration";
|
|
6
|
+
|
|
7
|
+
const API_URL = "https://api.kimi.com/coding/v1/usages";
|
|
8
|
+
const FETCH_TIMEOUT_MS = 15_000;
|
|
9
|
+
|
|
10
|
+
interface KimiQuota {
|
|
11
|
+
limit?: string;
|
|
12
|
+
used?: string;
|
|
13
|
+
remaining?: string;
|
|
14
|
+
resetTime?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface KimiUsagesPayload {
|
|
18
|
+
usage?: KimiQuota;
|
|
19
|
+
limits?: { window?: { duration?: number; timeUnit?: string }; detail?: KimiQuota }[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function readAuthKey(): string | null {
|
|
23
|
+
const path = join(agentDir(), "auth.json");
|
|
24
|
+
if (!existsSync(path)) return null;
|
|
25
|
+
try {
|
|
26
|
+
const auth = JSON.parse(readFileSync(path, "utf-8"));
|
|
27
|
+
const key = auth?.["kimi-coding"]?.key;
|
|
28
|
+
return typeof key === "string" && key ? key : null;
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function parseQuota(q: KimiQuota): UsageData | null {
|
|
35
|
+
const limit = Number(q.limit);
|
|
36
|
+
const used = Number(q.used);
|
|
37
|
+
if (!Number.isFinite(limit) || limit <= 0 || !Number.isFinite(used)) return null;
|
|
38
|
+
const resetMs = q.resetTime ? Date.parse(q.resetTime) : NaN;
|
|
39
|
+
const resetSec = Number.isFinite(resetMs) ? (resetMs - Date.now()) / 1000 : undefined;
|
|
40
|
+
return {
|
|
41
|
+
pct: (used / limit) * 100,
|
|
42
|
+
resetsIn: resetSec != null && resetSec > 0 ? formatDurationSeconds(resetSec) : undefined,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function parseUsage(p: KimiUsagesPayload): UsageReport {
|
|
47
|
+
const report: UsageReport = {};
|
|
48
|
+
if (p.usage) {
|
|
49
|
+
const weekly = parseQuota(p.usage);
|
|
50
|
+
if (weekly) report.weekly = weekly;
|
|
51
|
+
}
|
|
52
|
+
const detail = p.limits?.[0]?.detail;
|
|
53
|
+
if (detail) {
|
|
54
|
+
const session = parseQuota(detail);
|
|
55
|
+
if (session) report.session = session;
|
|
56
|
+
}
|
|
57
|
+
if (!report.session && !report.weekly) return { error: "could not parse usage" };
|
|
58
|
+
return report;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function makeKimiCodingProvider(name: string, cfg: KimiCodingConfig = {}): UsageProvider {
|
|
62
|
+
const resolveApiKey = () => cfg.apiKey || readAuthKey();
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
key: name,
|
|
66
|
+
matchProviders: cfg.matchProviders ?? [name, "kimi-coding"],
|
|
67
|
+
shortLabel: cfg.shortLabel ?? "KC",
|
|
68
|
+
label: cfg.label ?? "Kimi for Coding",
|
|
69
|
+
hidden: cfg.hidden,
|
|
70
|
+
detect: () => resolveApiKey() !== null,
|
|
71
|
+
|
|
72
|
+
fetchUsage: async (): Promise<UsageReport> => {
|
|
73
|
+
const apiKey = resolveApiKey();
|
|
74
|
+
if (!apiKey) return { error: "no API key — run /login kimi-coding or set apiKey in config" };
|
|
75
|
+
|
|
76
|
+
const controller = new AbortController();
|
|
77
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
const res = await fetch(API_URL, {
|
|
81
|
+
headers: {
|
|
82
|
+
accept: "application/json",
|
|
83
|
+
authorization: `Bearer ${apiKey}`,
|
|
84
|
+
},
|
|
85
|
+
signal: controller.signal,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
if (res.status === 401 || res.status === 403) return { error: "invalid API key" };
|
|
89
|
+
if (!res.ok) return { error: `HTTP ${res.status}` };
|
|
90
|
+
|
|
91
|
+
const payload: KimiUsagesPayload = await res.json();
|
|
92
|
+
return parseUsage(payload);
|
|
93
|
+
} catch (err: any) {
|
|
94
|
+
if (err?.name === "AbortError") return { error: "timeout" };
|
|
95
|
+
return { error: err?.message ?? String(err) };
|
|
96
|
+
} finally {
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
package/providers/xai.ts
CHANGED
|
@@ -48,7 +48,7 @@ function readPiCredentials(): XaiCredentials | null {
|
|
|
48
48
|
const path = PI_AUTH_PATH();
|
|
49
49
|
if (!existsSync(path)) return null;
|
|
50
50
|
const auth = readJson<{ xai?: XaiCredentials; "xai-auth"?: XaiCredentials }>(path);
|
|
51
|
-
const entry = auth?.["xai-auth"]
|
|
51
|
+
const entry = auth?.xai ?? auth?.["xai-auth"];
|
|
52
52
|
if (!entry?.access) return null;
|
|
53
53
|
return {
|
|
54
54
|
access: String(entry.access),
|
|
@@ -161,17 +161,21 @@ function parseWeeklyUsage(payload: unknown): WeeklyUsage {
|
|
|
161
161
|
throw new Error("could not parse usage");
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
const
|
|
164
|
+
const creditUsagePercentRaw = (config as Record<string, unknown>).creditUsagePercent;
|
|
165
165
|
const billingPeriodEnd = (config as Record<string, unknown>).billingPeriodEnd;
|
|
166
166
|
if (
|
|
167
|
-
typeof creditUsagePercent !== "number" ||
|
|
168
|
-
!Number.isFinite(creditUsagePercent) ||
|
|
169
167
|
typeof billingPeriodEnd !== "string" ||
|
|
170
168
|
!Number.isFinite(new Date(billingPeriodEnd).getTime())
|
|
171
169
|
) {
|
|
172
170
|
throw new Error("could not parse usage");
|
|
173
171
|
}
|
|
174
172
|
|
|
173
|
+
// Fresh billing cycle omits creditUsagePercent; treat missing/invalid as 0 instead of failing.
|
|
174
|
+
const creditUsagePercent =
|
|
175
|
+
typeof creditUsagePercentRaw === "number" && Number.isFinite(creditUsagePercentRaw)
|
|
176
|
+
? creditUsagePercentRaw
|
|
177
|
+
: 0;
|
|
178
|
+
|
|
175
179
|
return { creditUsagePercent, billingPeriodEnd };
|
|
176
180
|
}
|
|
177
181
|
|
package/providers/zai.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { ZaiConfig, UsageProvider, UsageData, UsageReport } from "../types";
|
|
4
|
+
import { agentDir } from "../core/config";
|
|
5
|
+
import { formatDurationSeconds } from "../utils/duration";
|
|
6
|
+
|
|
7
|
+
// Undocumented endpoint reverse-engineered from the z.ai dashboard XHR.
|
|
8
|
+
// CN mirror: https://open.bigmodel.cn/api/monitor/usage/quota/limit (same account data).
|
|
9
|
+
const API_URL = "https://api.z.ai/api/monitor/usage/quota/limit";
|
|
10
|
+
const FETCH_TIMEOUT_MS = 15_000;
|
|
11
|
+
|
|
12
|
+
interface ZaiLimit {
|
|
13
|
+
type?: string;
|
|
14
|
+
unit?: number;
|
|
15
|
+
number?: number;
|
|
16
|
+
percentage?: number;
|
|
17
|
+
nextResetTime?: number;
|
|
18
|
+
usage?: number;
|
|
19
|
+
currentValue?: number;
|
|
20
|
+
remaining?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface ZaiQuotaPayload {
|
|
24
|
+
code?: number;
|
|
25
|
+
success?: boolean;
|
|
26
|
+
msg?: string;
|
|
27
|
+
data?: { limits?: ZaiLimit[]; level?: string };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function readAuthKey(): string | null {
|
|
31
|
+
const path = join(agentDir(), "auth.json");
|
|
32
|
+
if (!existsSync(path)) return null;
|
|
33
|
+
try {
|
|
34
|
+
const auth = JSON.parse(readFileSync(path, "utf-8"));
|
|
35
|
+
const key = auth?.zai?.key;
|
|
36
|
+
return typeof key === "string" && key ? key : null;
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parseLimit(l: ZaiLimit): UsageData | null {
|
|
43
|
+
let pct = l.percentage;
|
|
44
|
+
if (typeof pct !== "number" || !Number.isFinite(pct)) {
|
|
45
|
+
if (typeof l.usage === "number" && l.usage > 0 && typeof l.currentValue === "number") {
|
|
46
|
+
pct = (l.currentValue / l.usage) * 100;
|
|
47
|
+
} else {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const resetSec =
|
|
52
|
+
typeof l.nextResetTime === "number" ? (l.nextResetTime - Date.now()) / 1000 : undefined;
|
|
53
|
+
return {
|
|
54
|
+
pct,
|
|
55
|
+
resetsIn: resetSec != null && resetSec > 0 ? formatDurationSeconds(resetSec) : undefined,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function parseUsage(payload: ZaiQuotaPayload): UsageReport {
|
|
60
|
+
const limits = payload.data?.limits;
|
|
61
|
+
if (!Array.isArray(limits)) return { error: payload.msg || "no usage data" };
|
|
62
|
+
|
|
63
|
+
const report: UsageReport = {};
|
|
64
|
+
for (const l of limits) {
|
|
65
|
+
const parsed = parseLimit(l);
|
|
66
|
+
if (!parsed) continue;
|
|
67
|
+
if (l.type === "TOKENS_LIMIT" && l.unit === 3) report.session ??= parsed;
|
|
68
|
+
else if (l.type === "TOKENS_LIMIT" && l.unit === 6) report.weekly ??= parsed;
|
|
69
|
+
else if (l.type === "TIME_LIMIT") report.monthly ??= parsed;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (!report.session && !report.weekly && !report.monthly) {
|
|
73
|
+
return { error: "could not parse usage" };
|
|
74
|
+
}
|
|
75
|
+
return report;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function makeZaiProvider(name: string, cfg: ZaiConfig = {}): UsageProvider {
|
|
79
|
+
const resolveApiKey = () => cfg.apiKey || readAuthKey();
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
key: name,
|
|
83
|
+
matchProviders: cfg.matchProviders ?? [name, "zai"],
|
|
84
|
+
shortLabel: cfg.shortLabel ?? "ZAI",
|
|
85
|
+
label: cfg.label ?? "Z.ai Coding Plan",
|
|
86
|
+
hidden: cfg.hidden,
|
|
87
|
+
detect: () => resolveApiKey() !== null,
|
|
88
|
+
|
|
89
|
+
fetchUsage: async (): Promise<UsageReport> => {
|
|
90
|
+
const apiKey = resolveApiKey();
|
|
91
|
+
if (!apiKey) return { error: "no API key — run /login zai or set apiKey in config" };
|
|
92
|
+
|
|
93
|
+
const controller = new AbortController();
|
|
94
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
const res = await fetch(API_URL, {
|
|
98
|
+
headers: {
|
|
99
|
+
accept: "application/json",
|
|
100
|
+
// bare key, no Bearer prefix
|
|
101
|
+
authorization: apiKey,
|
|
102
|
+
},
|
|
103
|
+
signal: controller.signal,
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
if (res.status === 401 || res.status === 403) return { error: "invalid API key" };
|
|
107
|
+
if (!res.ok) return { error: `HTTP ${res.status}` };
|
|
108
|
+
|
|
109
|
+
const payload: ZaiQuotaPayload = await res.json();
|
|
110
|
+
if (payload.success === false || (payload.code != null && payload.code !== 200)) {
|
|
111
|
+
return { error: payload.msg || `code ${payload.code}` };
|
|
112
|
+
}
|
|
113
|
+
return parseUsage(payload);
|
|
114
|
+
} catch (err: any) {
|
|
115
|
+
if (err?.name === "AbortError") return { error: "timeout" };
|
|
116
|
+
return { error: err?.message ?? String(err) };
|
|
117
|
+
} finally {
|
|
118
|
+
clearTimeout(timer);
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
package/types.ts
CHANGED
|
@@ -31,7 +31,10 @@ export type ProviderType =
|
|
|
31
31
|
| "ark"
|
|
32
32
|
| "opencode-go"
|
|
33
33
|
| "xai"
|
|
34
|
-
| "kiro"
|
|
34
|
+
| "kiro"
|
|
35
|
+
| "kimi-coding"
|
|
36
|
+
| "zai"
|
|
37
|
+
| "codex";
|
|
35
38
|
|
|
36
39
|
/** Shared optional fields for factories and config entries. */
|
|
37
40
|
export interface ProviderMeta {
|
|
@@ -40,6 +43,8 @@ export interface ProviderMeta {
|
|
|
40
43
|
label?: string;
|
|
41
44
|
/** If true, exclude from active providers (quota panel, footer). Login still works. */
|
|
42
45
|
hidden?: boolean;
|
|
46
|
+
/** If true, do not register / refuse registration entirely. */
|
|
47
|
+
disabled?: boolean;
|
|
43
48
|
}
|
|
44
49
|
|
|
45
50
|
/** Factory input — no type (caller already picked the factory). */
|
|
@@ -70,14 +75,41 @@ export interface XaiConfig extends ProviderMeta {}
|
|
|
70
75
|
|
|
71
76
|
export interface KiroConfig extends ProviderMeta {}
|
|
72
77
|
|
|
78
|
+
export interface KimiCodingConfig extends ProviderMeta {
|
|
79
|
+
/** Optional; falls back to the "kimi-coding" entry in pi's auth.json. */
|
|
80
|
+
apiKey?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface ZaiConfig extends ProviderMeta {
|
|
84
|
+
/** Optional; falls back to the "zai" entry in pi's auth.json. */
|
|
85
|
+
apiKey?: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface CodexConfig extends ProviderMeta {}
|
|
89
|
+
|
|
73
90
|
/** L1 entry after parse — name always set (auto: type, type-2, … when omitted/clashing). */
|
|
74
|
-
export type
|
|
91
|
+
export type BuiltinProviderConfig =
|
|
75
92
|
| ({ name: string; type: "deepseek" } & DeepseekConfig)
|
|
76
93
|
| ({ name: string; type: "newapi" } & NewApiConfig)
|
|
77
94
|
| ({ name: string; type: "ark" } & ArkConfig)
|
|
78
95
|
| ({ name: string; type: "opencode-go" } & OpencodeGoConfig)
|
|
79
96
|
| ({ name: string; type: "xai" } & XaiConfig)
|
|
80
|
-
| ({ name: string; type: "kiro" } & KiroConfig)
|
|
97
|
+
| ({ name: string; type: "kiro" } & KiroConfig)
|
|
98
|
+
| ({ name: string; type: "kimi-coding" } & KimiCodingConfig)
|
|
99
|
+
| ({ name: string; type: "zai" } & ZaiConfig)
|
|
100
|
+
| ({ name: string; type: "codex" } & CodexConfig);
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* L2 entry: no `type` — targets an externally-registered (custom) provider.
|
|
104
|
+
* Meta fields override the provider's own values at register time; all other
|
|
105
|
+
* fields pass through to `hub.getProviderConfig(name)`.
|
|
106
|
+
*/
|
|
107
|
+
export interface ExtensionProviderConfig extends ProviderMeta {
|
|
108
|
+
name: string;
|
|
109
|
+
[key: string]: unknown;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export type ProviderConfig = BuiltinProviderConfig | ExtensionProviderConfig;
|
|
81
113
|
|
|
82
114
|
export interface UsageHubConfig {
|
|
83
115
|
providers?: ProviderConfig[];
|
|
@@ -86,6 +118,10 @@ export interface UsageHubConfig {
|
|
|
86
118
|
export interface UsageHub {
|
|
87
119
|
register(p: UsageProvider): void;
|
|
88
120
|
unregister(key: string): void;
|
|
121
|
+
/** Instantiate a built-in provider and register it (auto name allocation). Returns its key, or null if unknown type / disabled. */
|
|
122
|
+
registerBuiltin(type: ProviderType, cfg?: ProviderMeta & Record<string, unknown>): string | null;
|
|
123
|
+
/** Raw config entry for a custom provider key, if the user added one. */
|
|
124
|
+
getProviderConfig(key: string): ExtensionProviderConfig | undefined;
|
|
89
125
|
list(): UsageProvider[];
|
|
90
126
|
/** Match model → cached one-line summary, or null if no provider / not fetched yet. */
|
|
91
127
|
getSummary(model?: { provider?: string }): string | null;
|