pi-usage-hub 1.0.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/.github/workflows/publish.yml +23 -0
- package/LICENSE +21 -0
- package/README.md +171 -0
- package/assets/usage-hub-footer.png +0 -0
- package/assets/usage-hub-panel.png +0 -0
- package/core/cache.ts +86 -0
- package/core/config.ts +152 -0
- package/core/registry.ts +73 -0
- package/examples/auth-providers.ts +42 -0
- package/index.ts +197 -0
- package/package.json +30 -0
- package/providers/ark.ts +154 -0
- package/providers/deepseek.ts +51 -0
- package/providers/kiro.ts +289 -0
- package/providers/newapi.ts +74 -0
- package/providers/opencode-go.ts +115 -0
- package/providers/xai.ts +311 -0
- package/session/collect.ts +275 -0
- package/types.ts +94 -0
- package/ui/format-report.ts +67 -0
- package/ui/format.ts +92 -0
- package/ui/session-panel.ts +178 -0
- package/ui/usage-window.ts +132 -0
- package/utils/chrome-cookies.ts +96 -0
- package/utils/duration.ts +17 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
name: Publish to npm
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
publish:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
id-token: write
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
|
|
16
|
+
- uses: actions/setup-node@v4
|
|
17
|
+
with:
|
|
18
|
+
node-version: 20
|
|
19
|
+
registry-url: https://registry.npmjs.org
|
|
20
|
+
|
|
21
|
+
- run: npm publish --provenance --access public
|
|
22
|
+
env:
|
|
23
|
+
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 ouzhenkun
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# pi-usage-hub
|
|
2
|
+
|
|
3
|
+
**Track provider quotas and balances in pi — `/usage-hub` panel, session stats, and a pull API for footer integration.**
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/pi-usage-hub)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
|
|
8
|
+
## Why
|
|
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.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pi install npm:pi-usage-hub
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Commands
|
|
19
|
+
|
|
20
|
+
| Command | Description |
|
|
21
|
+
|---------|-------------|
|
|
22
|
+
| `/usage-hub` | Show quotas and balances for detected providers |
|
|
23
|
+
| `/usage-hub session` | Show local session token and cost stats |
|
|
24
|
+
| `/usage-hub login <name>` | Open browser login for a cookie-based provider |
|
|
25
|
+
|
|
26
|
+
Inside the panel, **Tab** switches between Quota and Session.
|
|
27
|
+
|
|
28
|
+

|
|
29
|
+
|
|
30
|
+
## Configuration
|
|
31
|
+
|
|
32
|
+
Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel.
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
{
|
|
36
|
+
"providers": [
|
|
37
|
+
{
|
|
38
|
+
"type": "deepseek",
|
|
39
|
+
"apiKey": "sk-..."
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"name": "xh",
|
|
43
|
+
"type": "newapi",
|
|
44
|
+
"matchProviders": ["xh-cc", "xh-glm"],
|
|
45
|
+
"host": "https://example.com",
|
|
46
|
+
"token": "...",
|
|
47
|
+
"userId": "1"
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"name": "ocg",
|
|
51
|
+
"type": "opencode-go",
|
|
52
|
+
"workspaceId": "wrk_...",
|
|
53
|
+
"matchProviders": ["opencode-go"]
|
|
54
|
+
},
|
|
55
|
+
{ "type": "ark" },
|
|
56
|
+
{
|
|
57
|
+
"type": "xai",
|
|
58
|
+
"matchProviders": ["xai-auth", "xai", "grok-cli"]
|
|
59
|
+
},
|
|
60
|
+
{ "type": "kiro" }
|
|
61
|
+
]
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Common fields
|
|
66
|
+
|
|
67
|
+
| Field | Required | Description |
|
|
68
|
+
|-------|----------|-------------|
|
|
69
|
+
| `type` | yes | Built-in provider factory |
|
|
70
|
+
| `name` | no | Instance key; defaults to `type`, then `type-2`, `type-3`, and so on |
|
|
71
|
+
| `matchProviders` | no | Additional `model.provider` values mapped to this entry |
|
|
72
|
+
| `shortLabel` / `label` | no | Override the footer label or panel title |
|
|
73
|
+
|
|
74
|
+
### Provider types
|
|
75
|
+
|
|
76
|
+
| Type | Credentials | Notes |
|
|
77
|
+
|------|-------------|-------|
|
|
78
|
+
| `deepseek` | `apiKey` | Account balance |
|
|
79
|
+
| `newapi` | `host`, `token`, `userId` | Balance and today's spend; supports multiple instances |
|
|
80
|
+
| `opencode-go` | `workspaceId`; optional `auth` | Uses the configured auth cookie or macOS Chrome |
|
|
81
|
+
| `ark` | optional `cookie`, `csrfToken` | Uses the configured Cookie header or macOS Chrome |
|
|
82
|
+
| `xai` | — | Reads `auth.json` or `~/.grok/auth.json` |
|
|
83
|
+
| `kiro` | — | Reads the Kiro OAuth entry from `auth.json` |
|
|
84
|
+
|
|
85
|
+
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).
|
|
86
|
+
|
|
87
|
+
For ARK and OpenCode Go, configured `cookie` / `auth` values take priority over Chrome. Manual credentials disable `/usage-hub login` for that entry; replace them when they expire. Automatic Chrome cookie reading is **macOS only**.
|
|
88
|
+
|
|
89
|
+
### Related auth packages
|
|
90
|
+
|
|
91
|
+
These are companion packages, not npm peer dependencies:
|
|
92
|
+
|
|
93
|
+
| Type | Companion | Purpose |
|
|
94
|
+
|------|-----------|---------|
|
|
95
|
+
| `xai` | [`pi-xai-oauth`](https://www.npmjs.com/package/pi-xai-oauth) | `/login xai-auth` writes the OAuth entry to `auth.json` |
|
|
96
|
+
| `kiro` | [`pi-provider-kiro-dev`](https://www.npmjs.com/package/pi-provider-kiro-dev) | Provides `/login kiro`, models, and the `auth.json` entry |
|
|
97
|
+
|
|
98
|
+
pi-usage-hub only reads those credentials; it does not run their OAuth flows.
|
|
99
|
+
|
|
100
|
+
Built-in providers are the ones already used and smoke-tested by the author. The provider ecosystem is too broad to cover exhaustively. Add another provider through L2 registration, or fork the package and submit a PR.
|
|
101
|
+
|
|
102
|
+
## Pull API
|
|
103
|
+
|
|
104
|
+
The hub caches results for 60 seconds and deduplicates concurrent requests. It never pushes footer text: consumers refresh data, read the cached summary, and re-render when notified.
|
|
105
|
+
|
|
106
|
+
| API | Role |
|
|
107
|
+
|-----|------|
|
|
108
|
+
| `pi-usage-hub:ready` | Provides the hub; also emitted on `session_start` |
|
|
109
|
+
| `hub.refresh({ model?, force? })` | Refreshes the matching provider and returns its summary |
|
|
110
|
+
| `hub.getSummary(model?)` | Synchronously reads the cached one-line summary |
|
|
111
|
+
| `pi-usage-hub:updated` | Signals `{ key, summary }` after a cache update |
|
|
112
|
+
|
|
113
|
+
### Footer example
|
|
114
|
+
|
|
115
|
+

|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
type UsageHub = {
|
|
119
|
+
getSummary(model?: { provider?: string }): string | null;
|
|
120
|
+
refresh(opts?: {
|
|
121
|
+
model?: { provider?: string };
|
|
122
|
+
force?: boolean;
|
|
123
|
+
}): Promise<string | null>;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
let usageHub: UsageHub | null = null;
|
|
127
|
+
let requestRender: (() => void) | null = null;
|
|
128
|
+
|
|
129
|
+
const offReady = pi.events.on("pi-usage-hub:ready", (hub: UsageHub) => {
|
|
130
|
+
usageHub = hub;
|
|
131
|
+
requestRender?.();
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
const offUpdated = pi.events.on("pi-usage-hub:updated", () => {
|
|
135
|
+
requestRender?.();
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
139
|
+
void usageHub?.refresh({ model: ctx.model, force: true });
|
|
140
|
+
});
|
|
141
|
+
pi.on("model_select", async (event) => {
|
|
142
|
+
await usageHub?.refresh({ model: event.model, force: true });
|
|
143
|
+
});
|
|
144
|
+
pi.on("agent_end", async (_event, ctx) => {
|
|
145
|
+
await usageHub?.refresh({ model: ctx.model, force: true });
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
// Inside footer render():
|
|
149
|
+
// const usageText = usageHub?.getSummary(ctx.model);
|
|
150
|
+
// "XAI 87% · ↻ 3d 16h / M48%"
|
|
151
|
+
|
|
152
|
+
pi.on("session_shutdown", async () => {
|
|
153
|
+
offReady();
|
|
154
|
+
offUpdated();
|
|
155
|
+
usageHub = null;
|
|
156
|
+
});
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### L2 provider registration
|
|
160
|
+
|
|
161
|
+
See [`examples/auth-providers.ts`](./examples/auth-providers.ts) for a complete example.
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
pi.events.on("pi-usage-hub:ready", (hub) => hub.register(myProvider));
|
|
165
|
+
pi.events.emit("pi-usage-hub:register", myProvider);
|
|
166
|
+
pi.events.emit("pi-usage-hub:unregister", { key: "my-relay" });
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## License
|
|
170
|
+
|
|
171
|
+
MIT
|
|
Binary file
|
|
Binary file
|
package/core/cache.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { UsageProvider, UsageReport } from "../types";
|
|
2
|
+
import { shortReport } from "../ui/format-report";
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_TTL_MS = 60_000;
|
|
5
|
+
|
|
6
|
+
export interface CacheEntry {
|
|
7
|
+
report: UsageReport;
|
|
8
|
+
summary: string;
|
|
9
|
+
fetchedAt: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
type Subscriber = (e: { key: string; summary: string | null }) => void;
|
|
13
|
+
|
|
14
|
+
export class UsageCache {
|
|
15
|
+
private entries = new Map<string, CacheEntry>();
|
|
16
|
+
private inflight = new Map<string, Promise<CacheEntry>>();
|
|
17
|
+
private subscribers = new Set<Subscriber>();
|
|
18
|
+
|
|
19
|
+
constructor(private ttlMs = DEFAULT_TTL_MS) {}
|
|
20
|
+
|
|
21
|
+
getSummary(key: string): string | null {
|
|
22
|
+
return this.entries.get(key)?.summary ?? null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
getReport(key: string): UsageReport | null {
|
|
26
|
+
return this.entries.get(key)?.report ?? null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
invalidate(key?: string): void {
|
|
30
|
+
if (key) {
|
|
31
|
+
this.entries.delete(key);
|
|
32
|
+
this.notify(key, null);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const keys = [...this.entries.keys()];
|
|
36
|
+
this.entries.clear();
|
|
37
|
+
for (const k of keys) this.notify(k, null);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
subscribe(fn: Subscriber): () => void {
|
|
41
|
+
this.subscribers.add(fn);
|
|
42
|
+
return () => {
|
|
43
|
+
this.subscribers.delete(fn);
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async refreshProvider(provider: UsageProvider, force = false): Promise<CacheEntry> {
|
|
48
|
+
const hit = this.entries.get(provider.key);
|
|
49
|
+
if (!force && hit && Date.now() - hit.fetchedAt < this.ttlMs) return hit;
|
|
50
|
+
|
|
51
|
+
const existing = this.inflight.get(provider.key);
|
|
52
|
+
if (existing) return existing;
|
|
53
|
+
|
|
54
|
+
const job = (async () => {
|
|
55
|
+
let report: UsageReport;
|
|
56
|
+
try {
|
|
57
|
+
report = await provider.fetchUsage();
|
|
58
|
+
} catch (err) {
|
|
59
|
+
report = { error: err instanceof Error ? err.message : String(err) };
|
|
60
|
+
}
|
|
61
|
+
const entry: CacheEntry = {
|
|
62
|
+
report,
|
|
63
|
+
summary: shortReport(report, provider),
|
|
64
|
+
fetchedAt: Date.now(),
|
|
65
|
+
};
|
|
66
|
+
this.entries.set(provider.key, entry);
|
|
67
|
+
this.notify(provider.key, entry.summary);
|
|
68
|
+
return entry;
|
|
69
|
+
})().finally(() => {
|
|
70
|
+
this.inflight.delete(provider.key);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
this.inflight.set(provider.key, job);
|
|
74
|
+
return job;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private notify(key: string, summary: string | null): void {
|
|
78
|
+
for (const fn of this.subscribers) {
|
|
79
|
+
try {
|
|
80
|
+
fn({ key, summary });
|
|
81
|
+
} catch {
|
|
82
|
+
// ignore subscriber errors
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
package/core/config.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { ProviderConfig, ProviderType, UsageHubConfig } from "../types";
|
|
5
|
+
|
|
6
|
+
const TYPES = new Set<ProviderType>([
|
|
7
|
+
"deepseek",
|
|
8
|
+
"newapi",
|
|
9
|
+
"ark",
|
|
10
|
+
"opencode-go",
|
|
11
|
+
"xai",
|
|
12
|
+
"kiro",
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
export function agentDir(): string {
|
|
16
|
+
return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function configPath(): string {
|
|
20
|
+
return join(agentDir(), "pi-usage-hub.json");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
24
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function asStringArray(value: unknown): string[] | undefined {
|
|
28
|
+
if (!Array.isArray(value)) return undefined;
|
|
29
|
+
const items = value.filter((v): v is string => typeof v === "string");
|
|
30
|
+
return items.length > 0 ? items : undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Prefer explicit name; otherwise type, then type-2, type-3, … */
|
|
34
|
+
function allocateName(type: ProviderType, preferred: string | undefined, seen: Set<string>): string {
|
|
35
|
+
const base = preferred?.trim() || type;
|
|
36
|
+
if (!seen.has(base)) return base;
|
|
37
|
+
let n = 2;
|
|
38
|
+
while (seen.has(`${base}-${n}`)) n++;
|
|
39
|
+
return `${base}-${n}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parseProviderEntry(
|
|
43
|
+
raw: unknown,
|
|
44
|
+
index: number,
|
|
45
|
+
seen: Set<string>,
|
|
46
|
+
): ProviderConfig | null {
|
|
47
|
+
if (!isObject(raw)) {
|
|
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)) {
|
|
53
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: unknown or missing type`);
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const type = raw.type as ProviderType;
|
|
58
|
+
const preferred = typeof raw.name === "string" ? raw.name : undefined;
|
|
59
|
+
const name = allocateName(type, preferred, seen);
|
|
60
|
+
if (preferred?.trim() && name !== preferred.trim()) {
|
|
61
|
+
console.warn(`[pi-usage-hub] providers[${index}] name "${preferred.trim()}" taken, using "${name}"`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const meta = {
|
|
65
|
+
matchProviders: asStringArray(raw.matchProviders),
|
|
66
|
+
shortLabel: typeof raw.shortLabel === "string" ? raw.shortLabel : undefined,
|
|
67
|
+
label: typeof raw.label === "string" ? raw.label : undefined,
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
switch (type) {
|
|
71
|
+
case "deepseek": {
|
|
72
|
+
if (typeof raw.apiKey !== "string" || !raw.apiKey) {
|
|
73
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: deepseek requires apiKey`);
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
return { name, type: "deepseek", ...meta, apiKey: raw.apiKey };
|
|
77
|
+
}
|
|
78
|
+
case "newapi": {
|
|
79
|
+
if (
|
|
80
|
+
typeof raw.host !== "string" ||
|
|
81
|
+
typeof raw.token !== "string" ||
|
|
82
|
+
typeof raw.userId !== "string"
|
|
83
|
+
) {
|
|
84
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: newapi requires host, token, userId`);
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
name,
|
|
89
|
+
type: "newapi",
|
|
90
|
+
...meta,
|
|
91
|
+
host: raw.host,
|
|
92
|
+
token: raw.token,
|
|
93
|
+
userId: raw.userId,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
case "opencode-go": {
|
|
97
|
+
if (typeof raw.workspaceId !== "string" || !raw.workspaceId) {
|
|
98
|
+
console.warn(`[pi-usage-hub] skip providers[${index}]: opencode-go requires workspaceId`);
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
name,
|
|
103
|
+
type: "opencode-go",
|
|
104
|
+
...meta,
|
|
105
|
+
workspaceId: raw.workspaceId,
|
|
106
|
+
auth: typeof raw.auth === "string" ? raw.auth : undefined,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
case "ark":
|
|
110
|
+
return {
|
|
111
|
+
name,
|
|
112
|
+
type: "ark",
|
|
113
|
+
...meta,
|
|
114
|
+
cookie: typeof raw.cookie === "string" ? raw.cookie : undefined,
|
|
115
|
+
csrfToken: typeof raw.csrfToken === "string" ? raw.csrfToken : undefined,
|
|
116
|
+
};
|
|
117
|
+
case "xai":
|
|
118
|
+
return { name, type: "xai", ...meta };
|
|
119
|
+
case "kiro":
|
|
120
|
+
return { name, type: "kiro", ...meta };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function loadConfig(): UsageHubConfig {
|
|
125
|
+
const path = configPath();
|
|
126
|
+
if (!existsSync(path)) return { providers: [] };
|
|
127
|
+
|
|
128
|
+
let raw: unknown;
|
|
129
|
+
try {
|
|
130
|
+
raw = JSON.parse(readFileSync(path, "utf-8"));
|
|
131
|
+
} catch {
|
|
132
|
+
console.warn(`[pi-usage-hub] failed to parse ${path}`);
|
|
133
|
+
return { providers: [] };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (!isObject(raw) || !Array.isArray(raw.providers)) {
|
|
137
|
+
console.warn(`[pi-usage-hub] ${path} must be { "providers": [ ... ] }`);
|
|
138
|
+
return { providers: [] };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const providers: ProviderConfig[] = [];
|
|
142
|
+
const seen = new Set<string>();
|
|
143
|
+
|
|
144
|
+
for (let i = 0; i < raw.providers.length; i++) {
|
|
145
|
+
const parsed = parseProviderEntry(raw.providers[i], i, seen);
|
|
146
|
+
if (!parsed) continue;
|
|
147
|
+
seen.add(parsed.name);
|
|
148
|
+
providers.push(parsed);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return { providers };
|
|
152
|
+
}
|
package/core/registry.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { ProviderConfig, UsageProvider } from "../types";
|
|
2
|
+
import { makeDeepseekProvider } from "../providers/deepseek";
|
|
3
|
+
import { makeNewApiProvider } from "../providers/newapi";
|
|
4
|
+
import { makeArkProvider } from "../providers/ark";
|
|
5
|
+
import { makeOpencodeGoProvider } from "../providers/opencode-go";
|
|
6
|
+
import { makeXaiProvider } from "../providers/xai";
|
|
7
|
+
import { makeKiroProvider } from "../providers/kiro";
|
|
8
|
+
|
|
9
|
+
export class ProviderRegistry {
|
|
10
|
+
private providers = new Map<string, UsageProvider>();
|
|
11
|
+
|
|
12
|
+
register(provider: UsageProvider): void {
|
|
13
|
+
this.providers.set(provider.key, provider);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
unregister(key: string): void {
|
|
17
|
+
this.providers.delete(key);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
clear(): void {
|
|
21
|
+
this.providers.clear();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
list(): UsageProvider[] {
|
|
25
|
+
return [...this.providers.values()];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
get(key: string): UsageProvider | undefined {
|
|
29
|
+
return this.providers.get(key);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
detectActive(): UsageProvider[] {
|
|
33
|
+
return this.list().filter(p => {
|
|
34
|
+
try {
|
|
35
|
+
return p.detect();
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
matchModel(model?: { provider?: string }): UsageProvider | null {
|
|
43
|
+
const current = model?.provider;
|
|
44
|
+
if (!current) return null;
|
|
45
|
+
return this.detectActive().find(p =>
|
|
46
|
+
p.key === current || (p.matchProviders?.includes(current) ?? false),
|
|
47
|
+
) ?? null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
loadFromConfig(providers: ProviderConfig[]): void {
|
|
51
|
+
for (const cfg of providers) {
|
|
52
|
+
const provider = makeProvider(cfg);
|
|
53
|
+
if (provider) this.register(provider);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function makeProvider(cfg: ProviderConfig): UsageProvider | null {
|
|
59
|
+
switch (cfg.type) {
|
|
60
|
+
case "deepseek":
|
|
61
|
+
return makeDeepseekProvider(cfg.name, cfg);
|
|
62
|
+
case "newapi":
|
|
63
|
+
return makeNewApiProvider(cfg.name, cfg);
|
|
64
|
+
case "ark":
|
|
65
|
+
return makeArkProvider(cfg.name, cfg);
|
|
66
|
+
case "opencode-go":
|
|
67
|
+
return makeOpencodeGoProvider(cfg.name, cfg);
|
|
68
|
+
case "xai":
|
|
69
|
+
return makeXaiProvider(cfg.name, cfg);
|
|
70
|
+
case "kiro":
|
|
71
|
+
return makeKiroProvider(cfg.name, cfg);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example: register session/OAuth usage providers via L2 (not via config).
|
|
3
|
+
*
|
|
4
|
+
* Not loaded by the package. Copy into ~/.pi/agent/extensions/ or adapt.
|
|
5
|
+
*
|
|
6
|
+
* pi.events.on("pi-usage-hub:ready", hub => hub.register(...))
|
|
7
|
+
* pi.events.emit("pi-usage-hub:register", provider)
|
|
8
|
+
*
|
|
9
|
+
* Prefer L1 config when possible:
|
|
10
|
+
*
|
|
11
|
+
* { "name": "xai", "type": "xai", "matchProviders": ["xai-auth", "xai", "grok-cli"] }
|
|
12
|
+
*/
|
|
13
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { makeArkProvider } from "../providers/ark";
|
|
15
|
+
import { makeXaiProvider } from "../providers/xai";
|
|
16
|
+
import { makeKiroProvider } from "../providers/kiro";
|
|
17
|
+
import type { UsageHub, UsageProvider } from "../types";
|
|
18
|
+
|
|
19
|
+
const providers: UsageProvider[] = [
|
|
20
|
+
makeArkProvider("ark", { matchProviders: ["ark"] }),
|
|
21
|
+
makeXaiProvider("xai", {
|
|
22
|
+
matchProviders: ["xai-auth", "xai", "grok-cli"],
|
|
23
|
+
}),
|
|
24
|
+
makeKiroProvider("kiro", { matchProviders: ["kiro"] }),
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
export default function register(pi: ExtensionAPI) {
|
|
28
|
+
const attach = (hub: UsageHub) => {
|
|
29
|
+
for (const p of providers) hub.register(p);
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const offReady = pi.events.on("pi-usage-hub:ready", (hub: UsageHub) => {
|
|
33
|
+
attach(hub);
|
|
34
|
+
});
|
|
35
|
+
for (const p of providers) {
|
|
36
|
+
pi.events.emit("pi-usage-hub:register", p);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
pi.on("session_shutdown", async () => {
|
|
40
|
+
offReady();
|
|
41
|
+
});
|
|
42
|
+
}
|