cloudgpu-mcp 0.1.1 → 0.2.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/README.md CHANGED
@@ -92,6 +92,28 @@ extensions:
92
92
 
93
93
  To check the install, ask your agent: "List the GPUs available, then estimate the cost for a 24 GB GPU for one hour. Do not create anything." You should see `list_gpus` and `estimate_cost` calls and a quote, and nothing is rented.
94
94
 
95
+ ## Agent Skill
96
+
97
+ The same guidance is available as two [Agent Skills](https://agentskills.io):
98
+
99
+ - [`skills/cloudgpu/SKILL.md`](skills/cloudgpu/SKILL.md): renting and using a GPU. Claude Code loads it on demand when you ask for a GPU job. It expects the `cloudgpu` MCP tools to be installed (see above).
100
+ - [`skills/cloudgpu-model-api/SKILL.md`](skills/cloudgpu-model-api/SKILL.md): calling the OpenAI-compatible model API at `https://cloudgpu.app/v1` without renting a GPU. It works with the MCP tools or with just a `CLOUDGPU_API_KEY`.
101
+
102
+ - **Claude plugin:** both skills are included automatically when you install the CloudGPU Claude plugin from this repo's marketplace:
103
+
104
+ ```
105
+ /plugin marketplace add mrhy7176/cloudgpu-mcp
106
+ /plugin install cloudgpu@cloudgpu
107
+ ```
108
+
109
+ - **Claude Code, personal install:** copy `skills/cloudgpu/` and `skills/cloudgpu-model-api/` to `~/.claude/skills/`.
110
+ - **Claude Code, project install:** copy `skills/cloudgpu/` and `skills/cloudgpu-model-api/` to `.claude/skills/` in your project.
111
+ - **Cursor, Codex, Cline, Amp and other agents that read Agent Skills:** install both skills with the [skills CLI](https://skills.sh):
112
+
113
+ ```
114
+ npx skills add mrhy7176/cloudgpu-mcp
115
+ ```
116
+
95
117
  ## Tools
96
118
 
97
119
  | Tool | What it does |
@@ -142,6 +164,32 @@ The server wraps CloudGPU's public REST API, which any agent or script can call
142
164
  curl https://cloudgpu.app/v1/gpu/offers -H "Authorization: Bearer $CLOUDGPU_API_KEY"
143
165
  ```
144
166
 
167
+ ## Command-line tool
168
+
169
+ The package also installs a `cloudgpu` command for using the same API from a terminal (Node.js 18.3 or newer, no extra dependencies):
170
+
171
+ ```bash
172
+ npm install -g cloudgpu-mcp # or run it once with: npx -p cloudgpu-mcp cloudgpu --help
173
+ cloudgpu login # saves your key to ~/.config/cloudgpu/config.json (mode 0600)
174
+ cloudgpu offers # GPU models with live price and availability
175
+ cloudgpu up --gpu "RTX 4090" --template comfyui --max-minutes 120 --max-spend 5 --wait
176
+ cloudgpu ssh <id> # opens your system ssh to the instance
177
+ cloudgpu down <id> # destroys it and stops billing (asks first; --yes to skip)
178
+ ```
179
+
180
+ | Command | What it does |
181
+ |---|---|
182
+ | `login` | Save an API key (input hidden, or piped on stdin); checked against the API first |
183
+ | `offers [--template ID]` | GPU models, VRAM, live price per GPU-hour, availability |
184
+ | `templates` | Ready-made images and the GPU each recommends |
185
+ | `up --gpu MODEL [--template ID] [--count N] [--max-minutes N] [--max-spend USD] [--idle-minutes N] [--wait]` | Rent an instance; `--wait` polls until it is running or failed, then prints the SSH command and URL |
186
+ | `ls` / `status <id>` | Instances with status, minutes run and cost so far |
187
+ | `ssh <id> [-- ARGS]` | Run `ssh` with the instance's host, port and user; `--show-password` prints the password if there is one |
188
+ | `down <id> [--yes]` | Destroy the instance; its disk is erased, so download results first |
189
+ | `balance` | Balance and how many instances the account may run |
190
+
191
+ `CLOUDGPU_API_KEY` takes precedence over the saved key, and `CLOUDGPU_BASE_URL` overrides the API host. Read commands accept `--json`; SSH passwords are left out of JSON unless you pass `--show-password`. Every command has `--help`. Errors print the API's message and exit non-zero (2 for usage errors).
192
+
145
193
  ## Links
146
194
 
147
195
  - MCP docs: https://cloudgpu.app/docs/mcp
@@ -157,6 +205,7 @@ CloudGPU here means cloudgpu.app. Prepaid balance, billed per minute; when the b
157
205
  npm install
158
206
  npm test
159
207
  node src/index.js # stdio server; set CLOUDGPU_API_KEY first
208
+ node src/cli.js --help
160
209
  ```
161
210
 
162
211
  ## License
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "cloudgpu-mcp",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "mcpName": "io.github.mrhy7176/cloudgpu-mcp",
5
- "description": "MCP server for cloudgpu.app: let Claude Code, Cursor, Cline, opencode, goose and other MCP clients rent a GPU per minute, run a job, fetch the results and shut it down, with spending limits the platform enforces.",
5
+ "description": "MCP server and command-line tool for cloudgpu.app: let Claude Code, Cursor, Cline, opencode, goose and other MCP clients (or you, from a terminal) rent a GPU per minute, run a job, fetch the results and shut it down, with spending limits the platform enforces.",
6
6
  "type": "module",
7
7
  "bin": {
8
- "cloudgpu-mcp": "src/index.js"
8
+ "cloudgpu-mcp": "src/index.js",
9
+ "cloudgpu": "src/cli.js"
9
10
  },
10
11
  "main": "src/index.js",
11
12
  "files": [
@@ -15,7 +16,7 @@
15
16
  "LICENSE"
16
17
  ],
17
18
  "engines": {
18
- "node": ">=18"
19
+ "node": ">=18.3"
19
20
  },
20
21
  "scripts": {
21
22
  "test": "node --test test/*.test.js"
@@ -34,7 +35,8 @@
34
35
  "opencode",
35
36
  "goose",
36
37
  "fine-tuning",
37
- "cloudgpu"
38
+ "cloudgpu",
39
+ "cli"
38
40
  ],
39
41
  "homepage": "https://cloudgpu.app/docs/mcp",
40
42
  "repository": {
package/src/api.js CHANGED
@@ -10,10 +10,12 @@ export class ApiError extends Error {
10
10
  }
11
11
 
12
12
  export class CloudGpuApi {
13
- constructor({ apiKey, baseUrl = "https://cloudgpu.app", fetchImpl = globalThis.fetch } = {}) {
13
+ constructor({ apiKey, baseUrl = "https://cloudgpu.app", fetchImpl = globalThis.fetch, userAgent = "cloudgpu-mcp/0.1" } = {}) {
14
14
  this.apiKey = apiKey;
15
15
  this.baseUrl = baseUrl.replace(/\/+$/, "");
16
16
  this.fetch = fetchImpl;
17
+ // 命令行工具和 MCP 服务器共用这个客户端,用 User-Agent 区分来源
18
+ this.userAgent = userAgent;
17
19
  }
18
20
 
19
21
  async request(method, path, body) {
@@ -34,7 +36,7 @@ export class CloudGpuApi {
34
36
  headers: {
35
37
  Authorization: `Bearer ${this.apiKey}`,
36
38
  "Content-Type": "application/json",
37
- "User-Agent": "cloudgpu-mcp/0.1",
39
+ "User-Agent": this.userAgent,
38
40
  },
39
41
  body: body === undefined ? undefined : JSON.stringify(body),
40
42
  });
@@ -0,0 +1,781 @@
1
+ // cloudgpu 命令行工具的全部逻辑。src/cli.js 只是入口,这里导出 run() 方便测试在进程内调用。
2
+ // 只用 Node 18+ 自带模块,不加运行时依赖;HTTP 请求复用 api.js 里的 CloudGpuApi。
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import readline from "node:readline";
7
+ import { parseArgs } from "node:util";
8
+ import { spawn as nodeSpawn } from "node:child_process";
9
+ import { CloudGpuApi, ApiError, sleep as defaultSleep } from "./api.js";
10
+ import { redact } from "./guards.js";
11
+
12
+ export const VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
13
+
14
+ const KEYS_URL = "https://cloudgpu.app/api";
15
+ const BILLING_URL = "https://cloudgpu.app/billing";
16
+
17
+ // 参数或用法错误:退出码 2
18
+ export class UsageError extends Error {
19
+ constructor(message, command) {
20
+ super(message);
21
+ this.command = command;
22
+ }
23
+ }
24
+
25
+ // 运行时错误(实例失败、用户取消等):退出码默认 1
26
+ export class CliError extends Error {
27
+ constructor(message, exitCode = 1) {
28
+ super(message);
29
+ this.exitCode = exitCode;
30
+ }
31
+ }
32
+
33
+ // ── 命令定义 ─────────────────────────────────────────────────────────────
34
+ // options 直接交给 util.parseArgs;args 是位置参数的名字(目前最多一个)。
35
+
36
+ const JSON_OPT = { json: { type: "boolean" } };
37
+ const SHOW_PW = { "show-password": { type: "boolean" } };
38
+
39
+ const COMMANDS = {
40
+ login: {
41
+ summary: "Save an API key to ~/.config/cloudgpu/config.json",
42
+ usage: "cloudgpu login [--no-verify]",
43
+ details: [
44
+ "Prompts for the key (input hidden), or reads it from stdin: echo \"$KEY\" | cloudgpu login",
45
+ "The key is checked against the API before it is saved, unless --no-verify is given.",
46
+ "The file is written with 0600 permissions. CLOUDGPU_API_KEY, if set, takes precedence over the saved key.",
47
+ `Create a key at ${KEYS_URL}`,
48
+ ],
49
+ options: { "no-verify": { type: "boolean" } },
50
+ args: [],
51
+ },
52
+ offers: {
53
+ summary: "GPU models for rent, with live price and availability",
54
+ usage: "cloudgpu offers [--template <id>] [--json]",
55
+ details: ["--template <id> only GPUs with enough VRAM for that template (see `cloudgpu templates`)"],
56
+ options: { ...JSON_OPT, template: { type: "string" } },
57
+ args: [],
58
+ },
59
+ templates: {
60
+ summary: "Ready-made instance images (JupyterLab, ComfyUI, Ollama, ...)",
61
+ usage: "cloudgpu templates [--json]",
62
+ details: [],
63
+ options: { ...JSON_OPT },
64
+ args: [],
65
+ },
66
+ up: {
67
+ summary: "Rent a GPU instance",
68
+ usage:
69
+ 'cloudgpu up --gpu "RTX 4090" [--template <id>] [--count N] [--max-minutes N] [--max-spend USD] [--idle-minutes N] [--wait] [--json]',
70
+ details: [
71
+ "--gpu <model> GPU model as `cloudgpu offers` lists it (required)",
72
+ "--template <id> template id from `cloudgpu templates`; omit for a plain GPU with Python and CUDA",
73
+ "--count N number of GPUs, 1-8 (default 1)",
74
+ "--max-minutes N destroy the instance N minutes after it starts (enforced by the server)",
75
+ "--max-spend USD destroy the instance before it costs more than this (enforced by the server)",
76
+ "--idle-minutes N destroy after the GPU is idle this long; 0 = off, otherwise 10-1440",
77
+ "--wait poll until the instance is running or failed, then print SSH and URLs",
78
+ "--show-password with --wait, also print the SSH password if the API returns one",
79
+ "Costs money: billing is per minute from your prepaid balance until the instance is destroyed.",
80
+ ],
81
+ options: {
82
+ ...JSON_OPT,
83
+ ...SHOW_PW,
84
+ gpu: { type: "string" },
85
+ template: { type: "string" },
86
+ count: { type: "string" },
87
+ "max-minutes": { type: "string" },
88
+ "max-spend": { type: "string" },
89
+ "idle-minutes": { type: "string" },
90
+ wait: { type: "boolean" },
91
+ },
92
+ args: [],
93
+ },
94
+ ls: {
95
+ summary: "List instances (running, starting, and recently stopped)",
96
+ usage: "cloudgpu ls [--json]",
97
+ details: [],
98
+ options: { ...JSON_OPT },
99
+ args: [],
100
+ },
101
+ status: {
102
+ summary: "Show one instance: status, cost so far, SSH, URLs, limits",
103
+ usage: "cloudgpu status <id> [--json] [--show-password]",
104
+ details: [],
105
+ options: { ...JSON_OPT, ...SHOW_PW },
106
+ args: ["id"],
107
+ },
108
+ down: {
109
+ summary: "Destroy an instance (stops billing, erases its disk)",
110
+ usage: "cloudgpu down <id> [--yes] [--json]",
111
+ details: ["Asks for confirmation unless --yes (-y) is given. Download your results first."],
112
+ options: { ...JSON_OPT, yes: { type: "boolean", short: "y" } },
113
+ args: ["id"],
114
+ },
115
+ ssh: {
116
+ summary: "Open an SSH session to a running instance",
117
+ usage: "cloudgpu ssh <id> [--show-password] [-- <extra ssh args or remote command>]",
118
+ details: [
119
+ "Runs your system `ssh` with the host, port and user from the API.",
120
+ "The password is printed only with --show-password.",
121
+ ],
122
+ options: { ...SHOW_PW },
123
+ args: ["id"],
124
+ passthrough: true,
125
+ },
126
+ balance: {
127
+ summary: "Account balance and instance quota",
128
+ usage: "cloudgpu balance [--json]",
129
+ details: [],
130
+ options: { ...JSON_OPT },
131
+ args: [],
132
+ },
133
+ };
134
+
135
+ export function helpText(command) {
136
+ if (command && COMMANDS[command]) {
137
+ const c = COMMANDS[command];
138
+ return [`${c.summary}.`, "", `Usage: ${c.usage}`, ...(c.details.length ? ["", ...c.details.map((d) => " " + d)] : []), ""].join("\n");
139
+ }
140
+ const width = Math.max(...Object.keys(COMMANDS).map((k) => k.length)) + 2;
141
+ return [
142
+ `cloudgpu ${VERSION}: rent GPUs on cloudgpu.app from the command line.`,
143
+ "",
144
+ "Usage: cloudgpu <command> [options]",
145
+ "",
146
+ "Commands:",
147
+ ...Object.entries(COMMANDS).map(([k, c]) => " " + k.padEnd(width) + c.summary),
148
+ "",
149
+ "Options:",
150
+ " --json machine-readable output (offers, templates, ls, status, balance, up, down)",
151
+ " -h, --help help for a command: cloudgpu <command> --help",
152
+ " --version print the version",
153
+ "",
154
+ "Auth: CLOUDGPU_API_KEY, or the key saved by `cloudgpu login`. CLOUDGPU_BASE_URL overrides the API host.",
155
+ `Keys: ${KEYS_URL} Pricing: https://cloudgpu.app/pricing`,
156
+ "",
157
+ ].join("\n");
158
+ }
159
+
160
+ // ── 参数解析 ─────────────────────────────────────────────────────────────
161
+
162
+ /**
163
+ * 把 argv(不含 node 和脚本路径)解析成 { command, values, positionals, passthrough }。
164
+ * 特殊结果:command 为 "help" / "version" 时由 run() 直接打印。出错抛 UsageError。
165
+ */
166
+ export function parseCli(argv) {
167
+ // `--` 之后的内容原样交给 ssh,不参与解析
168
+ const dd = argv.indexOf("--");
169
+ const head = dd === -1 ? argv : argv.slice(0, dd);
170
+ const passthrough = dd === -1 ? [] : argv.slice(dd + 1);
171
+
172
+ const cmdIdx = head.findIndex((a) => !a.startsWith("-"));
173
+ const command = cmdIdx === -1 ? null : head[cmdIdx];
174
+ const rest = cmdIdx === -1 ? head : [...head.slice(0, cmdIdx), ...head.slice(cmdIdx + 1)];
175
+
176
+ if (!command || command === "help") {
177
+ if (head.includes("--version") || head.includes("-v")) return { command: "version" };
178
+ const topic = command === "help" ? rest.find((a) => !a.startsWith("-")) : undefined;
179
+ return { command: "help", topic };
180
+ }
181
+ const spec = COMMANDS[command];
182
+ if (!spec) throw new UsageError(`unknown command "${command}". Run \`cloudgpu --help\` to see the commands.`);
183
+ if (rest.includes("--help") || rest.includes("-h")) return { command: "help", topic: command };
184
+ if (passthrough.length && !spec.passthrough) throw new UsageError(`\`cloudgpu ${command}\` does not take arguments after --`, command);
185
+
186
+ let parsed;
187
+ try {
188
+ parsed = parseArgs({ args: rest, options: spec.options, allowPositionals: true, strict: true });
189
+ } catch (err) {
190
+ // util.parseArgs 的报错已经说明了是哪个选项
191
+ throw new UsageError(err.message.replace(/\s*To specify a positional argument.*$/s, ""), command);
192
+ }
193
+ const { values, positionals } = parsed;
194
+ if (positionals.length < spec.args.length) {
195
+ throw new UsageError(`missing <${spec.args[positionals.length]}>. Usage: ${spec.usage}`, command);
196
+ }
197
+ if (positionals.length > spec.args.length) {
198
+ throw new UsageError(`unexpected argument "${positionals[spec.args.length]}". Usage: ${spec.usage}`, command);
199
+ }
200
+ return { command, values, positionals, passthrough };
201
+ }
202
+
203
+ function intOpt(values, name, min, max) {
204
+ const v = values[name];
205
+ if (v === undefined) return undefined;
206
+ if (!/^\d+$/.test(v) || Number(v) < min || Number(v) > max) {
207
+ throw new UsageError(`--${name} must be a whole number from ${min} to ${max} (got "${v}")`, "up");
208
+ }
209
+ return Number(v);
210
+ }
211
+
212
+ /** 把 up 的选项变成 POST /v1/gpu/instances 的请求体(gpu_model 稍后用 offers 校正大小写)。 */
213
+ export function buildCreateBody(values) {
214
+ if (!values.gpu || !values.gpu.trim()) throw new UsageError('--gpu is required, e.g. --gpu "RTX 4090" (see `cloudgpu offers`)', "up");
215
+ const body = { gpu_model: values.gpu.trim() };
216
+ if (values.template) body.template = values.template;
217
+ body.gpu_count = intOpt(values, "count", 1, 8) ?? 1;
218
+ const maxMinutes = intOpt(values, "max-minutes", 1, 10080);
219
+ if (maxMinutes !== undefined) body.max_minutes = maxMinutes;
220
+ if (values["max-spend"] !== undefined) {
221
+ const s = values["max-spend"];
222
+ const n = Number(s);
223
+ if (!/^\d+(\.\d+)?$/.test(s) || !(n > 0)) throw new UsageError(`--max-spend must be a positive amount in USD (got "${s}")`, "up");
224
+ body.max_spend_usd = n;
225
+ }
226
+ const idle = intOpt(values, "idle-minutes", 0, 1440);
227
+ if (idle !== undefined) {
228
+ if (idle > 0 && idle < 10) throw new UsageError("--idle-minutes must be 0 (off) or from 10 to 1440", "up");
229
+ body.idle_minutes = idle;
230
+ }
231
+ return body;
232
+ }
233
+
234
+ // ── 配置文件 ─────────────────────────────────────────────────────────────
235
+
236
+ export function configPath(env) {
237
+ const base = env.XDG_CONFIG_HOME || path.join(env.HOME || env.USERPROFILE || os.homedir(), ".config");
238
+ return path.join(base, "cloudgpu", "config.json");
239
+ }
240
+
241
+ export function readConfig(env) {
242
+ const file = configPath(env);
243
+ let text;
244
+ try {
245
+ text = fs.readFileSync(file, "utf8");
246
+ } catch (err) {
247
+ if (err.code === "ENOENT") return {};
248
+ throw new CliError(`Could not read ${file}: ${err.message}`);
249
+ }
250
+ try {
251
+ const cfg = JSON.parse(text);
252
+ return cfg && typeof cfg === "object" ? cfg : {};
253
+ } catch {
254
+ throw new CliError(`${file} is not valid JSON. Fix it or run \`cloudgpu login\` again after deleting it.`);
255
+ }
256
+ }
257
+
258
+ /** 写配置:目录 0700,文件 0600;先写临时文件再改名,避免写一半。 */
259
+ export function writeConfig(env, cfg) {
260
+ const file = configPath(env);
261
+ const dir = path.dirname(file);
262
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
263
+ const tmp = `${file}.${process.pid}.tmp`;
264
+ fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
265
+ fs.chmodSync(tmp, 0o600); // umask 可能把 mode 改掉,这里再设一次
266
+ fs.renameSync(tmp, file);
267
+ return file;
268
+ }
269
+
270
+ /** 环境变量优先,其次是 login 保存的 key。 */
271
+ export function resolveApiKey(env) {
272
+ const fromEnv = (env.CLOUDGPU_API_KEY || "").trim();
273
+ if (fromEnv) return { key: fromEnv, source: "env" };
274
+ const key = (readConfig(env).api_key || "").trim();
275
+ return key ? { key, source: "config" } : { key: "", source: null };
276
+ }
277
+
278
+ // ── 输出格式 ─────────────────────────────────────────────────────────────
279
+
280
+ export function table(headers, rows) {
281
+ const cells = [headers, ...rows].map((r) => r.map((c) => (c == null || c === "" ? "-" : String(c))));
282
+ const widths = headers.map((_, i) => Math.max(...cells.map((r) => r[i].length)));
283
+ return cells.map((r) => r.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd()).join("\n") + "\n";
284
+ }
285
+
286
+ // 金额照 API 返回的数字显示,不做任何写死的价格
287
+ export function usd(n) {
288
+ if (n == null || n === "" || !Number.isFinite(Number(n))) return "-";
289
+ return "$" + Number(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 4 });
290
+ }
291
+
292
+ function gpuLabel(inst) {
293
+ return inst.gpu_model ? `${inst.gpu_model}${inst.gpu_count > 1 ? ` x${inst.gpu_count}` : ""}` : "-";
294
+ }
295
+
296
+ function sshCommand(ssh) {
297
+ if (!ssh || !ssh.host) return null;
298
+ return `ssh -p ${ssh.port || 22} ${ssh.user || "root"}@${ssh.host}`;
299
+ }
300
+
301
+ /** --json 输出里的实例:没有 --show-password 时去掉 SSH 密码。 */
302
+ function scrubInstance(inst, showPassword) {
303
+ if (!inst || !inst.ssh || showPassword || inst.ssh.password == null) return inst;
304
+ const { password, ...ssh } = inst.ssh;
305
+ return { ...inst, ssh: { ...ssh, password_hidden: true } };
306
+ }
307
+
308
+ function limitsText(l) {
309
+ if (!l) return null;
310
+ const parts = [];
311
+ if (l.max_minutes != null) parts.push(`max ${l.max_minutes} min`);
312
+ if (l.max_spend_usd != null) parts.push(`max ${usd(l.max_spend_usd)}`);
313
+ if (l.idle_minutes != null) parts.push(l.idle_minutes === 0 ? "idle shutdown off" : `idle ${l.idle_minutes} min`);
314
+ return parts.length ? parts.join(", ") : null;
315
+ }
316
+
317
+ export function instanceDetails(inst, { showPassword = false } = {}) {
318
+ const rows = [
319
+ ["ID", inst.id],
320
+ ["Status", inst.status],
321
+ ["GPU", gpuLabel(inst)],
322
+ ["Template", inst.template || "(none)"],
323
+ ["Price", inst.hourly_usd != null ? `${usd(inst.hourly_usd)}/hr` : null],
324
+ ["Running", inst.running_minutes != null ? `${inst.running_minutes} min` : null],
325
+ ["Cost", inst.cost_usd != null ? usd(inst.cost_usd) : null],
326
+ ["Limits", limitsText(inst.limits)],
327
+ ["Stopped by", inst.limits && inst.limits.stopped_by ? `${inst.limits.stopped_by} limit` : null],
328
+ ["Failure", inst.failure_reason || null],
329
+ ["SSH", inst.status === "running" ? sshCommand(inst.ssh) : null],
330
+ [
331
+ "Password",
332
+ inst.status === "running" && inst.ssh && inst.ssh.password
333
+ ? showPassword
334
+ ? inst.ssh.password
335
+ : "(hidden; add --show-password to print it)"
336
+ : null,
337
+ ],
338
+ ["URL", inst.api_url || null],
339
+ ].filter(([, v]) => v != null && v !== "");
340
+ const w = Math.max(...rows.map(([k]) => k.length)) + 2;
341
+ return rows.map(([k, v]) => k.padEnd(w) + v).join("\n") + "\n";
342
+ }
343
+
344
+ // ── 错误到文字的映射 ──────────────────────────────────────────────────────
345
+
346
+ /** 返回 { message, exitCode }。API 的报错直接显示 error.message。 */
347
+ export function describeError(err) {
348
+ if (err instanceof UsageError) {
349
+ const hint = err.command ? `Run \`cloudgpu ${err.command} --help\` for usage.` : "";
350
+ return { message: `cloudgpu: ${err.message}${hint && !err.message.includes("Usage:") ? "\n" + hint : ""}`, exitCode: 2 };
351
+ }
352
+ if (err instanceof ApiError) {
353
+ if (err.status === 0) return { message: `Error: ${err.message}`, exitCode: 1 };
354
+ let msg = `Error: ${err.message} (HTTP ${err.status}${err.code ? `, ${err.code}` : ""})`;
355
+ if (err.status === 401) msg += `\nCheck your API key: run \`cloudgpu login\` or set CLOUDGPU_API_KEY. Keys: ${KEYS_URL}`;
356
+ if (err.status === 402) msg += `\nTop up at ${BILLING_URL}`;
357
+ return { message: msg, exitCode: 1 };
358
+ }
359
+ if (err instanceof CliError) return { message: `Error: ${err.message}`, exitCode: err.exitCode };
360
+ return { message: `Error: ${err && err.message ? err.message : String(err)}`, exitCode: 1 };
361
+ }
362
+
363
+ // ── 交互输入 ─────────────────────────────────────────────────────────────
364
+
365
+ function readAll(stream) {
366
+ return new Promise((resolve, reject) => {
367
+ let data = "";
368
+ stream.setEncoding && stream.setEncoding("utf8");
369
+ stream.on("data", (c) => (data += c));
370
+ stream.on("end", () => resolve(data));
371
+ stream.on("error", reject);
372
+ });
373
+ }
374
+
375
+ /** 终端里读一行,不回显(输入 API key 用)。 */
376
+ function promptHidden(stdin, stderr, question) {
377
+ return new Promise((resolve, reject) => {
378
+ stderr.write(question);
379
+ let buf = "";
380
+ const done = (fn) => {
381
+ stdin.setRawMode(false);
382
+ stdin.pause();
383
+ stdin.removeListener("data", onData);
384
+ stderr.write("\n");
385
+ fn();
386
+ };
387
+ const onData = (chunk) => {
388
+ for (const ch of String(chunk)) {
389
+ if (ch === "\r" || ch === "\n") return done(() => resolve(buf));
390
+ if (ch === "\u0003") return done(() => reject(new CliError("Cancelled.", 130)));
391
+ if (ch === "\u007f" || ch === "\b") buf = buf.slice(0, -1);
392
+ else if (ch >= " ") buf += ch;
393
+ }
394
+ };
395
+ stdin.setEncoding("utf8");
396
+ stdin.setRawMode(true);
397
+ stdin.resume();
398
+ stdin.on("data", onData);
399
+ });
400
+ }
401
+
402
+ function promptLine(stdin, stderr, question) {
403
+ return new Promise((resolve) => {
404
+ const rl = readline.createInterface({ input: stdin, output: stderr, terminal: true });
405
+ rl.question(question, (answer) => {
406
+ rl.close();
407
+ resolve(answer);
408
+ });
409
+ });
410
+ }
411
+
412
+ // ── 主入口 ────────────────────────────────────────────────────────────────
413
+
414
+ /**
415
+ * 运行一条命令,返回退出码。ctx 里的东西都可以替换,方便测试:
416
+ * env, stdin, stdout, stderr, spawn, sleep, pollIntervalMs
417
+ */
418
+ export async function run(argv, ctx = {}) {
419
+ const env = ctx.env || process.env;
420
+ const stdout = ctx.stdout || process.stdout;
421
+ const stderr = ctx.stderr || process.stderr;
422
+ const out = (s) => stdout.write(s);
423
+ let apiKey = "";
424
+ try {
425
+ const p = parseCli(argv);
426
+ if (p.command === "version") {
427
+ out(VERSION + "\n");
428
+ return 0;
429
+ }
430
+ if (p.command === "help") {
431
+ out(helpText(p.topic));
432
+ return 0;
433
+ }
434
+ const c = {
435
+ ...p,
436
+ env,
437
+ out,
438
+ err: (s) => stderr.write(s),
439
+ stderr,
440
+ stdin: ctx.stdin || process.stdin,
441
+ spawn: ctx.spawn || nodeSpawn,
442
+ sleep: ctx.sleep || defaultSleep,
443
+ pollIntervalMs: ctx.pollIntervalMs ?? 5000,
444
+ baseUrl: env.CLOUDGPU_BASE_URL || "https://cloudgpu.app",
445
+ };
446
+ if (p.command === "login") return await cmdLogin(c);
447
+ // up 的参数先校验,写错了不用登录也能看到用法错误
448
+ if (p.command === "up") c.body = buildCreateBody(p.values);
449
+ apiKey = resolveApiKey(env).key;
450
+ if (!apiKey) {
451
+ throw new CliError(`Not logged in. Run \`cloudgpu login\` or set CLOUDGPU_API_KEY. Create a key at ${KEYS_URL}`);
452
+ }
453
+ c.api = new CloudGpuApi({ apiKey, baseUrl: c.baseUrl, userAgent: `cloudgpu-cli/${VERSION}` });
454
+ return await HANDLERS[p.command](c);
455
+ } catch (err) {
456
+ const { message, exitCode } = describeError(err);
457
+ stderr.write(redact(message, [apiKey]) + "\n");
458
+ return exitCode;
459
+ }
460
+ }
461
+
462
+ const HANDLERS = {
463
+ offers: cmdOffers,
464
+ templates: cmdTemplates,
465
+ up: cmdUp,
466
+ ls: cmdLs,
467
+ status: cmdStatus,
468
+ down: cmdDown,
469
+ ssh: cmdSsh,
470
+ balance: cmdBalance,
471
+ };
472
+
473
+ function printJson(c, obj) {
474
+ c.out(JSON.stringify(obj, null, 2) + "\n");
475
+ }
476
+
477
+ // ── 各命令 ────────────────────────────────────────────────────────────────
478
+
479
+ async function cmdLogin(c) {
480
+ const stdin = c.stdin;
481
+ let key;
482
+ if (stdin.isTTY && typeof stdin.setRawMode === "function") {
483
+ key = await promptHidden(stdin, { write: c.err }, `API key (create one at ${KEYS_URL}): `);
484
+ } else {
485
+ key = await readAll(stdin);
486
+ }
487
+ key = String(key || "").trim();
488
+ if (!key) throw new UsageError("no API key given. Type it at the prompt, or pipe it in: echo \"$KEY\" | cloudgpu login", "login");
489
+ if (/\s/.test(key)) throw new UsageError("the API key must be a single line without spaces", "login");
490
+
491
+ if (!c.values["no-verify"]) {
492
+ const api = new CloudGpuApi({ apiKey: key, baseUrl: c.baseUrl, userAgent: `cloudgpu-cli/${VERSION}` });
493
+ try {
494
+ await api.account();
495
+ } catch (err) {
496
+ // 校验失败就不保存,错误信息里不带 key
497
+ const { message } = describeError(err);
498
+ throw new CliError(`${redact(message.replace(/^Error: /, ""), [key])}\nThe key was not saved.`);
499
+ }
500
+ }
501
+ const cfg = readConfig(c.env);
502
+ cfg.api_key = key;
503
+ const file = writeConfig(c.env, cfg);
504
+ c.out(`Saved API key to ${file}\n`);
505
+ if ((c.env.CLOUDGPU_API_KEY || "").trim()) {
506
+ c.err("Note: CLOUDGPU_API_KEY is set in your environment and takes precedence over the saved key.\n");
507
+ }
508
+ return 0;
509
+ }
510
+
511
+ async function cmdOffers(c) {
512
+ let offers = await c.api.offers();
513
+ let tpl = null;
514
+ if (c.values.template) {
515
+ const templates = await c.api.templates();
516
+ tpl = templates.find((t) => t.id === c.values.template);
517
+ if (!tpl) {
518
+ throw new CliError(`No template "${c.values.template}". Templates: ${templates.map((t) => t.id).join(", ") || "(none)"}`);
519
+ }
520
+ // 按模板估计的显存过滤;min_gpu_count 取两者较大的一个
521
+ const need = Number(tpl.estimated_vram_gb) || 0;
522
+ const minCount = Math.max(1, Number(tpl.min_gpu_count) || 1);
523
+ offers = offers
524
+ .filter((o) => (Number(o.vram_gb) || 0) * Math.max(minCount, Number(o.min_gpu_count) || 1) >= need)
525
+ .map((o) => ({ ...o, min_gpu_count: Math.max(minCount, Number(o.min_gpu_count) || 1) }));
526
+ }
527
+ if (c.values.json) {
528
+ printJson(c, tpl ? { template: tpl.id, offers } : offers);
529
+ return 0;
530
+ }
531
+ if (!offers.length) {
532
+ c.out(tpl ? `No GPU on offer fits template ${tpl.id} right now.\n` : "No GPUs on offer right now.\n");
533
+ return 0;
534
+ }
535
+ c.out(
536
+ table(
537
+ ["GPU", "VRAM", "PER GPU-HOUR", "AVAILABLE", "MIN GPUS"],
538
+ offers.map((o) => [o.gpu_model, o.vram_gb != null ? `${o.vram_gb} GB` : null, usd(o.hourly_usd), o.available, o.min_gpu_count]),
539
+ ),
540
+ );
541
+ c.out("Prices and availability are live from the API and can change; billed per minute.\n");
542
+ if (tpl && tpl.recommended_gpu) c.out(`Template ${tpl.id} recommends: ${tpl.recommended_gpu}\n`);
543
+ return 0;
544
+ }
545
+
546
+ async function cmdTemplates(c) {
547
+ const templates = await c.api.templates();
548
+ if (c.values.json) {
549
+ printJson(c, templates);
550
+ return 0;
551
+ }
552
+ if (!templates.length) {
553
+ c.out("No templates.\n");
554
+ return 0;
555
+ }
556
+ c.out(
557
+ table(
558
+ ["ID", "NAME", "CATEGORY", "RECOMMENDED GPU", "MIN GPUS", "VRAM", "API URL"],
559
+ templates.map((t) => [
560
+ t.id,
561
+ t.name,
562
+ t.category,
563
+ t.recommended_gpu,
564
+ t.min_gpu_count,
565
+ t.estimated_vram_gb != null ? `${t.estimated_vram_gb} GB` : null,
566
+ t.has_api_endpoint ? "yes" : "no",
567
+ ]),
568
+ ),
569
+ );
570
+ return 0;
571
+ }
572
+
573
+ async function cmdUp(c) {
574
+ const body = c.body;
575
+ // 用 offers 把 GPU 名字校正成 API 的写法(大小写、空格不敏感)
576
+ const offers = await c.api.offers();
577
+ const norm = (s) => String(s).toLowerCase().replace(/\s+/g, "");
578
+ const offer = offers.find((o) => norm(o.gpu_model) === norm(body.gpu_model));
579
+ if (!offer) {
580
+ throw new CliError(`No GPU named "${body.gpu_model}". Available: ${offers.map((o) => o.gpu_model).join(", ") || "(none)"}`);
581
+ }
582
+ body.gpu_model = offer.gpu_model;
583
+ if (offer.available === "none") {
584
+ c.err(`Warning: the API reports no ${offer.gpu_model} available right now; the request may fail.\n`);
585
+ }
586
+
587
+ let inst = await c.api.create(body);
588
+ const showPassword = !!c.values["show-password"];
589
+ if (!c.values.wait) {
590
+ if (c.values.json) {
591
+ printJson(c, scrubInstance(inst, showPassword));
592
+ return 0;
593
+ }
594
+ c.out(`Created ${inst.id} (${gpuLabel(inst)}, status: ${inst.status}).\n`);
595
+ c.out(`Billing is per minute until it is destroyed. Check it with: cloudgpu status ${inst.id}\n`);
596
+ c.out(`Destroy it with: cloudgpu down ${inst.id}\n`);
597
+ return 0;
598
+ }
599
+
600
+ c.err(`Created ${inst.id}. Waiting for it to be running (Ctrl-C stops waiting; the instance keeps running).\n`);
601
+ inst = await waitForInstance(c, inst);
602
+ if (c.values.json) {
603
+ printJson(c, scrubInstance(inst, showPassword));
604
+ } else {
605
+ c.out(instanceDetails(inst, { showPassword }));
606
+ if (inst.status === "running") c.out(`\nConnect: cloudgpu ssh ${inst.id}\nDestroy: cloudgpu down ${inst.id}\n`);
607
+ }
608
+ if (inst.status === "running") return 0;
609
+ if (inst.status === "failed") {
610
+ c.err(`Instance ${inst.id} failed${inst.failure_reason ? `: ${inst.failure_reason}` : ""}. Failed instances are not charged.\n`);
611
+ } else {
612
+ c.err(`Instance ${inst.id} is ${inst.status}.\n`);
613
+ }
614
+ return 1;
615
+ }
616
+
617
+ /** 轮询直到 running(且有 SSH 信息)、failed 或 stopped。临时网络错误或 5xx 连续 5 次才放弃。 */
618
+ export async function waitForInstance(c, inst) {
619
+ const id = inst.id;
620
+ let last = inst.status;
621
+ let runningWithoutSsh = 0;
622
+ let failures = 0;
623
+ const onSigint = () => {
624
+ c.err(`\nStopped waiting. ${id} is still there and may be billing: cloudgpu status ${id} / cloudgpu down ${id}\n`);
625
+ process.exit(130);
626
+ };
627
+ process.once("SIGINT", onSigint);
628
+ try {
629
+ for (;;) {
630
+ if (inst.status === "running") {
631
+ if ((inst.ssh && inst.ssh.host) || ++runningWithoutSsh > 3) return inst;
632
+ } else if (inst.status !== "creating") {
633
+ return inst;
634
+ }
635
+ await c.sleep(c.pollIntervalMs);
636
+ try {
637
+ inst = await c.api.instance(id);
638
+ failures = 0;
639
+ } catch (err) {
640
+ const transient = err instanceof ApiError && (err.status === 0 || err.status >= 500);
641
+ if (!transient || ++failures >= 5) throw err;
642
+ continue;
643
+ }
644
+ if (inst.status !== last) {
645
+ c.err(`${id}: ${inst.status}\n`);
646
+ last = inst.status;
647
+ }
648
+ }
649
+ } finally {
650
+ process.removeListener("SIGINT", onSigint);
651
+ }
652
+ }
653
+
654
+ async function cmdLs(c) {
655
+ const list = await c.api.instances();
656
+ if (c.values.json) {
657
+ printJson(c, list.map((i) => scrubInstance(i, false)));
658
+ return 0;
659
+ }
660
+ if (!list.length) {
661
+ c.out("No instances.\n");
662
+ return 0;
663
+ }
664
+ c.out(
665
+ table(
666
+ ["ID", "STATUS", "GPU", "TEMPLATE", "PER HOUR", "RUNNING", "COST"],
667
+ list.map((i) => [
668
+ i.id,
669
+ i.status,
670
+ gpuLabel(i),
671
+ i.template,
672
+ usd(i.hourly_usd),
673
+ i.running_minutes != null ? `${i.running_minutes} min` : null,
674
+ usd(i.cost_usd),
675
+ ]),
676
+ ),
677
+ );
678
+ return 0;
679
+ }
680
+
681
+ async function cmdStatus(c) {
682
+ const inst = await c.api.instance(c.positionals[0]);
683
+ const showPassword = !!c.values["show-password"];
684
+ if (c.values.json) printJson(c, scrubInstance(inst, showPassword));
685
+ else c.out(instanceDetails(inst, { showPassword }));
686
+ return 0;
687
+ }
688
+
689
+ async function cmdDown(c) {
690
+ const id = c.positionals[0];
691
+ if (!c.values.yes) {
692
+ const stdin = c.stdin;
693
+ if (!stdin.isTTY) {
694
+ throw new UsageError(`refusing to destroy ${id} without confirmation in a non-interactive shell. Add --yes.`, "down");
695
+ }
696
+ const inst = await c.api.instance(id);
697
+ const what = `${id} (${gpuLabel(inst)}, ${inst.status}${inst.cost_usd != null ? `, cost so far ${usd(inst.cost_usd)}` : ""})`;
698
+ const answer = await promptLine(stdin, c.stderr, `Destroy ${what}? Its disk is erased. [y/N] `);
699
+ if (!/^y(es)?$/i.test(String(answer).trim())) {
700
+ c.err("Not destroyed.\n");
701
+ return 1;
702
+ }
703
+ }
704
+ let inst;
705
+ let note = "Destroyed. Billing has stopped.";
706
+ try {
707
+ inst = await c.api.destroy(id);
708
+ } catch (err) {
709
+ if (err instanceof ApiError && err.code === "cannot_destroy") {
710
+ // 已经停了(到了限额、余额用完、开机失败):不算错误
711
+ const cur = await c.api.instance(id).catch(() => null);
712
+ if (cur && cur.status !== "running" && cur.status !== "creating") {
713
+ inst = cur;
714
+ note = `Already ${cur.status}; nothing to do.`;
715
+ }
716
+ } else if (err instanceof ApiError && err.code === "instance_provisioning") {
717
+ throw new CliError(`${err.message}\nThe instance is still being created. Run \`cloudgpu down ${id}\` again once \`cloudgpu status ${id}\` shows running or failed.`);
718
+ }
719
+ if (!inst) throw err;
720
+ }
721
+ if (c.values.json) {
722
+ printJson(c, scrubInstance(inst, false));
723
+ return 0;
724
+ }
725
+ c.out(`${id}: ${note}${inst.cost_usd != null ? ` Final cost: ${usd(inst.cost_usd)}.` : ""}\n`);
726
+ return 0;
727
+ }
728
+
729
+ async function cmdSsh(c) {
730
+ const id = c.positionals[0];
731
+ const inst = await c.api.instance(id);
732
+ if (inst.status !== "running") {
733
+ throw new CliError(
734
+ `Instance ${id} is ${inst.status}` +
735
+ (inst.status === "creating"
736
+ ? `; wait for it with \`cloudgpu status ${id}\` until it is running.`
737
+ : inst.failure_reason
738
+ ? `: ${inst.failure_reason}`
739
+ : "."),
740
+ );
741
+ }
742
+ const ssh = inst.ssh;
743
+ if (!ssh || !ssh.host) throw new CliError(`Instance ${id} has no SSH login yet; try again shortly.`);
744
+ if (ssh.password) {
745
+ if (c.values["show-password"]) c.err(`Password: ${ssh.password}\n`);
746
+ else c.err("This instance uses a password login. Run with --show-password to print it.\n");
747
+ }
748
+ const args = ["-p", String(ssh.port || 22), `${ssh.user || "root"}@${ssh.host}`, ...c.passthrough];
749
+ return await new Promise((resolve, reject) => {
750
+ let child;
751
+ try {
752
+ child = c.spawn("ssh", args, { stdio: "inherit" });
753
+ } catch (err) {
754
+ reject(err);
755
+ return;
756
+ }
757
+ child.on("error", (err) => {
758
+ if (err.code === "ENOENT") reject(new CliError("`ssh` was not found. Install an OpenSSH client and try again."));
759
+ else reject(err);
760
+ });
761
+ child.on("exit", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
762
+ });
763
+ }
764
+
765
+ async function cmdBalance(c) {
766
+ const a = await c.api.account();
767
+ if (c.values.json) {
768
+ printJson(c, a);
769
+ return 0;
770
+ }
771
+ const rows = [["Balance", usd(a.balance_usd)]];
772
+ if (a.max_running_instances != null) {
773
+ rows.push(["Instances", `${a.running_instances ?? "?"} running of ${a.max_running_instances} allowed`]);
774
+ }
775
+ if (a.gpu_api_enabled === false) rows.push(["GPU API", "not enabled for this account"]);
776
+ if (a.billing) rows.push(["Billing", a.billing]);
777
+ rows.push(["Top up", a.top_up_url || BILLING_URL]);
778
+ const w = Math.max(...rows.map(([k]) => k.length)) + 2;
779
+ c.out(rows.map(([k, v]) => k.padEnd(w) + v).join("\n") + "\n");
780
+ return 0;
781
+ }
package/src/cli.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ // cloudgpu 命令行入口。逻辑都在 cli-core.js 里,这里只负责把退出码交给进程。
3
+ import { run } from "./cli-core.js";
4
+
5
+ process.exitCode = await run(process.argv.slice(2));
package/src/index.js CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  shq,
28
28
  } from "./guards.js";
29
29
 
30
- const VERSION = "0.1.1";
30
+ const VERSION = "0.2.0";
31
31
  const HERE = path.dirname(fileURLToPath(import.meta.url));
32
32
  const RULES = fs.readFileSync(path.join(HERE, "..", "rules", "cloudgpu.md"), "utf8");
33
33
 
@@ -297,7 +297,7 @@ if (!cfg.readOnly) {
297
297
  .default(60)
298
298
  .describe("Destroy after the GPU has been idle this long; 0 turns it off; otherwise at least 10"),
299
299
  },
300
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
300
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
301
301
  },
302
302
  wrap(async ({ quote_id, user_confirmed, max_spend_usd, max_hours, idle_minutes = 60 }) => {
303
303
  if (user_confirmed !== true) {