pi-usage-hub 1.0.8 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -2
- package/assets/usage-hub-panel.png +0 -0
- package/assets/usage-hub-session.png +0 -0
- package/core/config.ts +75 -78
- package/core/registry.ts +71 -21
- package/index.ts +7 -1
- package/package.json +1 -1
- package/providers/kimi-coding.ts +101 -0
- package/providers/xai.ts +8 -4
- package/providers/zai.ts +122 -0
- package/types.ts +35 -3
package/README.md
CHANGED
|
@@ -27,6 +27,8 @@ Inside the panel, **Tab** switches between Quota and Session. In the Quota view,
|
|
|
27
27
|
|
|
28
28
|

|
|
29
29
|
|
|
30
|
+

|
|
31
|
+
|
|
30
32
|
## Configuration
|
|
31
33
|
|
|
32
34
|
Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel.
|
|
@@ -57,7 +59,9 @@ Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel
|
|
|
57
59
|
"type": "xai",
|
|
58
60
|
"matchProviders": ["xai-auth", "xai", "grok-cli"]
|
|
59
61
|
},
|
|
60
|
-
{ "type": "kiro" }
|
|
62
|
+
{ "type": "kiro" },
|
|
63
|
+
{ "type": "kimi-coding" },
|
|
64
|
+
{ "type": "zai" }
|
|
61
65
|
]
|
|
62
66
|
}
|
|
63
67
|
```
|
|
@@ -71,6 +75,7 @@ Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel
|
|
|
71
75
|
| `matchProviders` | no | Additional `model.provider` values mapped to this entry |
|
|
72
76
|
| `shortLabel` / `label` | no | Override the footer label or panel title |
|
|
73
77
|
| `hidden` | no | Exclude from panel and footer; `/usage-hub login` still works |
|
|
78
|
+
| `disabled` | no | Do not register at all; on untyped entries, refuses that provider's registration |
|
|
74
79
|
|
|
75
80
|
### Provider types
|
|
76
81
|
|
|
@@ -82,6 +87,8 @@ Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel
|
|
|
82
87
|
| `ark` | optional `cookie`, `csrfToken` | Uses the configured Cookie header or macOS Chrome | [火山引擎](https://console.volcengine.com/ark) |
|
|
83
88
|
| `xai` | — | Reads `auth.json` or `~/.grok/auth.json` | [x.ai/grok](https://x.ai/grok) |
|
|
84
89
|
| `kiro` | — | Reads the Kiro OAuth entry from `auth.json` | [kiro.dev](https://kiro.dev) |
|
|
90
|
+
| `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) |
|
|
91
|
+
| `zai` | optional `apiKey` | 5h window, weekly, and monthly search quota; falls back to the `zai` entry in `auth.json` | [z.ai](https://z.ai) |
|
|
85
92
|
|
|
86
93
|
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).
|
|
87
94
|
|
|
@@ -93,7 +100,6 @@ These are companion packages, not npm peer dependencies:
|
|
|
93
100
|
|
|
94
101
|
| Type | Companion | Purpose |
|
|
95
102
|
|------|-----------|---------|
|
|
96
|
-
| `xai` | [`pi-xai-oauth`](https://www.npmjs.com/package/pi-xai-oauth) | `/login xai-auth` writes the OAuth entry to `auth.json` |
|
|
97
103
|
| `kiro` | [`pi-provider-kiro-dev`](https://www.npmjs.com/package/pi-provider-kiro-dev) | Provides `/login kiro`, models, and the `auth.json` entry |
|
|
98
104
|
|
|
99
105
|
pi-usage-hub only reads those credentials; it does not run their OAuth flows.
|
|
@@ -110,6 +116,39 @@ pi.events.emit("pi-usage-hub:register", myProvider);
|
|
|
110
116
|
pi.events.emit("pi-usage-hub:unregister", { key: "my-relay" });
|
|
111
117
|
```
|
|
112
118
|
|
|
119
|
+
Re-registering the same key overwrites (registration is idempotent), so the ready-listener + emit combination above never duplicates a provider.
|
|
120
|
+
|
|
121
|
+
### Configure a custom provider from JSON
|
|
122
|
+
|
|
123
|
+
`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:
|
|
124
|
+
|
|
125
|
+
```json
|
|
126
|
+
{
|
|
127
|
+
"providers": [
|
|
128
|
+
{ "type": "kimi-coding" },
|
|
129
|
+
{
|
|
130
|
+
"name": "qianwen",
|
|
131
|
+
"shortLabel": "QW",
|
|
132
|
+
"hidden": false,
|
|
133
|
+
"cookie": "login_qianwenai_ticket=..."
|
|
134
|
+
}
|
|
135
|
+
]
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
pi.events.on("pi-usage-hub:ready", (hub) => {
|
|
141
|
+
const cfg = hub.getProviderConfig("qianwen"); // { shortLabel, hidden, cookie, ... }
|
|
142
|
+
const cookie = typeof cfg?.cookie === "string" ? cfg.cookie : undefined;
|
|
143
|
+
});
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
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.
|
|
147
|
+
|
|
148
|
+
### Register a built-in from an extension
|
|
149
|
+
|
|
150
|
+
`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`.
|
|
151
|
+
|
|
113
152
|
## Pull API
|
|
114
153
|
|
|
115
154
|
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.
|
|
Binary file
|
|
Binary file
|
package/core/config.ts
CHANGED
|
@@ -1,16 +1,32 @@
|
|
|
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
|
+
};
|
|
14
30
|
|
|
15
31
|
export function agentDir(): string {
|
|
16
32
|
return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
@@ -30,6 +46,16 @@ function asStringArray(value: unknown): string[] | undefined {
|
|
|
30
46
|
return items.length > 0 ? items : undefined;
|
|
31
47
|
}
|
|
32
48
|
|
|
49
|
+
function parseMeta(raw: Record<string, unknown>): ProviderMeta {
|
|
50
|
+
return {
|
|
51
|
+
matchProviders: asStringArray(raw.matchProviders),
|
|
52
|
+
shortLabel: typeof raw.shortLabel === "string" ? raw.shortLabel : undefined,
|
|
53
|
+
label: typeof raw.label === "string" ? raw.label : undefined,
|
|
54
|
+
hidden: typeof raw.hidden === "boolean" ? raw.hidden : undefined,
|
|
55
|
+
disabled: typeof raw.disabled === "boolean" ? raw.disabled : undefined,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
33
59
|
/** Prefer explicit name; otherwise type, then type-2, type-3, … */
|
|
34
60
|
function allocateName(type: ProviderType, preferred: string | undefined, seen: Set<string>): string {
|
|
35
61
|
const base = preferred?.trim() || type;
|
|
@@ -39,17 +65,12 @@ function allocateName(type: ProviderType, preferred: string | undefined, seen: S
|
|
|
39
65
|
return `${base}-${n}`;
|
|
40
66
|
}
|
|
41
67
|
|
|
42
|
-
function
|
|
43
|
-
raw: unknown
|
|
68
|
+
function parseBuiltinEntry(
|
|
69
|
+
raw: Record<string, unknown>,
|
|
44
70
|
index: number,
|
|
45
71
|
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)) {
|
|
72
|
+
): BuiltinProviderConfig | null {
|
|
73
|
+
if (typeof raw.type !== "string" || !(raw.type in BUILTIN_SCHEMAS)) {
|
|
53
74
|
console.warn(`[pi-usage-hub] skip providers[${index}]: unknown or missing type`);
|
|
54
75
|
return null;
|
|
55
76
|
}
|
|
@@ -61,65 +82,43 @@ function parseProviderEntry(
|
|
|
61
82
|
console.warn(`[pi-usage-hub] providers[${index}] name "${preferred.trim()}" taken, using "${name}"`);
|
|
62
83
|
}
|
|
63
84
|
|
|
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
|
-
};
|
|
85
|
+
const schema = BUILTIN_SCHEMAS[type];
|
|
86
|
+
const required = schema.required ?? [];
|
|
87
|
+
for (const field of required) {
|
|
88
|
+
if (typeof raw[field] !== "string" || !raw[field]) {
|
|
89
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: ${type} requires ${required.join(", ")}`);
|
|
90
|
+
return null;
|
|
109
91
|
}
|
|
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
92
|
}
|
|
93
|
+
|
|
94
|
+
const fields: Record<string, string> = {};
|
|
95
|
+
for (const field of [...required, ...(schema.optional ?? [])]) {
|
|
96
|
+
const value = raw[field];
|
|
97
|
+
if (typeof value === "string") fields[field] = value;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
seen.add(name);
|
|
101
|
+
return { name, type, ...parseMeta(raw), ...fields } as BuiltinProviderConfig;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function parseExtensionEntry(
|
|
105
|
+
raw: Record<string, unknown>,
|
|
106
|
+
index: number,
|
|
107
|
+
): ExtensionProviderConfig | null {
|
|
108
|
+
if (typeof raw.name !== "string" || !raw.name.trim()) {
|
|
109
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: entry without type requires a name`);
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
return { ...raw, ...parseMeta(raw), name: raw.name.trim() };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function parseProviderEntry(raw: unknown, index: number, seen: Set<string>): ProviderConfig | null {
|
|
116
|
+
if (!isObject(raw)) {
|
|
117
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: not an object`);
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
if (raw.type == null) return parseExtensionEntry(raw, index);
|
|
121
|
+
return parseBuiltinEntry(raw, index, seen);
|
|
123
122
|
}
|
|
124
123
|
|
|
125
124
|
export function loadConfig(): UsageHubConfig {
|
|
@@ -144,9 +143,7 @@ export function loadConfig(): UsageHubConfig {
|
|
|
144
143
|
|
|
145
144
|
for (let i = 0; i < raw.providers.length; i++) {
|
|
146
145
|
const parsed = parseProviderEntry(raw.providers[i], i, seen);
|
|
147
|
-
if (
|
|
148
|
-
seen.add(parsed.name);
|
|
149
|
-
providers.push(parsed);
|
|
146
|
+
if (parsed) providers.push(parsed);
|
|
150
147
|
}
|
|
151
148
|
|
|
152
149
|
return { providers };
|
package/core/registry.ts
CHANGED
|
@@ -1,16 +1,62 @@
|
|
|
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
|
+
|
|
18
|
+
const FACTORIES = {
|
|
19
|
+
deepseek: makeDeepseekProvider,
|
|
20
|
+
newapi: makeNewApiProvider,
|
|
21
|
+
ark: makeArkProvider,
|
|
22
|
+
"opencode-go": makeOpencodeGoProvider,
|
|
23
|
+
xai: makeXaiProvider,
|
|
24
|
+
kiro: makeKiroProvider,
|
|
25
|
+
"kimi-coding": makeKimiCodingProvider,
|
|
26
|
+
zai: makeZaiProvider,
|
|
27
|
+
} satisfies Record<ProviderType, (name: string, cfg: any) => UsageProvider>;
|
|
28
|
+
|
|
29
|
+
function makeProvider(cfg: BuiltinProviderConfig): UsageProvider {
|
|
30
|
+
const factory = FACTORIES[cfg.type] as (name: string, cfg: unknown) => UsageProvider;
|
|
31
|
+
return factory(cfg.name, cfg);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Config-entry meta wins over the provider's own values, per explicitly-set field. */
|
|
35
|
+
function applyMeta(p: UsageProvider, cfg: ExtensionProviderConfig): UsageProvider {
|
|
36
|
+
return {
|
|
37
|
+
...p,
|
|
38
|
+
matchProviders: cfg.matchProviders ?? p.matchProviders,
|
|
39
|
+
shortLabel: cfg.shortLabel ?? p.shortLabel,
|
|
40
|
+
label: cfg.label ?? p.label,
|
|
41
|
+
hidden: cfg.hidden ?? p.hidden,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function allocateName(base: string, taken: (name: string) => boolean): string {
|
|
46
|
+
if (!taken(base)) return base;
|
|
47
|
+
let n = 2;
|
|
48
|
+
while (taken(`${base}-${n}`)) n++;
|
|
49
|
+
return `${base}-${n}`;
|
|
50
|
+
}
|
|
8
51
|
|
|
9
52
|
export class ProviderRegistry {
|
|
10
53
|
private providers = new Map<string, UsageProvider>();
|
|
54
|
+
private extensionConfigs = new Map<string, ExtensionProviderConfig>();
|
|
11
55
|
|
|
12
56
|
register(provider: UsageProvider): void {
|
|
13
|
-
this.
|
|
57
|
+
const cfg = this.extensionConfigs.get(provider.key);
|
|
58
|
+
if (cfg?.disabled) return;
|
|
59
|
+
this.providers.set(provider.key, cfg ? applyMeta(provider, cfg) : provider);
|
|
14
60
|
}
|
|
15
61
|
|
|
16
62
|
unregister(key: string): void {
|
|
@@ -29,6 +75,21 @@ export class ProviderRegistry {
|
|
|
29
75
|
return this.providers.get(key);
|
|
30
76
|
}
|
|
31
77
|
|
|
78
|
+
getExtensionConfig(key: string): ExtensionProviderConfig | undefined {
|
|
79
|
+
return this.extensionConfigs.get(key);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
registerBuiltin(type: ProviderType, cfg: ProviderMeta & Record<string, unknown> = {}): string | null {
|
|
83
|
+
const factory = FACTORIES[type] as ((name: string, cfg: unknown) => UsageProvider) | undefined;
|
|
84
|
+
if (!factory || cfg.disabled) return null;
|
|
85
|
+
const preferred = typeof (cfg as { name?: unknown }).name === "string"
|
|
86
|
+
? (cfg as { name: string }).name.trim()
|
|
87
|
+
: "";
|
|
88
|
+
const name = allocateName(preferred || type, n => this.providers.has(n));
|
|
89
|
+
this.register(factory(name, cfg));
|
|
90
|
+
return name;
|
|
91
|
+
}
|
|
92
|
+
|
|
32
93
|
detectActive(): UsageProvider[] {
|
|
33
94
|
return this.list().filter(p => {
|
|
34
95
|
if (p.hidden) return false;
|
|
@@ -50,25 +111,14 @@ export class ProviderRegistry {
|
|
|
50
111
|
|
|
51
112
|
loadFromConfig(providers: ProviderConfig[]): void {
|
|
52
113
|
for (const cfg of providers) {
|
|
53
|
-
|
|
54
|
-
|
|
114
|
+
if (typeof (cfg as { type?: unknown }).type === "string") {
|
|
115
|
+
const builtin = cfg as BuiltinProviderConfig;
|
|
116
|
+
if (builtin.disabled) continue;
|
|
117
|
+
// Name pre-allocated by the config parser; register verbatim (last write wins).
|
|
118
|
+
this.register(makeProvider(builtin));
|
|
119
|
+
} else {
|
|
120
|
+
this.extensionConfigs.set(cfg.name, cfg as ExtensionProviderConfig);
|
|
121
|
+
}
|
|
55
122
|
}
|
|
56
123
|
}
|
|
57
124
|
}
|
|
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
|
},
|
|
@@ -189,7 +195,7 @@ export default function register(pi: ExtensionAPI) {
|
|
|
189
195
|
const termWidth = process.stdout.columns ?? 80;
|
|
190
196
|
return {
|
|
191
197
|
width: Math.min(Math.floor(termWidth * 0.65), 100),
|
|
192
|
-
minWidth:
|
|
198
|
+
minWidth: 80,
|
|
193
199
|
maxHeight: "80%",
|
|
194
200
|
anchor: "center",
|
|
195
201
|
visible: (_tw, termHeight) => {
|
package/package.json
CHANGED
|
@@ -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,9 @@ export type ProviderType =
|
|
|
31
31
|
| "ark"
|
|
32
32
|
| "opencode-go"
|
|
33
33
|
| "xai"
|
|
34
|
-
| "kiro"
|
|
34
|
+
| "kiro"
|
|
35
|
+
| "kimi-coding"
|
|
36
|
+
| "zai";
|
|
35
37
|
|
|
36
38
|
/** Shared optional fields for factories and config entries. */
|
|
37
39
|
export interface ProviderMeta {
|
|
@@ -40,6 +42,8 @@ export interface ProviderMeta {
|
|
|
40
42
|
label?: string;
|
|
41
43
|
/** If true, exclude from active providers (quota panel, footer). Login still works. */
|
|
42
44
|
hidden?: boolean;
|
|
45
|
+
/** If true, do not register / refuse registration entirely. */
|
|
46
|
+
disabled?: boolean;
|
|
43
47
|
}
|
|
44
48
|
|
|
45
49
|
/** Factory input — no type (caller already picked the factory). */
|
|
@@ -70,14 +74,38 @@ export interface XaiConfig extends ProviderMeta {}
|
|
|
70
74
|
|
|
71
75
|
export interface KiroConfig extends ProviderMeta {}
|
|
72
76
|
|
|
77
|
+
export interface KimiCodingConfig extends ProviderMeta {
|
|
78
|
+
/** Optional; falls back to the "kimi-coding" entry in pi's auth.json. */
|
|
79
|
+
apiKey?: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface ZaiConfig extends ProviderMeta {
|
|
83
|
+
/** Optional; falls back to the "zai" entry in pi's auth.json. */
|
|
84
|
+
apiKey?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
73
87
|
/** L1 entry after parse — name always set (auto: type, type-2, … when omitted/clashing). */
|
|
74
|
-
export type
|
|
88
|
+
export type BuiltinProviderConfig =
|
|
75
89
|
| ({ name: string; type: "deepseek" } & DeepseekConfig)
|
|
76
90
|
| ({ name: string; type: "newapi" } & NewApiConfig)
|
|
77
91
|
| ({ name: string; type: "ark" } & ArkConfig)
|
|
78
92
|
| ({ name: string; type: "opencode-go" } & OpencodeGoConfig)
|
|
79
93
|
| ({ name: string; type: "xai" } & XaiConfig)
|
|
80
|
-
| ({ name: string; type: "kiro" } & KiroConfig)
|
|
94
|
+
| ({ name: string; type: "kiro" } & KiroConfig)
|
|
95
|
+
| ({ name: string; type: "kimi-coding" } & KimiCodingConfig)
|
|
96
|
+
| ({ name: string; type: "zai" } & ZaiConfig);
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* L2 entry: no `type` — targets an externally-registered (custom) provider.
|
|
100
|
+
* Meta fields override the provider's own values at register time; all other
|
|
101
|
+
* fields pass through to `hub.getProviderConfig(name)`.
|
|
102
|
+
*/
|
|
103
|
+
export interface ExtensionProviderConfig extends ProviderMeta {
|
|
104
|
+
name: string;
|
|
105
|
+
[key: string]: unknown;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export type ProviderConfig = BuiltinProviderConfig | ExtensionProviderConfig;
|
|
81
109
|
|
|
82
110
|
export interface UsageHubConfig {
|
|
83
111
|
providers?: ProviderConfig[];
|
|
@@ -86,6 +114,10 @@ export interface UsageHubConfig {
|
|
|
86
114
|
export interface UsageHub {
|
|
87
115
|
register(p: UsageProvider): void;
|
|
88
116
|
unregister(key: string): void;
|
|
117
|
+
/** Instantiate a built-in provider and register it (auto name allocation). Returns its key, or null if unknown type / disabled. */
|
|
118
|
+
registerBuiltin(type: ProviderType, cfg?: ProviderMeta & Record<string, unknown>): string | null;
|
|
119
|
+
/** Raw config entry for a custom provider key, if the user added one. */
|
|
120
|
+
getProviderConfig(key: string): ExtensionProviderConfig | undefined;
|
|
89
121
|
list(): UsageProvider[];
|
|
90
122
|
/** Match model → cached one-line summary, or null if no provider / not fetched yet. */
|
|
91
123
|
getSummary(model?: { provider?: string }): string | null;
|