voltagegpu-cli 1.3.1__py3-none-any.whl → 2.0.0__py3-none-any.whl

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.
volt/__init__.py CHANGED
@@ -1,5 +1,5 @@
1
- """VoltageGPU command-line interface and Python SDK."""
2
-
3
- __version__ = "1.3.1"
4
-
5
- __all__ = ["__version__"]
1
+ """VoltageGPU command-line interface and Python SDK."""
2
+
3
+ __version__ = "2.0.0"
4
+
5
+ __all__ = ["__version__"]
volt/cli/cmd_account.py CHANGED
@@ -107,7 +107,10 @@ def balance_cmd(state: AppState, as_json: bool) -> None:
107
107
  if as_json:
108
108
  echo_json(bal.to_dict())
109
109
  return
110
- console.print(f"Balance [bold green]{money(bal.balance)}[/bold green] {esc(bal.currency)}")
110
+ if bal.balance is None:
111
+ info(f"Balance hidden: {esc(bal.balance_hidden or 'this key cannot read the account balance')}")
112
+ else:
113
+ console.print(f"Balance [bold green]{money(bal.balance)}[/bold green] {esc(bal.currency)}")
111
114
  if bal.active_pods is not None:
112
115
  info(f"Running {bal.active_pods} pod{'s' if bal.active_pods != 1 else ''}")
113
116
  hint(f"Top up: {esc(bal.top_up_url)}")
volt/cli/vgpu.py ADDED
@@ -0,0 +1,475 @@
1
+ """`vgpu`: the short command for scripts and AI agents (next to `voltagegpu`).
2
+
3
+ vgpu ls [--kind vm|cpu|standard|baremetal|sandbox] [--gpu H100] [--json]
4
+ vgpu up TIER --name N --ttl 1h -y [--json]
5
+ vgpu ps | exec N "cmd" [-d] | scp N remote local | rm N -y | attest N | whoami
6
+
7
+ The key is read from VOLT_API_KEY or VOLTAGEGPU_API_KEY (or the file written by
8
+ `voltagegpu login`) and never printed. Every machine gets a deadline (--ttl).
9
+ Exit codes are a contract, see EXIT_CODES; `exec` returns the remote command's
10
+ own code (255 when SSH itself fails).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import secrets
18
+ import shlex
19
+ import subprocess
20
+ import sys
21
+ import time
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+ from typing import Any, Dict, List, Mapping, Optional, Tuple
25
+
26
+ import click
27
+
28
+ from .. import __version__
29
+ from ..sdk import attest
30
+ from ..sdk.catalog import filter_offers, list_offers
31
+ from ..sdk.config import API_KEYS_PAGE
32
+ from ..sdk.errors import ApiError, ConfigError, scrub
33
+ from ..sdk.fleet import Instance, NameStore, check_name, deploy, list_instances, release, resolve
34
+ from ..sdk.remote import RemotePathError, detached_command, exec_argv, scp_argv
35
+ from ..sdk.ssh import find_ssh_binary
36
+ from ..sdk.ttl import KINDS, TtlError, parse_ttl, plan_ttl
37
+ from .main import configure_stream
38
+ from .state import AppState
39
+
40
+ EXIT_CODES = {
41
+ 0: "ok",
42
+ 1: "error",
43
+ 2: "usage",
44
+ 3: "api key missing, malformed or refused",
45
+ 4: "api key scope missing",
46
+ 5: "not found",
47
+ 6: "balance or api key budget exceeded (402)",
48
+ 7: "unavailable, sold out or over --max-price",
49
+ 8: "attestation failed",
50
+ 9: "attestation incomplete or local tool missing",
51
+ }
52
+
53
+ # Seams for the tests (no ssh binary, no waiting).
54
+ _sleep = time.sleep
55
+ _run = subprocess.run
56
+
57
+
58
+ def _tool(name: str) -> Optional[str]:
59
+ return find_ssh_binary(name=name)
60
+
61
+
62
+ class Fail(Exception):
63
+ def __init__(self, exit_code: int, message: str, code: Optional[str] = None, extra: Optional[Mapping[str, Any]] = None) -> None:
64
+ super().__init__(message)
65
+ self.exit_code = exit_code
66
+ self.message = message
67
+ self.code = code or {2: "USAGE", 5: "NOT_FOUND", 7: "UNAVAILABLE", 8: "ATTESTATION_FAILED", 9: "TOOL_MISSING"}.get(exit_code, "ERROR")
68
+ self.extra = dict(extra or {})
69
+
70
+
71
+ def api_fail(exc: ApiError) -> Fail:
72
+ payload = exc.payload or {}
73
+ raw_code = payload.get("error") if isinstance(payload.get("error"), str) else None
74
+ code = raw_code if raw_code and raw_code.isupper() and " " not in raw_code else str(payload.get("code") or f"HTTP_{exc.status_code or 0}")
75
+ status = exc.status_code
76
+ exit_code = {401: 3, 403: 4, 404: 5, 402: 6, 409: 7, 410: 7, 429: 7, 503: 7, 400: 2, 422: 2}.get(status, 1)
77
+ if status == 403 and code not in ("API_KEY_SCOPE_MISSING", "API_KEY_ACCOUNT_RESOURCE"):
78
+ exit_code = 7 # offer closed or account not eligible: not a scope problem
79
+ extra = {k: payload[k] for k in ("window", "budget_usd", "spent_usd", "requested_usd", "charged", "required_scope") if k in payload}
80
+ message = exc.message
81
+ if code == "API_KEY_BUDGET_EXCEEDED":
82
+ message = f"Stop: {exc.message} Nothing was charged. Ask the account owner to raise the budget; do not retry."
83
+ elif exit_code == 3:
84
+ message = f"The API refused the key (HTTP {status}). Check VOLT_API_KEY; keys are created at {API_KEYS_PAGE}."
85
+ return Fail(exit_code, message, code, {"http_status": status, **extra})
86
+
87
+
88
+ def ssh_key_needed(exc: ApiError, kind: str, given: bool, how: str) -> Optional[Fail]:
89
+ """The 400 of a standard GPU when the account has several SSH keys and none was named.
90
+
91
+ ``how`` names the way to give one (``--ssh-key-id`` for the CLI, ``ssh_key_ids`` for MCP).
92
+ The API answers it before any charge; its text is the only marker (no code in the body).
93
+ """
94
+ if kind != "standard" or given or exc.status_code != 400 or "more than one ssh key" not in exc.message.lower():
95
+ return None
96
+ return Fail(2, f"This account has several SSH keys: pass {how} with one key id (the account owner lists them with "
97
+ "`voltagegpu ssh-keys list`). Nothing was charged.", "SSH_KEY_ID_REQUIRED", {"http_status": 400})
98
+
99
+
100
+ def _emit(as_json: bool, data: Any, human: str) -> None:
101
+ click.echo(json.dumps(data, indent=2, default=str) if as_json else human)
102
+
103
+
104
+ def _state(ctx: click.Context) -> AppState:
105
+ return ctx.ensure_object(AppState)
106
+
107
+
108
+ def _confirm(yes: bool, question: str) -> None:
109
+ if yes:
110
+ return
111
+ if not sys.stdin.isatty():
112
+ raise Fail(2, f"{question} Not a terminal: pass -y to confirm.")
113
+ if not click.confirm(question, default=False):
114
+ raise click.Abort()
115
+
116
+
117
+ def _find(ctx: click.Context, ref: str) -> Instance:
118
+ return find_instance(_state(ctx).client(), ref)
119
+
120
+
121
+ def _reachable(inst: Instance):
122
+ target = inst.target
123
+ if target is None:
124
+ raise Fail(7, f"{inst.name or inst.id} is not reachable over SSH yet (status {inst.status}). Wait, then run `vgpu ps`.")
125
+ return target
126
+
127
+
128
+ def _need(tool: str) -> str:
129
+ path = _tool(tool)
130
+ if not path:
131
+ raise Fail(9, f"`{tool}` was not found on PATH (OpenSSH client). Install it, then retry.")
132
+ return path
133
+
134
+
135
+ def _identity(identity: Optional[str]) -> Optional[str]:
136
+ return identity or os.environ.get("VGPU_SSH_KEY") or None
137
+
138
+
139
+ def _money(value: Optional[float]) -> str:
140
+ return f"${value:.2f}/h" if isinstance(value, (int, float)) else "?"
141
+
142
+
143
+ @click.group(context_settings={"help_option_names": ["-h", "--help"], "max_content_width": 110})
144
+ @click.version_option(__version__, "-V", "--version", prog_name="vgpu")
145
+ @click.option("--base-url", envvar="VOLT_BASE_URL", hidden=True)
146
+ @click.pass_context
147
+ def vgpu(ctx: click.Context, base_url: Optional[str]) -> None:
148
+ """VoltageGPU for scripts and AI agents: Confidential VMs, Confidential CPU, standard GPUs, dedicated machines, sandboxes.
149
+
150
+ \b
151
+ Always give --ttl, release with `vgpu rm` when done, stop on exit code 6
152
+ (budget or balance), and call a machine confidential only after `vgpu attest`
153
+ returns VERIFIED. Exit codes: 0 ok, 1 error, 2 usage, 3 key, 4 scope,
154
+ 5 not found, 6 budget/balance (402), 7 unavailable, 8 attestation failed,
155
+ 9 attestation incomplete or tool missing.
156
+ """
157
+ state = ctx.ensure_object(AppState)
158
+ state.base_url = base_url
159
+ ctx.call_on_close(state.close)
160
+
161
+
162
+ @vgpu.command("ls")
163
+ @click.option("--kind", type=click.Choice(KINDS), help="Only this kind of machine.")
164
+ @click.option("--gpu", help="GPU model contains this text (H100, a5000...).")
165
+ @click.option("--max-price", type=float, help="Only offers at or under this price per hour (USD).")
166
+ @click.option("--all", "all_", is_flag=True, help="Include sold-out offers.")
167
+ @click.option("--json", "as_json", is_flag=True)
168
+ @click.pass_context
169
+ def ls_cmd(ctx: click.Context, kind: Optional[str], gpu: Optional[str], max_price: Optional[float], all_: bool, as_json: bool) -> None:
170
+ """Offers with the price charged, cheapest first."""
171
+ offers, errors = list_offers(_state(ctx).client(), (kind,) if kind else KINDS)
172
+ offers = filter_offers(offers, gpu=gpu, max_price=max_price, include_sold_out=all_)
173
+ for err in errors:
174
+ click.echo(f"warning: {scrub(err)}", err=True)
175
+ lines = [f"{'KIND':<10} {'TIER':<38} {'PRICE':>10} {'AVAIL':>5} NAME"]
176
+ lines += [f"{o.kind:<10} {o.tier:<38} {_money(o.price_per_hour):>10} {'' if o.available is None else o.available:>5} "
177
+ f"{o.name}{' [' + o.tee + ']' if o.tee else ''}" for o in offers]
178
+ _emit(as_json, [o.to_dict() for o in offers], "\n".join(lines) if offers else "No offer matches.")
179
+
180
+
181
+ def _wait_ready_client(client: Any, pod_id: str, timeout: int) -> Optional[Instance]:
182
+ for _ in range(max(1, timeout // 10)):
183
+ inst = resolve(list_instances(client), pod_id)
184
+ if inst is not None and inst.target is not None:
185
+ return inst
186
+ _sleep(10)
187
+ return None
188
+
189
+
190
+ @vgpu.command("up")
191
+ @click.argument("tier")
192
+ @click.option("--name", required=True, help="Your name for the machine (lowercase, digits, hyphens).")
193
+ @click.option("--ttl", required=True, help="Deadline: 45m, 1h, 6h, 2d. Mandatory: the machine stops by itself then.")
194
+ @click.option("--kind", type=click.Choice(KINDS), help="Look the tier up in this kind only.")
195
+ @click.option("--image", help="Sandbox image (ubuntu-24.04 by default).")
196
+ @click.option("--max-price", type=float, help="Refuse if the hourly price is above this (USD).")
197
+ @click.option("-y", "--yes", is_flag=True, help="Do not ask for confirmation (required when not in a terminal).")
198
+ @click.option("--wait/--no-wait", default=True, help="Wait until SSH answers (default).")
199
+ @click.option("--timeout", default=900, show_default=True, help="Seconds to wait for SSH.")
200
+ @click.option("--ssh-key-id", "ssh_key_ids", multiple=True,
201
+ help="SSH key id to bind: one for a standard GPU (needed when the account has several keys); "
202
+ "repeatable for dedicated machines and sandboxes.")
203
+ @click.option("--show-secret", is_flag=True, help="Print the sudo password of a Confidential VM (shown once, never stored).")
204
+ @click.option("--json", "as_json", is_flag=True)
205
+ @click.pass_context
206
+ def up_cmd(ctx: click.Context, tier: str, name: str, ttl: str, kind: Optional[str], image: Optional[str], max_price: Optional[float],
207
+ yes: bool, wait: bool, timeout: int, ssh_key_ids: tuple, show_secret: bool, as_json: bool) -> None:
208
+ """Start a machine. Charges the first hour now; the unused part comes back when released."""
209
+ check_name(name)
210
+ seconds = parse_ttl(ttl)
211
+ client = _state(ctx).client()
212
+ offers, _ = list_offers(client, (kind,) if kind else KINDS)
213
+ offer = next((o for o in offers if o.tier == tier), None)
214
+ if offer is None:
215
+ raise Fail(5, f"Unknown tier {tier!r}. Run `vgpu ls` for the current offers.")
216
+ if not offer.in_stock:
217
+ raise Fail(7, f"{tier} is sold out right now. Run `vgpu ls` for what is available.", "SOLD_OUT")
218
+ if max_price is not None and (offer.price_per_hour is None or offer.price_per_hour > max_price):
219
+ raise Fail(7, f"{tier} costs {_money(offer.price_per_hour)}, above --max-price {max_price}.", "OVER_MAX_PRICE")
220
+ plan = plan_ttl(offer.kind, seconds)
221
+ names = NameStore()
222
+ known = names.load().get(name)
223
+ if known and resolve(list_instances(client), known.get("id", "")):
224
+ raise Fail(2, f"A running machine is already named {name!r}. Pick another --name or `vgpu rm {name} -y`.")
225
+ _confirm(yes, f"Start {offer.kind} {tier} at {_money(offer.price_per_hour)} (first hour prepaid), stopping after {ttl}?")
226
+ try:
227
+ result = deploy(client, offer, name, plan, image=image, ssh_key_ids=list(ssh_key_ids) or None)
228
+ except ApiError as exc:
229
+ if exc.status_code == 0:
230
+ raise Fail(1, "The deploy request got no answer: a machine may have started and been charged. Run `vgpu ps` "
231
+ "before trying again; vgpu never retries a deploy by itself.", "NO_ANSWER") from None
232
+ needed = ssh_key_needed(exc, offer.kind, bool(ssh_key_ids), "--ssh-key-id")
233
+ if needed:
234
+ raise needed from None
235
+ raise
236
+ secret = result.pop("_sudo_password", None)
237
+ names.put(name, {"id": result["id"], "kind": result["kind"], "tier": tier, "created_at": datetime.now(timezone.utc).isoformat()})
238
+ ready = _wait_ready_client(client, result["id"], timeout) if wait else None
239
+ result.update({"ssh": ready.ssh if ready else None, "ssh_ready": bool(ready), "status": ready.status if ready else "STARTING"})
240
+ if show_secret and secret:
241
+ result["sudo_password"] = secret
242
+ human = (f"Started {name} ({result['id']}), {offer.kind} {tier}, {_money(result['hourly_price'])}, stops after {ttl}.\n"
243
+ + (f"SSH: {result['ssh']}" if ready else "Not reachable yet: `vgpu ps` shows when SSH is ready."))
244
+ _emit(as_json, result, human)
245
+
246
+
247
+ @vgpu.command("ps")
248
+ @click.option("--json", "as_json", is_flag=True)
249
+ @click.pass_context
250
+ def ps_cmd(ctx: click.Context, as_json: bool) -> None:
251
+ """Machines of this key (or of the account for a full key)."""
252
+ rows = list_instances(_state(ctx).client())
253
+ lines = [f"{'NAME':<20} {'ID':<38} {'KIND':<10} {'STATUS':<10} {'PRICE':>10} SSH"]
254
+ lines += [f"{(i.name or '-'):<20} {i.id:<38} {i.kind:<10} {i.status:<10} {_money(i.hourly_price):>10} "
255
+ f"{i.ssh if i.ssh_ready else '-'}" for i in rows]
256
+ _emit(as_json, [i.to_dict() for i in rows], "\n".join(lines) if rows else "No machine.")
257
+
258
+
259
+ @vgpu.command("exec", context_settings={"ignore_unknown_options": True})
260
+ @click.argument("ref")
261
+ @click.argument("command", nargs=-1, required=True, type=click.UNPROCESSED)
262
+ @click.option("-d", "--detach", is_flag=True, help="Start in the background; prints the PID and the log path.")
263
+ @click.option("-i", "--identity", help="Private key file (default: VGPU_SSH_KEY, then your ssh defaults).")
264
+ @click.option("--json", "as_json", is_flag=True)
265
+ @click.pass_context
266
+ def exec_cmd(ctx: click.Context, ref: str, command: tuple, detach: bool, identity: Optional[str], as_json: bool) -> None:
267
+ """Run a command on the machine over SSH, with your local key."""
268
+ text = command[0] if len(command) == 1 else shlex.join(command)
269
+ inst = _find(ctx, ref)
270
+ target = _reachable(inst)
271
+ ssh = _need("ssh")
272
+ if not detach:
273
+ proc = _run(exec_argv(target, inst.id, text, identity=_identity(identity), ssh_bin=ssh))
274
+ ctx.exit(proc.returncode)
275
+ job = secrets.token_hex(4)
276
+ remote, log = detached_command(text, job)
277
+ proc = _run(exec_argv(target, inst.id, remote, identity=_identity(identity), ssh_bin=ssh), capture_output=True, timeout=120)
278
+ out = (proc.stdout or b"").decode("utf-8", "replace").strip().splitlines()
279
+ if proc.returncode != 0 or not out or not out[-1].strip().isdigit():
280
+ raise Fail(1, f"Could not start the background command (ssh exit {proc.returncode}).")
281
+ data = {"name": inst.name, "id": inst.id, "job": job, "pid": int(out[-1]), "log": log}
282
+ _emit(as_json, data, f"Started PID {data['pid']}, log {log}. Read it with: vgpu exec {ref} 'tail -n 50 {log}'")
283
+
284
+
285
+ @vgpu.command("scp")
286
+ @click.argument("ref")
287
+ @click.argument("source")
288
+ @click.argument("destination")
289
+ @click.option("--up", "upload", is_flag=True, help="Copy local SOURCE to remote DESTINATION (default: download).")
290
+ @click.option("-r", "--recursive", is_flag=True)
291
+ @click.option("-i", "--identity", help="Private key file (default: VGPU_SSH_KEY).")
292
+ @click.pass_context
293
+ def scp_cmd(ctx: click.Context, ref: str, source: str, destination: str, upload: bool, recursive: bool, identity: Optional[str]) -> None:
294
+ """Copy files: `vgpu scp N /remote/path ./local` (or --up ./local /remote/path)."""
295
+ inst = _find(ctx, ref)
296
+ target = _reachable(inst)
297
+ argv = scp_argv(target, inst.id, source, destination, upload=upload, recursive=recursive,
298
+ identity=_identity(identity), scp_bin=_need("scp"))
299
+ ctx.exit(_run(argv).returncode)
300
+
301
+
302
+ @vgpu.command("rm")
303
+ @click.argument("ref")
304
+ @click.option("-y", "--yes", is_flag=True)
305
+ @click.option("--json", "as_json", is_flag=True)
306
+ @click.pass_context
307
+ def rm_cmd(ctx: click.Context, ref: str, yes: bool, as_json: bool) -> None:
308
+ """Release a machine (the unused prepaid time of a standard pod is refunded)."""
309
+ inst = _find(ctx, ref)
310
+ _confirm(yes, f"Release {inst.name or inst.id} ({inst.kind})? Its disk is deleted.")
311
+ data = release(_state(ctx).client(), inst)
312
+ NameStore().remove_id(inst.id)
313
+ _emit(as_json, data, f"Released {inst.name or inst.id}.")
314
+
315
+
316
+ def _attest_failure(kind: str, challenge: str, check: str, detail: str) -> Tuple[Dict[str, Any], int]:
317
+ return {"verified": False, "status": "NOT_VERIFIED", "tee": attest.TEE[kind], "challenge": challenge, "failed": [check], "detail": detail}, 8
318
+
319
+
320
+ def find_instance(client: Any, ref: str) -> Instance:
321
+ inst = resolve(list_instances(client), ref)
322
+ if inst is None:
323
+ raise Fail(5, f"No machine named or with id {ref!r} for this key. Run `vgpu ps`.")
324
+ return inst
325
+
326
+
327
+ def attest_machine(client: Any, ref: str, *, out: Optional[str], offline: bool, identity: Optional[str],
328
+ vmpl: int = 0) -> Tuple[Dict[str, Any], int]:
329
+ """The whole `vgpu attest` (CLI and local MCP server): result and exit code (0, 8 or 9).
330
+
331
+ ``vmpl``: Confidential CPU only, the VMPL level the SEV-SNP report is requested at (SNP_VMPL).
332
+ """
333
+ inst = find_instance(client, ref)
334
+ try:
335
+ script = attest.load_script(inst.kind)
336
+ except attest.AttestError as exc:
337
+ raise Fail(2 if inst.kind not in attest.SCRIPTS else 9, str(exc)) from None
338
+ target = _reachable(inst)
339
+ ssh, scp = _need("ssh"), _need("scp")
340
+ challenge = attest.new_challenge(inst.kind)
341
+ folder = Path(out or f"vgpu-attest-{inst.id}-{int(time.time())}")
342
+ folder.mkdir(parents=True, exist_ok=True)
343
+ key = _identity(identity)
344
+ level = vmpl if inst.kind == "cpu" else None
345
+ proc = _run(exec_argv(target, inst.id, attest.remote_command(challenge, level), identity=key, ssh_bin=ssh),
346
+ input=script, capture_output=True, timeout=1800)
347
+ log = folder / "in-the-vm.log"
348
+ log.write_bytes((proc.stdout or b"") + (proc.stderr or b""))
349
+ if proc.returncode != 0 and inst.kind == "cpu" and proc.returncode in attest.SNP_SCRIPT_EXIT:
350
+ name = attest.SNP_SCRIPT_EXIT[proc.returncode]
351
+ return _attest_failure(inst.kind, challenge, name,
352
+ f"the proof script refused the report ({name}, exit {proc.returncode}, SNP_VMPL={level}); see {log}")
353
+ if proc.returncode != 0:
354
+ return _attest_failure(inst.kind, challenge, "in_vm_script", f"the proof script exited with {proc.returncode}; see {log}")
355
+ archive = folder / Path(attest.ARCHIVES[inst.kind]).name
356
+ copy = _run(scp_argv(target, inst.id, attest.ARCHIVES[inst.kind], str(archive), identity=key, scp_bin=scp))
357
+ if copy.returncode != 0 or not archive.is_file():
358
+ return _attest_failure(inst.kind, challenge, "archive_copy", f"could not copy {attest.ARCHIVES[inst.kind]} (scp exit {copy.returncode})")
359
+ try:
360
+ extracted = attest.extract_archive(archive, folder / "proof")
361
+ if inst.kind == "vm":
362
+ result = attest.verify_gpu(extracted, challenge, offline=offline)
363
+ else:
364
+ result = attest.verify_cpu(extracted, challenge, snpguest=_tool("snpguest"), runner=_run, vmpl=vmpl)
365
+ except attest.ToolMissing as exc:
366
+ raise Fail(9, str(exc)) from None
367
+ except attest.AttestError as exc:
368
+ return _attest_failure(inst.kind, challenge, "archive", str(exc))
369
+ data = {"name": inst.name, "id": inst.id, **result.to_dict(), "folder": str(folder)}
370
+ return data, 0 if result.verified else 9 if result.status == "INCOMPLETE" else 8
371
+
372
+
373
+ @vgpu.command("attest")
374
+ @click.argument("ref")
375
+ @click.option("--offline", is_flag=True, help="GPU: use the collateral inside the bundle, no network call.")
376
+ @click.option("--out", type=click.Path(file_okay=False), help="Folder for the archive and the report.")
377
+ @click.option("-i", "--identity", help="Private key file (default: VGPU_SSH_KEY).")
378
+ @click.option("--vmpl", type=click.IntRange(0, 3), default=0, show_default=True,
379
+ help="Confidential CPU: VMPL level the SEV-SNP report is requested at (the script asks again at 1 if 0 is refused).")
380
+ @click.option("--json", "as_json", is_flag=True)
381
+ @click.pass_context
382
+ def attest_cmd(ctx: click.Context, ref: str, offline: bool, out: Optional[str], identity: Optional[str], vmpl: int,
383
+ as_json: bool) -> None:
384
+ """Prove the machine is a genuine TEE: challenge drawn here, proofs made in the VM, checked here."""
385
+ data, code = attest_machine(_state(ctx).client(), ref, out=out, offline=offline, identity=identity, vmpl=vmpl)
386
+ failed = data.get("failed") or []
387
+ human = f"{data['status']}: {data['tee']}, challenge {data['challenge'][:16]}..." + (f" failed: {', '.join(failed)}" if failed else "")
388
+ if data.get("detail"):
389
+ human += f" ({data['detail']})"
390
+ if (data.get("facts") or {}).get("vmpl_fallback"):
391
+ human += " (VMPL 0 refused: the guest is not at VMPL 0; report requested at VMPL 1)"
392
+ _emit(as_json, data, human)
393
+ raise click.exceptions.Exit(code)
394
+
395
+
396
+ @vgpu.command("whoami")
397
+ @click.option("--json", "as_json", is_flag=True)
398
+ @click.pass_context
399
+ def whoami_cmd(ctx: click.Context, as_json: bool) -> None:
400
+ """The key's scopes, visibility, budgets and spend, and the balance (the key itself is never shown)."""
401
+ state = _state(ctx)
402
+ client = state.client()
403
+ try:
404
+ raw = client.call("GET", "/volt/whoami")
405
+ except ApiError as exc:
406
+ if exc.status_code != 404:
407
+ raise
408
+ bal = client.get_balance()
409
+ raw = {"balance": bal.balance, "balance_hidden": bal.balance_hidden, "key": {}}
410
+ key = raw.get("key") if isinstance(raw, Mapping) and isinstance(raw.get("key"), Mapping) else {}
411
+ data: Dict[str, Any] = {"key": {**key, "masked": client.config.masked_key}, "balance": raw.get("balance"),
412
+ "currency": raw.get("currency", "USD"), "base_url": client.config.base_url}
413
+ if raw.get("balance") is None:
414
+ data["balance_hidden"] = raw.get("balance_hidden") or "This key cannot read the account balance."
415
+ lines: List[str] = [f"key {data['key']['masked']} {key.get('name') or ''}".rstrip(),
416
+ f"scopes {', '.join(key.get('scopes') or []) or 'full access'}",
417
+ f"machines {key.get('pod_visibility') or 'account'}",
418
+ f"budgets {json.dumps(key.get('budgets_usd') or {})} spent {json.dumps(key.get('spent_usd') or {})}",
419
+ f"balance {data['balance']} {data['currency']}" if data["balance"] is not None
420
+ else f"balance hidden ({data['balance_hidden']})"]
421
+ _emit(as_json, data, "\n".join(lines))
422
+
423
+
424
+ @vgpu.command("mcp")
425
+ def mcp_cmd() -> None:
426
+ """Local MCP server over stdio (ls, up, ps, exec, scp, rm, attest, inference, whoami) for AI agents."""
427
+ from ..mcp.server import run_stdio
428
+
429
+ run_stdio()
430
+
431
+
432
+ def _report(fail: Fail, as_json: bool) -> int:
433
+ message = scrub(fail.message)
434
+ if as_json:
435
+ click.echo(json.dumps({"error": {"code": fail.code, "message": message, "exit_code": fail.exit_code, **fail.extra}}, indent=2))
436
+ click.echo(f"Error: {message}", err=True)
437
+ return fail.exit_code
438
+
439
+
440
+ def main(argv: Optional[List[str]] = None) -> None:
441
+ configure_stream(sys.stdout)
442
+ configure_stream(sys.stderr)
443
+ args = list(sys.argv[1:] if argv is None else argv)
444
+ as_json = "--json" in args
445
+ debug = os.environ.get("VOLT_DEBUG") == "1"
446
+ try:
447
+ code = vgpu.main(args=args, prog_name="vgpu", standalone_mode=False)
448
+ sys.exit(code if isinstance(code, int) else 0)
449
+ except click.exceptions.Exit as exc:
450
+ sys.exit(exc.exit_code)
451
+ except click.exceptions.Abort:
452
+ click.echo("Aborted.", err=True)
453
+ sys.exit(1)
454
+ except click.ClickException as exc:
455
+ exc.show()
456
+ sys.exit(2 if isinstance(exc, click.UsageError) else exc.exit_code)
457
+ except Fail as fail:
458
+ sys.exit(_report(fail, as_json))
459
+ except ApiError as exc:
460
+ if debug:
461
+ raise
462
+ sys.exit(_report(api_fail(exc), as_json))
463
+ except ConfigError as exc:
464
+ sys.exit(_report(Fail(3, str(exc), "API_KEY_MISSING"), as_json))
465
+ except (TtlError, RemotePathError, ValueError) as exc:
466
+ sys.exit(_report(Fail(2, str(exc)), as_json))
467
+ except subprocess.TimeoutExpired:
468
+ sys.exit(_report(Fail(1, "The remote command timed out."), as_json))
469
+ except KeyboardInterrupt:
470
+ click.echo("Interrupted.", err=True)
471
+ sys.exit(130)
472
+
473
+
474
+ if __name__ == "__main__":
475
+ main()
volt/mcp/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Local MCP server of the `vgpu` command (stdio)."""