srvprice-cli 0.0.0-stage → 0.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/lib/host.js ADDED
@@ -0,0 +1,1156 @@
1
+ 'use strict';
2
+
3
+ // 厂商适配层:srvprice 不做控制面,把统一命令转发给厂商自己的 CLI 执行。
4
+ // 适配器契约统一:输入统一参数,输出统一 host 结构;厂商差异消化在这里。
5
+ // 消化不了的(CLI 没装、版本不够、凭据失效、厂商报错)一律明确报出,不吞错。
6
+
7
+ const { execFile } = require('child_process');
8
+ const { CliError, EXIT } = require('./core');
9
+
10
+ const DEFAULT_TIMEOUT = 120000;
11
+
12
+ // 测试 / 特殊环境可直接指定某厂商 CLI 的可执行路径
13
+ function binFor(vendor, fallback) {
14
+ return process.env[`SRVPRICE_BIN_${vendor.toUpperCase()}`] || fallback;
15
+ }
16
+
17
+ // 多地域查询进度:SRVPRICE_PROGRESS=1 时向 stderr 写 JSONL
18
+ // {"level":"progress","provider":"tencent","done":3,"total":19,"region":"ap-beijing"}
19
+ function emitProgress(vendor, done, total, region) {
20
+ if (process.env.SRVPRICE_PROGRESS !== '1') return;
21
+ try {
22
+ process.stderr.write(JSON.stringify({
23
+ level: 'progress', provider: vendor, done, total, region: region || null
24
+ }) + '\n');
25
+ } catch (_) { /* 进度写不出去不影响主流程 */ }
26
+ }
27
+
28
+ // 限制并发数地跑一批任务(多地域查询用:腾讯 19 个地域同时起 19 个 tccli 太重)
29
+ async function mapLimit(items, limit, fn) {
30
+ const out = new Array(items.length);
31
+ let next = 0;
32
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
33
+ while (true) {
34
+ const i = next++;
35
+ if (i >= items.length) return;
36
+ out[i] = await fn(items[i], i);
37
+ }
38
+ });
39
+ await Promise.all(workers);
40
+ return out;
41
+ }
42
+
43
+ function run(bin, args, opts) {
44
+ const timeout = ((opts && opts.timeout) || DEFAULT_TIMEOUT);
45
+ // 允许把某厂商 CLI 指向一个 JS 脚本(测试桩 / 自封装 wrapper)
46
+ const isScript = /\.(c|m)?js$/i.test(bin);
47
+ const cmd = isScript ? process.execPath : bin;
48
+ const cmdArgs = isScript ? [bin, ...args] : args;
49
+ return new Promise((resolve, reject) => {
50
+ const child = execFile(cmd, cmdArgs, { timeout, maxBuffer: 32 * 1024 * 1024, windowsHide: true }, (err, stdout, stderr) => {
51
+ if (!err) return resolve({ stdout, stderr });
52
+ if (err.code === 'ENOENT') {
53
+ return reject(new CliError(EXIT.CRED,
54
+ `厂商 CLI 未安装:${bin}`,
55
+ { vendor: opts && opts.vendor, reason: 'cli_missing', bin }));
56
+ }
57
+ if (err.killed || err.signal) {
58
+ return reject(new CliError(EXIT.VENDOR,
59
+ `${bin} 执行超时(${timeout}ms)`,
60
+ { vendor: opts && opts.vendor, reason: 'timeout' }));
61
+ }
62
+ const text = `${stderr || ''} ${stdout || ''}`.trim();
63
+ // ★ 凭据在、但子账号没绑资源策略:UCloud 返回 RetCode 299「IAM permission error」。
64
+ // 归到凭据/权限类(5),别让用户以为是厂商故障或 CLI 版本问题。
65
+ if (/IAM permission error|RetCode:\s*299/i.test(text)) {
66
+ return reject(new CliError(EXIT.CRED,
67
+ `${bin} 权限不足(RetCode 299):请给该子账号绑定资源只读策略或加入项目授予只读角色`,
68
+ { vendor: opts && opts.vendor, reason: 'permission_denied', stderr: text.slice(0, 2000) }));
69
+ }
70
+ // 中文厂商的提示也要识别(天翼云:access_key 未配置,请通过…设置)
71
+ // ★ 真机核对(2026-11-19):火山 `credentials not configured, please run 've login' or 've configure set'`;
72
+ // 百度 `Error: no profile configured; run \`bce configure set\``;腾讯 `secretId is invalid`(退出码 255);
73
+ // 火山缺地域 `region not set, please set it via profile, --region flag, or VOLCENGINE_REGION…`。
74
+ // ★ 真机核对(2026-11-20,国外五家,退出码都是非 0):
75
+ // AWS `NoRegion: You must specify a region`(253)/ 有地域时 `NoCredentials: Unable to locate credentials`;
76
+ // doctl 把错误 JSON 打在 **stdout**:`access token is required. (hint: run 'doctl auth init')`;
77
+ // hcloud `no active context or token (see \`hcloud context --help\`)`;
78
+ // vultr `set VULTR_API_KEY as an environment variable or add 'api-key' to your config file`;
79
+ // linode-cli 没 configure 时直接起交互向导(非 TTY 下 EOFError 崩栈)——同样归为「凭据/配置缺失」。
80
+ const authLike = /InvalidAccessKeyId|SignatureDoesNotMatch|Unauthorized|Authentication failed|not logged in|No credential|credential.*not found|credentials not configured|no profile configured|secretId is invalid|region not set|profile configuration failed|ConfigurationError|Please run.*configure|run `?bce configure set|load current configuration failed|403 Forbidden|access_key\s*未配置|secret_key\s*未配置|CTYUN_AK|NoRegion|Unable to locate credentials|NoCredentials|AuthFailure|not able to validate|InvalidClientTokenId|access token is required|no active context or token|VULTR_API_KEY|Welcome to the Linode CLI|EOFError/i;
81
+ if (authLike.test(text)) {
82
+ return reject(new CliError(EXIT.CRED,
83
+ `${bin} 凭据缺失或失效:${describeError(text)}`,
84
+ { vendor: opts && opts.vendor, reason: 'auth_failed', stderr: text.slice(0, 4000) }));
85
+ }
86
+ return reject(new CliError(EXIT.VENDOR,
87
+ `${bin} 执行失败:${describeError(text)}`,
88
+ { vendor: opts && opts.vendor, reason: 'vendor_error', stderr: text.slice(0, 4000), code: err.code }));
89
+ });
90
+ // ★ 真机核对(2026-11-20):linode-cli 没 configure 时会起交互向导问
91
+ // 「Try it anyway? [y/N]:」,stdin 不关就**挂到超时**(stdio:'ignore' 在 Windows 上也照样挂)。
92
+ // 这里立刻关掉 stdin 发 EOF:它随即 EOFError,按凭据缺失报出。
93
+ // 本 CLI 所有厂商命令都是非交互的(写操作确认由 srvprice 自己做),不需要 stdin。
94
+ if (child.stdin) child.stdin.end();
95
+ });
96
+ }
97
+
98
+ function firstLine(s) {
99
+ const l = String(s || '').split(/\r?\n/).find((x) => x.trim());
100
+ return (l || '').trim().slice(0, 300);
101
+ }
102
+
103
+ // 有些新版 CLI 把错误打成单行 JSON(阿里云 3.5.4 就是),直接取 message 比截断整段 JSON 可读。
104
+ function describeError(s) {
105
+ const t = String(s || '').trim();
106
+ if (t.startsWith('{')) {
107
+ try {
108
+ const j = JSON.parse(t);
109
+ if (j && j.message) {
110
+ const hint = j.recovery && j.recovery.hint;
111
+ return `${j.message}${hint ? '(' + hint + ')' : ''}`.slice(0, 300);
112
+ }
113
+ // doctl 的未登录错误:{"errors":[{"detail":"…access token is required…"}]}
114
+ if (j && Array.isArray(j.errors) && j.errors[0] && j.errors[0].detail) {
115
+ return String(j.errors[0].detail).slice(0, 300);
116
+ }
117
+ } catch (_) { /* 不是 JSON 就回落到首行 */ }
118
+ }
119
+ // linode-cli 没 configure:先打欢迎语、再因 EOF 崩栈,首行是 traceback,对用户没有信息量
120
+ if (/Welcome to the Linode CLI/i.test(t)) {
121
+ return 'linode-cli 尚未配置:先运行 `linode-cli configure --token` 录入个人令牌';
122
+ }
123
+ return firstLine(s);
124
+ }
125
+
126
+ function parseJson(text, vendor, what) {
127
+ try {
128
+ return JSON.parse(text);
129
+ } catch (e) {
130
+ throw new CliError(EXIT.VENDOR,
131
+ `${vendor} 的 ${what} 输出不是合法 JSON(可能 CLI 版本差异)`,
132
+ { vendor, reason: 'parse_error', preview: String(text).slice(0, 500) });
133
+ }
134
+ }
135
+
136
+ function normStatus(raw) {
137
+ const s = String(raw || '').toLowerCase();
138
+ if (/^(running|active|on|started|ok)$/.test(s)) return 'running';
139
+ if (/^(stopped|off|offline|halted|shutdown)$/.test(s)) return 'stopped';
140
+ if (/^(pending|starting|provisioning|rebooting|stopping|shutting-down|terminated|deleting)$/.test(s)) return s === 'stopping' || s === 'shutting-down' ? 'stopping' : (s === 'pending' || s === 'starting' || s === 'provisioning' ? 'starting' : s);
141
+ return s || 'unknown';
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // 适配器
146
+ // ---------------------------------------------------------------------------
147
+
148
+ // UCloud 的策略常是**项目级**的:不带 --project-id 会直接 RetCode 299。
149
+ // 这里按 profile 里有没有默认项目,回落到 `ucloud project list` 的第一个/默认项目。
150
+ const _ucloudProjectCache = new Map();
151
+
152
+ async function ucloudProject(bin, ctx) {
153
+ if (ctx && ctx.projectId) return ctx.projectId;
154
+ if (process.env.SRVPRICE_UCLOUD_PROJECT) return process.env.SRVPRICE_UCLOUD_PROJECT;
155
+ if (_ucloudProjectCache.has(bin)) return _ucloudProjectCache.get(bin);
156
+ let id = null;
157
+ try {
158
+ const { stdout } = await run(bin, ['project', 'list', '--output', 'json'], { vendor: 'ucloud', timeout: 20000 });
159
+ const arr = JSON.parse(stdout);
160
+ const pick = (arr || []).find((p) => p.IsDefault) || (arr || [])[0];
161
+ id = (pick && pick.ProjectId) || null;
162
+ } catch (_) { id = null; }
163
+ _ucloudProjectCache.set(bin, id);
164
+ return id;
165
+ }
166
+
167
+ // 天翼云的资源池(region)ID 不是猜出来的:用官方 `common ListRegions` 取。
168
+ const _ctyunRegionCache = new Map();
169
+
170
+ async function ctyunRegions(bin, ctx) {
171
+ if (ctx && ctx.region) return [{ id: ctx.region, code: null }];
172
+ if (_ctyunRegionCache.has(bin)) return _ctyunRegionCache.get(bin);
173
+ try {
174
+ const { stdout } = await run(bin, ['common', 'ListRegions', '--output', 'json'],
175
+ { vendor: 'ctyun', timeout: 30000 });
176
+ const j = JSON.parse(stdout);
177
+ const list = (j.returnObj && j.returnObj.regionList) || j.regionList || [];
178
+ const out = list.filter((r) => r && r.regionID && r.openapiAvailable !== false)
179
+ .map((r) => ({ id: r.regionID, code: r.regionCode || r.regionName || null }));
180
+ _ctyunRegionCache.set(bin, out);
181
+ return out;
182
+ } catch (e) {
183
+ throw new CliError(EXIT.CRED,
184
+ '天翼云取资源池失败(检查凭据):' + e.message,
185
+ { vendor: 'ctyun', reason: e.reason || 'auth_failed' });
186
+ }
187
+ }
188
+
189
+ // ★ 2026-11-20:火山/腾讯的 ECS 接口是**按地域**查的,适配器原来只查配置的默认地域
190
+ // (火山 cn-beijing、腾讯 ap-guangzhou)——别的地域有机器会被静默漏掉。这里跟百度
191
+ // 一样:没给 --region 就先取官方地域表,再逐个地域列(并发限 6)。
192
+
193
+ // 官方地域表的兜底值:DescribeRegions 本身失败时(权限异常等)仍能查主地域。
194
+ const VOLC_FALLBACK_REGIONS = ['cn-beijing', 'cn-shanghai', 'cn-guangzhou',
195
+ 'cn-hongkong', 'ap-southeast-1', 'ap-southeast-3'];
196
+ const TENCENT_FALLBACK_REGIONS = ['ap-guangzhou', 'ap-beijing', 'ap-shanghai',
197
+ 'ap-hongkong', 'ap-singapore', 'na-ashburn'];
198
+ // AWS:describe-regions 取不到时的兜底(商用分区的主要地域)
199
+ const AWS_FALLBACK_REGIONS = ['us-east-1', 'us-west-1', 'us-west-2', 'eu-west-1',
200
+ 'eu-central-1', 'ap-northeast-1', 'ap-southeast-1', 'ap-south-1', 'ca-central-1', 'sa-east-1'];
201
+
202
+ async function volcRegions(bin, ctx) {
203
+ try {
204
+ const args = ['ecs', 'DescribeRegions'];
205
+ if (ctx.vendorProfile) args.push('--profile', ctx.vendorProfile);
206
+ const { stdout } = await run(bin, args, { vendor: 'volcengine', timeout: ctx.timeout });
207
+ const j = parseJson(stdout, 'volcengine', 'DescribeRegions');
208
+ const list = (j.Result && j.Result.Regions) || [];
209
+ const ids = list.map((r) => r && r.RegionId).filter(Boolean);
210
+ return ids.length ? ids : VOLC_FALLBACK_REGIONS;
211
+ } catch (_) {
212
+ return VOLC_FALLBACK_REGIONS;
213
+ }
214
+ }
215
+
216
+ async function awsRegions(bin, ctx) {
217
+ try {
218
+ // describe-regions 自己也是地域型调用,必须带一个地域;us-east-1 在任何商用账号都可用。
219
+ // 不加 --all-regions:默认只返回账号已启用的地域,避免往 opt-in 地域发无谓请求。
220
+ const args = ['ec2', 'describe-regions', '--region', 'us-east-1', '--output', 'json'];
221
+ if (ctx.vendorProfile) args.push('--profile', ctx.vendorProfile);
222
+ const { stdout } = await run(bin, args, { vendor: 'aws', timeout: ctx.timeout });
223
+ const j = parseJson(stdout, 'aws', 'describe-regions');
224
+ const ids = (j.Regions || []).map((r) => r && r.RegionName).filter(Boolean);
225
+ return ids.length ? ids : AWS_FALLBACK_REGIONS;
226
+ } catch (e) {
227
+ // 未登录就别退化成「N 个地域各报一次」——直接把凭据错误抛给上层
228
+ if (e && e.reason === 'auth_failed') throw e;
229
+ return AWS_FALLBACK_REGIONS;
230
+ }
231
+ }
232
+
233
+ async function tencentRegions(bin, ctx) {
234
+ try {
235
+ const args = ['cvm', 'DescribeRegions'];
236
+ if (ctx.vendorProfile) args.push('--profile', ctx.vendorProfile);
237
+ const { stdout } = await run(bin, args, { vendor: 'tencent', timeout: ctx.timeout });
238
+ const j = parseJson(stdout, 'tccli', 'DescribeRegions');
239
+ const ids = (j.RegionSet || []).map((r) => r && r.Region).filter(Boolean);
240
+ return ids.length ? ids : TENCENT_FALLBACK_REGIONS;
241
+ } catch (_) {
242
+ return TENCENT_FALLBACK_REGIONS;
243
+ }
244
+ }
245
+
246
+ const ADAPTERS = {
247
+ aliyun: {
248
+ id: 'aliyun',
249
+ label: '阿里云',
250
+ bin: 'aliyun',
251
+ contextFlag: '--Profile',
252
+ // 3.3.0+ 插件化:需先 `aliyun plugin install --names ecs`;旧 PascalCase 命令仍可用。
253
+ spec_verified: 'verified',
254
+ async list(ctx) {
255
+ const bin = binFor('aliyun', 'aliyun');
256
+ const base = ['ecs', 'DescribeInstances', '--MaxResults', '100'];
257
+ if (ctx.region) base.push('--RegionId', ctx.region);
258
+ if (ctx.vendorProfile) base.push('--Profile', ctx.vendorProfile);
259
+ // PageNumber/PageSize 即将废弃,按官方推荐用 NextToken + MaxResults 翻页
260
+ const out = [];
261
+ let nextToken = null;
262
+ for (let page = 0; page < 10; page++) {
263
+ const args = nextToken ? [...base, '--NextToken', nextToken] : base;
264
+ const { stdout } = await run(bin, args, { vendor: 'aliyun', timeout: ctx.timeout });
265
+ const j = parseJson(stdout, 'aliyun', 'DescribeInstances');
266
+ const set = (j.Instances && j.Instances.Instance) || [];
267
+ for (const it of set) {
268
+ out.push({
269
+ id: `aliyun:${it.InstanceId}`,
270
+ provider: 'aliyun',
271
+ instance_id: it.InstanceId,
272
+ name: it.InstanceName || '',
273
+ region: it.RegionId || ctx.region || null,
274
+ status: normStatus(it.Status),
275
+ public_ipv4: (it.PublicIpAddress && it.PublicIpAddress.IpAddress && it.PublicIpAddress.IpAddress[0]) || null,
276
+ type: it.InstanceType || null
277
+ });
278
+ }
279
+ nextToken = j.NextToken || null;
280
+ if (!nextToken) break;
281
+ }
282
+ return out;
283
+ },
284
+ actionArgs(kind, instanceId) {
285
+ const map = { start: 'StartInstance', stop: 'StopInstance', reboot: 'RebootInstance' };
286
+ return ['ecs', map[kind], '--InstanceId', instanceId];
287
+ }
288
+ },
289
+
290
+ aws: {
291
+ id: 'aws',
292
+ label: 'AWS',
293
+ bin: 'aws',
294
+ async list(ctx) {
295
+ const bin = binFor('aws', 'aws');
296
+ // ★ 2026-11-20(zhao 派单):EC2 是地域型服务,原来只查默认地域,别的地域的实例会**静默漏掉**。
297
+ // 照腾讯/火山/百度的做法:没给 --region 就先取 describe-regions,再逐地域并发查(限 6)。
298
+ const regions = ctx.region ? [ctx.region] : await awsRegions(bin, ctx);
299
+ const failures = [];
300
+ let doneCount = 0;
301
+ const results = await mapLimit(regions, 6, async (region) => {
302
+ try {
303
+ const args = ['ec2', 'describe-instances', '--output', 'json', '--region', region,
304
+ '--filters', 'Name=instance-state-name,Values=pending,running,shutting-down,stopping,stopped'];
305
+ if (ctx.vendorProfile) args.push('--profile', ctx.vendorProfile);
306
+ const { stdout } = await run(bin, args, { vendor: 'aws', timeout: ctx.timeout });
307
+ const j = parseJson(stdout, 'aws', 'describe-instances');
308
+ const rows = [];
309
+ for (const r of j.Reservations || []) {
310
+ for (const it of r.Instances || []) {
311
+ const nameTag = (it.Tags || []).find((t) => t.Key === 'Name');
312
+ rows.push({
313
+ id: `aws:${it.InstanceId}`,
314
+ provider: 'aws',
315
+ instance_id: it.InstanceId,
316
+ name: (nameTag && nameTag.Value) || '',
317
+ region: (it.Placement && it.Placement.AvailabilityZone) || region,
318
+ status: normStatus(it.State && it.State.Name),
319
+ public_ipv4: it.PublicIpAddress || null,
320
+ type: it.InstanceType || null
321
+ });
322
+ }
323
+ }
324
+ return rows;
325
+ } catch (e) {
326
+ failures.push({ region, message: e.message, reason: e.reason || 'error' });
327
+ return [];
328
+ } finally {
329
+ emitProgress('aws', ++doneCount, regions.length, region);
330
+ }
331
+ });
332
+ const out = results.flat();
333
+ if (!out.length && failures.length) {
334
+ const reasons = failures.map((f) => f.reason);
335
+ const reason = reasons.includes('auth_failed') ? 'auth_failed'
336
+ : (reasons.includes('permission_denied') ? 'permission_denied' : reasons[0]);
337
+ throw new CliError(reason === 'auth_failed' ? EXIT.CRED : EXIT.VENDOR,
338
+ `AWS ${failures.length} 个地域查询失败:${failures[0].message}`,
339
+ { vendor: 'aws', reason });
340
+ }
341
+ return out;
342
+ },
343
+ actionArgs(kind, instanceId) {
344
+ const map = { start: 'start-instances', stop: 'stop-instances', reboot: 'reboot-instances' };
345
+ return ['ec2', map[kind], '--instance-ids', instanceId];
346
+ }
347
+ },
348
+
349
+ tencent: {
350
+ id: 'tencent',
351
+ label: '腾讯云',
352
+ bin: 'tccli',
353
+ // 真机核对(tccli 3.1.202.1 / Python 3.12):`tccli cvm DescribeInstances help` 与参数展开均可用
354
+ spec_verified: 'verified',
355
+ async list(ctx) {
356
+ const bin = binFor('tencent', 'tccli');
357
+ // ★ 2026-11-20:同火山——没给 --region 就遍历 DescribeRegions 的全部地域,
358
+ // 否则别的地域的 CVM 会被静默漏掉(真机 19 个地域)。
359
+ const regions = ctx.region ? [ctx.region] : await tencentRegions(bin, ctx);
360
+ const failures = [];
361
+ let doneCount = 0;
362
+ const results = await mapLimit(regions, 6, async (region) => {
363
+ try {
364
+ const args = ['cvm', 'DescribeInstances', '--Limit', '100', '--region', region];
365
+ if (ctx.vendorProfile) args.push('--profile', ctx.vendorProfile);
366
+ const { stdout } = await run(bin, args, { vendor: 'tencent', timeout: ctx.timeout });
367
+ const j = parseJson(stdout, 'tccli', 'DescribeInstances');
368
+ return (j.InstanceSet || []).map((it) => ({
369
+ id: `tencent:${it.InstanceId}`,
370
+ provider: 'tencent',
371
+ instance_id: it.InstanceId,
372
+ name: it.InstanceName || '',
373
+ region: (it.Placement && it.Placement.Zone) || region,
374
+ status: normStatus(it.InstanceState),
375
+ public_ipv4: (it.PublicIpAddresses && it.PublicIpAddresses[0]) || null,
376
+ type: it.InstanceType || null
377
+ }));
378
+ } catch (e) {
379
+ failures.push({ region, message: e.message, reason: e.reason || 'error' });
380
+ return [];
381
+ } finally {
382
+ emitProgress('tencent', ++doneCount, regions.length, region);
383
+ }
384
+ });
385
+ const out = results.flat();
386
+ if (!out.length && failures.length) {
387
+ const reasons = failures.map((f) => f.reason);
388
+ const reason = reasons.includes('auth_failed') ? 'auth_failed'
389
+ : (reasons.includes('permission_denied') ? 'permission_denied' : reasons[0]);
390
+ throw new CliError(reason === 'auth_failed' ? EXIT.CRED : EXIT.VENDOR,
391
+ `腾讯云 ${failures.length} 个地域查询失败:${failures[0].message}`,
392
+ { vendor: 'tencent', reason });
393
+ }
394
+ return out;
395
+ },
396
+ actionArgs(kind, instanceId) {
397
+ const map = { start: 'StartInstances', stop: 'StopInstances', reboot: 'RebootInstances' };
398
+ return ['cvm', map[kind], '--InstanceIds', JSON.stringify([instanceId])];
399
+ }
400
+ },
401
+
402
+ doctl: {
403
+ id: 'doctl',
404
+ label: 'DigitalOcean',
405
+ bin: 'doctl',
406
+ async list(ctx) {
407
+ const args = ['compute', 'droplet', 'list', '--output', 'json'];
408
+ const { stdout } = await run(binFor('doctl', 'doctl'), args, { vendor: 'doctl', timeout: ctx.timeout });
409
+ const j = parseJson(stdout, 'doctl', 'droplet list');
410
+ return (Array.isArray(j) ? j : []).map((d) => ({
411
+ id: `doctl:${d.id}`,
412
+ provider: 'doctl',
413
+ instance_id: String(d.id),
414
+ name: d.name || '',
415
+ region: (d.region && d.region.slug) || null,
416
+ status: normStatus(d.status),
417
+ public_ipv4: ((d.networks && d.networks.v4) || []).find((n) => n.type === 'public') ? ((d.networks.v4.find((n) => n.type === 'public')).ip_address) : null,
418
+ type: (d.size && d.size.slug) || d.size_slug || null
419
+ }));
420
+ },
421
+ actionArgs(kind, instanceId) {
422
+ const map = { start: 'power-on', stop: 'shutdown', reboot: 'reboot' };
423
+ return ['compute', 'droplet-action', map[kind], instanceId];
424
+ }
425
+ },
426
+
427
+ hcloud: {
428
+ id: 'hcloud',
429
+ label: 'Hetzner',
430
+ bin: 'hcloud',
431
+ async list(ctx) {
432
+ const args = ['server', 'list', '-o', 'json'];
433
+ if (ctx.vendorProfile) args.push('--context', ctx.vendorProfile);
434
+ const { stdout } = await run(binFor('hcloud', 'hcloud'), args, { vendor: 'hcloud', timeout: ctx.timeout });
435
+ const j = parseJson(stdout, 'hcloud', 'server list');
436
+ return (Array.isArray(j) ? j : []).map((s) => ({
437
+ id: `hcloud:${s.id}`,
438
+ provider: 'hcloud',
439
+ instance_id: String(s.id),
440
+ name: s.name || '',
441
+ // ★ 真机核对(hcloud 1.70.2,2026-11-20):`server list` 列里只有 location,没有 datacenter;
442
+ // datacenter 属性已于 2026-07-01 从 API 响应移除,旧字段只作低版本回退。
443
+ region: (s.location && s.location.name) ||
444
+ (s.datacenter && s.datacenter.location && s.datacenter.location.name) || null,
445
+ status: normStatus(s.status),
446
+ public_ipv4: (s.public_net && s.public_net.ipv4 && s.public_net.ipv4.ip) || null,
447
+ type: (s.server_type && s.server_type.name) || null
448
+ }));
449
+ },
450
+ actionArgs(kind, instanceId) {
451
+ const map = { start: 'poweron', stop: 'shutdown', reboot: 'reboot' };
452
+ return ['server', map[kind], instanceId];
453
+ }
454
+ },
455
+
456
+ vultr: {
457
+ id: 'vultr',
458
+ label: 'Vultr',
459
+ bin: 'vultr-cli',
460
+ async list(ctx) {
461
+ const args = ['instance', 'list', '-o', 'json'];
462
+ const { stdout } = await run(binFor('vultr', 'vultr-cli'), args, { vendor: 'vultr', timeout: ctx.timeout });
463
+ const j = parseJson(stdout, 'vultr-cli', 'instance list');
464
+ const arr = Array.isArray(j) ? j : (j.instances || []);
465
+ return arr.map((s) => ({
466
+ id: `vultr:${s.id}`,
467
+ provider: 'vultr',
468
+ instance_id: String(s.id),
469
+ name: s.label || s.hostname || '',
470
+ region: s.region || null,
471
+ status: normStatus(s.power_status || s.status),
472
+ public_ipv4: s.main_ip || null,
473
+ type: s.plan || null
474
+ }));
475
+ },
476
+ actionArgs(kind, instanceId) {
477
+ // ★ 真机核对(vultr-cli 3.11.0 `instance --help`,2026-11-20):子命令只有 start / stop / restart,
478
+ // **没有 halt / reboot**(那是裸金属的命令)。stop 底层就是 POST /halt,restart 底层是 /reboot。
479
+ const map = { start: 'start', stop: 'stop', reboot: 'restart' };
480
+ return ['instance', map[kind], instanceId];
481
+ }
482
+ },
483
+
484
+ ucloud: {
485
+ id: 'ucloud',
486
+ label: 'UCloud',
487
+ bin: 'ucloud',
488
+ spec_verified: 'verified', // 2026-11-19 真机核对 v0.3.10:--output json 可用
489
+ async list(ctx) {
490
+ // ★ 真机核对(ucloud-cli 0.3.10):-j/--json 与 --output json 都存在;
491
+ // 显式用 --output json,比 --json 更确定。
492
+ // ★ UCloud 分两种实例:uhost(云主机)与 ulhost(轻量应用服务器),
493
+ // 权限也是分开的两条策略;这里两个都列,合并成一个列表。
494
+ const bin = binFor('ucloud', 'ucloud');
495
+ const projectId = await ucloudProject(bin, ctx);
496
+ const out = [];
497
+ const errs = [];
498
+ for (const kind of ['uhost', 'ulhost']) {
499
+ try {
500
+ const args = [kind, 'list', '--output', 'json'];
501
+ if (projectId) args.push('--project-id', projectId);
502
+ // ★ 真机:uhost 默认只看 profile/region(cn-bj2),**不加 --all-region 会漏掉别的地域**
503
+ // (165 在 sg-02,就是这么被漏掉的)。没显式给 region 时按全地域列。
504
+ if (ctx.region) args.push('--region', ctx.region);
505
+ else args.push('--all-region', 'true');
506
+ const res = await run(bin, args, { vendor: 'ucloud', timeout: ctx.timeout });
507
+ const rawAll = `${res.stdout || ''}${res.stderr || ''}`;
508
+ // ★ 真机:未配凭据时退出码仍是 0,只打印一句提示(见 auth_failed 测试)
509
+ if (/private-key is empty|Execute command 'ucloud init\|config'|public-key is empty/i.test(rawAll)) {
510
+ throw new CliError(EXIT.CRED,
511
+ 'UCloud 未配置凭据:先运行 `ucloud init` 或 `ucloud config add`,或用 SRVPRICE_UCLOUD_PUBLIC_KEY / _PRIVATE_KEY 注入',
512
+ { vendor: 'ucloud', reason: 'auth_failed' });
513
+ }
514
+ // ★ 真机:权限不足时也是退出码 0 + 一行 RetCode 299
515
+ if (/IAM permission error|RetCode:\s*299/i.test(rawAll)) {
516
+ throw new CliError(EXIT.CRED,
517
+ `${bin} 权限不足(RetCode 299):请给该子账号绑定资源只读策略或加入项目授予只读角色`,
518
+ { vendor: 'ucloud', reason: 'permission_denied' });
519
+ }
520
+ const raw = String(res.stdout || '').trim();
521
+ if (!raw || raw === '[]') continue;
522
+ const j = parseJson(raw, 'ucloud', kind + ' list');
523
+ const set = j.UHostSet || j.ULHostSet || (Array.isArray(j) ? j : []);
524
+ for (const s of set) {
525
+ // ★ 真机字段(v0.3.10 --all-region):ResourceID / UHostName / State / Zone / PublicIP / Type
526
+ // ——不是 API 文档里的 UHostId / Name。
527
+ const iid = s.ResourceID || s.UHostId || s.ULHostId || s.Id || s.id;
528
+ if (!iid) continue;
529
+ const ips = s.IPs || s.IPSet || [];
530
+ const pub = (Array.isArray(ips) ? ips : []).find((x) => x && (x.Type === 'International' || x.Type === 'Bgp' || x.Type === 'Public'));
531
+ out.push({
532
+ id: `ucloud:${iid}`,
533
+ provider: 'ucloud',
534
+ instance_id: iid,
535
+ name: s.UHostName || s.ULHostName || s.Name || s.name || '',
536
+ region: s.Zone || s.Region || s.region || null,
537
+ status: normStatus(s.State || s.Status || s.status),
538
+ public_ipv4: (pub && pub.IP) || s.PublicIP || s.public_ip || null,
539
+ type: kind === 'ulhost' ? 'ULHost' : (s.Type || s.UHostType || s.MachineType || null)
540
+ });
541
+ }
542
+ } catch (e) {
543
+ // 一条策略没给不会拖垮另一条;但如果一条主机都没有,就如实报出来
544
+ errs.push({ kind, message: e.message, reason: e.reason || 'error', code: e.exitCode });
545
+ }
546
+ }
547
+ if (!out.length && errs.length) {
548
+ const reasons = errs.map((e) => e.reason);
549
+ const reason = reasons.includes('permission_denied') ? 'permission_denied'
550
+ : (reasons.includes('auth_failed') ? 'auth_failed' : reasons[0]);
551
+ throw new CliError(EXIT.CRED,
552
+ errs.map((e) => e.message).join(';') + '(云主机与轻量是两条独立策略,缺哪条就在 IAM 补哪条)',
553
+ { vendor: 'ucloud', reason });
554
+ }
555
+ return out;
556
+ },
557
+ actionArgs(kind, instanceId) {
558
+ // 官方文档:uhost/ulhost 都是 start|stop|restart,参数名各是 --uhost-id / --ulhost-id
559
+ const map = { start: 'start', stop: 'stop', reboot: 'restart' };
560
+ if (String(instanceId).startsWith('ulhost-')) {
561
+ return ['ulhost', map[kind], '--ulhost-id', instanceId];
562
+ }
563
+ return ['uhost', map[kind], '--uhost-id', instanceId];
564
+ }
565
+ },
566
+
567
+ jdcloud: {
568
+ id: 'jdcloud',
569
+ label: '京东云',
570
+ bin: 'jdc',
571
+ spec_verified: 'verified',
572
+ async list(ctx) {
573
+ // ★ 真机核对(jdcloud-cli 1.2.12):--output 是**全局参数**,必须放在子命令之前;
574
+ // 放后面会报 "unrecognized arguments"。
575
+ const args = ['--output', 'json', 'vm', 'describe-instances'];
576
+ if (ctx.region) args.push('--region-id', ctx.region);
577
+ const res = await run(binFor('jdcloud', 'jdc'), args, { vendor: 'jdcloud', timeout: ctx.timeout });
578
+ const rawAll = `${res.stdout || ''}${res.stderr || ''}`;
579
+ // 真机:未配置时打印一句提示、**退出码仍是 0**
580
+ if (/jdc configure add|add cli configure/i.test(rawAll)) {
581
+ throw new CliError(EXIT.CRED,
582
+ '京东云未配置凭据:先运行 `jdc configure add --access-key … --secret-key …`',
583
+ { vendor: 'jdcloud', reason: 'auth_failed' });
584
+ }
585
+ const j = parseJson(res.stdout, 'jdc', 'describe-instances');
586
+ const set = (j.result && j.result.instances) || j.instances || [];
587
+ return set.map((s) => ({
588
+ id: `jdcloud:${s.instanceId}`,
589
+ provider: 'jdcloud',
590
+ instance_id: s.instanceId,
591
+ name: s.instanceName || s.name || '',
592
+ region: s.az || s.region || ctx.region || null,
593
+ status: normStatus(s.status),
594
+ public_ipv4: (s.publicIpAddress || (s.elasticIpAddress && s.elasticIpAddress.ipAddress)) || null,
595
+ type: s.instanceType || null
596
+ }));
597
+ },
598
+ actionArgs(kind, instanceId) {
599
+ // ★ 真机核对(1.2.12 --help):单数命令 + `--instance-id`(带连字符),
600
+ // 不是博客里的 reboot-instances / --instanceId。
601
+ const map = { start: 'start-instance', stop: 'stop-instance', reboot: 'reboot-instance' };
602
+ return ['vm', map[kind], '--instance-id', instanceId];
603
+ }
604
+ },
605
+
606
+ ctyun: {
607
+ id: 'ctyun',
608
+ label: '天翼云',
609
+ bin: 'ctyun-cli',
610
+ spec_verified: 'verified', // 2026-11-19 按官方 ctyun-cli 0.4.0 --help 与真机输出核对
611
+ async list(ctx) {
612
+ // ★ 官方 CLI 是 API 式操作名(ListEcsInstances),且 --regionID 必填;
613
+ // 但 `common ListRegions` 可以自取资源池,所以不给 region 就全量遍历。
614
+ const bin = binFor('ctyun', 'ctyun-cli');
615
+ const regions = await ctyunRegions(bin, ctx);
616
+ const failures = [];
617
+ const out = [];
618
+ // ★ 真机:27 个资源池同时起进程会把 TLS 握手打超时,限制并发到 4
619
+ const LIMIT = 6;
620
+ let doneCount = 0;
621
+ const results = [];
622
+ for (let i = 0; i < regions.length; i += LIMIT) {
623
+ const batch = regions.slice(i, i + LIMIT);
624
+ results.push(...await Promise.all(batch.map(async (r) => {
625
+ try {
626
+ const args = ['ecs', 'ListEcsInstances', '--regionID', r.id,
627
+ '--pageSize', '50', '--output', 'json'];
628
+ const res = await run(bin, args, { vendor: 'ctyun', timeout: ctx.timeout });
629
+ const j = parseJson(String(res.stdout || '').trim(), 'ctyun-cli', 'ListEcsInstances');
630
+ const body = j.returnObj || j.result || j;
631
+ // ★ 真机字段:returnObj.results(不是 instances)
632
+ const set = body.results || body.instances || body.instanceList || (Array.isArray(body) ? body : []);
633
+ return (set || []).map((it) => ({
634
+ id: `ctyun:${it.instanceID || it.instanceId || it.id}`,
635
+ provider: 'ctyun',
636
+ instance_id: String(it.instanceID || it.instanceId || it.id),
637
+ name: it.displayName || it.instanceName || it.name || '',
638
+ region: r.code || it.regionID || r.id,
639
+ status: normStatus(it.instanceStatus || it.status || it.state),
640
+ public_ipv4: it.publicIP || it.publicIp || it.eipAddress || null,
641
+ type: it.flavorName || it.flavorID || it.instanceType || null
642
+ }));
643
+ } catch (e) {
644
+ // 真机:海外/非大陆公有云资源池会报「仅支持中国大陆公有云资源池」——跳过,不算失败
645
+ if (/仅支持中国大陆公有云资源池|不在支持范围内/.test(e.message)) return [];
646
+ failures.push({ region: r.code || r.id, message: e.message, reason: e.reason || 'error' });
647
+ return [];
648
+ } finally {
649
+ emitProgress('ctyun', ++doneCount, regions.length, r.id);
650
+ }
651
+ })));
652
+ }
653
+ for (const arr of results) out.push(...arr);
654
+ if (!out.length && failures.length) {
655
+ const reasons = failures.map((f) => f.reason);
656
+ const reason = reasons.includes('auth_failed') ? 'auth_failed'
657
+ : (reasons.includes('permission_denied') ? 'permission_denied' : reasons[0]);
658
+ throw new CliError(reason === 'auth_failed' ? EXIT.CRED : EXIT.VENDOR,
659
+ `天翼云 ${failures.length} 个资源池查询失败:${failures[0].message}`,
660
+ { vendor: 'ctyun', reason });
661
+ }
662
+ return out;
663
+ },
664
+ actionArgs(kind, instanceId) {
665
+ // 官方:StartEcsInstance / StopEcsInstance / RebootEcsInstance --instanceID(regionID 由调用层补)
666
+ const map = { start: 'StartEcsInstance', stop: 'StopEcsInstance', reboot: 'RebootEcsInstance' };
667
+ return ['ecs', map[kind], '--instanceID', instanceId];
668
+ }
669
+ },
670
+
671
+ volcengine: {
672
+ id: 'volcengine',
673
+ label: '火山引擎',
674
+ bin: 've',
675
+ // 真机核对(ve 2.0.2,2026-11-19 `--help`):
676
+ // `ve ecs DescribeInstances [--InstanceIds.N] [--MaxResults] [--NextToken]`,JSON 信封 ResponseMetadata + Result
677
+ // `ve ecs StartInstance|StopInstance|RebootInstance --InstanceId i-xxx`;Stop 另有 --ForceStop / --StoppedMode
678
+ spec_verified: 'verified',
679
+ async list(ctx) {
680
+ const bin = binFor('volcengine', 've');
681
+ const regions = ctx.region ? [ctx.region] : await volcRegions(bin, ctx);
682
+ const failures = [];
683
+ let doneCount = 0;
684
+ const results = await mapLimit(regions, 6, async (region) => {
685
+ try {
686
+ const rows = [];
687
+ const base = ['ecs', 'DescribeInstances', '--MaxResults', '100', '--region', region];
688
+ if (ctx.vendorProfile) base.push('--profile', ctx.vendorProfile);
689
+ let nextToken = null;
690
+ for (let page = 0; page < 10; page++) {
691
+ const args = nextToken ? [...base, '--NextToken', nextToken] : base;
692
+ const { stdout } = await run(bin, args, { vendor: 'volcengine', timeout: ctx.timeout });
693
+ const j = parseJson(stdout, 'volcengine', 'DescribeInstances');
694
+ const result = j.Result || j.result || j;
695
+ const set = result.Instances || (Array.isArray(result) ? result : []);
696
+ for (const it of set) {
697
+ const iid = it.InstanceId;
698
+ if (!iid) continue;
699
+ rows.push({
700
+ id: `volcengine:${iid}`,
701
+ provider: 'volcengine',
702
+ instance_id: iid,
703
+ name: it.InstanceName || '',
704
+ region: it.RegionId || region,
705
+ // 真机状态值是大写:RUNNING / STOPPED / STARTING / STOPPING / REBOOTING
706
+ status: normStatus(it.Status),
707
+ public_ipv4: (it.EipAddress && it.EipAddress.IpAddress) || it.PublicIpAddress || null,
708
+ type: it.InstanceTypeId || it.InstanceType || null
709
+ });
710
+ }
711
+ nextToken = result.NextToken || null;
712
+ if (!nextToken) break;
713
+ }
714
+ return rows;
715
+ } catch (e) {
716
+ failures.push({ region, message: e.message, reason: e.reason || 'error' });
717
+ return [];
718
+ } finally {
719
+ emitProgress('volcengine', ++doneCount, regions.length, region);
720
+ }
721
+ });
722
+ const out = results.flat();
723
+ if (!out.length && failures.length) {
724
+ const reasons = failures.map((f) => f.reason);
725
+ const reason = reasons.includes('auth_failed') ? 'auth_failed'
726
+ : (reasons.includes('permission_denied') ? 'permission_denied' : reasons[0]);
727
+ throw new CliError(reason === 'auth_failed' ? EXIT.CRED : EXIT.VENDOR,
728
+ `火山引擎 ${failures.length} 个地域查询失败:${failures[0].message}`,
729
+ { vendor: 'volcengine', reason });
730
+ }
731
+ return out;
732
+ },
733
+ actionArgs(kind, instanceId) {
734
+ const map = { start: 'StartInstance', stop: 'StopInstance', reboot: 'RebootInstance' };
735
+ return ['ecs', map[kind], '--InstanceId', instanceId];
736
+ }
737
+ },
738
+
739
+ baidu: {
740
+ id: 'baidu',
741
+ label: '百度智能云',
742
+ bin: 'bce',
743
+ // 真机核对(bce 0.1.148,2026-11-19 `--help`):
744
+ // `bce bcc ListInstances --region bj --marker … --maxKeys 100`;`isTruncated / nextMarker / instances[]`
745
+ // `bce bcc StartInstance|StopInstance|RebootInstance --instanceId i-xxx`(Stop/Reboot 另有 --forceStop)
746
+ spec_verified: 'verified',
747
+ async list(ctx) {
748
+ const bin = binFor('baidu', 'bce');
749
+ // BCC 的 endpoint 表:bj / gz / su / bd / hkg;没给 --region 就按这五个地域全量列。
750
+ const regions = ctx.region ? [ctx.region] : ['bj', 'gz', 'su', 'bd', 'hkg'];
751
+ const failures = [];
752
+ let doneCount = 0;
753
+ const results = await Promise.all(regions.map(async (region) => {
754
+ try {
755
+ const rows = [];
756
+ let marker = null;
757
+ for (let page = 0; page < 10; page++) {
758
+ const args = ['bcc', 'ListInstances', '--region', region, '--maxKeys', '100'];
759
+ if (ctx.vendorProfile) args.push('--profile', ctx.vendorProfile);
760
+ if (marker) args.push('--marker', marker);
761
+ const { stdout } = await run(bin, args, { vendor: 'baidu', timeout: ctx.timeout });
762
+ const j = parseJson(stdout, 'bce', 'ListInstances');
763
+ const set = j.instances || (j.result && j.result.instances) || [];
764
+ for (const it of set) {
765
+ const iid = it.id || it.instanceId;
766
+ if (!iid) continue;
767
+ rows.push({
768
+ id: `baidu:${iid}`,
769
+ provider: 'baidu',
770
+ instance_id: String(iid),
771
+ name: it.name || it.instanceName || '',
772
+ region: it.zoneName || region,
773
+ status: normStatus(it.status),
774
+ public_ipv4: it.publicIp || it.publicIpAddress || null,
775
+ type: it.type || it.instanceType || null
776
+ });
777
+ }
778
+ marker = j.nextMarker || null;
779
+ if (!j.isTruncated || !marker) break;
780
+ }
781
+ return rows;
782
+ } catch (e) {
783
+ failures.push({ region, message: e.message, reason: e.reason || 'error' });
784
+ return [];
785
+ } finally {
786
+ emitProgress('baidu', ++doneCount, regions.length, region);
787
+ }
788
+ }));
789
+ const out = results.flat();
790
+ if (!out.length && failures.length) {
791
+ const reasons = failures.map((f) => f.reason);
792
+ const reason = reasons.includes('auth_failed') ? 'auth_failed'
793
+ : (reasons.includes('permission_denied') ? 'permission_denied' : reasons[0]);
794
+ throw new CliError(reason === 'auth_failed' ? EXIT.CRED : EXIT.VENDOR,
795
+ `百度智能云 ${failures.length} 个地域查询失败:${failures[0].message}`,
796
+ { vendor: 'baidu', reason });
797
+ }
798
+ return out;
799
+ },
800
+ actionArgs(kind, instanceId) {
801
+ const map = { start: 'StartInstance', stop: 'StopInstance', reboot: 'RebootInstance' };
802
+ return ['bcc', map[kind], '--instanceId', instanceId];
803
+ }
804
+ },
805
+
806
+ west: {
807
+ id: 'west',
808
+ label: '西部数码',
809
+ bin: 'west-api', // 无官方 CLI:适配器直接调 HTTP API
810
+ direct: true,
811
+ spec_verified: 'verified', // 2026-11-20 客服确认银牌代理可用服务器接口;只核对接口名
812
+ async list(ctx) {
813
+ const west = require('./west');
814
+ // GET /server/?act=list&pageno=&limit=&serverroom=
815
+ const data = await west.listServers({
816
+ pageno: 1,
817
+ limit: 100,
818
+ serverroom: ctx.region || undefined,
819
+ timeout: ctx.timeout
820
+ });
821
+ const rooms = await west.roomNames({ timeout: ctx.timeout });
822
+ return west.mapItems(data && data.items, ctx.region, rooms);
823
+ },
824
+ // host status 用:按 ip 查真实运行状态(列表接口没有状态字段)
825
+ async getStatus(ctx, host) {
826
+ const west = require('./west');
827
+ if (!host || !host.public_ipv4) return host;
828
+ const d = await west.serverStatus({ ip: host.public_ipv4, timeout: ctx.timeout });
829
+ return Object.assign({}, host, west.mapStatus(d));
830
+ },
831
+ // host snapshots 用(只读)
832
+ async snapshots(ctx, host) {
833
+ const west = require('./west');
834
+ if (!host || !host.public_ipv4) throw new CliError(EXIT.NOT_FOUND, '该实例没有公网 IP,无法查询快照');
835
+ const d = await west.snapshots({ ip: host.public_ipv4, timeout: ctx.timeout });
836
+ return west.mapSnapshots(d);
837
+ },
838
+ actionArgs() {
839
+ // 第一期只读:写操作一律拒绝(CLI 层 read_only 闸之外的第二道)
840
+ throw new CliError(EXIT.USAGE, '西部数码第一期只读:不支持 start/stop/reboot', {
841
+ vendor: 'west', reason: 'read_only'
842
+ });
843
+ }
844
+ },
845
+
846
+ linode: {
847
+ id: 'linode',
848
+ label: 'Linode',
849
+ bin: 'linode-cli',
850
+ async list(ctx) {
851
+ // ★ 真机核对(linode-cli 5.70.0 `--help`,2026-11-20):CLI 有 --page/--page-size,
852
+ // --all-rows 关闭分页一次取全;--json 输出对象数组。
853
+ const args = ['linodes', 'list', '--json', '--all-rows'];
854
+ const { stdout } = await run(binFor('linode', 'linode-cli'), args, { vendor: 'linode', timeout: ctx.timeout });
855
+ const j = parseJson(stdout, 'linode-cli', 'linodes list');
856
+ return (Array.isArray(j) ? j : []).map((s) => ({
857
+ id: `linode:${s.id}`,
858
+ provider: 'linode',
859
+ instance_id: String(s.id),
860
+ name: s.label || '',
861
+ region: s.region || null,
862
+ status: normStatus(s.status),
863
+ public_ipv4: (s.ipv4 && s.ipv4[0]) || null,
864
+ type: s.type || null
865
+ }));
866
+ },
867
+ actionArgs(kind, instanceId) {
868
+ const map = { start: 'boot', stop: 'shutdown', reboot: 'reboot' };
869
+ return ['linodes', map[kind], instanceId];
870
+ }
871
+ }
872
+ };
873
+
874
+ const VENDOR_IDS = Object.keys(ADAPTERS);
875
+
876
+ function getAdapter(name) {
877
+ const a = ADAPTERS[name];
878
+ if (!a) {
879
+ throw new CliError(EXIT.USAGE,
880
+ `不支持的厂商:${name}(已支持:${VENDOR_IDS.join(', ')})`);
881
+ }
882
+ return a;
883
+ }
884
+
885
+ // 探测厂商 CLI 自身有没有配置凭据(主机操作走的是它的登录态,不是我们的 credentials.json)
886
+ // 返回 {checked: bool, configured: bool|null, detail: str}
887
+ async function probeCreds(vendor, timeout) {
888
+ if (vendor === 'west') {
889
+ const c = require('./west').creds();
890
+ return {
891
+ checked: true,
892
+ configured: !!(c.user && c.pass),
893
+ detail: '西部 API 凭据来自环境变量(由 vault 注入)'
894
+ };
895
+ }
896
+ const bin = binFor(vendor, (ADAPTERS[vendor] || {}).bin || vendor);
897
+ try {
898
+ if (vendor === 'ucloud') {
899
+ const { stdout } = await run(bin, ['config', 'list'], { vendor, timeout: timeout || 15000 });
900
+ const txt = String(stdout || '').trim();
901
+ let n = null;
902
+ try { n = JSON.parse(txt).length; } catch (_) { n = txt && txt !== '[]' ? 1 : 0; }
903
+ return { checked: true, configured: n > 0, detail: `ucloud config list: ${n} 个配置` };
904
+ }
905
+ // ★ 真机核对(2026-11-19):阿里云/火山/百度在**没有任何配置档案**时退出码仍是 0,
906
+ // 只能靠输出文本判断(阿里云是 JSON ConfigurationError)。腾讯 credential 段为空表示没配 AK。
907
+ if (vendor === 'aliyun') {
908
+ // 阿里云把 ConfigurationError 打到 stderr,run() 会按 authLike 抛 auth_failed——这里当作“未配置”
909
+ try {
910
+ const res = await run(bin, ['configure', 'list'], { vendor, timeout: timeout || 15000 });
911
+ const text = `${res.stdout || ''}\n${res.stderr || ''}`;
912
+ const configured = !/ConfigurationError|profile configuration failed/i.test(text) &&
913
+ String(res.stdout || '').trim().length > 0;
914
+ return { checked: true, configured, detail: 'aliyun configure list: ' + (configured ? '有可用 profile' : '无可用 profile') };
915
+ } catch (e) {
916
+ if (e.reason === 'auth_failed') {
917
+ return { checked: true, configured: false, detail: 'aliyun configure list: 无可用 profile' };
918
+ }
919
+ throw e;
920
+ }
921
+ }
922
+ if (vendor === 'volcengine') {
923
+ const res = await run(bin, ['configure', 'list'], { vendor, timeout: timeout || 15000 });
924
+ const text = `${res.stdout || ''}\n${res.stderr || ''}`;
925
+ const configured = !/尚未创建配置档案|no profiles?/i.test(text) && String(res.stdout || '').trim().length > 0;
926
+ return { checked: true, configured, detail: 've configure list: ' + (configured ? '有配置档案' : '尚未创建配置档案') };
927
+ }
928
+ if (vendor === 'baidu') {
929
+ const res = await run(bin, ['configure', 'list'], { vendor, timeout: timeout || 15000 });
930
+ const text = `${res.stdout || ''}\n${res.stderr || ''}`;
931
+ const configured = !/暂无 profile|no profile/i.test(text) && String(res.stdout || '').trim().length > 0;
932
+ return { checked: true, configured, detail: 'bce configure list: ' + (configured ? '有 profile' : '暂无 profile') };
933
+ }
934
+ if (vendor === 'tencent') {
935
+ const res = await run(bin, ['configure', 'list'], { vendor, timeout: timeout || 15000 });
936
+ const text = `${res.stdout || ''}\n${res.stderr || ''}`;
937
+ const configured = /secretId\s*=/i.test(text);
938
+ return { checked: true, configured, detail: 'tccli configure list: ' + (configured ? '已配置 secretId' : 'credential 段为空') };
939
+ }
940
+ } catch (e) {
941
+ return { checked: true, configured: null, detail: e.message.slice(0, 160) };
942
+ }
943
+ return { checked: false, configured: null, detail: '' };
944
+ }
945
+
946
+ // 检测某厂商 CLI 是否可用(装没装、版本)
947
+ async function probe(vendor, timeout) {
948
+ const a = getAdapter(vendor);
949
+ // 直连 API 的厂商标配器(如西部数码)没有 CLI:“已装”= 适配器可用
950
+ if (a.direct) {
951
+ return { id: vendor, label: a.label, bin: '(HTTP API)', installed: true, version: 'HTTP API' };
952
+ }
953
+ const bin = binFor(vendor, a.bin);
954
+ // ★ 真机核对(2026-11-19):阿里云 `--version` 会打印整棵命令树 JSON,要用 `version` 子命令;
955
+ // 百度 bce 没有 `--version`(报 unknown flag),同样用 `version` 子命令。
956
+ // ★ 真机核对(2026-11-20):doctl / hcloud / vultr-cli 都不认 `--version`(unknown flag),
957
+ // 分别是 `doctl version` / `hcloud version` / `vultr-cli version`;aws 与 linode-cli 认 `--version`。
958
+ const versionArgs = {
959
+ vultr: [['version'], ['--version']],
960
+ doctl: [['version']],
961
+ hcloud: [['version']],
962
+ aliyun: [['version']],
963
+ baidu: [['version']]
964
+ };
965
+ const attempts = versionArgs[vendor] || [['--version']];
966
+ try {
967
+ let out = null;
968
+ let lastErr = null;
969
+ for (const args of attempts) {
970
+ try {
971
+ out = await run(bin, args, { vendor, timeout: Math.min(timeout || 15000, 20000) });
972
+ break;
973
+ } catch (e) {
974
+ lastErr = e;
975
+ if (e.reason === 'cli_missing') throw e;
976
+ }
977
+ }
978
+ if (!out) throw lastErr;
979
+ const text = `${out.stdout}\n${out.stderr}`.trim().split(/\r?\n/).filter(Boolean).slice(0, 3).join(' ');
980
+ return { id: vendor, label: a.label, bin, installed: true, version: text.replace(/\s+/g, ' ').slice(0, 120) };
981
+ } catch (e) {
982
+ return {
983
+ id: vendor,
984
+ label: a.label,
985
+ bin,
986
+ installed: false,
987
+ version: null,
988
+ error: e.message,
989
+ reason: e.reason || 'cli_missing'
990
+ };
991
+ }
992
+ }
993
+
994
+ // 解析 "provider:instance-id"
995
+ function parseHostId(raw) {
996
+ const s = String(raw || '');
997
+ const idx = s.indexOf(':');
998
+ if (idx <= 0) {
999
+ throw new CliError(EXIT.USAGE,
1000
+ `主机 ID 必须是 <provider>:<instance-id> 形式(如 aliyun:i-0123abcd),收到:${s}`);
1001
+ }
1002
+ return { provider: s.slice(0, idx), instanceId: s.slice(idx + 1) };
1003
+ }
1004
+
1005
+ // ★ 2026-11-20:跨地域列出的实例,写命令必须带对地域(AWS 不给 --region 会 NoRegion / NotFound;
1006
+ // 腾讯跨地域后停在默认地域)。从列表里的 AZ/可用区反推地域:
1007
+ // aws us-west-2a → us-west-2
1008
+ // tencent ap-beijing-3 → ap-beijing(ap-shanghai-fsi-1 → ap-shanghai-fsi)
1009
+ // 其它厂商列表里存的就是可直接用的地域/机房标识,或 CLI 自带默认地域,不额外推导。
1010
+ function regionForHost(host) {
1011
+ if (!host || !host.region) return null;
1012
+ const r = String(host.region);
1013
+ if (host.provider === 'aws') return /[a-z]$/.test(r) ? r.replace(/[a-z]$/, '') : r;
1014
+ if (host.provider === 'tencent') return /-\d+$/.test(r) ? r.replace(/-\d+$/, '') : r;
1015
+ return null;
1016
+ }
1017
+
1018
+ // 显式 --region / profile 默认地域优先;没有时用实例所在地域补齐,供 actionCommand/runAction/waitFor 使用。
1019
+ function actionCtx(ctx, host) {
1020
+ if (ctx.region) return ctx;
1021
+ const region = regionForHost(host);
1022
+ return region ? Object.assign({}, ctx, { region }) : ctx;
1023
+ }
1024
+
1025
+ function hostCtx(opts, profile) {
1026
+ return {
1027
+ region: opts.region && opts.region !== true ? String(opts.region) : (profile && profile.default_region) || null,
1028
+ vendorProfile: opts.vendorProfile && opts.vendorProfile !== true ? String(opts.vendorProfile) : null,
1029
+ projectId: opts.project && opts.project !== true ? String(opts.project) : null,
1030
+ timeout: opts.timeout ? (parseInt(opts.timeout, 10) * 1000) : DEFAULT_TIMEOUT
1031
+ };
1032
+ }
1033
+
1034
+ async function listAcross(opts, profile, io) {
1035
+ const only = opts.provider && opts.provider !== true ? require('./core').asArray(opts.provider) : [];
1036
+ const ids = only.length ? only.map((p) => { getAdapter(p); return p; }) : VENDOR_IDS;
1037
+ const ctx = hostCtx(opts, profile);
1038
+ const results = [];
1039
+ const errors = [];
1040
+
1041
+ for (const id of ids) {
1042
+ try {
1043
+ const hosts = await getAdapter(id).list(ctx);
1044
+ results.push(...hosts);
1045
+ } catch (e) {
1046
+ // 单厂商失败不拖垮整表:记录错误,明确报出是哪家、哪一层
1047
+ errors.push({ provider: id, message: e.message, reason: e.reason || 'error', exit_code: e.exitCode || EXIT.GENERAL });
1048
+ }
1049
+ }
1050
+
1051
+ for (const err of errors) {
1052
+ io.warn(`${err.provider} 未纳入本次结果:${err.message}`, err);
1053
+ }
1054
+ return { hosts: results, errors };
1055
+ }
1056
+
1057
+ async function findHost(rawId, opts, profile) {
1058
+ const { provider, instanceId } = parseHostId(rawId);
1059
+ const adapter = getAdapter(provider);
1060
+ const ctx = hostCtx(opts, profile);
1061
+ const hosts = await adapter.list(ctx);
1062
+ const host = hosts.find((h) => h.instance_id === instanceId);
1063
+ if (!host) {
1064
+ throw new CliError(EXIT.NOT_FOUND,
1065
+ `在 ${provider} 账号下未找到实例 ${instanceId}` +
1066
+ (ctx.region ? `(当前 region=${ctx.region})` : `(未指定 --region,部分厂商默认地域可能不含该实例)`),
1067
+ { provider, instance_id: instanceId });
1068
+ }
1069
+ return { adapter, ctx, host };
1070
+ }
1071
+
1072
+ // 把「一次写操作要执行的厂商命令」拼出来(dry-run 打印与真执行共用同一份,避免预览和实际不一致)
1073
+ function actionCommand(vendor, kind, instanceId, ctx) {
1074
+ const adapter = getAdapter(vendor);
1075
+ const args = adapter.actionArgs(kind, instanceId);
1076
+ const bin = binFor(vendor, adapter.bin);
1077
+ const extra = [];
1078
+ if (ctx.region) {
1079
+ if (vendor === 'aliyun') extra.push('--RegionId', ctx.region);
1080
+ else if (vendor === 'aws' || vendor === 'tencent' || vendor === 'ucloud' ||
1081
+ vendor === 'volcengine' || vendor === 'baidu') extra.push('--region', ctx.region);
1082
+ else if (vendor === 'jdcloud') extra.push('--region-id', ctx.region);
1083
+ else if (vendor === 'ctyun') extra.push('--regionID', ctx.region);
1084
+ }
1085
+ if (ctx.vendorProfile) {
1086
+ if (vendor === 'aws') extra.push('--profile', ctx.vendorProfile);
1087
+ else if (vendor === 'tencent') extra.push('--profile', ctx.vendorProfile);
1088
+ else if (vendor === 'aliyun') extra.push('--Profile', ctx.vendorProfile);
1089
+ else if (vendor === 'hcloud') extra.push('--context', ctx.vendorProfile);
1090
+ else if (vendor === 'volcengine' || vendor === 'baidu') extra.push('--profile', ctx.vendorProfile);
1091
+ }
1092
+ return { bin, args: [...args, ...extra] };
1093
+ }
1094
+
1095
+ async function runAction(vendor, kind, instanceId, ctx) {
1096
+ const adapter = getAdapter(vendor);
1097
+ const args = adapter.actionArgs(kind, instanceId);
1098
+ const bin = binFor(vendor, adapter.bin);
1099
+ const extra = [];
1100
+ if (ctx.region) {
1101
+ if (vendor === 'aliyun') extra.push('--RegionId', ctx.region);
1102
+ else if (vendor === 'aws' || vendor === 'tencent' || vendor === 'ucloud' ||
1103
+ vendor === 'volcengine' || vendor === 'baidu') extra.push('--region', ctx.region);
1104
+ else if (vendor === 'jdcloud') extra.push('--region-id', ctx.region);
1105
+ else if (vendor === 'ctyun') extra.push('--regionID', ctx.region);
1106
+ // doctl / hcloud / vultr / linode 的实例操作不需要地域参数
1107
+ }
1108
+ if (ctx.vendorProfile) {
1109
+ if (vendor === 'aws') extra.push('--profile', ctx.vendorProfile);
1110
+ else if (vendor === 'tencent') extra.push('--profile', ctx.vendorProfile);
1111
+ else if (vendor === 'aliyun') extra.push('--Profile', ctx.vendorProfile);
1112
+ else if (vendor === 'hcloud') extra.push('--context', ctx.vendorProfile);
1113
+ else if (vendor === 'volcengine' || vendor === 'baidu') extra.push('--profile', ctx.vendorProfile);
1114
+ }
1115
+ const display = [bin, ...args, ...extra].join(' ');
1116
+ const { stdout, stderr } = await run(bin, [...args, ...extra], { vendor, timeout: ctx.timeout });
1117
+ return { command: display, stdout, stderr };
1118
+ }
1119
+
1120
+ const TARGET_STATUS = { start: 'running', stop: 'stopped', reboot: 'running' };
1121
+
1122
+ async function waitFor(adapter, ctx, instanceId, until, io, opts) {
1123
+ const timeoutMs = (parseInt(opts.timeout || '300', 10) || 300) * 1000;
1124
+ const intervalMs = (parseInt(opts.pollInterval || '5', 10) || 5) * 1000;
1125
+ const deadline = Date.now() + timeoutMs;
1126
+ let last = null;
1127
+ while (Date.now() < deadline) {
1128
+ const hosts = await adapter.list(ctx);
1129
+ const h = hosts.find((x) => x.instance_id === instanceId);
1130
+ last = h ? h.status : null;
1131
+ if (h && h.status === until) return h;
1132
+ io.info(`等待 ${instanceId} 进入 ${until} …(当前 ${last || '未知'})`);
1133
+ await new Promise((r) => setTimeout(r, intervalMs));
1134
+ }
1135
+ throw new CliError(EXIT.VENDOR,
1136
+ `等待超时:${instanceId} 未在 ${timeoutMs / 1000}s 内进入 ${until}(最后状态 ${last || '未知'})`,
1137
+ { instance_id: instanceId, last_status: last, reason: 'wait_timeout' });
1138
+ }
1139
+
1140
+ module.exports = {
1141
+ ADAPTERS,
1142
+ actionCommand,
1143
+ probeCreds,
1144
+ VENDOR_IDS,
1145
+ getAdapter,
1146
+ probe,
1147
+ parseHostId,
1148
+ hostCtx,
1149
+ actionCtx,
1150
+ regionForHost,
1151
+ listAcross,
1152
+ findHost,
1153
+ runAction,
1154
+ waitFor,
1155
+ TARGET_STATUS
1156
+ };