dotop-gpu-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/src/wizard.mjs ADDED
@@ -0,0 +1,1056 @@
1
+ // 交互式下单向导:检查 Key → 选公钥 → 选可用区 → 选显卡 → 选规格 → 选镜像
2
+ // → 选计费 → 报价 → 下单 → 轮询进度 → 打印 SSH 命令
3
+ //
4
+ // 结构是一个小步骤机:每个步骤都可以返回上一步。
5
+ // 之所以不做成线性流程,是因为真实场景里经常要改主意 —— 比如选的可用区
6
+ // 显卡售罄、或者报价后发现包月比预期贵,这时候应该退回去改选择,
7
+ // 而不是让用户 Ctrl+C 重来一遍。
8
+ //
9
+ // 确认页是「修改中心」:改计费 / 改期数 / 改镜像 / 改规格 / 换公钥都在确认页就地完成,
10
+ // 改完直接回到确认页,不会把后面的步骤重新走一遍。
11
+ import { selectOne, selectCount, ask, confirm, BACK, inputExhausted } from './prompts.mjs';
12
+ import {
13
+ paint,
14
+ money,
15
+ duration,
16
+ ts,
17
+ billingText,
18
+ progressLine,
19
+ pollDecision,
20
+ } from './render.mjs';
21
+ import { scanLocalKeys, fingerprintOf, sshDir } from './sshkeys.mjs';
22
+
23
+ const POLL_INTERVAL_MS = 3000;
24
+ const POLL_TIMEOUT_MS = 10 * 60 * 1000;
25
+
26
+ // 步骤常量:用整数方便表达「上一步」
27
+ const STEP_SSH = 1;
28
+ const STEP_ZONE = 2;
29
+ const STEP_GPU_TYPE = 3;
30
+ const STEP_PLAN = 4;
31
+ const STEP_IMAGE = 5;
32
+ const STEP_BILLING = 6;
33
+ const STEP_CONFIRM = 7;
34
+ const STEP_DONE = 8;
35
+
36
+ // 一次向导运行只生成一次幂等键:重试 / 重跑同一次下单必须复用它
37
+ export function newIdempotencyKey() {
38
+ const now = new Date();
39
+ const stamp =
40
+ now.getFullYear().toString() +
41
+ String(now.getMonth() + 1).padStart(2, '0') +
42
+ String(now.getDate()).padStart(2, '0') +
43
+ String(now.getHours()).padStart(2, '0') +
44
+ String(now.getMinutes()).padStart(2, '0') +
45
+ String(now.getSeconds()).padStart(2, '0');
46
+ const rand = Math.random().toString(36).slice(2, 8);
47
+ return `dotop-gpu-${stamp}-${rand}`;
48
+ }
49
+
50
+ // 向导主流程。
51
+ //
52
+ // preset:命令行已经指定的选项(见 src/rentflow.mjs 的 resolvePreset)。
53
+ // 命中的步骤直接跳过,没命中的照常问 —— 这就是「混合模式」:
54
+ // `dotop-gpu rent --zone z2 --billing daily` 只会问剩下没给的部分。
55
+ // yes:确认页不问,直接下单(配合 preset 用)。
56
+ // dryRun:只打印报价,不下单。
57
+ // noWait:下单后不等建机完成,立刻返回租约号。
58
+ export async function runWizard(
59
+ client,
60
+ { auto = false, preset = null, yes = false, dryRun = false, noWait = false } = {},
61
+ ) {
62
+ // 各步骤的选择结果。回退时要把受影响的下游清空,避免「换了可用区
63
+ // 还拿着上一个区的 plan_id 去下单」。
64
+ const picked = {
65
+ sshKey: null,
66
+ zone: null,
67
+ group: null,
68
+ plan: null,
69
+ image: null,
70
+ images: null,
71
+ imagesFor: '',
72
+ billing: null,
73
+ commitmentCount: 0,
74
+ quote: null,
75
+ };
76
+ // 命令行预置项:一旦被向导消费掉就删除标记,回退时不让它再抢着用
77
+ const given = preset ? { ...preset } : null;
78
+ const has = (field) => Boolean(given && given[field] !== undefined);
79
+
80
+ let zones = [];
81
+ let step = STEP_SSH;
82
+ // 有预置参数时没有交互可回退(脚本里不该弹菜单),auto 同理。
83
+ const canBack = !auto && !yes;
84
+
85
+ while (step < STEP_DONE) {
86
+ if (step === STEP_SSH) {
87
+ if (has('sshKey')) {
88
+ picked.sshKey = given.sshKey;
89
+ step = STEP_ZONE;
90
+ continue;
91
+ }
92
+ // 第一步没有「上一步」可退,所以不给 allowBack:菜单里不该出现退不回去的选项。
93
+ // 另外必须显式判 BACK —— 它是 Symbol(truthy),漏判会把它当成公钥赋给 picked.sshKey,
94
+ // 后面确认页就显示 undefined 并带着空公钥一路走到下单。
95
+ const key = await pickSSHKey(client, { auto: auto || yes, current: picked.sshKey, allowBack: false });
96
+ if (key === BACK) continue;
97
+ if (!key) return;
98
+ picked.sshKey = key;
99
+ step = STEP_ZONE;
100
+ continue;
101
+ }
102
+
103
+ if (step === STEP_ZONE) {
104
+ if (has('zone')) {
105
+ picked.zone = given.zone;
106
+ delete given.zone;
107
+ step = STEP_GPU_TYPE;
108
+ continue;
109
+ }
110
+ if (zones.length === 0) {
111
+ zones = (await client.listZones()).items || [];
112
+ if (zones.length === 0) {
113
+ console.log(paint.red('当前没有可用区,无法下单。'));
114
+ return;
115
+ }
116
+ }
117
+ // 可用区列表本身只有 zone_key/name/state(open 契约里就这三个字段),
118
+ // 库存要逐区查 gpu-types 再累加 —— 并发发出去,整体耗时约等于最慢的一个区。
119
+ console.log(paint.dim('正在查询各可用区库存…'));
120
+ const stock = await loadZoneStock(client, zones);
121
+ const choice = await selectOne('选择可用区', zones, {
122
+ render: (z) => `${z.name} ${paint.dim(`(${z.zone_key})`)} ${zoneStockText(stock.get(z.zone_key))}`,
123
+ // 默认选中第一个有货的区,省得用户还要自己扫一遍
124
+ defaultIndex: firstInStockIndex(zones, stock),
125
+ allowBack: canBack,
126
+ });
127
+ if (choice === BACK) {
128
+ step = STEP_SSH;
129
+ continue;
130
+ }
131
+ if (!choice) return;
132
+ // 换了可用区:下游全部失效
133
+ picked.zone = choice;
134
+ picked.group = null;
135
+ picked.plan = null;
136
+ picked.image = null;
137
+ picked.images = null;
138
+ picked.imagesFor = '';
139
+ picked.billing = null;
140
+ picked.quote = null;
141
+ step = STEP_GPU_TYPE;
142
+ continue;
143
+ }
144
+
145
+ if (step === STEP_GPU_TYPE) {
146
+ const groups = (await client.listGpuTypes(picked.zone.zone_key)).items || [];
147
+ const sellable = groups.filter((g) => (g.plans || []).length > 0);
148
+
149
+ if (sellable.length === 0) {
150
+ console.log(paint.yellow(`可用区 ${picked.zone.name} 当前没有可售规格。`));
151
+ step = STEP_ZONE; // 自动退回选可用区
152
+ continue;
153
+ }
154
+
155
+ // 指定了 --plan:直接用它反查属于哪个显卡组,跳过两步选择。
156
+ // 库存仍然要检查 —— 命令行指定不等于平台一定还有货。
157
+ if (has('plan')) {
158
+ const target = given.plan;
159
+ const host = sellable.find((g) => (g.plans || []).some((p) => p.id === target.id));
160
+ if (!host) {
161
+ console.log(
162
+ paint.red(
163
+ `规格 ${target.name}(id=${target.id})不属于可用区 ${picked.zone.name},换一个区或改 --plan。`,
164
+ ),
165
+ );
166
+ return;
167
+ }
168
+ if (!(Number(host.available) > 0)) {
169
+ console.log(paint.red(`型号 ${host.gpu_type_name} 在 ${picked.zone.name} 已售罄,换一个区或换规格。`));
170
+ return;
171
+ }
172
+ picked.group = host;
173
+ picked.plan = target;
174
+ delete given.plan;
175
+ picked.image = null;
176
+ picked.images = null;
177
+ picked.imagesFor = '';
178
+ picked.billing = null;
179
+ picked.quote = null;
180
+ step = STEP_IMAGE;
181
+ continue;
182
+ }
183
+
184
+ const inStock = sellable.filter((g) => g.available > 0);
185
+ if (inStock.length === 0) {
186
+ // 关键体验点:售罄不能把整个向导退掉,应该退回到可用区那一步重选
187
+ console.log(paint.yellow(`可用区 ${picked.zone.name} 的显卡当前已售罄。`));
188
+ console.log(paint.dim('换一个可用区试试(回车回到「选择可用区」)。'));
189
+ step = STEP_ZONE;
190
+ continue;
191
+ }
192
+
193
+ const choice = auto || yes
194
+ ? inStock[0]
195
+ : await selectOne('选择显卡型号', sellable, {
196
+ render: (g) =>
197
+ `${g.gpu_type_name} ${g.available > 0 ? paint.dim(`可售 ${g.available} 张`) : paint.red('已售罄')}`,
198
+ allowBack: canBack,
199
+ });
200
+ if (choice === BACK) {
201
+ step = STEP_ZONE;
202
+ continue;
203
+ }
204
+ if (!choice) return;
205
+
206
+ if (choice.available <= 0) {
207
+ console.log(paint.red(`${choice.gpu_type_name} 已售罄,换个型号或换可用区。`));
208
+ continue; // 停在本步重新选
209
+ }
210
+
211
+ picked.group = choice;
212
+ picked.plan = null;
213
+ picked.image = null;
214
+ picked.images = null;
215
+ picked.imagesFor = '';
216
+ picked.billing = null;
217
+ picked.quote = null;
218
+ step = STEP_PLAN;
219
+ continue;
220
+ }
221
+
222
+ if (step === STEP_PLAN) {
223
+ const plans = picked.group.plans || [];
224
+ const choice = auto || yes
225
+ ? plans[0]
226
+ : await selectOne('选择规格', plans, { render: (p) => planLabel(p), allowBack: canBack });
227
+ if (choice === BACK) {
228
+ step = STEP_GPU_TYPE;
229
+ continue;
230
+ }
231
+ if (!choice) return;
232
+ picked.plan = choice;
233
+ picked.billing = null;
234
+ picked.quote = null;
235
+ step = STEP_IMAGE;
236
+ continue;
237
+ }
238
+
239
+ if (step === STEP_IMAGE) {
240
+ if (!picked.images || picked.imagesFor !== picked.zone.zone_key) {
241
+ const images = (await client.listImages(picked.zone.zone_key)).items || [];
242
+ if (images.length === 0) {
243
+ console.log(paint.red(`可用区 ${picked.zone.name} 没有可用镜像。`));
244
+ console.log(paint.dim('回车回到「选择可用区」。'));
245
+ step = STEP_ZONE;
246
+ continue;
247
+ }
248
+ picked.images = images;
249
+ picked.imagesFor = picked.zone.zone_key;
250
+ }
251
+ if (has('image')) {
252
+ const target = given.image;
253
+ // --image 也要属于当前可用区:open 的镜像是按区下发的
254
+ if (!picked.images.some((i) => i.id === target.id)) {
255
+ console.log(
256
+ paint.red(`镜像 ${target.name}(id=${target.id})不属于可用区 ${picked.zone.name},改 --image 或换区。`),
257
+ );
258
+ return;
259
+ }
260
+ picked.image = target;
261
+ delete given.image;
262
+ picked.billing = null;
263
+ picked.quote = null;
264
+ step = STEP_BILLING;
265
+ continue;
266
+ }
267
+ const choice = auto || yes
268
+ ? picked.images[0]
269
+ : await selectOne('选择镜像', picked.images, {
270
+ render: (i) => imageLabel(i),
271
+ allowBack: canBack,
272
+ });
273
+ if (choice === BACK) {
274
+ step = STEP_PLAN;
275
+ continue;
276
+ }
277
+ if (!choice) return;
278
+ picked.image = choice;
279
+ picked.billing = null;
280
+ picked.quote = null;
281
+ step = STEP_BILLING;
282
+ continue;
283
+ }
284
+
285
+ if (step === STEP_BILLING) {
286
+ // --billing 已指定:直接按该档位建选项(不弹菜单),期数用 --count
287
+ if (has('billing')) {
288
+ const mode = given.billing;
289
+ const choices = await buildBillingChoices(client, picked);
290
+ const found = choices.find((c) => c.mode === mode);
291
+ if (!found) {
292
+ console.log(
293
+ paint.red(
294
+ `${picked.plan.name} 没有开通「${billingText(mode)}」这一档,可用:${choices.map((c) => c.mode).join(' / ')}`,
295
+ ),
296
+ );
297
+ return;
298
+ }
299
+ const applied = await applyBilling(picked, found, {
300
+ auto: true,
301
+ askPeriods: false,
302
+ });
303
+ if (!applied) return;
304
+ if (mode !== 'on-demand' && has('count')) {
305
+ picked.commitmentCount = given.count;
306
+ delete given.count;
307
+ }
308
+ delete given.billing;
309
+ step = STEP_CONFIRM;
310
+ continue;
311
+ }
312
+
313
+ const choice = auto || yes
314
+ ? (await buildBillingChoices(client, picked))[0]
315
+ : await selectOne('选择计费方式', await buildBillingChoices(client, picked), {
316
+ render: (m) => m.label,
317
+ allowBack: canBack,
318
+ });
319
+ if (choice === BACK) {
320
+ step = STEP_IMAGE;
321
+ continue;
322
+ }
323
+ if (!choice) return;
324
+
325
+ await applyBilling(picked, choice, { auto });
326
+ step = STEP_CONFIRM;
327
+ continue;
328
+ }
329
+
330
+ if (step === STEP_CONFIRM) {
331
+ const quote = await client.quoteRental({
332
+ zoneKey: picked.zone.zone_key,
333
+ planId: picked.plan.id,
334
+ billingMode: picked.billing.mode,
335
+ commitmentCount: picked.commitmentCount,
336
+ });
337
+ picked.quote = quote;
338
+
339
+ printSummary(picked, quote);
340
+
341
+ // --dry-run:只报价格,不产生费用。余额不足也照样打印,方便先看清楚再充值。
342
+ if (dryRun) {
343
+ console.log(paint.dim('(--dry-run:只报价,未下单)'));
344
+ return;
345
+ }
346
+
347
+ // --yes / --quick:跳过确认页直接下单。此时 summary 已经打印过,
348
+ // 用户能在输出里看到完整参数与报价,脚本里靠退出码判定结果。
349
+ if (auto || yes) {
350
+ // 余额明显不够就别提交了:服务端一定会拒,还白占一个幂等键
351
+ if (quote.balance && quote.balance.enough === false) {
352
+ const gap = Math.round((quote.balance.required - quote.balance.available) * 100) / 100;
353
+ console.log(paint.red(`余额不足(还差 ${money(gap)}),未下单。`));
354
+ console.log(paint.dim('充值后重跑,或去掉 --yes 手动确认。'));
355
+ return;
356
+ }
357
+ step = STEP_DONE;
358
+ continue;
359
+ }
360
+
361
+ // 第一项不加色:选中行整行已经是青色粗体,再叠一层绿会花,
362
+ // 也让「当前光标在这一项」这个唯一视觉信号变弱。
363
+ const cycleMode = picked.billing && picked.billing.mode !== 'on-demand';
364
+ const confirmItems = [
365
+ { key: 'yes', label: '确认下单' },
366
+ { key: 'billing', label: '改计费方式' },
367
+ ];
368
+ if (cycleMode) confirmItems.push({ key: 'count', label: '改购买期数' });
369
+ confirmItems.push(
370
+ { key: 'image', label: '改镜像' },
371
+ { key: 'plan', label: '改规格' },
372
+ { key: 'ssh', label: '换 SSH 公钥' },
373
+ { key: 'zone', label: '改可用区' },
374
+ { key: 'cancel', label: '取消' },
375
+ );
376
+
377
+ const choice = await selectOne('确认下单?', confirmItems, {
378
+ render: (c) => c.label,
379
+ allowBack: false,
380
+ // 这一步会产生费用:管道模式下空行/回车不再等于「确认下单」,必须显式序号。
381
+ // 2026-12-04 就因为喂入的行数多了一行空行,静默发出了真实下单请求。
382
+ explicitOnly: true,
383
+ });
384
+ // 输入耗尽(非交互管道跑完)不能当成「确认下单」:
385
+ // selectOne 会退回默认项,直接下单就是意外扣费。宁可当作取消。
386
+ if (choice && choice.key === 'yes' && inputExhausted()) {
387
+ console.log(paint.yellow('输入已结束,按「取消」处理(未下单)。'));
388
+ console.log(paint.dim('确定要下单请用交互模式,或用 dotop-gpu rent --quick 显式下单。'));
389
+ return;
390
+ }
391
+ if (!choice || choice.key === 'cancel') {
392
+ console.log(paint.dim('已取消。'));
393
+ return;
394
+ }
395
+
396
+ // ── 以下都在确认页就地改,改完直接回到确认页 ──
397
+ if (choice.key === 'billing') {
398
+ const mode = await selectOne('改计费方式', await buildBillingChoices(client, picked), {
399
+ render: (m) => m.label,
400
+ allowBack: true,
401
+ backLabel: '不改了,回确认页',
402
+ });
403
+ if (mode === BACK || !mode) continue;
404
+ const applied = await applyBilling(picked, mode, { auto });
405
+ if (!applied) continue; // 期数菜单按了 b,回确认页
406
+ continue;
407
+ }
408
+
409
+ // 期数单独成项,就地改完回确认页
410
+ if (choice.key === 'count') {
411
+ picked.commitmentCount = await askPeriodCount(picked);
412
+ picked.quote = null;
413
+ continue;
414
+ }
415
+
416
+ if (choice.key === 'image') {
417
+ const images = picked.images || (await client.listImages(picked.zone.zone_key)).items || [];
418
+ picked.images = images;
419
+ picked.imagesFor = picked.zone.zone_key;
420
+ const img = await selectOne('改镜像', images, {
421
+ render: (i) => imageLabel(i),
422
+ allowBack: true,
423
+ backLabel: '不改了,回确认页',
424
+ });
425
+ if (img === BACK || !img) continue;
426
+ picked.image = img;
427
+ continue;
428
+ }
429
+
430
+ if (choice.key === 'plan') {
431
+ const plan = await selectOne('改规格', picked.group.plans || [], {
432
+ render: (p) => planLabel(p),
433
+ allowBack: true,
434
+ backLabel: '不改了,回确认页',
435
+ });
436
+ if (plan === BACK || !plan) continue;
437
+ picked.plan = plan;
438
+ // 换了规格,原来的计费档位可能没开通,重新选一次(仍在确认页内完成)
439
+ const mode = await selectOne('该规格可选计费方式', await buildBillingChoices(client, picked), {
440
+ render: (m) => m.label,
441
+ allowBack: true,
442
+ backLabel: '不改了,回确认页',
443
+ });
444
+ if (mode === BACK || !mode) continue;
445
+ await applyBilling(picked, mode, { auto });
446
+ continue;
447
+ }
448
+
449
+ if (choice.key === 'ssh') {
450
+ const key = await pickSSHKey(client, { auto, current: picked.sshKey, allowBack: true });
451
+ if (key === BACK || !key) continue;
452
+ picked.sshKey = key;
453
+ continue;
454
+ }
455
+
456
+ if (choice.key === 'zone') {
457
+ // 换区必须重选规格和镜像(它们的 id 属于该区),这条退回步骤流是合理的
458
+ picked.quote = null;
459
+ step = STEP_ZONE;
460
+ continue;
461
+ }
462
+
463
+ step = STEP_DONE;
464
+ continue;
465
+ }
466
+ }
467
+
468
+ // ⑦ 下单
469
+ // 兜底:任何一步把选中项丢成空值时都必须停在这里,不能带着空公钥/空规格去下单。
470
+ if (!picked.sshKey || !picked.zone || !picked.plan || !picked.image || !picked.billing) {
471
+ console.log(paint.red('下单信息不完整,已中止。请重新运行 dotop-gpu rent。'));
472
+ return;
473
+ }
474
+ // --idem 指定时复用它:脚本里重跑同一条命令必须命中同一次下单,
475
+ // 而不是每次都生成新键把机器开两台。
476
+ const idempotencyKey = (preset && preset.idem) || newIdempotencyKey();
477
+ let detail;
478
+ const createBody = {
479
+ zone_key: picked.zone.zone_key,
480
+ plan_id: picked.plan.id,
481
+ image_id: picked.image.id,
482
+ ssh_key_ids: [picked.sshKey.id],
483
+ idempotency_key: idempotencyKey,
484
+ billing_mode: picked.billing.mode,
485
+ commitment_count: picked.commitmentCount,
486
+ };
487
+ if (preset && preset.userData) createBody.user_data = preset.userData;
488
+ if (preset && preset.autoRenew !== undefined) createBody.auto_renew = preset.autoRenew;
489
+ try {
490
+ detail = await client.createRental(createBody);
491
+ } catch (err) {
492
+ console.log(paint.red(`下单失败:${err.message}`));
493
+ console.log(paint.dim(`幂等键:${idempotencyKey}(同参数重试可复用,避免重复下单)`));
494
+ if (err.errorCode === 'insufficient_stock') {
495
+ console.log(paint.dim('库存被抢光了。重新运行向导换一个可用区/型号。'));
496
+ }
497
+ return;
498
+ }
499
+
500
+ console.log(paint.green(`✔ 已受理:${detail.rental_no}(id=${detail.id})`));
501
+ console.log(paint.dim(`幂等键:${idempotencyKey}`));
502
+
503
+ // --no-wait:脚本里只要租约号,不等建机完成
504
+ if (noWait) {
505
+ console.log(paint.dim(`(--no-wait:未等待建机完成)继续查看:dotop-gpu show ${detail.id}`));
506
+ return;
507
+ }
508
+
509
+ // ⑧ 轮询建机进度
510
+ const final = await pollUntilReady(client, detail);
511
+ if (!final) return;
512
+
513
+ // ⑨ 打印登录方式
514
+ printSSH(final, picked.quote);
515
+ }
516
+
517
+ // ─── 计费 ────────────────────────────────────────────────
518
+
519
+ // 组装计费选项:按量 + 该规格已开通的各周期。
520
+ async function buildBillingChoices(client, picked) {
521
+ const onDemandQuote = await client.quoteRental({
522
+ zoneKey: picked.zone.zone_key,
523
+ planId: picked.plan.id,
524
+ billingMode: 'on-demand',
525
+ });
526
+ return [
527
+ {
528
+ mode: 'on-demand',
529
+ label: `按量计费 — ${money(onDemandQuote.gpu_cost_per_hour)}/小时,随用随停`,
530
+ },
531
+ ...(onDemandQuote.cycles || [])
532
+ .filter((c) => c.enabled)
533
+ .map((c) => ({
534
+ mode: c.billing_mode,
535
+ label: `${billingText(c.billing_mode)} — ${money(c.total)}/${cycleUnit(c.billing_mode)}(原价 ${money(c.original_total)},省 ${money(c.saved)})`,
536
+ })),
537
+ ];
538
+ }
539
+
540
+ // 应用计费选择;周期模式紧接着问购买期数。
541
+ //
542
+ // 期数以前是一行隐藏的文本提问,选完计费方式后不显眼地出现,用户感觉像
543
+ // 「莫名其妙又要按一次回车」。现在期数是一个独立的光标菜单(↑/↓ + Enter),
544
+ // 标题和当前值都写在屏幕上,选几次、第几次按回车都是明确的。
545
+ //
546
+ // 返回 false 表示用户在期数菜单按 b 返回,需要重新选计费方式。
547
+ async function applyBilling(picked, choice, { auto = false, askPeriods = true } = {}) {
548
+ const sameMode = picked.billing && picked.billing.mode === choice.mode;
549
+ picked.billing = choice;
550
+ picked.quote = null;
551
+
552
+ if (choice.mode === 'on-demand') {
553
+ picked.commitmentCount = 0;
554
+ return true;
555
+ }
556
+
557
+ // 同周期重复选择:保留原期数,不再追问
558
+ if (sameMode && picked.commitmentCount > 0) return true;
559
+ if (auto || !askPeriods) {
560
+ picked.commitmentCount = 1;
561
+ return true;
562
+ }
563
+
564
+ const count = await selectCount(`购买期数 — ${billingText(choice.mode)}`, {
565
+ current: 1,
566
+ maxPeriod: 12,
567
+ allowBack: true,
568
+ });
569
+ if (count === BACK) return false;
570
+ if (!count) return false;
571
+ picked.commitmentCount = count;
572
+ return true;
573
+ }
574
+
575
+ // 确认页改期数:同样的光标菜单,回车前的当前值就是现值。
576
+ async function askPeriodCount(picked) {
577
+ const current = picked.commitmentCount > 0 ? picked.commitmentCount : 1;
578
+ const count = await selectCount(`购买期数 — ${billingText(picked.billing.mode)}`, {
579
+ current,
580
+ maxPeriod: 12,
581
+ allowBack: true,
582
+ });
583
+ if (count === BACK || !count) return current;
584
+ return count;
585
+ }
586
+
587
+ // ─── 展示 ────────────────────────────────────────────────
588
+
589
+ function printSummary(picked, quote) {
590
+ console.log('');
591
+ console.log(paint.bold('──── 下单确认 ────'));
592
+ console.log(`可用区 ${picked.zone.name} (${picked.zone.zone_key})`);
593
+ const plan = picked.plan;
594
+ const specBits = [`${plan.gpu_card_count} 卡`];
595
+ if (plan.vram_gb > 0) specBits.push(`${plan.vram_gb}G 显存`);
596
+ if (plan.cpu > 0) specBits.push(`${plan.cpu}C${plan.memory_gb > 0 ? `${plan.memory_gb}G` : ''}`);
597
+ if (plan.disk_gib > 0) specBits.push(`${plan.disk_gib}G 盘`);
598
+ console.log(`规格 ${plan.name} · ${specBits.join(' / ')}`);
599
+ console.log(`镜像 ${picked.image.name}`);
600
+ console.log(`公钥 ${picked.sshKey.name} ${paint.dim(picked.sshKey.fingerprint || '')}`);
601
+ console.log(
602
+ `计费 ${billingText(quote.billing_mode)}${picked.commitmentCount > 1 ? ` × ${picked.commitmentCount} 期` : ''}`,
603
+ );
604
+ console.log(`单价 ${money(quote.gpu_cost_per_hour)}/小时`);
605
+ if (quote.total !== null && quote.total !== undefined) {
606
+ console.log(
607
+ `总额 ${paint.bold(money(quote.total))}${quote.saved ? paint.dim(`(原价 ${money(quote.original_total)},省 ${money(quote.saved)})`) : ''}`,
608
+ );
609
+ console.log(`时长 ${duration((quote.hours || 0) * 3600)}`);
610
+ } else {
611
+ console.log('总额 按实际使用时长结算');
612
+ }
613
+ for (const line of balanceLines(quote)) console.log(line);
614
+ console.log('');
615
+ }
616
+
617
+ // balanceLines 确认页的余额三行:余额 / 下单后 / 不足提示。
618
+ //
619
+ // 全部读服务端下发的 quote.balance,客户端不做任何价格计算 ——
620
+ // 门槛公式(周期一次付清 vs 按量覆盖 N 分钟)只有服务端知道,
621
+ // 自己算会出现「页面说够、点下去说不够」。
622
+ //
623
+ // 两种计费方式语义不同,文案必须分开:
624
+ // - 周期:下单时一次性付清 N 期,下单后余额 = 余额 − 总额,这个值有实际意义。
625
+ // - 按量:下单不预扣(只在建机成功后按分钟滚动扣费),
626
+ // 所以「下单后余额」就是当前余额,只提示起租门槛要覆盖几分钟。
627
+ function balanceLines(quote) {
628
+ const b = quote && quote.balance;
629
+ if (!b) return ['余额 ' + paint.dim('未知(钱包信息读取失败)')];
630
+
631
+ const cycle = quote.total !== null && quote.total !== undefined;
632
+ const lines = [];
633
+
634
+ if (cycle) {
635
+ lines.push(`余额 ${money(b.available)}`);
636
+ if (b.enough) {
637
+ lines.push(`下单后 ${money(b.after)}`);
638
+ } else {
639
+ // 差额自己算(available/required 都是服务端给的绝对值,减法不涉及价格口径)
640
+ const gap = Math.round((b.required - b.available) * 100) / 100;
641
+ lines.push(`余额不足 ${paint.red(`还差 ${money(gap)}`)}`);
642
+ lines.push(paint.red(` 当前 ${money(b.available)},本次需付 ${money(b.required)};`));
643
+ lines.push(paint.red(' 请先充值后再下单,否则提交会被服务端拒绝。'));
644
+ }
645
+ return lines;
646
+ }
647
+
648
+ const gate = b.gate_minutes > 0 ? `起租需覆盖 ${b.gate_minutes} 分钟,约 ${money(b.required)}` : '';
649
+ lines.push(`余额 ${money(b.available)}${gate ? paint.dim(`(${gate})`) : ''}`);
650
+ if (b.enough) {
651
+ lines.push(`下单后 ${money(b.available)}${paint.dim('(按量不预扣,建机成功后按实际分钟扣费)')}`);
652
+ } else {
653
+ const gap = Math.round((b.required - b.available) * 100) / 100;
654
+ lines.push(`余额不足 ${paint.red(`还差 ${money(gap)}`)}`);
655
+ lines.push(paint.red(` 按量起租需覆盖 ${b.gate_minutes} 分钟(约 ${money(b.required)});`));
656
+ lines.push(paint.red(' 请先充值后再下单,否则提交会被服务端拒绝。'));
657
+ }
658
+ return lines;
659
+ }
660
+
661
+ function cycleUnit(mode) {
662
+ return { daily: '天', weekly: '周', monthly: '月', yearly: '年' }[mode] || '期';
663
+ }
664
+
665
+ function imageLabel(i) {
666
+ return `${i.name}${i.os_distro ? paint.dim(` (${i.os_distro})`) : ''}${i.summary ? paint.dim(` — ${i.summary}`) : ''}`;
667
+ }
668
+
669
+ // 规格标签:只有非零字段才展示。有些规格的 vram/cpu/memory/disk 是 0(未填),
670
+ // 硬拼会让用户看到「0C0G」这种无意义内容。
671
+ function planLabel(p) {
672
+ const parts = [`${p.gpu_card_count}卡`];
673
+ if (p.vram_gb > 0) parts.push(`${p.vram_gb}G显存`);
674
+ const cpu = [];
675
+ if (p.cpu > 0) cpu.push(`${p.cpu}C`);
676
+ if (p.memory_gb > 0) cpu.push(`${p.memory_gb}G`);
677
+ if (cpu.length) parts.push(cpu.join(''));
678
+ if (p.disk_gib > 0) parts.push(`${p.disk_gib}G盘`);
679
+ const hourly = money(p.gpu_price_per_card_minute * 60 * p.gpu_card_count);
680
+ return `${p.name} · ${parts.join(' / ')} · ${hourly}/小时`;
681
+ }
682
+
683
+ // 各区剩余卡数。
684
+ //
685
+ // open 契约里 /zones 只有 zone_key/name/state 三个字段,没有库存;库存来自
686
+ // /zones/{az}/gpu-types 的 available 之和。这里一次并发查完所有区,
687
+ // 让「选可用区」这一步就能看到「剩余 N 卡可用」。
688
+ //
689
+ // 单区查询失败不影响整步:记成 unknown,界面上显示「库存未知」,
690
+ // 而不是让整个向导因为某个区接口抖动而挂掉。
691
+ async function loadZoneStock(client, zones) {
692
+ const entries = await Promise.all(
693
+ zones.map(async (z) => {
694
+ try {
695
+ const groups = (await client.listGpuTypes(z.zone_key)).items || [];
696
+ const cards = groups.reduce((sum, g) => sum + (Number(g.available) || 0), 0);
697
+ const sellable = groups.some((g) => (g.plans || []).length > 0);
698
+ return [z.zone_key, { cards, sellable }];
699
+ } catch {
700
+ return [z.zone_key, null];
701
+ }
702
+ }),
703
+ );
704
+ return new Map(entries);
705
+ }
706
+
707
+ // 库存文案:有货绿色、售罄红色、查不到就灰色未知。
708
+ function zoneStockText(info) {
709
+ if (!info) return paint.dim('库存未知');
710
+ if (!info.sellable) return paint.red('暂无可售规格');
711
+ if (info.cards > 0) return paint.green(`剩余 ${info.cards} 卡可用`);
712
+ return paint.red('已售罄');
713
+ }
714
+
715
+ // 默认光标落在第一个有货的区;全售罄就回到第一个。
716
+ function firstInStockIndex(zones, stock) {
717
+ const i = zones.findIndex((z) => {
718
+ const info = stock.get(z.zone_key);
719
+ return info && info.sellable && info.cards > 0;
720
+ });
721
+ return i >= 0 ? i : 0;
722
+ }
723
+
724
+ // ─── 公钥 ────────────────────────────────────────────────
725
+
726
+ // 选公钥。界面上把「来源」和「管理」分清楚:
727
+ // 1) 平台上已经上传过的公钥(GET /ssh-keys)
728
+ // 2) 本机 ~/.ssh/*.pub(只读公钥文件,绝不读私钥)
729
+ // 3) 手动粘贴一行公钥
730
+ // 4) 删除已有公钥(删完回到这个列表,不用退出向导)
731
+ // 返回 Key 对象 / BACK / null(取消)。
732
+ async function pickSSHKey(client, { auto, current, allowBack }) {
733
+ let items = (await client.listSSHKeys()).items || [];
734
+ if (items.length > 0 && auto) return items[0];
735
+
736
+ // 被删掉的公钥不能继续当「当前选中」,否则确认页会拿一把已不存在的数据下单
737
+ let cur = current;
738
+ // 刚上传 / 刚复用的那把:刷新列表后把光标停在它上面并标注
739
+ let freshId = null;
740
+ let reused = false;
741
+
742
+ // 内部小循环:上传/粘贴无论成功还是失败、删完公钥、中途取消,都回到这个列表。
743
+ // 上传成功后也不再直接往下走 —— 用户要先在列表里看到这把公钥确实出现了,
744
+ // 再按回车确认用它下单;上传失败也停在这里,方便立刻重试或换个来源。
745
+ while (true) {
746
+ const options = items.map((k) => ({ kind: 'existing', key: k }));
747
+ options.push({ kind: 'upload', label: '+ 上传本机公钥' });
748
+ options.push({ kind: 'paste', label: '+ 手动粘贴公钥' });
749
+ if (items.length > 0) options.push({ kind: 'delete', label: '− 删除已有公钥' });
750
+
751
+ const freshIndex = freshId ? items.findIndex((k) => k.id === freshId) : -1;
752
+ const choice = await selectOne(
753
+ items.length > 0 ? '选择 SSH 公钥' : '还没有 SSH 公钥,先选一个来源',
754
+ options,
755
+ {
756
+ render: (o) => {
757
+ // 动作项(上传/粘贴)用黄色,**刻意避开菜单选中色(青色粗体)**:
758
+ // 两者同色时,未选中的动作项看起来像是被选中了,光标位置反而找不着。
759
+ if (o.kind === 'upload') return paint.yellow(`${o.label} ${paint.dim(`(来自本机 ${sshDir() || '~/.ssh'})`)}`);
760
+ if (o.kind === 'paste') return paint.yellow(o.label);
761
+ if (o.kind === 'delete') return paint.dim(o.label);
762
+ const k = o.key;
763
+ const isCur = cur && cur.id === k.id ? paint.green(' ← 当前') : '';
764
+ const isFresh =
765
+ freshId && freshId === k.id
766
+ ? paint.green(reused ? ' ← 已在平台(复用)' : ' ← 刚上传')
767
+ : '';
768
+ return `${k.name}${k.description ? paint.dim(` — ${k.description}`) : ''} ${paint.dim(k.fingerprint)}${isCur}${isFresh}`;
769
+ },
770
+ defaultIndex: freshIndex >= 0 ? freshIndex : 0,
771
+ allowBack,
772
+ },
773
+ );
774
+ if (choice === BACK) return BACK;
775
+ if (!choice) return null;
776
+ if (choice.kind === 'existing') return choice.key;
777
+
778
+ if (choice.kind === 'delete') {
779
+ const deletedId = await deleteSSHKey(client, items);
780
+ if (deletedId && cur && cur.id === deletedId) cur = null;
781
+ if (deletedId) {
782
+ freshId = null;
783
+ reused = false;
784
+ }
785
+ items = (await client.listSSHKeys()).items || [];
786
+ continue;
787
+ }
788
+
789
+ const created =
790
+ choice.kind === 'paste'
791
+ ? await pasteSSHKey(client)
792
+ : await uploadLocalSSHKey(client);
793
+ // 成功 / 复用 / 失败 / 取消 —— 一律刷新列表回到选择界面
794
+ items = (await client.listSSHKeys()).items || [];
795
+ freshId = created ? created.id : null;
796
+ reused = !!(created && created.__reused);
797
+ if (freshId) {
798
+ console.log(
799
+ paint.dim(
800
+ reused
801
+ ? '已回到公钥列表,光标停在这把已有公钥上,按回车继续。'
802
+ : '已回到公钥列表,光标停在这把公钥上,按回车继续。',
803
+ ),
804
+ );
805
+ } else {
806
+ console.log(paint.dim('已回到公钥列表,可以重试或换一个来源。'));
807
+ }
808
+ }
809
+ }
810
+
811
+ // 在向导里删除公钥:选一把 → 二次确认 → 删除。返回被删的 id(没删则 null)。
812
+ async function deleteSSHKey(client, items) {
813
+ const target = await selectOne(
814
+ '删除哪把公钥?',
815
+ [...items, { __back: true, name: '← 返回公钥列表' }],
816
+ {
817
+ render: (k) =>
818
+ k.__back
819
+ ? paint.dim(k.name)
820
+ : `${k.name}${k.description ? paint.dim(` — ${k.description}`) : ''} ${paint.dim(k.fingerprint)}`,
821
+ allowBack: false,
822
+ },
823
+ );
824
+ if (!target || target.__back) return null;
825
+
826
+ const ok = await confirm(
827
+ `确认删除公钥「${target.name}」?\n ${paint.dim(target.fingerprint)}\n 已用它创建的租约不受影响,但之后不能再选它下单。`,
828
+ { defaultValue: false, actionYes: '删除', actionNo: '取消(不删)' },
829
+ );
830
+ if (!ok) {
831
+ console.log(paint.dim(`已取消,公钥「${target.name}」没有删除。`));
832
+ return null;
833
+ }
834
+
835
+ try {
836
+ await client.deleteSSHKey(target.id);
837
+ console.log(paint.green(`✔ 已删除公钥 ${target.name}(id=${target.id})`));
838
+ return target.id;
839
+ } catch (err) {
840
+ console.log(paint.red(`删除失败:${err.message}`));
841
+ return null;
842
+ }
843
+ }
844
+
845
+ // 从本机 ~/.ssh 选一个 *.pub 上传
846
+ async function uploadLocalSSHKey(client) {
847
+ const dir = sshDir();
848
+ const local = scanLocalKeys();
849
+ if (local.length === 0) {
850
+ console.log(paint.yellow(`没找到本机公钥(${dir || '~/.ssh'}/*.pub)。`));
851
+ console.log(paint.dim('可以先用 ssh-keygen -t ed25519 生成,或改用「手动粘贴公钥」。'));
852
+ return null; // 回到公钥列表重选
853
+ }
854
+
855
+ const picked = await selectOne(
856
+ `选择要上传的本机公钥 ${paint.dim(`(${dir})`)}`,
857
+ [...local, { __back: true, name: '← 返回公钥列表' }],
858
+ {
859
+ render: (k) => (k.__back ? paint.dim(k.name) : `${k.name} ${paint.dim(fingerprintOf(k.publicKey))}`),
860
+ allowBack: false,
861
+ },
862
+ );
863
+ if (!picked || picked.__back) return null;
864
+
865
+ const description = `dotop-gpu 上传(${picked.file})`;
866
+ const ok = await confirmUploadKey({
867
+ name: picked.name,
868
+ fingerprint: fingerprintOf(picked.publicKey),
869
+ description,
870
+ });
871
+ if (!ok) {
872
+ console.log(paint.dim('已取消上传,公钥没有添加。'));
873
+ return null;
874
+ }
875
+
876
+ try {
877
+ const created = await client.createSSHKey({
878
+ name: picked.name,
879
+ description,
880
+ publicKey: picked.publicKey,
881
+ });
882
+ console.log(paint.green(`✔ 已上传公钥 ${created.name}(id=${created.id})`));
883
+ return created;
884
+ } catch (err) {
885
+ return await recoverFromDuplicate(client, err, picked.publicKey, picked.name);
886
+ }
887
+ }
888
+
889
+ // 手动粘贴:从剪贴板/别处拿一行公钥
890
+ async function pasteSSHKey(client) {
891
+ // 所有格式说明一次性放在最前面,别拆到提问前后各一句。
892
+ // 以前「名称最长 64 字符」那句挂在指纹后面,用户粘完公钥才看到,
893
+ // 想改名字时已经过了提问点,等于白说。
894
+ console.log(paint.dim('格式:<类型> <base64> [备注],一整行;备注可省略'));
895
+ console.log(paint.dim(' 例:ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... laptop-ed25519'));
896
+ console.log(paint.dim('「名称」最长 64 字符,建议用能认出机器的名字,如 laptop-ed25519'));
897
+ console.log(paint.dim('粘贴后自动算指纹、查重;直接回车返回公钥列表'));
898
+ // 粘贴时容易带进尾部空格/换行,也可能一次粘进多行(有的编辑器会带换行)。
899
+ // 这里只取第一行有效内容,避免后续字段错位。
900
+ const pasted = await ask('公钥内容', { defaultValue: '' });
901
+ const raw = String(pasted || '')
902
+ .split(/\r?\n/)
903
+ .map((l) => l.trim())
904
+ .find((l) => l && !l.startsWith('#')) || '';
905
+ if (!raw) return null;
906
+
907
+ const fp = fingerprintOf(raw);
908
+ if (!fp) {
909
+ console.log(paint.red('这行看起来不是有效公钥(解析不出指纹)。'));
910
+ console.log(paint.dim(`收到的内容:${raw.slice(0, 60)}${raw.length > 60 ? '…' : ''}`));
911
+ return null;
912
+ }
913
+ console.log(paint.dim(`指纹 ${fp}`));
914
+
915
+ // 名字的默认值要在提问前就算好并作为 defaultValue 显示出来。
916
+ // 之前这里问完再判空,用户按提示「回车用默认」时会被当成取消,
917
+ // 于是公钥静默没上传 —— 这是那次修复的核心。
918
+ //
919
+ // 默认取公钥第三段(备注/注释);没有备注就取 <类型>-<指纹前 8 位>,
920
+ // 不用 cli-key-时间戳 —— 那种名字事后完全分辨不出是哪台机器的钥匙。
921
+ const comment = raw.split(/\s+/).slice(2).join(' ').trim();
922
+ const keyType = raw.split(/\s+/)[0] || 'ssh';
923
+ const fpTail = fp.replace('SHA256:', '').slice(0, 8);
924
+ const autoName = trimToRunes(comment || `${keyType}-${fpTail}`, 64);
925
+
926
+ const nameRaw = await ask(`公钥名称`, { defaultValue: autoName });
927
+ if (inputExhausted()) return null;
928
+ const name = trimToRunes(nameRaw || autoName, 64);
929
+
930
+ // 粘贴这条路以前直接上传、不问确认,而「上传本机公钥」那条路是问的 ——
931
+ // 两条路行为不一致,用户粘完公钥没看到「按 y 确认」就以为卡住了。
932
+ const description = 'dotop-gpu 手动粘贴';
933
+ const ok = await confirmUploadKey({ name, fingerprint: fp, description });
934
+ if (!ok) {
935
+ console.log(paint.dim('已取消上传,公钥没有添加。'));
936
+ return null;
937
+ }
938
+
939
+ try {
940
+ const created = await client.createSSHKey({ name, description, publicKey: raw });
941
+ console.log(paint.green(`✔ 已上传公钥 ${created.name}(id=${created.id})`));
942
+ return created;
943
+ } catch (err) {
944
+ return await recoverFromDuplicate(client, err, raw, name);
945
+ }
946
+ }
947
+
948
+ // 上传前的二次确认:把「要传什么」摆出来再问,别让用户凭记忆决定。
949
+ // 两条上传路径(本机选取 / 手动粘贴)共用,保证文案和行为一致。
950
+ async function confirmUploadKey({ name, fingerprint, description }) {
951
+ const lines = [`将上传这把公钥:`, ` 名称 ${name}`, ` 指纹 ${paint.dim(fingerprint)}`];
952
+ if (description) lines.push(` 描述 ${paint.dim(description)}`);
953
+ return await confirm(lines.join('\n'), {
954
+ defaultValue: true,
955
+ actionYes: '上传',
956
+ actionNo: '不传',
957
+ });
958
+ }
959
+
960
+ // 按「字符数」截断(不是字节数):服务端 name 上限 64 个字符
961
+ function trimToRunes(s, max) {
962
+ const arr = Array.from(String(s || ''));
963
+ return arr.length > max ? arr.slice(0, max).join('') : arr.join('');
964
+ }
965
+
966
+ // 409 = 这把公钥已经在平台上了,按指纹找出来直接复用。
967
+ // 复用和「刚创建」在列表里要区分标注,否则用户会以为自己刚新建了一把。
968
+ async function recoverFromDuplicate(client, err, publicKey, fallbackName) {
969
+ console.log(paint.red(`上传失败:${err.message}`));
970
+ if (err.httpStatus === 409) {
971
+ const again = (await client.listSSHKeys()).items || [];
972
+ const fp = fingerprintOf(publicKey);
973
+ const hit = again.find((k) => k.fingerprint === fp);
974
+ if (hit) {
975
+ console.log(paint.dim(`平台上有同指纹的公钥「${hit.name}」(id=${hit.id}),直接复用,不用重新上传。`));
976
+ return { ...hit, __reused: true };
977
+ }
978
+ }
979
+ console.log(paint.dim(`(公钥名 ${fallbackName})`));
980
+ return null;
981
+ }
982
+
983
+ // ─── 轮询 ────────────────────────────────────────────────
984
+
985
+ async function pollUntilReady(client, detail) {
986
+ const startedAt = Date.now();
987
+ let current = detail;
988
+ let lastLine = '';
989
+
990
+ while (true) {
991
+ const elapsed = Math.floor((Date.now() - startedAt) / 1000);
992
+ const decision = pollDecision(current);
993
+
994
+ const line = progressLine(current, elapsed);
995
+ if (process.stdout.isTTY) {
996
+ process.stdout.write(`\r${line}${' '.repeat(Math.max(0, lastLine.length - line.length))}`);
997
+ } else if (decision !== 'continue') {
998
+ console.log(line);
999
+ }
1000
+ lastLine = line;
1001
+
1002
+ if (decision === 'done') {
1003
+ if (process.stdout.isTTY) process.stdout.write('\n');
1004
+ return current;
1005
+ }
1006
+ if (decision === 'fail') {
1007
+ if (process.stdout.isTTY) process.stdout.write('\n');
1008
+ if (current.state === 'running' && current.boot_state === 'timeout') {
1009
+ console.log(paint.yellow('系统启动超时:实例已创建但没能在时限内就绪,请到控制台查看。'));
1010
+ } else {
1011
+ console.log(paint.red(`创建失败(state=${current.state})`));
1012
+ }
1013
+ if (current.last_error) console.log(paint.dim(`原因:${current.last_error}`));
1014
+ console.log(paint.dim(`租约 id=${current.id} 仍在,可用于排查或销毁。`));
1015
+ return null;
1016
+ }
1017
+
1018
+ if (Date.now() - startedAt > POLL_TIMEOUT_MS) {
1019
+ if (process.stdout.isTTY) process.stdout.write('\n');
1020
+ console.log(paint.yellow(`等待超过 ${duration(POLL_TIMEOUT_MS / 1000)},先停下。`));
1021
+ console.log(paint.dim(`用 dotop-gpu show ${current.id} 继续查看。`));
1022
+ return null;
1023
+ }
1024
+
1025
+ await sleep(POLL_INTERVAL_MS);
1026
+ try {
1027
+ current = await client.getRental(detail.id);
1028
+ } catch (err) {
1029
+ // 单次查询失败不当作失败结论,继续重试
1030
+ if (elapsed > 30) console.log(paint.dim(`查询失败,重试中:${err.message}`));
1031
+ }
1032
+ }
1033
+ }
1034
+
1035
+ function printSSH(detail, quote) {
1036
+ console.log('');
1037
+ console.log(paint.green('✔ 实例已就绪'));
1038
+ console.log('');
1039
+ console.log(`租约 ${detail.rental_no}(id=${detail.id})`);
1040
+ console.log(`可用区 ${detail.zone_name} (${detail.zone_key})`);
1041
+ console.log(`规格 ${detail.gpu_model} × ${detail.gpu_count} 卡${detail.vram_gb ? ` / ${detail.vram_gb}G 显存` : ''}`);
1042
+ console.log(`镜像 ${detail.image_name}`);
1043
+ console.log(`公网 IP ${detail.floating_ip || paint.dim('(无)')}`);
1044
+ console.log(`计费 ${billingText(detail.billing_mode)} · ${money(detail.hourly_cost)}/小时`);
1045
+ if (detail.expires_at) console.log(`到期 ${ts(detail.expires_at)}`);
1046
+ console.log('');
1047
+ console.log(paint.bold('登录命令(直接复制执行):'));
1048
+ console.log(paint.cyan(` ${detail.ssh.command}`));
1049
+ console.log('');
1050
+ console.log(paint.dim(`停止计费:dotop-gpu stop ${detail.id}`));
1051
+ console.log(paint.dim(`销毁实例:dotop-gpu destroy ${detail.id}`));
1052
+ }
1053
+
1054
+ function sleep(ms) {
1055
+ return new Promise((r) => setTimeout(r, ms));
1056
+ }