dmlops 0.2.10__py3-none-win_amd64.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.
dmlops/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """dmlops — track MLOps experiments from any machine.
2
+
3
+ Quick start::
4
+
5
+ import dmlops as mlops
6
+
7
+ mlops.login(server="http://mlops.example:18081", username="you@example.com")
8
+ run = mlops.create_experiment(job="train", name="my-train", out_dir="./runs/exp")
9
+ for epoch in range(10):
10
+ run.log_metric({"loss": {"total": ...}}, epoch=epoch, split="train")
11
+ run.finish() # also automatic at interpreter exit
12
+ """
13
+
14
+ from ._auth import login, require_transport, resolve_server, resolve_token, whoami
15
+ from ._run import Job, Task, Run, create_experiment
16
+ from ._transport import SDK_VERSION as __version__
17
+ from .exceptions import (
18
+ MlopsAuthError,
19
+ MlopsCancelled,
20
+ MlopsConflict,
21
+ MlopsError,
22
+ )
23
+
24
+ __all__ = [
25
+ "Job",
26
+ "Task",
27
+ "Run",
28
+ "__version__",
29
+ "create_experiment",
30
+ "login",
31
+ "MlopsAuthError",
32
+ "MlopsCancelled",
33
+ "MlopsConflict",
34
+ "MlopsError",
35
+ "whoami",
36
+ ]
dmlops/_auth.py ADDED
@@ -0,0 +1,668 @@
1
+ """Login / credential resolution for the MLOps platform.
2
+
3
+ Credential chain (first hit wins):
4
+
5
+ - server: ``login(server=...)`` > ``MLOPS_SERVER`` env >
6
+ ``~/.mlops/config.json`` (shared with the CLI) > legacy
7
+ ``~/.cache/mlops/config.json`` > shared credentials ``api_base``
8
+ - token: ``MLOPS_TOKEN`` env > shared CLI credentials
9
+ (``~/.mlops/credentials``) > legacy ``~/.cache/mlops/token``
10
+
11
+ ``login(username=..., password=...)`` forces a fresh login: it exchanges the
12
+ password for a short-lived session, mints a 30-day API key named
13
+ ``sdk:<hostname>`` with scope ``sdk``, and stores only the ``ak_...`` PAT in
14
+ the CLI-shared credentials file (password never touches disk). A bare
15
+ ``login()`` reuses local credentials; in a terminal with none, it opens an
16
+ interactive TUI (arrow-key select, ghost-prefilled server/email) offering
17
+ email + password or browser device authorization.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import getpass
23
+ import json
24
+ import os
25
+ import shutil
26
+ import socket
27
+ import stat
28
+ import subprocess
29
+ import sys
30
+ import time
31
+ import webbrowser
32
+ from pathlib import Path
33
+ from typing import Any
34
+
35
+ from ._transport import Transport
36
+ from . import _tui
37
+ from .exceptions import MlopsAuthError, MlopsError
38
+
39
+ _MLC_DIR = Path.home() / ".mlops"
40
+ _CREDENTIALS_FILE = _MLC_DIR / "credentials"
41
+ _MLC_CONFIG = _MLC_DIR / "config.json"
42
+
43
+ # Legacy pre-sharing locations, read-only fallback.
44
+ _CACHE_DIR = Path.home() / ".cache" / "mlops"
45
+ _TOKEN_FILE = _CACHE_DIR / "token"
46
+ _CONFIG_FILE = _CACHE_DIR / "config.json"
47
+
48
+ _DEFAULT_API_PORT = 13080
49
+ _DEVICE_POLL_MAX_SECONDS = 600
50
+ _DEFAULT_SERVER_HINT = "10.9.0.35"
51
+ _LOGIN_MAX_ATTEMPTS = 3
52
+
53
+
54
+ def _email_domain() -> str:
55
+ """Email suffix for the interactive prompt (CLI ``MLOPS_EMAIL_DOMAIN``)."""
56
+ value = (os.environ.get("MLOPS_EMAIL_DOMAIN") or "").strip()
57
+ if value:
58
+ return value if value.startswith("@") else f"@{value}"
59
+ return "@dreamsports.ai"
60
+
61
+
62
+ _server: str | None = None
63
+ _token: str | None = None
64
+ # Failure reason from the most recent login() call, if it returned False.
65
+ _login_failure: str | None = None
66
+
67
+ _NO_CREDENTIALS_MSG = (
68
+ "no credentials — pass username/password, set MLOPS_TOKEN, "
69
+ "run `mlops auth login`, or run mlops.login() in a terminal"
70
+ )
71
+
72
+
73
+ def _no_credentials_error() -> MlopsAuthError:
74
+ if (os.environ.get("MLOPS_TOKEN") or "").strip():
75
+ # The token exists but cannot be used without a server — naming the
76
+ # missing piece beats the generic "no credentials" (which claims the
77
+ # opposite).
78
+ return MlopsAuthError(
79
+ "MLOPS_TOKEN is set but no server is known — set MLOPS_SERVER "
80
+ "(or run `mlops auth login` once) so the token can be used"
81
+ )
82
+ return MlopsAuthError(_NO_CREDENTIALS_MSG)
83
+
84
+
85
+ def _write_private(path: Path, text: str) -> None:
86
+ directory = path.parent
87
+ created = not directory.exists()
88
+ directory.mkdir(parents=True, exist_ok=True)
89
+ path.write_text(text, encoding="utf-8")
90
+ try:
91
+ if created:
92
+ os.chmod(directory, stat.S_IRWXU)
93
+ os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
94
+ except OSError:
95
+ pass
96
+
97
+
98
+ def _read_json_object(path: Path) -> dict[str, Any] | None:
99
+ try:
100
+ raw = json.loads(path.read_text(encoding="utf-8"))
101
+ except (OSError, ValueError):
102
+ return None
103
+ return raw if isinstance(raw, dict) else None
104
+
105
+
106
+ # --- CLI-shared credential files (~/.mlops) ---------------------------------
107
+
108
+
109
+ def _shared_credentials_path() -> Path:
110
+ """Effective credentials file: config ``credentialsPath`` when valid."""
111
+ default = _MLC_DIR / "credentials"
112
+ raw = _read_json_object(_MLC_CONFIG)
113
+ configured = str((raw or {}).get("credentialsPath") or "").strip()
114
+ if not configured:
115
+ return default
116
+ if configured == "~":
117
+ candidate = Path.home()
118
+ elif configured.startswith("~/"):
119
+ candidate = Path.home() / configured[2:]
120
+ else:
121
+ candidate = Path(configured)
122
+ if not candidate.is_absolute() or candidate.is_dir():
123
+ return default
124
+ return candidate
125
+
126
+
127
+ def _read_shared_credentials() -> dict[str, Any] | None:
128
+ path = _shared_credentials_path()
129
+ if not path.is_file():
130
+ return None
131
+ raw = _read_json_object(path)
132
+ if raw is None:
133
+ return None
134
+ api_base = raw.get("api_base")
135
+ api_key = raw.get("api_key")
136
+ if not (isinstance(api_base, str) and api_base.strip()):
137
+ return None
138
+ if not (isinstance(api_key, str) and api_key.strip()):
139
+ return None
140
+ return raw
141
+
142
+
143
+ def _write_shared_credentials(
144
+ server_root: str,
145
+ token: str,
146
+ key_id: str | None,
147
+ user: dict[str, Any],
148
+ roles: list[str],
149
+ ) -> None:
150
+ payload: dict[str, Any] = {
151
+ "api_base": f"{server_root}/api",
152
+ "api_key": token,
153
+ "user": {
154
+ "id": str(user.get("id") or ""),
155
+ "email": str(user.get("email") or ""),
156
+ "display_name": str(user.get("display_name") or ""),
157
+ "roles": [str(role) for role in roles],
158
+ },
159
+ }
160
+ if key_id:
161
+ payload["api_key_id"] = key_id
162
+ _write_private(_shared_credentials_path(), json.dumps(payload, indent=2))
163
+
164
+
165
+ def _host_of(value: str) -> str:
166
+ """Bare ``host`` / ``host:port`` out of any server URL (CLI host_of)."""
167
+ trimmed = value.strip()
168
+ for scheme in ("http://", "https://"):
169
+ if trimmed.startswith(scheme):
170
+ trimmed = trimmed[len(scheme) :]
171
+ break
172
+ return trimmed.split("/", 1)[0]
173
+
174
+
175
+ def _write_shared_server(server_root: str) -> None:
176
+ raw = _read_json_object(_MLC_CONFIG) or {}
177
+ raw["server"] = _host_of(server_root)
178
+ _write_private(_MLC_CONFIG, json.dumps(raw, indent=2))
179
+
180
+
181
+ def _root_of_api_base(api_base: str) -> str:
182
+ """CLI api_base carries an ``/api`` suffix; the SDK server root does not."""
183
+ value = api_base.strip().rstrip("/")
184
+ if value.endswith("/api"):
185
+ value = value[: -len("/api")]
186
+ return value
187
+
188
+
189
+ def _remove_legacy_cache() -> None:
190
+ for path in (_TOKEN_FILE, _CONFIG_FILE):
191
+ try:
192
+ if path.is_file():
193
+ path.unlink()
194
+ except OSError:
195
+ pass
196
+
197
+
198
+ # --- legacy cache (read-only fallback) --------------------------------------
199
+
200
+
201
+ def _cached_token() -> str | None:
202
+ try:
203
+ value = _TOKEN_FILE.read_text(encoding="utf-8").strip()
204
+ except OSError:
205
+ return None
206
+ return value or None
207
+
208
+
209
+ def _cached_server() -> str | None:
210
+ raw = _read_json_object(_CONFIG_FILE)
211
+ value = str((raw or {}).get("server") or "").strip()
212
+ return value or None
213
+
214
+
215
+ def _mlc_server() -> str | None:
216
+ raw = _read_json_object(_MLC_CONFIG)
217
+ value = str((raw or {}).get("server") or "").strip()
218
+ return value or None
219
+
220
+
221
+ # --- resolution --------------------------------------------------------------
222
+
223
+
224
+ def _normalize_server(value: str) -> str:
225
+ """Bare ``host`` / ``host:port`` → http URL; URLs pass through (no slash)."""
226
+ trimmed = value.strip().rstrip("/")
227
+ if "://" in trimmed:
228
+ return trimmed
229
+ if ":" not in trimmed:
230
+ trimmed = f"{trimmed}:{_DEFAULT_API_PORT}"
231
+ return f"http://{trimmed}"
232
+
233
+
234
+ def resolve_server(explicit: str | None = None, *, interactive: bool = True) -> str:
235
+ """Resolve the platform base URL (no trailing slash)."""
236
+ if explicit and explicit.strip():
237
+ return _normalize_server(explicit)
238
+ env = os.environ.get("MLOPS_SERVER")
239
+ if env and env.strip():
240
+ return _normalize_server(env)
241
+ mlc = _mlc_server()
242
+ if mlc:
243
+ return _normalize_server(mlc)
244
+ legacy = _cached_server()
245
+ if legacy:
246
+ return _normalize_server(legacy)
247
+ creds = _read_shared_credentials()
248
+ if creds is not None:
249
+ return _root_of_api_base(str(creds["api_base"]))
250
+ if not interactive or not sys.stdin.isatty():
251
+ raise MlopsError(
252
+ "server unknown — pass server=..., set MLOPS_SERVER, "
253
+ "or run mlops.login() interactively once"
254
+ )
255
+ if _tui.available():
256
+ value = _tui.prompt_server(_DEFAULT_SERVER_HINT)
257
+ if value is None:
258
+ raise MlopsAuthError("login cancelled")
259
+ else:
260
+ value = input("MLOps server URL (e.g. http://mlops.example:18081): ").strip()
261
+ if not value:
262
+ raise MlopsError("empty server URL")
263
+ value = _normalize_server(value)
264
+ _write_shared_server(value)
265
+ return value
266
+
267
+
268
+ def _try_resolve_server(explicit: str | None = None) -> str | None:
269
+ try:
270
+ return resolve_server(explicit, interactive=False)
271
+ except MlopsError:
272
+ return None
273
+
274
+
275
+ def _resolve_local(server: str | None) -> tuple[str, str] | None:
276
+ """Resolve ``(server_root, pat)`` from local sources; never prompts."""
277
+ env_token = (os.environ.get("MLOPS_TOKEN") or "").strip()
278
+ if env_token and server:
279
+ return server, env_token
280
+ creds = _read_shared_credentials()
281
+ if creds is not None:
282
+ cred_server = _root_of_api_base(str(creds["api_base"]))
283
+ if server is None:
284
+ return cred_server, str(creds["api_key"]).strip()
285
+ if cred_server == server:
286
+ return server, str(creds["api_key"]).strip()
287
+ legacy = _cached_token()
288
+ if legacy and server:
289
+ return server, legacy
290
+ return None
291
+
292
+
293
+ def resolve_token(explicit: str | None = None) -> str | None:
294
+ """Resolve a PAT without touching the network (no server matching)."""
295
+ if explicit and explicit.strip():
296
+ return explicit.strip()
297
+ env = (os.environ.get("MLOPS_TOKEN") or "").strip()
298
+ if env:
299
+ return env
300
+ creds = _read_shared_credentials()
301
+ if creds is not None:
302
+ return str(creds["api_key"]).strip()
303
+ return _cached_token()
304
+
305
+
306
+ # --- login paths -------------------------------------------------------------
307
+
308
+
309
+ def _login_session(base: str, username: str, password: str) -> tuple[str, dict[str, Any], list[str]]:
310
+ """POST /api/auth/login → (session_token, user, roles); 401 propagates."""
311
+ login_t = Transport(base)
312
+ data = login_t.request("POST", "/api/auth/login", {"email": username, "password": password})
313
+ session_token = (data or {}).get("session_token") or (data or {}).get("sessionToken")
314
+ if not session_token:
315
+ raise MlopsAuthError("login response missing session token")
316
+ user = dict((data or {}).get("user") or {})
317
+ roles = [str(role) for role in ((data or {}).get("roles") or [])]
318
+ return session_token, user, roles
319
+
320
+
321
+ def _mint_sdk_key(base: str, session_token: str) -> tuple[str, str | None]:
322
+ """POST /api/auth/api-keys with the session cookie → (pat, key_id)."""
323
+ key_t = Transport(base)
324
+ data = key_t.request(
325
+ "POST",
326
+ "/api/auth/api-keys",
327
+ {
328
+ "name": f"sdk:{socket.gethostname()}",
329
+ "scopes": ["sdk"],
330
+ "expires_days": 30,
331
+ },
332
+ headers={"Cookie": f"session={session_token}"},
333
+ )
334
+ pat = (data or {}).get("token")
335
+ if not pat:
336
+ raise MlopsAuthError("api key response missing token")
337
+ key_id = str(((data or {}).get("key") or {}).get("id") or "") or None
338
+ return pat, key_id
339
+
340
+
341
+ def _password_login(
342
+ base: str, username: str, password: str
343
+ ) -> tuple[str, str | None, dict[str, Any], list[str]]:
344
+ session_token, user, roles = _login_session(base, username, password)
345
+ pat, key_id = _mint_sdk_key(base, session_token)
346
+ if not user.get("email"):
347
+ # Older servers may not embed the profile in the login response.
348
+ me = Transport(base, pat).request("GET", "/api/auth/me") or {}
349
+ user = {key: me.get(key) for key in ("id", "email", "display_name")}
350
+ roles = roles or [str(role) for role in (me.get("roles") or [])]
351
+ return pat, key_id, user, roles
352
+
353
+
354
+ def _interactive_password_login(
355
+ base: str, email: str
356
+ ) -> tuple[str, str | None, dict[str, Any], list[str]] | None:
357
+ """TUI password prompt with 401 retries; None means "back to email"."""
358
+ attempt = 0
359
+ while True:
360
+ password = _tui.prompt_password()
361
+ if password is None:
362
+ return None
363
+ try:
364
+ session_token, user, roles = _login_session(base, email, password)
365
+ break
366
+ except MlopsAuthError:
367
+ attempt += 1
368
+ if attempt >= _LOGIN_MAX_ATTEMPTS:
369
+ raise MlopsAuthError(
370
+ f"invalid email or password ({_LOGIN_MAX_ATTEMPTS} attempts)"
371
+ ) from None
372
+ left = _LOGIN_MAX_ATTEMPTS - attempt
373
+ sys.stderr.write(
374
+ f"\x1b[33mInvalid email or password. {left} attempt(s) left.\x1b[0m\n"
375
+ )
376
+ sys.stderr.flush()
377
+ pat, key_id = _mint_sdk_key(base, session_token)
378
+ if not user.get("email"):
379
+ me = Transport(base, pat).request("GET", "/api/auth/me") or {}
380
+ user = {key: me.get(key) for key in ("id", "email", "display_name")}
381
+ roles = roles or [str(role) for role in (me.get("roles") or [])]
382
+ return pat, key_id, user, roles
383
+
384
+
385
+ def _open_url_prefer_chrome(url: str) -> bool:
386
+ """Open ``url`` in Chrome when available, else the system default browser.
387
+
388
+ Browser output is detached (DEVNULL + new session) so GTK/browser logs
389
+ never reach the terminal. Returns False when no browser could be launched.
390
+ """
391
+ if sys.platform == "win32": # pragma: no cover — Windows only
392
+ for getter in (lambda: webbrowser.get("chrome"), webbrowser.get):
393
+ try:
394
+ getter().open(url)
395
+ return True
396
+ except webbrowser.Error:
397
+ continue
398
+ return False
399
+ if sys.platform == "darwin": # pragma: no cover — macOS only
400
+ commands = [["open", "-a", "Google Chrome", url], ["open", url]]
401
+ else:
402
+ commands = []
403
+ for name in ("google-chrome", "google-chrome-stable", "chromium", "chromium-browser"):
404
+ path = shutil.which(name)
405
+ if path:
406
+ commands.append([path, url])
407
+ break
408
+ commands.append(["xdg-open", url])
409
+ for command in commands:
410
+ try:
411
+ subprocess.Popen(
412
+ command,
413
+ stdout=subprocess.DEVNULL,
414
+ stderr=subprocess.DEVNULL,
415
+ start_new_session=True,
416
+ )
417
+ return True
418
+ except OSError:
419
+ continue
420
+ return False
421
+
422
+
423
+ def _device_login(base: str) -> tuple[str, str | None, dict[str, Any], list[str]]:
424
+ transport = Transport(base)
425
+ data = transport.request(
426
+ "POST", "/api/auth/device/start", {"label": f"sdk:{socket.gethostname()}"}
427
+ )
428
+ device_code = (data or {}).get("device_code")
429
+ user_code = (data or {}).get("user_code")
430
+ if not device_code or not user_code:
431
+ raise MlopsAuthError("device authorization start failed")
432
+ verification_uri = (data or {}).get("verification_uri") or "/device"
433
+ expires_in = int((data or {}).get("expires_in") or _DEVICE_POLL_MAX_SECONDS)
434
+ interval = max(int((data or {}).get("interval") or 2), 1)
435
+ url = f"{base}{verification_uri}?code={user_code}"
436
+ _tui.print_device_instructions(
437
+ user_code=str(user_code), url=url, expires_in=expires_in
438
+ )
439
+ _open_url_prefer_chrome(url)
440
+ deadline = time.monotonic() + expires_in
441
+ while time.monotonic() < deadline:
442
+ time.sleep(interval)
443
+ try:
444
+ data = transport.request("POST", "/api/auth/device/poll", {"device_code": device_code})
445
+ except MlopsError:
446
+ # Transient network/server error: keep polling until the deadline
447
+ # instead of aborting the whole login on one blip.
448
+ continue
449
+ status = (data or {}).get("status")
450
+ if status == "approved":
451
+ pat = (data or {}).get("token")
452
+ if not pat:
453
+ raise MlopsAuthError("device poll response missing token")
454
+ key_id = str((data or {}).get("key_id") or "") or None
455
+ user = dict((data or {}).get("user") or {})
456
+ roles = [str(role) for role in ((data or {}).get("roles") or [])]
457
+ return pat, key_id, user, roles
458
+ if status == "denied":
459
+ raise MlopsAuthError("authorization denied in browser")
460
+ if status == "expired":
461
+ raise MlopsAuthError("device code expired — run mlops.login() again")
462
+ raise MlopsAuthError("device code expired — run mlops.login() again")
463
+
464
+
465
+ def _persist(server_root: str, token: str, key_id: str | None, user: dict[str, Any], roles: list[str]) -> None:
466
+ _write_shared_credentials(server_root, token, key_id, user, roles)
467
+ _write_shared_server(server_root)
468
+ _remove_legacy_cache()
469
+
470
+
471
+ def login(
472
+ username: str | None = None,
473
+ *,
474
+ password: str | None = None,
475
+ server: str | None = None,
476
+ ) -> bool:
477
+ """Authenticate this process against the platform.
478
+
479
+ Resolution order:
480
+
481
+ 1. Explicit ``username`` (+ ``password``) forces a fresh password login,
482
+ ignoring every cache — the new PAT replaces stored credentials.
483
+ 2. Local credentials: ``MLOPS_TOKEN`` (with a known server), the shared
484
+ CLI credentials file, then the legacy cache. No network; in a terminal
485
+ the success line is printed when the shared credentials file supplied
486
+ the token.
487
+ 3. Interactive terminal UI: email + password, or browser device
488
+ authorization.
489
+
490
+ Returns ``True`` on success. Any authentication failure (wrong password,
491
+ denied/expired device authorization, cancelled prompt, unreachable
492
+ server, no credentials in a non-interactive session) prints a one-line
493
+ notice on stderr and returns ``False`` instead of raising; the reason is
494
+ remembered so the next platform call raises an ``MlopsAuthError`` that
495
+ names it. Only usage errors (``password`` without ``username``) still
496
+ raise ``MlopsError``.
497
+ """
498
+ global _login_failure
499
+ if password is not None and username is None:
500
+ raise MlopsError("password requires username")
501
+ _login_failure = None
502
+ try:
503
+ _login_flow(username, password=password, server=server)
504
+ except MlopsError as exc:
505
+ _login_failure = str(exc)
506
+ _tui.print_login_failure(str(exc))
507
+ return False
508
+ return True
509
+
510
+
511
+ def _login_flow(
512
+ username: str | None,
513
+ *,
514
+ password: str | None,
515
+ server: str | None,
516
+ ) -> None:
517
+ global _server, _token
518
+
519
+ if username is not None:
520
+ base = resolve_server(server)
521
+ if password is None:
522
+ if sys.stdin.isatty():
523
+ if _tui.available():
524
+ password = _tui.prompt_password(f"Password for {username}")
525
+ if password is None:
526
+ raise MlopsAuthError("login cancelled")
527
+ else:
528
+ password = getpass.getpass(f"Password for {username}: ")
529
+ else:
530
+ raise MlopsAuthError("password required (non-interactive stdin)")
531
+ pat, key_id, user, roles = _password_login(base, username, password)
532
+ _persist(base, pat, key_id, user, roles)
533
+ _server, _token = base, pat
534
+ return
535
+
536
+ hit = _resolve_local(_try_resolve_server(server))
537
+ if hit is not None:
538
+ _server, _token = hit
539
+ if sys.stdout.isatty():
540
+ creds = _read_shared_credentials()
541
+ user = (creds or {}).get("user") or {}
542
+ if (
543
+ creds is not None
544
+ and str(creds.get("api_key") or "").strip() == hit[1]
545
+ and (user.get("email") or user.get("display_name"))
546
+ ):
547
+ _tui.print_login_success(
548
+ display_name=str(user.get("display_name") or user.get("email") or ""),
549
+ email=str(user.get("email") or ""),
550
+ )
551
+ return
552
+
553
+ if not sys.stdin.isatty():
554
+ raise _no_credentials_error()
555
+
556
+ if not _tui.available():
557
+ base = resolve_server(server)
558
+ _tui.print_brand_header()
559
+ print()
560
+ pat, key_id, user, roles = _legacy_interactive(base)
561
+ _persist(base, pat, key_id, user, roles)
562
+ _tui.print_login_success(
563
+ display_name=str(user.get("display_name") or user.get("email") or ""),
564
+ email=str(user.get("email") or ""),
565
+ )
566
+ _server, _token = base, pat
567
+ return
568
+
569
+ _tui.print_brand_header()
570
+ print()
571
+ base = _try_resolve_server(server)
572
+ if base is None:
573
+ host = _tui.prompt_server(_DEFAULT_SERVER_HINT)
574
+ if host is None:
575
+ raise MlopsAuthError("login cancelled")
576
+ base = _normalize_server(host)
577
+ _write_shared_server(base)
578
+ bundle: tuple[str, str | None, dict[str, Any], list[str]]
579
+ step = "method"
580
+ while True:
581
+ if step == "method":
582
+ method = _tui.select(
583
+ "Login method",
584
+ [
585
+ "Email + password",
586
+ "Authorize in browser (uses your logged-in web session)",
587
+ ],
588
+ )
589
+ if method is None:
590
+ raise MlopsAuthError("login cancelled") # widget printed the reason
591
+ step = "email" if method == 0 else "device"
592
+ elif step == "email":
593
+ email = _tui.prompt_email("admin", _email_domain())
594
+ if email is None:
595
+ step = "method"
596
+ continue
597
+ step = "password"
598
+ elif step == "password":
599
+ result = _interactive_password_login(base, email)
600
+ if result is None:
601
+ step = "email"
602
+ continue
603
+ bundle = result
604
+ break
605
+ else:
606
+ bundle = _device_login(base)
607
+ break
608
+ pat, key_id, user, roles = bundle
609
+ _persist(base, pat, key_id, user, roles)
610
+ _tui.print_login_success(
611
+ display_name=str(user.get("display_name") or user.get("email") or ""),
612
+ email=str(user.get("email") or ""),
613
+ )
614
+ _server, _token = base, pat
615
+
616
+
617
+ def _legacy_interactive(base: str) -> tuple[str, str | None, dict[str, Any], list[str]]:
618
+ """Plain-text menu for non-TTY / unsupported terminals."""
619
+ choice = input(
620
+ f"No MLOps credentials found for {base}.\n"
621
+ " 1) Email + password\n"
622
+ " 2) Authorize in browser (uses your logged-in web session)\n"
623
+ "Choice [1]: "
624
+ ).strip()
625
+ if choice in ("", "1"):
626
+ email = input("Email: ").strip()
627
+ if not email:
628
+ raise MlopsAuthError("empty email")
629
+ password = getpass.getpass(f"Password for {email}: ")
630
+ return _password_login(base, email, password)
631
+ if choice == "2":
632
+ return _device_login(base)
633
+ raise MlopsAuthError(f"unknown choice: {choice}")
634
+
635
+
636
+ def whoami() -> dict[str, Any]:
637
+ """Return the current user's profile (401 → ``MlopsAuthError``).
638
+
639
+ In a terminal the profile is also printed as a formatted summary block;
640
+ the return value is unchanged either way.
641
+ """
642
+ transport = require_transport()
643
+ data = transport.request("GET", "/api/auth/me")
644
+ if sys.stdout.isatty():
645
+ _tui.print_profile(
646
+ display_name=str((data or {}).get("display_name") or ""),
647
+ email=str((data or {}).get("email") or ""),
648
+ roles=[str(r) for r in (data or {}).get("roles") or []],
649
+ permissions=[str(p) for p in (data or {}).get("permissions") or []],
650
+ server=_server or "",
651
+ )
652
+ return dict(data or {})
653
+
654
+
655
+ def require_transport() -> Transport:
656
+ """Transport for the resolved credentials; ``login()`` is implicit."""
657
+ global _server, _token
658
+ if _server is None or _token is None:
659
+ hit = _resolve_local(_try_resolve_server(None))
660
+ if hit is None:
661
+ if _login_failure is not None:
662
+ raise MlopsAuthError(
663
+ f"not logged in — mlops.login() failed: {_login_failure}; "
664
+ "retry login() or set MLOPS_TOKEN"
665
+ )
666
+ raise _no_credentials_error()
667
+ _server, _token = hit
668
+ return Transport(_server, _token)