aixxai 1.6.8 → 1.6.9

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.
Binary file
package/bin/aixx.js CHANGED
@@ -1,137 +1,139 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * AIXX CLI
5
- * 让你的AI调用万物。
6
- *
7
- * 用法:
8
- * npx aixxai install [推荐码/绑定码/S####] 安装AIXX skill;S编号=买断技能门禁安装
9
- * npx aixxai install --yes 非交互安装(脚本/CI用,跳过确认)
10
- * npx aixxai search <关键词> 搜索AIXX能力库(数据/技能,免key)
11
- * npx aixxai installed 查看安装状态(skill/账号/版本)
12
- * npx aixxai config 配置/查看AIXX
13
- * npx aixxai test 测试AIXX是否可用
14
- * npx aixxai balance 查询账户余额
15
- * npx aixxai models 列出可用模型(分组)
16
- * npx aixxai recharge [金额] 充值引导
17
- * npx aixxai --version 查看版本
18
- */
19
-
20
- import { readFileSync } from 'fs';
21
- import { fileURLToPath } from 'url';
22
- import { dirname, join } from 'path';
23
- import { install } from '../src/commands/install.js';
24
- import { search } from '../src/commands/search.js';
25
- import { installed } from '../src/commands/installed.js';
26
- import { config } from '../src/commands/config.js';
27
- import { test } from '../src/commands/test.js';
28
- import { balance } from '../src/commands/balance.js';
29
- import { models } from '../src/commands/models.js';
30
- import { recharge } from '../src/commands/recharge.js';
31
- import { aci } from '../src/commands/aci.js';
32
- import { market } from '../src/commands/market.js';
33
- import { servers } from '../src/commands/servers.js';
34
- import { showHelp, showVersion } from '../src/commands/help.js';
35
-
36
- // 版本号从 package.json 读(单一来源,别再硬编码)
37
- const __dirname = dirname(fileURLToPath(import.meta.url));
38
- const VERSION = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')).version;
39
-
40
- // 默认AIXX后端地址:统一走萬安云域名网关入口(详见 src/utils/env.js 注释)
41
- // 改完后请全局搜索 "安全警告" 同步更新 env.js 与 templates/QUICKSTART.md 中的同名地址。
42
- export const DEFAULT_BASE_URL = 'https://console.aixx.ai/v1';
43
-
44
- // 命令表:所有子命令的单一来源(新增命令在这里加一行即可)。
45
- // 未知命令的"你想用的是不是"近似匹配也从这张表取已知命令名,不另写一份。
46
- const COMMANDS = [
47
- { name: 'install', aliases: ['i'], run: install },
48
- { name: 'search', run: search },
49
- { name: 'installed', run: installed },
50
- { name: 'config', aliases: ['c'], run: config },
51
- { name: 'test', aliases: ['t'], run: test },
52
- { name: 'balance', aliases: ['b'], run: balance },
53
- { name: 'models', aliases: ['m'], run: models },
54
- { name: 'recharge', aliases: ['r'], run: recharge },
55
- { name: 'market', run: market }, /* 1030产品版: 行情数据订阅(docs/PLAN_MARKET_API_1030.md), 不进help带外态 */
56
- { name: 'aci', run: aci }, /* 已并入market, 保留指路 */
57
- { name: 'servers', run: servers }, /* 1022版: 萬安云服务器货架 */
58
- ];
59
-
60
- // help/version 不吃子参数(走 flag/无参分支),但命令名仍参与下面的近似匹配
61
- const BUILTIN_NAMES = ['help', 'version'];
62
-
63
- // 零依赖近似匹配的兜底:a 是否按顺序出现在 b 里(允许跳字,serch 也能对上 search)
64
- function isSubsequence(a, b) {
65
- let i = 0;
66
- for (const ch of b) {
67
- if (ch === a[i]) i++;
68
- }
69
- return i === a.length;
70
- }
71
-
72
- // 未知命令 → 猜用户想输什么。小写比较;规则:前缀相同 / 互相包含 / 子序列。最多返回3个。
73
- function didYouMean(input) {
74
- const s = input.toLowerCase();
75
- return [...COMMANDS.map(c => c.name), ...BUILTIN_NAMES]
76
- .filter(n => {
77
- const t = n.toLowerCase();
78
- return t.startsWith(s) || s.startsWith(t) || t.includes(s) || s.includes(t) || isSubsequence(s, t);
79
- })
80
- .slice(0, 3);
81
- }
82
-
83
- async function main() {
84
- const args = process.argv.slice(2);
85
- const command = args[0];
86
- const subArgs = args.slice(1);
87
-
88
- // 裸命令即安装(1007 定版:命令越短越好)——npx aixxai 直接进安装,帮助走 help/--help
89
- if (command === undefined) {
90
- const installEntry = COMMANDS.find(c => c.name === 'install');
91
- if (installEntry) {
92
- await installEntry.run(subArgs);
93
- return;
94
- }
95
- }
96
-
97
- const entry = COMMANDS.find(c => c.name === command || c.aliases?.includes(command));
98
- if (entry) {
99
- await entry.run(subArgs);
100
- return;
101
- }
102
-
103
- switch (command) {
104
- case '--version':
105
- case '-v':
106
- case 'version':
107
- showVersion(VERSION);
108
- break;
109
- case '--help':
110
- case '-h':
111
- case 'help':
112
- showHelp(VERSION);
113
- break;
114
- default: {
115
- // 卡170(1011 定版"安装命令带唯一码"): 未知参数不再直接报错——当作码传给 install。
116
- // 覆盖 npx aixxai <CODE>(不带 install 子命令)的用法;install 内部会先查云侧区分绑定码/推荐码。
117
- const installEntry = COMMANDS.find(c => c.name === 'install');
118
- if (installEntry && command && !command.startsWith('-')) {
119
- await installEntry.run([command, ...subArgs]);
120
- return;
121
- }
122
- console.error(`未知命令: ${command}`);
123
- const guesses = didYouMean(command);
124
- if (guesses.length > 0) {
125
- console.error(`你想用的是不是: ${guesses.join(', ')}`);
126
- } else {
127
- console.error('运行 aixx help 查看全部命令');
128
- }
129
- process.exit(1);
130
- }
131
- }
132
- }
133
-
134
- main().catch(err => {
135
- console.error('❌ 发生错误:', err.message);
136
- process.exit(1);
137
- });
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * AIXX CLI
5
+ * 让你的AI调用万物。
6
+ *
7
+ * 用法:
8
+ * npx aixxai install [推荐码/绑定码/S####] 安装AIXX skill;S编号=买断技能门禁安装
9
+ * npx aixxai install --yes 非交互安装(脚本/CI用,跳过确认)
10
+ * npx aixxai search <关键词> 搜索AIXX能力库(数据/技能,免key)
11
+ * npx aixxai installed 查看安装状态(skill/账号/版本)
12
+ * npx aixxai config 配置/查看AIXX
13
+ * npx aixxai test 测试AIXX是否可用
14
+ * npx aixxai balance 查询账户余额
15
+ * npx aixxai models 列出可用模型(分组)
16
+ * npx aixxai recharge [金额] 充值引导
17
+ * npx aixxai --version 查看版本
18
+ */
19
+
20
+ import { readFileSync } from 'fs';
21
+ import { fileURLToPath } from 'url';
22
+ import { dirname, join } from 'path';
23
+ import { install } from '../src/commands/install.js';
24
+ import { search } from '../src/commands/search.js';
25
+ import { installed } from '../src/commands/installed.js';
26
+ import { config } from '../src/commands/config.js';
27
+ import { test } from '../src/commands/test.js';
28
+ import { balance } from '../src/commands/balance.js';
29
+ import { models } from '../src/commands/models.js';
30
+ import { recharge } from '../src/commands/recharge.js';
31
+ import { aci } from '../src/commands/aci.js';
32
+ import { market } from '../src/commands/market.js';
33
+ import { servers } from '../src/commands/servers.js';
34
+ import { status } from '../src/commands/status.js';
35
+ import { showHelp, showVersion } from '../src/commands/help.js';
36
+
37
+ // 版本号从 package.json 读(单一来源,别再硬编码)
38
+ const __dirname = dirname(fileURLToPath(import.meta.url));
39
+ const VERSION = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')).version;
40
+
41
+ // 默认AIXX后端地址:统一走萬安云域名网关入口(详见 src/utils/env.js 注释)
42
+ // 改完后请全局搜索 "安全警告" 同步更新 env.js 与 templates/QUICKSTART.md 中的同名地址。
43
+ export const DEFAULT_BASE_URL = 'https://console.aixx.ai/v1';
44
+
45
+ // 命令表:所有子命令的单一来源(新增命令在这里加一行即可)。
46
+ // 未知命令的"你想用的是不是"近似匹配也从这张表取已知命令名,不另写一份。
47
+ const COMMANDS = [
48
+ { name: 'install', aliases: ['i'], run: install },
49
+ { name: 'search', run: search },
50
+ { name: 'installed', run: installed },
51
+ { name: 'config', aliases: ['c'], run: config },
52
+ { name: 'test', aliases: ['t'], run: test },
53
+ { name: 'balance', aliases: ['b'], run: balance },
54
+ { name: 'models', aliases: ['m'], run: models },
55
+ { name: 'recharge', aliases: ['r'], run: recharge },
56
+ { name: 'market', run: market }, /* 1030产品版: 行情数据订阅(docs/PLAN_MARKET_API_1030.md), 不进help带外态 */
57
+ { name: 'aci', run: aci }, /* 已并入market, 保留指路 */
58
+ { name: 'servers', run: servers }, /* 1022版: 萬安云服务器货架 */
59
+ { name: 'status', aliases: ['st'], run: status }, /* 1120 K哥令: 身份编号给到agent·一条命令看全貌 */
60
+ ];
61
+
62
+ // help/version 不吃子参数(走 flag/无参分支),但命令名仍参与下面的近似匹配
63
+ const BUILTIN_NAMES = ['help', 'version'];
64
+
65
+ // 零依赖近似匹配的兜底:a 是否按顺序出现在 b 里(允许跳字,serch 也能对上 search)
66
+ function isSubsequence(a, b) {
67
+ let i = 0;
68
+ for (const ch of b) {
69
+ if (ch === a[i]) i++;
70
+ }
71
+ return i === a.length;
72
+ }
73
+
74
+ // 未知命令 → 猜用户想输什么。小写比较;规则:前缀相同 / 互相包含 / 子序列。最多返回3个。
75
+ function didYouMean(input) {
76
+ const s = input.toLowerCase();
77
+ return [...COMMANDS.map(c => c.name), ...BUILTIN_NAMES]
78
+ .filter(n => {
79
+ const t = n.toLowerCase();
80
+ return t.startsWith(s) || s.startsWith(t) || t.includes(s) || s.includes(t) || isSubsequence(s, t);
81
+ })
82
+ .slice(0, 3);
83
+ }
84
+
85
+ async function main() {
86
+ const args = process.argv.slice(2);
87
+ const command = args[0];
88
+ const subArgs = args.slice(1);
89
+
90
+ // 裸命令即安装(1007 定版:命令越短越好)——npx aixxai 直接进安装,帮助走 help/--help
91
+ if (command === undefined) {
92
+ const installEntry = COMMANDS.find(c => c.name === 'install');
93
+ if (installEntry) {
94
+ await installEntry.run(subArgs);
95
+ return;
96
+ }
97
+ }
98
+
99
+ const entry = COMMANDS.find(c => c.name === command || c.aliases?.includes(command));
100
+ if (entry) {
101
+ await entry.run(subArgs);
102
+ return;
103
+ }
104
+
105
+ switch (command) {
106
+ case '--version':
107
+ case '-v':
108
+ case 'version':
109
+ showVersion(VERSION);
110
+ break;
111
+ case '--help':
112
+ case '-h':
113
+ case 'help':
114
+ showHelp(VERSION);
115
+ break;
116
+ default: {
117
+ // 卡170(1011 定版"安装命令带唯一码"): 未知参数不再直接报错——当作码传给 install。
118
+ // 覆盖 npx aixxai <CODE>(不带 install 子命令)的用法;install 内部会先查云侧区分绑定码/推荐码。
119
+ const installEntry = COMMANDS.find(c => c.name === 'install');
120
+ if (installEntry && command && !command.startsWith('-')) {
121
+ await installEntry.run([command, ...subArgs]);
122
+ return;
123
+ }
124
+ console.error(`未知命令: ${command}`);
125
+ const guesses = didYouMean(command);
126
+ if (guesses.length > 0) {
127
+ console.error(`你想用的是不是: ${guesses.join(', ')}`);
128
+ } else {
129
+ console.error('运行 aixx help 查看全部命令');
130
+ }
131
+ process.exit(1);
132
+ }
133
+ }
134
+ }
135
+
136
+ main().catch(err => {
137
+ console.error('❌ 发生错误:', err.message);
138
+ process.exit(1);
139
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aixxai",
3
- "version": "1.6.8",
3
+ "version": "1.6.9",
4
4
  "description": "AIXX CLI - 让你的AI调用万物。One command, every AI model. By AIXX (Wanan Exchange), the verification-first compute exchange. 安装:npx aixxai",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,168 +1,170 @@
1
- /**
2
- * AIXX CLI - balance 命令
3
- *
4
- * 查询当前账户余额、已用额度。
5
- *
6
- * 数据来源(New-API兼容接口):
7
- * 1. GET /v1/dashboard/billing/subscription → hard_limit_usd(总额度,美元)
8
- * 2. GET /v1/dashboard/billing/usage → 已用量(可能多种格式,做兜底)
9
- *
10
- * 展示时换算成人民币(按 1 USD ≈ 7 元,只是给用户一个直观感受)。
11
- * "还剩约N次对话":按每次对话约 ¥0.01 预估(最便宜模型单次几厘到几分)。
12
- */
13
-
14
- import { DEFAULT_BASE_URL } from '../../bin/aixx.js';
15
- import { loadApiKey, maskKey } from '../utils/env.js';
16
-
17
- // 美元→人民币换算(仅用于展示,给用户一个直观感受)
18
- const USD_TO_CNY = 7;
19
- // 预估单次对话成本(元),用于"还能聊多少次"
20
- const COST_PER_CHAT_CNY = 0.01;
21
- // 所有对外请求统一 15 秒超时
22
- const FETCH_TIMEOUT = 15000;
23
- // 网络/超时异常统一成友好提示
24
- function friendlyNetErr(err) {
25
- return err?.name === 'TimeoutError' || err?.name === 'AbortError'
26
- ? '连接超时,请检查网络'
27
- : err?.message || String(err);
28
- }
29
-
30
- /**
31
- * apiKey 读取统一走 src/utils/env.js 的 loadApiKey:
32
- * 环境变量 AIXX_API_KEY → ~/.aixx/config.json → ~/.aixx/account.json
33
- */
34
-
35
- export async function balance(subArgs) {
36
- console.log('╔══════════════════════════════════════════╗');
37
- console.log('║ AIXX 账户余额 ║');
38
- console.log('╚══════════════════════════════════════════╝\n');
39
-
40
- const apiKey = loadApiKey();
41
- const baseUrl = process.env.AIXX_BASE_URL || DEFAULT_BASE_URL;
42
-
43
- if (!apiKey) {
44
- console.error('❌ 未找到AIXX API Key');
45
- console.error(' 请先运行 npx aixxai install,或设置环境变量 AIXX_API_KEY');
46
- process.exit(1);
47
- }
48
-
49
- console.log(`使用Key: ${maskKey(apiKey)}`);
50
- console.log(`后端地址: ${baseUrl}\n`);
51
-
52
- // 0. 优先调 /v1/account(2026-08-28新增,能拿到真实账户余额,包括unlimited token)
53
- try {
54
- const acctResp = await fetch(`${baseUrl}/account`, {
55
- headers: { Authorization: `Bearer ${apiKey}` },
56
- signal: AbortSignal.timeout(FETCH_TIMEOUT),
57
- });
58
- if (acctResp.ok) {
59
- const acct = await acctResp.json();
60
- console.log('────────────────────────────────────');
61
- console.log(`👤 账户:${acct.username || '未知'}`);
62
- console.log(`💰 账户余额:¥${(acct.balance_cny ?? 0).toFixed(2)}($${(acct.balance_usd ?? 0).toFixed(2)})`);
63
- console.log(`📊 已用额度:¥${(acct.used_cny ?? 0).toFixed(2)}`);
64
- if (acct.unlimited_token) console.log(`♾️ Token模式:不限量(按账户余额扣费)`);
65
- console.log('────────────────────────────────────');
66
- console.log(`\n💡 充值入口:${acct.topup_url || baseUrl.replace(/\/v1$/, '') + '/console/topup'}\n`);
67
- return;
68
- }
69
- } catch {
70
- // /v1/account 不可用 → 降级到旧的 billing 接口
71
- }
72
-
73
- // 1. 降级:查总额度(subscription)
74
- let hardLimitUsd = 0;
75
- try {
76
- const resp = await fetch(`${baseUrl}/dashboard/billing/subscription`, {
77
- headers: { Authorization: `Bearer ${apiKey}` },
78
- signal: AbortSignal.timeout(FETCH_TIMEOUT),
79
- });
80
- if (!resp.ok) {
81
- if (resp.status === 401) {
82
- console.error('❌ API Key 无效(401),请重新 install 或检查 key');
83
- process.exit(1);
84
- }
85
- console.error(`❌ 查询余额失败: HTTP ${resp.status}`);
86
- process.exit(1);
87
- }
88
- const data = await resp.json();
89
- // New-API/OpenAI兼容:hard_limit_usd 是总额度
90
- hardLimitUsd =
91
- data.hard_limit_usd ??
92
- data.hard_limit ??
93
- data.data?.hard_limit_usd ??
94
- 0;
95
- } catch (err) {
96
- console.error(`❌ ${friendlyNetErr(err)}`);
97
- process.exit(1);
98
- }
99
-
100
- // 2. 查已用量(usage)
101
- // 不同后端字段不一样,尽量兜底
102
- let usedUsd = 0;
103
- try {
104
- // 用一个宽日期范围,确保能查到所有用量
105
- const today = new Date();
106
- const start = `${today.getFullYear()}-01-01`;
107
- const end = `${today.getFullYear()}-12-31`;
108
- const resp = await fetch(
109
- `${baseUrl}/dashboard/billing/usage?start_date=${start}&end_date=${end}`,
110
- {
111
- headers: { Authorization: `Bearer ${apiKey}` },
112
- signal: AbortSignal.timeout(FETCH_TIMEOUT),
113
- }
114
- );
115
- if (resp.ok) {
116
- const data = await resp.json();
117
- // 常见字段优先级
118
- usedUsd =
119
- data.total_usage ??
120
- data.total_cost ??
121
- data.data?.total_usage ??
122
- data.cumulative_usage ??
123
- 0;
124
- // New-API 的 total_usage 单位有时是"分(美元)",要除以100
125
- // 这里做个粗判断:如果usedUsd比hardLimit还大100倍,多半是没除100
126
- if (usedUsd > 0 && hardLimitUsd > 0 && usedUsd > hardLimitUsd * 50) {
127
- usedUsd = usedUsd / 100;
128
- }
129
- } else {
130
- // usage 接口挂了不影响主流程,总额度照常显示
131
- console.log(' (用量接口未返回数据,仅显示总额度)\n');
132
- }
133
- } catch (err) {
134
- console.log(' (用量查询失败,仅显示总额度)\n');
135
- }
136
-
137
- // 3. 计算并展示
138
- // New-API 的"无限额度"哨兵:hard_limit_usd >= 100000000(1亿)表示这个token不限额。
139
- // 直接显示真实数字(¥7亿)会吓到用户,所以单独走"无限额度"分支。
140
- const UNLIMITED_SENTINEL = 100000000;
141
- const isUnlimited = hardLimitUsd >= UNLIMITED_SENTINEL;
142
- const usedCny = usedUsd * USD_TO_CNY;
143
-
144
- console.log('────────────────────────────────────');
145
- if (isUnlimited) {
146
- // unlimited token(New-API对unlimited_quota=true的token返回1亿作为标记)
147
- // 实际是"按账户余额扣费",不是真的无限。账户余额是注册送的¥5起,用完就停。
148
- // billing接口拿不到真实账户余额(它对unlimited token只返回1亿标记),
149
- // 所以这里如实告知用户,引导去后台查精确余额。
150
- console.log(`💰 计费方式:按账户余额扣费(注册送$0.5试用额度,用完需充值)`);
151
- console.log(`📊 已用额度:¥${usedCny.toFixed(2)}`);
152
- console.log(`💡 精确余额请登录AIXX后台查看:${baseUrl.replace(/\/v1$/, '')}`);
153
- } else {
154
- // 正常有限额度
155
- const remainingUsd = Math.max(0, hardLimitUsd - usedUsd);
156
- const totalCny = hardLimitUsd * USD_TO_CNY;
157
- const remainingCny = remainingUsd * USD_TO_CNY;
158
- const approxChats = Math.floor(remainingCny / COST_PER_CHAT_CNY);
159
- console.log(`💰 当前余额:¥${remainingCny.toFixed(2)}(还剩约 ${approxChats.toLocaleString()} 次对话)`);
160
- console.log(`📊 已用额度:¥${usedCny.toFixed(2)}`);
161
- console.log(`💳 账户总额度:¥${totalCny.toFixed(2)}($${hardLimitUsd.toFixed(2)})`);
162
- }
163
- console.log('────────────────────────────────────');
164
- console.log('\n💡 提示:');
165
- console.log(' - 新用户注册送 $0.5 试用额度');
166
- console.log(' - glm-4-air 便宜,省着用能聊很久');
167
- console.log(' - 余额不足时运行 aixx recharge 查看充值方式\n');
168
- }
1
+ /**
2
+ * AIXX CLI - balance 命令
3
+ *
4
+ * 查询当前账户余额、已用额度。
5
+ *
6
+ * 数据来源(New-API兼容接口):
7
+ * 1. GET /v1/dashboard/billing/subscription → hard_limit_usd(总额度,美元)
8
+ * 2. GET /v1/dashboard/billing/usage → 已用量(可能多种格式,做兜底)
9
+ *
10
+ * 展示时换算成人民币(按 1 USD ≈ 7 元,只是给用户一个直观感受)。
11
+ * "还剩约N次对话":按每次对话约 ¥0.01 预估(最便宜模型单次几厘到几分)。
12
+ */
13
+
14
+ import { DEFAULT_BASE_URL } from '../../bin/aixx.js';
15
+ import { loadApiKey, maskKey } from '../utils/env.js';
16
+
17
+ // 美元→人民币换算(仅用于展示,给用户一个直观感受)
18
+ const USD_TO_CNY = 7;
19
+ // 预估单次对话成本(元),用于"还能聊多少次"
20
+ const COST_PER_CHAT_CNY = 0.01;
21
+ // 所有对外请求统一 15 秒超时
22
+ const FETCH_TIMEOUT = 15000;
23
+ // 网络/超时异常统一成友好提示
24
+ function friendlyNetErr(err) {
25
+ return err?.name === 'TimeoutError' || err?.name === 'AbortError'
26
+ ? '连接超时,请检查网络'
27
+ : err?.message || String(err);
28
+ }
29
+
30
+ /**
31
+ * apiKey 读取统一走 src/utils/env.js 的 loadApiKey:
32
+ * 环境变量 AIXX_API_KEY → ~/.aixx/config.json → ~/.aixx/account.json
33
+ */
34
+
35
+ export async function balance(subArgs) {
36
+ console.log('╔══════════════════════════════════════════╗');
37
+ console.log('║ AIXX 账户余额 ║');
38
+ console.log('╚══════════════════════════════════════════╝\n');
39
+
40
+ const apiKey = loadApiKey();
41
+ const baseUrl = process.env.AIXX_BASE_URL || DEFAULT_BASE_URL;
42
+
43
+ if (!apiKey) {
44
+ console.error('❌ 未找到AIXX API Key');
45
+ console.error(' 请先运行 npx aixxai install,或设置环境变量 AIXX_API_KEY');
46
+ process.exit(1);
47
+ }
48
+
49
+ console.log(`使用Key: ${maskKey(apiKey)}`);
50
+ console.log(`后端地址: ${baseUrl}\n`);
51
+
52
+ // 0. 优先调 /v1/account(2026-08-28新增,能拿到真实账户余额,包括unlimited token)
53
+ try {
54
+ const acctResp = await fetch(`${baseUrl}/account`, {
55
+ headers: { Authorization: `Bearer ${apiKey}` },
56
+ signal: AbortSignal.timeout(FETCH_TIMEOUT),
57
+ });
58
+ if (acctResp.ok) {
59
+ const acct = await acctResp.json();
60
+ console.log('────────────────────────────────────');
61
+ console.log(`👤 账户:${acct.username || '未知'}`);
62
+ console.log(`💰 账户余额:¥${(acct.balance_cny ?? 0).toFixed(2)}($${(acct.balance_usd ?? 0).toFixed(2)})`);
63
+ console.log(`📊 已用额度:¥${(acct.used_cny ?? 0).toFixed(2)}`);
64
+ if (acct.unlimited_token) console.log(`♾️ Token模式:不限量(按账户余额扣费)`);
65
+ console.log('────────────────────────────────────');
66
+ console.log(`\n💡 充值入口:${acct.topup_url || baseUrl.replace(/\/v1$/, '') + '/console/topup'}\n`);
67
+ return;
68
+ }
69
+ } catch {
70
+ // /v1/account 不可用 → 降级到旧的 billing 接口
71
+ }
72
+
73
+ // 1. 降级:查总额度(subscription)
74
+ let hardLimitUsd = 0;
75
+ try {
76
+ const resp = await fetch(`${baseUrl}/dashboard/billing/subscription`, {
77
+ headers: { Authorization: `Bearer ${apiKey}` },
78
+ signal: AbortSignal.timeout(FETCH_TIMEOUT),
79
+ });
80
+ if (!resp.ok) {
81
+ if (resp.status === 401) {
82
+ console.error('❌ API Key 无效(401),请重新 install 或检查 key');
83
+ process.exit(1);
84
+ }
85
+ console.error(`❌ 查询余额失败: HTTP ${resp.status}`);
86
+ process.exit(1);
87
+ }
88
+ const data = await resp.json();
89
+ // New-API/OpenAI兼容:hard_limit_usd 是总额度
90
+ hardLimitUsd =
91
+ data.hard_limit_usd ??
92
+ data.hard_limit ??
93
+ data.data?.hard_limit_usd ??
94
+ 0;
95
+ } catch (err) {
96
+ console.error(`❌ ${friendlyNetErr(err)}`);
97
+ process.exit(1);
98
+ }
99
+
100
+ // 2. 查已用量(usage)
101
+ // 不同后端字段不一样,尽量兜底
102
+ let usedUsd = 0;
103
+ try {
104
+ // 用一个宽日期范围,确保能查到所有用量
105
+ const today = new Date();
106
+ const start = `${today.getFullYear()}-01-01`;
107
+ const end = `${today.getFullYear()}-12-31`;
108
+ const resp = await fetch(
109
+ `${baseUrl}/dashboard/billing/usage?start_date=${start}&end_date=${end}`,
110
+ {
111
+ headers: { Authorization: `Bearer ${apiKey}` },
112
+ signal: AbortSignal.timeout(FETCH_TIMEOUT),
113
+ }
114
+ );
115
+ if (resp.ok) {
116
+ const data = await resp.json();
117
+ // 常见字段优先级
118
+ usedUsd =
119
+ data.total_usage ??
120
+ data.total_cost ??
121
+ data.data?.total_usage ??
122
+ data.cumulative_usage ??
123
+ 0;
124
+ // New-API 的 total_usage 单位有时是"分(美元)",要除以100
125
+ // 这里做个粗判断:如果usedUsd比hardLimit还大100倍,多半是没除100
126
+ if (usedUsd > 0 && hardLimitUsd > 0 && usedUsd > hardLimitUsd * 50) {
127
+ usedUsd = usedUsd / 100;
128
+ }
129
+ } else {
130
+ // usage 接口挂了不影响主流程,总额度照常显示
131
+ console.log(' (用量接口未返回数据,仅显示总额度)\n');
132
+ }
133
+ } catch (err) {
134
+ console.log(' (用量查询失败,仅显示总额度)\n');
135
+ }
136
+
137
+ // 3. 计算并展示
138
+ // New-API 的"无限额度"哨兵:hard_limit_usd >= 100000000(1亿)表示这个token不限额。
139
+ // 直接显示真实数字(¥7亿)会吓到用户,所以单独走"无限额度"分支。
140
+ const UNLIMITED_SENTINEL = 100000000;
141
+ const isUnlimited = hardLimitUsd >= UNLIMITED_SENTINEL;
142
+ const usedCny = usedUsd * USD_TO_CNY;
143
+
144
+ console.log('────────────────────────────────────');
145
+ if (isUnlimited) {
146
+ // unlimited token(New-API对unlimited_quota=true的token返回1亿作为标记)
147
+ // 实际是"按账户余额扣费",不是真的无限。账户余额是注册送的¥5起,用完就停。
148
+ // billing接口拿不到真实账户余额(它对unlimited token只返回1亿标记),
149
+ // 所以这里如实告知用户,引导去后台查精确余额。
150
+ console.log(`💰 计费方式:按账户余额扣费(注册送$0.5试用额度,用完需充值)`);
151
+ // 1120 WorkBuddy实测: unlimited档下dashboard/billing/usage返回的单位不可信(曾显示¥58969虚惊)
152
+ // 按账户余额扣费时"已用"以账户维度为准——这里不再展示误算值, 引导官方端点
153
+ console.log(`📊 已用额度:以账户维度计(请用下方官方入口查看精确值)`);
154
+ console.log(`💡 精确余额请登录AIXX后台查看:${baseUrl.replace(/\/v1$/, '')}`);
155
+ } else {
156
+ // 正常有限额度
157
+ const remainingUsd = Math.max(0, hardLimitUsd - usedUsd);
158
+ const totalCny = hardLimitUsd * USD_TO_CNY;
159
+ const remainingCny = remainingUsd * USD_TO_CNY;
160
+ const approxChats = Math.floor(remainingCny / COST_PER_CHAT_CNY);
161
+ console.log(`💰 当前余额:¥${remainingCny.toFixed(2)}(还剩约 ${approxChats.toLocaleString()} 次对话)`);
162
+ console.log(`📊 已用额度:¥${usedCny.toFixed(2)}`);
163
+ console.log(`💳 账户总额度:¥${totalCny.toFixed(2)}($${hardLimitUsd.toFixed(2)})`);
164
+ }
165
+ console.log('────────────────────────────────────');
166
+ console.log('\n💡 提示:');
167
+ console.log(' - 新用户注册送 $0.5 试用额度');
168
+ console.log(' - glm-4-air 便宜,省着用能聊很久');
169
+ console.log(' - 余额不足时运行 aixx recharge 查看充值方式\n');
170
+ }