tokenwallet-mcp 1.0.1 → 1.0.3
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 +60 -21
- package/dist/collectors/claude.js +5 -4
- package/dist/collectors/gemini.js +55 -26
- package/dist/collectors/index.js +9 -18
- package/dist/collectors/muse-code.js +58 -0
- package/dist/collectors/status-quota.js +61 -0
- package/dist/collectors/types.js +0 -9
- package/dist/collectors/{grok.js → xai.js} +13 -9
- package/dist/config.js +57 -32
- package/dist/index.js +48 -32
- package/dist/server.js +147 -115
- package/dist/statusline.js +15 -0
- package/dist/update.js +69 -0
- package/package.json +3 -2
- package/dist/collectors/cursor.js +0 -108
package/README.md
CHANGED
|
@@ -8,29 +8,26 @@ Official MCP server for [TokenWallet](https://token-wallet.app) — connect your
|
|
|
8
8
|
|
|
9
9
|
## Installation
|
|
10
10
|
|
|
11
|
-
### CLI (Codex CLI / Claude Code
|
|
11
|
+
### CLI (Codex CLI / Claude Code)
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
14
|
# Codex CLI
|
|
15
|
-
codex mcp add tokenwallet -- npx -y tokenwallet-mcp
|
|
15
|
+
codex mcp add tokenwallet -- npx -y --prefer-online tokenwallet-mcp@latest --provider openai
|
|
16
16
|
|
|
17
17
|
# Claude Code
|
|
18
|
-
claude mcp add tokenwallet -- npx -y tokenwallet-mcp
|
|
19
|
-
|
|
20
|
-
# Gemini CLI
|
|
21
|
-
gemini mcp add tokenwallet npx -y tokenwallet-mcp
|
|
18
|
+
claude mcp add tokenwallet -- npx -y --prefer-online tokenwallet-mcp@latest --provider claude
|
|
22
19
|
```
|
|
23
20
|
|
|
24
|
-
### Desktop & IDE (
|
|
21
|
+
### Desktop & IDE (Claude Desktop / Windsurf / Cline & more)
|
|
25
22
|
|
|
26
|
-
Add the following to your client's MCP configuration file
|
|
23
|
+
Add the following to your client's MCP configuration file and replace `<provider>` with the provider ID, such as `claude`.
|
|
27
24
|
|
|
28
25
|
```json
|
|
29
26
|
{
|
|
30
27
|
"mcpServers": {
|
|
31
28
|
"tokenwallet": {
|
|
32
29
|
"command": "npx",
|
|
33
|
-
"args": ["-y", "tokenwallet-mcp"]
|
|
30
|
+
"args": ["-y", "--prefer-online", "tokenwallet-mcp@latest", "--provider", "<provider>"]
|
|
34
31
|
}
|
|
35
32
|
}
|
|
36
33
|
}
|
|
@@ -46,7 +43,7 @@ Add to your user or workspace `.vscode/mcp.json`:
|
|
|
46
43
|
"tokenwallet": {
|
|
47
44
|
"type": "stdio",
|
|
48
45
|
"command": "npx",
|
|
49
|
-
"args": ["-y", "tokenwallet-mcp"]
|
|
46
|
+
"args": ["-y", "--prefer-online", "tokenwallet-mcp@latest", "--provider", "<provider>"]
|
|
50
47
|
}
|
|
51
48
|
}
|
|
52
49
|
}
|
|
@@ -57,7 +54,11 @@ Add to your user or workspace `.vscode/mcp.json`:
|
|
|
57
54
|
1. After installation, start a conversation in your AI client and say:
|
|
58
55
|
**"Connect to TokenWallet"**
|
|
59
56
|
2. Open the **TokenWallet** app on your phone, tap **+** → select the platform → **Scan QR Code** (or enter the 8-character pairing code manually).
|
|
60
|
-
3.
|
|
57
|
+
3. After pairing, view your quota in TokenWallet.
|
|
58
|
+
|
|
59
|
+
### Updates
|
|
60
|
+
|
|
61
|
+
The launch command resolves npm's latest stable version whenever the client starts the MCP server. To update an older setup, tell your agent **“Update my existing TokenWallet MCP and use the latest stable release without pinning a version.”** Clients that support MCP prompts can also use `update_tokenwallet`. The `check_tokenwallet_updates` tool reports the version of the running process and the latest npm release.
|
|
61
62
|
|
|
62
63
|
---
|
|
63
64
|
|
|
@@ -67,20 +68,17 @@ Add to your user or workspace `.vscode/mcp.json`:
|
|
|
67
68
|
|
|
68
69
|
### 安装方式
|
|
69
70
|
|
|
70
|
-
#### 命令行客户端(Codex CLI / Claude Code
|
|
71
|
+
#### 命令行客户端(Codex CLI / Claude Code)
|
|
71
72
|
|
|
72
73
|
```bash
|
|
73
74
|
# Codex CLI
|
|
74
|
-
codex mcp add tokenwallet -- npx -y tokenwallet-mcp
|
|
75
|
+
codex mcp add tokenwallet -- npx -y --prefer-online tokenwallet-mcp@latest --provider openai
|
|
75
76
|
|
|
76
77
|
# Claude Code
|
|
77
|
-
claude mcp add tokenwallet -- npx -y tokenwallet-mcp
|
|
78
|
-
|
|
79
|
-
# Gemini CLI
|
|
80
|
-
gemini mcp add tokenwallet npx -y tokenwallet-mcp
|
|
78
|
+
claude mcp add tokenwallet -- npx -y --prefer-online tokenwallet-mcp@latest --provider claude
|
|
81
79
|
```
|
|
82
80
|
|
|
83
|
-
#### 桌面端与 IDE(
|
|
81
|
+
#### 桌面端与 IDE(Claude Desktop / Windsurf / Cline 等)
|
|
84
82
|
|
|
85
83
|
在对应客户端的 MCP 配置文件中加入(其他任何支持 MCP 协议的 IDE 或 AI 客户端均可按相同方式配置使用):
|
|
86
84
|
|
|
@@ -89,7 +87,7 @@ gemini mcp add tokenwallet npx -y tokenwallet-mcp
|
|
|
89
87
|
"mcpServers": {
|
|
90
88
|
"tokenwallet": {
|
|
91
89
|
"command": "npx",
|
|
92
|
-
"args": ["-y", "tokenwallet-mcp"]
|
|
90
|
+
"args": ["-y", "--prefer-online", "tokenwallet-mcp@latest", "--provider", "<provider>"]
|
|
93
91
|
}
|
|
94
92
|
}
|
|
95
93
|
}
|
|
@@ -105,15 +103,56 @@ gemini mcp add tokenwallet npx -y tokenwallet-mcp
|
|
|
105
103
|
"tokenwallet": {
|
|
106
104
|
"type": "stdio",
|
|
107
105
|
"command": "npx",
|
|
108
|
-
"args": ["-y", "tokenwallet-mcp"]
|
|
106
|
+
"args": ["-y", "--prefer-online", "tokenwallet-mcp@latest", "--provider", "<provider>"]
|
|
109
107
|
}
|
|
110
108
|
}
|
|
111
109
|
}
|
|
112
110
|
```
|
|
113
111
|
|
|
112
|
+
将配置中的 `<provider>` 替换为对应的供应商 ID,例如 `claude`。
|
|
113
|
+
|
|
114
114
|
### 快速开始
|
|
115
115
|
|
|
116
116
|
1. 安装完成后,在 AI 客户端对话中输入:
|
|
117
117
|
**「帮我连接 TokenWallet」**
|
|
118
118
|
2. 打开手机上的 **词元钱包(TokenWallet)** App,点击右上角 **+** → 选择对应平台 → **扫描二维码**(若无法扫码可手动输入 8 位配对码)。
|
|
119
|
-
3.
|
|
119
|
+
3. 配对完成后,在词元钱包中查看额度。
|
|
120
|
+
|
|
121
|
+
### 更新 MCP
|
|
122
|
+
|
|
123
|
+
配置中的 `@latest` 是 npm 的发布标签。客户端每次启动 MCP 时都会在线解析最新稳定版,无需在配置里改版本号。已经在运行的 MCP 会检查更新,并在有新版时提示重新加载。
|
|
124
|
+
|
|
125
|
+
已有安装可以直接告诉原来的 AI 助手:**「帮我升级现有的 TokenWallet MCP,以后每次连接用 npm 最新版,保留现有供应商和连接配置。」** 支持 MCP 提示词的客户端也可以选用 `update_tokenwallet`,或让助手调用 `check_tokenwallet_updates` 查看当前运行版本和 npm 最新版。
|
|
126
|
+
|
|
127
|
+
### 发布 npm 新版本
|
|
128
|
+
|
|
129
|
+
#### 首次配置
|
|
130
|
+
|
|
131
|
+
在 [npm 包设置](https://www.npmjs.com/package/tokenwallet-mcp/access) 的 **Trusted Publisher** 中选择 **GitHub Actions**,填写下表并保存。 [npm 配置文档](https://docs.npmjs.com/trusted-publishers/#for-github-actions)
|
|
132
|
+
|
|
133
|
+
| 字段 | 值 |
|
|
134
|
+
| --- | --- |
|
|
135
|
+
| Organization or user | `token-wallet-app` |
|
|
136
|
+
| Repository | `mcp` |
|
|
137
|
+
| Workflow filename | `publish.yml` |
|
|
138
|
+
| Environment | 留空 |
|
|
139
|
+
| Allowed actions | 勾选 `npm publish` |
|
|
140
|
+
|
|
141
|
+
#### 每次发版
|
|
142
|
+
|
|
143
|
+
确认工作区里的发布内容已经提交。在 MCP 仓库根目录执行以下命令。这个例子将 `1.0.1` 升到 `1.0.2`。
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
git switch main
|
|
147
|
+
git pull --ff-only origin main
|
|
148
|
+
npm version patch
|
|
149
|
+
git push --atomic origin main v1.0.2
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
`npm version patch` 会更新 `package.json` 和 `package-lock.json`,并创建版本提交和标签。以后发版时,把最后一条命令里的 `v1.0.2` 换成 `npm version` 输出的标签。
|
|
153
|
+
|
|
154
|
+
标签推送后,在 GitHub 的 **Actions → Publish to npm** 查看结果。流水线会核对标签、运行类型检查和测试,再构建并发布。成功后执行以下命令,确认输出为刚发布的版本号:
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
npm view tokenwallet-mcp@latest version
|
|
158
|
+
```
|
|
@@ -80,9 +80,10 @@ export async function collectClaudeQuota() {
|
|
|
80
80
|
}
|
|
81
81
|
if (data.extra_usage?.is_enabled &&
|
|
82
82
|
typeof data.extra_usage.monthly_limit === 'number' &&
|
|
83
|
-
data.extra_usage.monthly_limit > 0
|
|
84
|
-
|
|
85
|
-
const
|
|
83
|
+
data.extra_usage.monthly_limit > 0 &&
|
|
84
|
+
typeof data.extra_usage.used_credits === 'number') {
|
|
85
|
+
const used = data.extra_usage.used_credits;
|
|
86
|
+
const remaining = Math.max(0, (data.extra_usage.monthly_limit - used) / 100);
|
|
86
87
|
meters.push({
|
|
87
88
|
meterKey: 'extra',
|
|
88
89
|
product: 'claude-code',
|
|
@@ -90,7 +91,7 @@ export async function collectClaudeQuota() {
|
|
|
90
91
|
kind: 'balance',
|
|
91
92
|
window: 'month',
|
|
92
93
|
remaining,
|
|
93
|
-
total: data.extra_usage.monthly_limit,
|
|
94
|
+
total: data.extra_usage.monthly_limit / 100,
|
|
94
95
|
unit: 'USD',
|
|
95
96
|
observedAt: now,
|
|
96
97
|
});
|
|
@@ -7,39 +7,67 @@ function readGeminiAccessToken() {
|
|
|
7
7
|
if (envToken)
|
|
8
8
|
return envToken;
|
|
9
9
|
const geminiHome = process.env.GEMINI_CLI_HOME || path.join(os.homedir(), '.gemini');
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (parsed.access_token?.trim()) {
|
|
20
|
-
return parsed.access_token.trim();
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
catch {
|
|
24
|
-
// Try next candidate
|
|
25
|
-
}
|
|
10
|
+
const credFile = path.join(geminiHome, 'oauth_creds.json');
|
|
11
|
+
if (!fs.existsSync(credFile))
|
|
12
|
+
return null;
|
|
13
|
+
try {
|
|
14
|
+
const parsed = JSON.parse(fs.readFileSync(credFile, 'utf8'));
|
|
15
|
+
return parsed.access_token?.trim() || null;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
26
19
|
}
|
|
27
|
-
|
|
20
|
+
}
|
|
21
|
+
async function resolveCodeAssistContext(headers) {
|
|
22
|
+
const res = await fetch('https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist', {
|
|
23
|
+
method: 'POST',
|
|
24
|
+
headers,
|
|
25
|
+
body: JSON.stringify({
|
|
26
|
+
metadata: {
|
|
27
|
+
ideType: 'GEMINI_CLI',
|
|
28
|
+
pluginType: 'GEMINI',
|
|
29
|
+
},
|
|
30
|
+
}),
|
|
31
|
+
signal: AbortSignal.timeout(6000),
|
|
32
|
+
}).catch(() => null);
|
|
33
|
+
if (!res || !res.ok)
|
|
34
|
+
return {};
|
|
35
|
+
const payload = (await res.json().catch(() => null));
|
|
36
|
+
if (!payload)
|
|
37
|
+
return {};
|
|
38
|
+
const rawProj = payload.cloudaicompanionProject;
|
|
39
|
+
const project = typeof rawProj === 'string'
|
|
40
|
+
? rawProj.trim() || undefined
|
|
41
|
+
: typeof rawProj?.id === 'string'
|
|
42
|
+
? rawProj.id.trim() || undefined
|
|
43
|
+
: undefined;
|
|
44
|
+
const tierName = (payload.paidTier?.name || payload.currentTier?.name || '').trim() || undefined;
|
|
45
|
+
return { project, plan: tierName };
|
|
28
46
|
}
|
|
29
47
|
export async function collectGeminiQuota() {
|
|
30
48
|
const token = readGeminiAccessToken();
|
|
31
49
|
if (!token)
|
|
32
50
|
return null;
|
|
33
|
-
const
|
|
51
|
+
const headers = {
|
|
52
|
+
Authorization: `Bearer ${token}`,
|
|
53
|
+
'Content-Type': 'application/json',
|
|
54
|
+
Accept: 'application/json',
|
|
55
|
+
};
|
|
56
|
+
const { project, plan } = await resolveCodeAssistContext(headers);
|
|
57
|
+
let res = await fetch('https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota', {
|
|
34
58
|
method: 'POST',
|
|
35
|
-
headers
|
|
36
|
-
|
|
37
|
-
'Content-Type': 'application/json',
|
|
38
|
-
Accept: 'application/json',
|
|
39
|
-
},
|
|
40
|
-
body: JSON.stringify({}),
|
|
59
|
+
headers,
|
|
60
|
+
body: JSON.stringify(project ? { project } : {}),
|
|
41
61
|
signal: AbortSignal.timeout(8000),
|
|
42
62
|
}).catch(() => null);
|
|
63
|
+
if ((!res || !res.ok) && project) {
|
|
64
|
+
res = await fetch('https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota', {
|
|
65
|
+
method: 'POST',
|
|
66
|
+
headers,
|
|
67
|
+
body: JSON.stringify({}),
|
|
68
|
+
signal: AbortSignal.timeout(8000),
|
|
69
|
+
}).catch(() => null);
|
|
70
|
+
}
|
|
43
71
|
if (!res || !res.ok)
|
|
44
72
|
return null;
|
|
45
73
|
const data = (await res.json().catch(() => null));
|
|
@@ -50,7 +78,7 @@ export async function collectGeminiQuota() {
|
|
|
50
78
|
const flashBuckets = data.buckets.filter((b) => b.modelId?.toLowerCase().includes('flash'));
|
|
51
79
|
const meters = [];
|
|
52
80
|
const pickLowest = (list) => list
|
|
53
|
-
.filter((b) => typeof b.remainingFraction === 'number')
|
|
81
|
+
.filter((b) => typeof b.remainingFraction === 'number' && Number.isFinite(b.remainingFraction))
|
|
54
82
|
.sort((a, b) => (a.remainingFraction ?? 1) - (b.remainingFraction ?? 1))[0];
|
|
55
83
|
const pro = pickLowest(proBuckets);
|
|
56
84
|
if (pro && typeof pro.remainingFraction === 'number') {
|
|
@@ -90,7 +118,7 @@ export async function collectGeminiQuota() {
|
|
|
90
118
|
meters.push({
|
|
91
119
|
meterKey: 'default',
|
|
92
120
|
product: 'gemini',
|
|
93
|
-
label: first.modelId || '
|
|
121
|
+
label: first.modelId || 'Gemini',
|
|
94
122
|
kind: 'percent',
|
|
95
123
|
window: 'day',
|
|
96
124
|
remaining: Math.max(0, Math.min(100, Math.round(first.remainingFraction * 1000) / 10)),
|
|
@@ -105,6 +133,7 @@ export async function collectGeminiQuota() {
|
|
|
105
133
|
return null;
|
|
106
134
|
return {
|
|
107
135
|
brand: 'gemini',
|
|
136
|
+
plan,
|
|
108
137
|
observedAt: now,
|
|
109
138
|
source: 'gemini-cli',
|
|
110
139
|
meters,
|
package/dist/collectors/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { readLatestCodexQuota } from '../codex-reader.js';
|
|
2
2
|
import { collectClaudeQuota } from './claude.js';
|
|
3
|
-
import { collectCursorQuota } from './cursor.js';
|
|
4
3
|
import { collectGeminiQuota } from './gemini.js';
|
|
5
|
-
import {
|
|
4
|
+
import { collectMuseCodeQuota } from './muse-code.js';
|
|
5
|
+
import { collectXaiQuota } from './xai.js';
|
|
6
|
+
import { readStatusQuota } from './status-quota.js';
|
|
6
7
|
export async function collectQuotaForBrand(brand) {
|
|
7
8
|
switch (brand) {
|
|
8
9
|
case 'openai': {
|
|
@@ -18,24 +19,14 @@ export async function collectQuotaForBrand(brand) {
|
|
|
18
19
|
};
|
|
19
20
|
}
|
|
20
21
|
case 'claude':
|
|
21
|
-
return collectClaudeQuota();
|
|
22
|
-
case 'cursor':
|
|
23
|
-
return collectCursorQuota();
|
|
22
|
+
return readStatusQuota('claude') ?? collectClaudeQuota();
|
|
24
23
|
case 'gemini':
|
|
25
|
-
return collectGeminiQuota();
|
|
26
|
-
case '
|
|
27
|
-
return
|
|
24
|
+
return readStatusQuota('gemini') ?? collectGeminiQuota();
|
|
25
|
+
case 'muse-code':
|
|
26
|
+
return collectMuseCodeQuota();
|
|
27
|
+
case 'xai':
|
|
28
|
+
return collectXaiQuota();
|
|
28
29
|
default:
|
|
29
30
|
return null;
|
|
30
31
|
}
|
|
31
32
|
}
|
|
32
|
-
export async function collectAllLocalQuotas() {
|
|
33
|
-
const results = await Promise.all([
|
|
34
|
-
collectQuotaForBrand('openai'),
|
|
35
|
-
collectQuotaForBrand('claude'),
|
|
36
|
-
collectQuotaForBrand('cursor'),
|
|
37
|
-
collectQuotaForBrand('gemini'),
|
|
38
|
-
collectQuotaForBrand('grok'),
|
|
39
|
-
]);
|
|
40
|
-
return results.filter((snap) => snap !== null);
|
|
41
|
-
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { toRemainingPercent } from './types.js';
|
|
5
|
+
const runFile = promisify(execFile);
|
|
6
|
+
const allowanceWindow = z.object({
|
|
7
|
+
usedPercent: z.number().min(0).max(100),
|
|
8
|
+
resetsAtMs: z.number().int().positive().nullish(),
|
|
9
|
+
});
|
|
10
|
+
const usageResponse = z.object({
|
|
11
|
+
allowance: z.object({
|
|
12
|
+
tier: z.string().trim().nullish(),
|
|
13
|
+
window: allowanceWindow.nullish(),
|
|
14
|
+
weekly: allowanceWindow.nullish(),
|
|
15
|
+
asOfMs: z.number().int().positive().nullish(),
|
|
16
|
+
}).nullish(),
|
|
17
|
+
});
|
|
18
|
+
export async function collectMuseCodeQuota() {
|
|
19
|
+
try {
|
|
20
|
+
const windows = process.platform === 'win32';
|
|
21
|
+
// The Windows installer puts a muse.cmd launcher on PATH.
|
|
22
|
+
const command = windows ? process.env.ComSpec || 'cmd.exe' : 'muse';
|
|
23
|
+
const args = windows ? ['/d', '/c', 'muse', 'usage', '--json'] : ['usage', '--json'];
|
|
24
|
+
const { stdout } = await runFile(command, args, {
|
|
25
|
+
encoding: 'utf8',
|
|
26
|
+
timeout: 15_000,
|
|
27
|
+
maxBuffer: 128 * 1024,
|
|
28
|
+
windowsHide: true,
|
|
29
|
+
});
|
|
30
|
+
const response = usageResponse.safeParse(JSON.parse(stdout));
|
|
31
|
+
if (!response.success || !response.data.allowance)
|
|
32
|
+
return null;
|
|
33
|
+
const { tier, window, weekly, asOfMs } = response.data.allowance;
|
|
34
|
+
const observedAt = asOfMs ?? Date.now();
|
|
35
|
+
const meters = [];
|
|
36
|
+
const periods = [
|
|
37
|
+
{ reading: window, meterKey: '5h', period: '5h', label: '5 小时' },
|
|
38
|
+
{ reading: weekly, meterKey: '7d', period: 'week', label: '每周额度' },
|
|
39
|
+
];
|
|
40
|
+
for (const { reading, meterKey, period, label } of periods) {
|
|
41
|
+
if (!reading)
|
|
42
|
+
continue;
|
|
43
|
+
const remaining = toRemainingPercent(reading.usedPercent);
|
|
44
|
+
if (remaining === undefined)
|
|
45
|
+
continue;
|
|
46
|
+
meters.push({
|
|
47
|
+
meterKey, product: 'muse-code', label, kind: 'percent', window: period,
|
|
48
|
+
remaining, total: 100, unit: '%', resetsAt: reading.resetsAtMs ?? undefined, observedAt,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if (!meters.length)
|
|
52
|
+
return null;
|
|
53
|
+
return { brand: 'muse-code', source: 'muse-code', plan: tier || undefined, meters, observedAt };
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CONFIG_DIR } from '../config.js';
|
|
4
|
+
import { toEpochMs } from './types.js';
|
|
5
|
+
export function captureStatusQuota(brand, data) {
|
|
6
|
+
const observedAt = Date.now();
|
|
7
|
+
const meters = [];
|
|
8
|
+
if (brand === 'gemini' && (!data.product || data.product === 'gemini')) {
|
|
9
|
+
for (const [id, bucket] of Object.entries(data.quota ?? {})) {
|
|
10
|
+
if (!bucket || bucket.disabled)
|
|
11
|
+
continue;
|
|
12
|
+
const fraction = bucket.remaining_fraction;
|
|
13
|
+
const amount = bucket.remaining_amount;
|
|
14
|
+
const percent = typeof fraction === 'number' && fraction >= 0 && fraction <= 1;
|
|
15
|
+
if (!percent && !(typeof amount === 'number' && Number.isFinite(amount) && amount >= 0))
|
|
16
|
+
continue;
|
|
17
|
+
meters.push({
|
|
18
|
+
meterKey: id, product: brand, label: id, kind: percent ? 'percent' : 'count',
|
|
19
|
+
remaining: percent ? Math.round(fraction * 1000) / 10 : amount,
|
|
20
|
+
total: percent ? 100 : undefined, unit: percent ? '%' : undefined,
|
|
21
|
+
resetsAt: toEpochMs(bucket.reset_time), observedAt,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
else if (brand === 'claude') {
|
|
26
|
+
for (const [id, window] of [['five_hour', '5h'], ['seven_day', 'week']]) {
|
|
27
|
+
const bucket = data.rate_limits?.[id];
|
|
28
|
+
const used = bucket?.used_percentage;
|
|
29
|
+
if (typeof used !== 'number' || !(used >= 0 && used <= 100))
|
|
30
|
+
continue;
|
|
31
|
+
meters.push({
|
|
32
|
+
meterKey: window === 'week' ? '7d' : '5h', product: 'claude-code',
|
|
33
|
+
label: window === 'week' ? '每周额度' : '5 小时', kind: 'percent', window,
|
|
34
|
+
remaining: Math.round((100 - used) * 10) / 10, total: 100, unit: '%',
|
|
35
|
+
resetsAt: toEpochMs(bucket?.resets_at), observedAt,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (!meters.length)
|
|
40
|
+
return null;
|
|
41
|
+
const snapshot = { brand, source: brand + '-statusline', meters, observedAt };
|
|
42
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
43
|
+
const file = path.join(CONFIG_DIR, brand + '-quota.json');
|
|
44
|
+
const tmp = file + '.' + process.pid;
|
|
45
|
+
fs.writeFileSync(tmp, JSON.stringify(snapshot), { mode: 0o600 });
|
|
46
|
+
fs.renameSync(tmp, file);
|
|
47
|
+
return snapshot;
|
|
48
|
+
}
|
|
49
|
+
export function readStatusQuota(brand) {
|
|
50
|
+
try {
|
|
51
|
+
const snapshot = JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, brand + '-quota.json'), 'utf8'));
|
|
52
|
+
if (snapshot.brand !== brand || !Array.isArray(snapshot.meters) || !snapshot.meters.length)
|
|
53
|
+
return null;
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
const meters = snapshot.meters.filter(m => m.resetsAt === undefined || m.resetsAt > now);
|
|
56
|
+
return meters.length ? { ...snapshot, meters } : null;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
package/dist/collectors/types.js
CHANGED
|
@@ -1,12 +1,3 @@
|
|
|
1
|
-
export function maskEmail(email) {
|
|
2
|
-
if (!email || !email.includes('@'))
|
|
3
|
-
return undefined;
|
|
4
|
-
const [user, domain] = email.trim().split('@');
|
|
5
|
-
if (!user || !domain)
|
|
6
|
-
return undefined;
|
|
7
|
-
const prefix = user.length <= 2 ? user[0] : user.slice(0, 2);
|
|
8
|
-
return `${prefix}***@${domain}`;
|
|
9
|
-
}
|
|
10
1
|
export function toRemainingPercent(usedPercent) {
|
|
11
2
|
if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent))
|
|
12
3
|
return undefined;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export async function
|
|
1
|
+
export async function collectXaiQuota() {
|
|
2
2
|
const mgmtKey = process.env.XAI_MANAGEMENT_API_KEY?.trim();
|
|
3
3
|
const teamId = process.env.XAI_TEAM_ID?.trim();
|
|
4
4
|
if (!mgmtKey || !teamId)
|
|
@@ -11,16 +11,20 @@ export async function collectGrokQuota() {
|
|
|
11
11
|
},
|
|
12
12
|
signal: AbortSignal.timeout(8000),
|
|
13
13
|
}).catch(() => null);
|
|
14
|
-
if (!res
|
|
15
|
-
|
|
14
|
+
if (!res)
|
|
15
|
+
throw new Error('无法连接 xAI Management API,请检查本机网络。');
|
|
16
|
+
if (!res.ok)
|
|
17
|
+
throw new Error('xAI 账单查询失败(HTTP ' + res.status + '),请检查团队 ID 和管理密钥的账单读取权限。');
|
|
16
18
|
const data = (await res.json().catch(() => null));
|
|
17
19
|
if (!data)
|
|
18
20
|
return null;
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
21
|
+
const raw = data.total?.val;
|
|
22
|
+
if (typeof raw !== 'number' && !(typeof raw === 'string' && /^-?\d+$/.test(raw)))
|
|
23
|
+
return null;
|
|
24
|
+
const cents = Number(raw);
|
|
25
|
+
if (!Number.isSafeInteger(cents))
|
|
22
26
|
return null;
|
|
23
|
-
//
|
|
27
|
+
// Prepaid credits are negative entries on the USD-cent ledger.
|
|
24
28
|
const now = Date.now();
|
|
25
29
|
const meters = [
|
|
26
30
|
{
|
|
@@ -28,13 +32,13 @@ export async function collectGrokQuota() {
|
|
|
28
32
|
product: 'xai',
|
|
29
33
|
label: '可用余额',
|
|
30
34
|
kind: 'balance',
|
|
31
|
-
remaining: Math.
|
|
35
|
+
remaining: Math.max(0, -cents / 100),
|
|
32
36
|
unit: 'USD',
|
|
33
37
|
observedAt: now,
|
|
34
38
|
},
|
|
35
39
|
];
|
|
36
40
|
return {
|
|
37
|
-
brand: '
|
|
41
|
+
brand: 'xai',
|
|
38
42
|
observedAt: now,
|
|
39
43
|
source: 'xai-billing',
|
|
40
44
|
meters,
|
package/dist/config.js
CHANGED
|
@@ -2,20 +2,50 @@ import fs from 'node:fs';
|
|
|
2
2
|
import os from 'node:os';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
const DEFAULT_API_URL = process.env.TOKENWALLET_API_URL || 'https://api.token-wallet.app/v1';
|
|
5
|
-
const CONFIG_DIR = process.env.TOKENWALLET_MCP_HOME || path.join(os.homedir(), '.tokenwallet-mcp');
|
|
6
|
-
const
|
|
7
|
-
export function
|
|
8
|
-
const
|
|
9
|
-
|
|
5
|
+
export const CONFIG_DIR = process.env.TOKENWALLET_MCP_HOME || path.join(os.homedir(), '.tokenwallet-mcp');
|
|
6
|
+
export const providerIds = ['openai', 'claude', 'gemini', 'muse-code', 'xai', 'deepseek', 'openrouter', 'other'];
|
|
7
|
+
export function explicitProvider() {
|
|
8
|
+
const index = process.argv.indexOf('--provider');
|
|
9
|
+
const value = index < 0 ? process.env.TOKENWALLET_PROVIDER : process.argv[index + 1];
|
|
10
|
+
if (index < 0 && !value)
|
|
11
|
+
return undefined;
|
|
12
|
+
const provider = providerIds.find(id => id === value);
|
|
13
|
+
if (!provider)
|
|
14
|
+
throw new Error('请在本客户端的 MCP 启动参数中指定 --provider,或设置 TOKENWALLET_PROVIDER。支持:' + providerIds.join(', '));
|
|
15
|
+
return provider;
|
|
10
16
|
}
|
|
11
|
-
export function
|
|
17
|
+
export function configuredProvider() {
|
|
18
|
+
const provider = explicitProvider();
|
|
19
|
+
if (!provider)
|
|
20
|
+
throw new Error('请为 TokenWallet MCP 指定 --provider。支持:' + providerIds.join(', '));
|
|
21
|
+
return provider;
|
|
22
|
+
}
|
|
23
|
+
export function providerForClient(clientName) {
|
|
24
|
+
const parts = clientName?.toLowerCase().split(/[^a-z0-9]+/) ?? [];
|
|
25
|
+
if (parts.includes('codex'))
|
|
26
|
+
return 'openai';
|
|
27
|
+
if (parts.includes('claude'))
|
|
28
|
+
return 'claude';
|
|
29
|
+
if (parts.includes('gemini'))
|
|
30
|
+
return 'gemini';
|
|
31
|
+
if (parts.includes('muse') && parts.includes('code'))
|
|
32
|
+
return 'muse-code';
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
export function getApiBaseUrl(provider = explicitProvider()) {
|
|
36
|
+
const url = process.env.TOKENWALLET_API_URL || (provider ? loadConfig(provider).apiBaseUrl : DEFAULT_API_URL);
|
|
37
|
+
return url.replace(/\/+$/, '');
|
|
38
|
+
}
|
|
39
|
+
export function loadConfig(provider = configuredProvider()) {
|
|
40
|
+
const scoped = path.join(CONFIG_DIR, provider, 'config.json');
|
|
41
|
+
const file = fs.existsSync(scoped) ? scoped : path.join(CONFIG_DIR, 'config.json');
|
|
12
42
|
try {
|
|
13
|
-
if (fs.existsSync(
|
|
14
|
-
const parsed = JSON.parse(fs.readFileSync(
|
|
43
|
+
if (fs.existsSync(file)) {
|
|
44
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
15
45
|
return {
|
|
16
46
|
apiBaseUrl: parsed.apiBaseUrl || DEFAULT_API_URL,
|
|
17
|
-
connections: Array.isArray(parsed.connections) ? parsed.connections : [],
|
|
18
|
-
pendingSessions: Array.isArray(parsed.pendingSessions) ? parsed.pendingSessions : [],
|
|
47
|
+
connections: Array.isArray(parsed.connections) ? parsed.connections.filter(c => c.brand === provider).slice(0, 1) : [],
|
|
48
|
+
pendingSessions: Array.isArray(parsed.pendingSessions) ? parsed.pendingSessions.filter(s => s.brand === provider) : [],
|
|
19
49
|
};
|
|
20
50
|
}
|
|
21
51
|
}
|
|
@@ -28,39 +58,34 @@ export function loadConfig() {
|
|
|
28
58
|
pendingSessions: [],
|
|
29
59
|
};
|
|
30
60
|
}
|
|
31
|
-
export function saveConfig(config) {
|
|
32
|
-
|
|
33
|
-
fs.
|
|
61
|
+
export function saveConfig(config, provider = configuredProvider()) {
|
|
62
|
+
const directory = path.join(CONFIG_DIR, provider);
|
|
63
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
64
|
+
fs.writeFileSync(path.join(directory, 'config.json'), JSON.stringify(config, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
34
65
|
}
|
|
35
|
-
export function savePendingSession(session) {
|
|
36
|
-
const cfg = loadConfig();
|
|
66
|
+
export function savePendingSession(session, provider = configuredProvider()) {
|
|
67
|
+
const cfg = loadConfig(provider);
|
|
37
68
|
const now = Date.now();
|
|
38
69
|
const active = cfg.pendingSessions.filter((s) => s.sessionId !== session.sessionId && s.expiresAt > now);
|
|
39
70
|
active.unshift(session);
|
|
40
71
|
cfg.pendingSessions = active.slice(0, 10);
|
|
41
|
-
saveConfig(cfg);
|
|
72
|
+
saveConfig(cfg, provider);
|
|
42
73
|
}
|
|
43
|
-
export function removePendingSession(sessionId) {
|
|
44
|
-
const cfg = loadConfig();
|
|
74
|
+
export function removePendingSession(sessionId, provider = configuredProvider()) {
|
|
75
|
+
const cfg = loadConfig(provider);
|
|
45
76
|
cfg.pendingSessions = cfg.pendingSessions.filter((s) => s.sessionId !== sessionId);
|
|
46
|
-
saveConfig(cfg);
|
|
77
|
+
saveConfig(cfg, provider);
|
|
47
78
|
}
|
|
48
|
-
export function upsertBoundConnection(conn) {
|
|
49
|
-
const cfg = loadConfig();
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
cfg.connections[existingIdx] = conn;
|
|
53
|
-
}
|
|
54
|
-
else {
|
|
55
|
-
cfg.connections.unshift(conn);
|
|
56
|
-
}
|
|
57
|
-
saveConfig(cfg);
|
|
79
|
+
export function upsertBoundConnection(conn, provider = configuredProvider()) {
|
|
80
|
+
const cfg = loadConfig(provider);
|
|
81
|
+
cfg.connections = [conn];
|
|
82
|
+
saveConfig(cfg, provider);
|
|
58
83
|
}
|
|
59
|
-
export function markConnectionReported(cardId, reportedAt = Date.now()) {
|
|
60
|
-
const cfg = loadConfig();
|
|
84
|
+
export function markConnectionReported(cardId, reportedAt = Date.now(), provider = configuredProvider()) {
|
|
85
|
+
const cfg = loadConfig(provider);
|
|
61
86
|
const target = cfg.connections.find((c) => c.cardId === cardId);
|
|
62
87
|
if (target) {
|
|
63
88
|
target.lastReportedAt = reportedAt;
|
|
64
|
-
saveConfig(cfg);
|
|
89
|
+
saveConfig(cfg, provider);
|
|
65
90
|
}
|
|
66
91
|
}
|