opensees-cli 0.1.0a10__tar.gz → 0.2.0__tar.gz

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.
Files changed (28) hide show
  1. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/PKG-INFO +16 -13
  2. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/README.md +15 -12
  3. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/pyproject.toml +1 -1
  4. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/__init__.py +1 -1
  5. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/admin.py +80 -0
  6. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/api.py +111 -8
  7. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/auth.py +77 -20
  8. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/config.py +40 -1
  9. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/files.py +113 -35
  10. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/main.py +79 -49
  11. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/path_setup.py +52 -30
  12. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/run.py +703 -170
  13. opensees_cli-0.2.0/src/opensees_cli/version.py +180 -0
  14. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli.egg-info/PKG-INFO +16 -13
  15. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli.egg-info/SOURCES.txt +1 -0
  16. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/tests/test_api.py +57 -1
  17. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/tests/test_auth_commands.py +3 -1
  18. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/tests/test_config.py +12 -0
  19. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/tests/test_files_commands.py +1 -1
  20. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/tests/test_main_commands.py +59 -36
  21. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/tests/test_run_commands.py +15 -14
  22. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/setup.cfg +0 -0
  23. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli/__main__.py +0 -0
  24. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli.egg-info/dependency_links.txt +0 -0
  25. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli.egg-info/entry_points.txt +0 -0
  26. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli.egg-info/requires.txt +0 -0
  27. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/src/opensees_cli.egg-info/top_level.txt +0 -0
  28. {opensees_cli-0.1.0a10 → opensees_cli-0.2.0}/tests/test_admin_commands.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: opensees_cli
3
- Version: 0.1.0a10
3
+ Version: 0.2.0
4
4
  Summary: Run OpenSees simulations in the cloud from the command line.
5
5
  Author: Minjie Zhu
6
6
  License: Proprietary
@@ -78,15 +78,12 @@ ops run submit ./model.py --timeout 300 --wait
78
78
  ops set-path
79
79
  ops version
80
80
  ops status
81
- ops quota
82
81
  ops help
83
82
  ```
84
83
 
85
84
  - `set-path`: interactive prompt to add the `ops` launcher directory to your `PATH` (use `python -m opensees_cli set-path` if `ops` is not on `PATH` yet)
86
85
  - `version`: print CLI version
87
- - `status`: show account details, signup time, and quota (calls the API)
88
- - `quota`: show your current run quota
89
-
86
+ - `status`: show account details, signup time, and usage quota (calls the API)
90
87
  ## Auth Commands
91
88
 
92
89
  ```bash
@@ -105,7 +102,8 @@ ops auth help
105
102
  ## Run Commands
106
103
 
107
104
  ```bash
108
- ops run submit ./model.py --timeout 120 --wait
105
+ ops run submit ./model.py --timeout 120
106
+ ops run submit ./model.py --wait
109
107
  ops run status <run_id>
110
108
  ops run output <run_id>
111
109
  ops run result <run_id>
@@ -116,12 +114,12 @@ ops run help
116
114
 
117
115
  ### `run submit` options
118
116
 
119
- - `file` (required positional): path to a `.py` simulation script
117
+ - `file` (required positional): local path to a `.py` file (uploaded if the path exists under its filename), or a cloud path such as `model.py` or `lab/model.py`
120
118
  - `--timeout`, `-t`: max wall time per task in seconds (default `120`). The API requires your **monthly runtime remaining** ≥ `timeout ×` number of tasks. Runs above **900s** use Fargate when configured; otherwise the **900s** Lambda limit applies.
121
- - `--wait/--no-wait`: stream output until completion (default `--wait`)
119
+ - `--wait`, `-w`: wait and stream output until completion (default: return immediately with the analysis ID on stdout; progress on stderr)
122
120
 
123
- Validation enforced by CLI:
124
- - file must exist
121
+ Validation enforced by CLI (local uploads):
122
+ - path must exist on disk and be a regular file
125
123
  - file extension must be `.py`
126
124
  - file size must be <= 200 KB
127
125
 
@@ -131,18 +129,23 @@ Validation enforced by CLI:
131
129
 
132
130
  ```bash
133
131
  ops status
134
- ops quota
135
132
  ```
136
133
 
137
- ### Submit and monitor a run later
134
+ ### Submit and monitor a run later (default)
138
135
 
139
136
  ```bash
140
- ops run submit ./model.py --no-wait
137
+ ops run submit ./model.py
141
138
  ops run status <run_id>
142
139
  ops run output <run_id>
143
140
  ops run result <run_id>
144
141
  ```
145
142
 
143
+ ### Submit and wait for live output
144
+
145
+ ```bash
146
+ ops run submit ./model.py --wait
147
+ ```
148
+
146
149
  ### Reset password
147
150
 
148
151
  ```bash
@@ -55,15 +55,12 @@ ops run submit ./model.py --timeout 300 --wait
55
55
  ops set-path
56
56
  ops version
57
57
  ops status
58
- ops quota
59
58
  ops help
60
59
  ```
61
60
 
62
61
  - `set-path`: interactive prompt to add the `ops` launcher directory to your `PATH` (use `python -m opensees_cli set-path` if `ops` is not on `PATH` yet)
63
62
  - `version`: print CLI version
64
- - `status`: show account details, signup time, and quota (calls the API)
65
- - `quota`: show your current run quota
66
-
63
+ - `status`: show account details, signup time, and usage quota (calls the API)
67
64
  ## Auth Commands
68
65
 
69
66
  ```bash
@@ -82,7 +79,8 @@ ops auth help
82
79
  ## Run Commands
83
80
 
84
81
  ```bash
85
- ops run submit ./model.py --timeout 120 --wait
82
+ ops run submit ./model.py --timeout 120
83
+ ops run submit ./model.py --wait
86
84
  ops run status <run_id>
87
85
  ops run output <run_id>
88
86
  ops run result <run_id>
@@ -93,12 +91,12 @@ ops run help
93
91
 
94
92
  ### `run submit` options
95
93
 
96
- - `file` (required positional): path to a `.py` simulation script
94
+ - `file` (required positional): local path to a `.py` file (uploaded if the path exists under its filename), or a cloud path such as `model.py` or `lab/model.py`
97
95
  - `--timeout`, `-t`: max wall time per task in seconds (default `120`). The API requires your **monthly runtime remaining** ≥ `timeout ×` number of tasks. Runs above **900s** use Fargate when configured; otherwise the **900s** Lambda limit applies.
98
- - `--wait/--no-wait`: stream output until completion (default `--wait`)
96
+ - `--wait`, `-w`: wait and stream output until completion (default: return immediately with the analysis ID on stdout; progress on stderr)
99
97
 
100
- Validation enforced by CLI:
101
- - file must exist
98
+ Validation enforced by CLI (local uploads):
99
+ - path must exist on disk and be a regular file
102
100
  - file extension must be `.py`
103
101
  - file size must be <= 200 KB
104
102
 
@@ -108,18 +106,23 @@ Validation enforced by CLI:
108
106
 
109
107
  ```bash
110
108
  ops status
111
- ops quota
112
109
  ```
113
110
 
114
- ### Submit and monitor a run later
111
+ ### Submit and monitor a run later (default)
115
112
 
116
113
  ```bash
117
- ops run submit ./model.py --no-wait
114
+ ops run submit ./model.py
118
115
  ops run status <run_id>
119
116
  ops run output <run_id>
120
117
  ops run result <run_id>
121
118
  ```
122
119
 
120
+ ### Submit and wait for live output
121
+
122
+ ```bash
123
+ ops run submit ./model.py --wait
124
+ ```
125
+
123
126
  ### Reset password
124
127
 
125
128
  ```bash
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "opensees_cli"
7
- version = "0.1.0a10"
7
+ version = "0.2.0"
8
8
  description = "Run OpenSees simulations in the cloud from the command line."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,3 +1,3 @@
1
1
  """OpenSees CLI — run structural simulations in the cloud."""
2
2
 
3
- __version__ = "0.1.0a10"
3
+ __version__ = "0.2.0"
@@ -1,5 +1,6 @@
1
1
  """Admin CLI commands."""
2
2
 
3
+ import json
3
4
  import re
4
5
  from typing import Any, Optional
5
6
 
@@ -274,3 +275,82 @@ def set_quota(
274
275
  except api.ApiError as e:
275
276
  console.print(f"[red]{e.message}[/red]")
276
277
  raise typer.Exit(1)
278
+
279
+
280
+ @app.command("workers")
281
+ def workers(
282
+ as_json: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
283
+ ):
284
+ """Show live Lambda + Fargate worker activity (low-level).
285
+
286
+ \b
287
+ Lambda: reports the configured simulation function plus the CloudWatch
288
+ ConcurrentExecutions max over the last 5 minutes (AWS does not
289
+ expose individual in-flight invocations).
290
+ Fargate: lists every running ECS task in the configured cluster.
291
+ """
292
+ try:
293
+ r = api.get("/admin/workers")
294
+ except api.ApiError as e:
295
+ console.print(f"[red]{e.message}[/red]")
296
+ raise typer.Exit(1)
297
+
298
+ if as_json:
299
+ typer.echo(json.dumps(r, indent=2, ensure_ascii=False))
300
+ return
301
+
302
+ lam = r.get("lambda") or {}
303
+ fg = r.get("fargate") or {}
304
+
305
+ console.print("[bold]Lambda[/bold]")
306
+ if not lam.get("configured"):
307
+ console.print(f" [dim]not configured: {lam.get('reason', 'unknown')}[/dim]")
308
+ else:
309
+ console.print(f" Function: {lam.get('function_name', '-')}")
310
+ console.print(f" State: {lam.get('state', '-')}")
311
+ console.print(f" Timeout: {lam.get('timeout', '-')}s")
312
+ console.print(f" Memory: {lam.get('memory_size', '-')} MB")
313
+ win = lam.get("metric_window_seconds", 0)
314
+ ce = lam.get("concurrent_executions_max")
315
+ inv = lam.get("invocations_sum")
316
+ console.print(
317
+ f" Concurrent (last {win}s): "
318
+ f"max={ce if ce is not None else '-'} · invocations={inv if inv is not None else '-'}"
319
+ )
320
+ if lam.get("metric_error"):
321
+ console.print(f" [red]Metric error: {lam['metric_error']}[/red]")
322
+ if lam.get("configuration_error"):
323
+ console.print(f" [red]Config error: {lam['configuration_error']}[/red]")
324
+
325
+ console.print()
326
+ console.print("[bold]Fargate[/bold]")
327
+ if not fg.get("configured"):
328
+ console.print(f" [dim]not configured: {fg.get('reason', 'unknown')}[/dim]")
329
+ return
330
+ console.print(f" Cluster: {fg.get('cluster', '-')}")
331
+ console.print(f" Running tasks: {fg.get('running_count', 0)}")
332
+ if fg.get("error"):
333
+ console.print(f" [red]Error: {fg['error']}[/red]")
334
+ return
335
+
336
+ tasks = fg.get("tasks") or []
337
+ if not tasks:
338
+ return
339
+
340
+ table = Table(show_header=True)
341
+ table.add_column("Task ID", style="dim", max_width=12)
342
+ table.add_column("Status")
343
+ table.add_column("Container")
344
+ table.add_column("CPU", justify="right")
345
+ table.add_column("Memory", justify="right")
346
+ table.add_column("Started")
347
+ for t in tasks:
348
+ table.add_row(
349
+ (t.get("task_id") or "")[:12],
350
+ t.get("last_status", "-") or "-",
351
+ t.get("container_status", "-") or "-",
352
+ t.get("cpu", "-") or "-",
353
+ t.get("memory", "-") or "-",
354
+ _to_local(t["started_at"]) if t.get("started_at") else "-",
355
+ )
356
+ console.print(table)
@@ -10,6 +10,7 @@ import httpx
10
10
 
11
11
  from opensees_cli import __version__
12
12
  from opensees_cli.config import (
13
+ clear_credentials,
13
14
  get_access_token,
14
15
  get_api_url,
15
16
  get_refresh_token,
@@ -18,6 +19,9 @@ from opensees_cli.config import (
18
19
  )
19
20
 
20
21
  TIMEOUT = 30.0
22
+ # Seconds before access-token expiry to refresh proactively (when expires_at is known).
23
+ _REFRESH_BUFFER_SEC = 300
24
+ _session_ok: Optional[bool] = None
21
25
 
22
26
 
23
27
  class ApiError(Exception):
@@ -28,6 +32,17 @@ class ApiError(Exception):
28
32
  super().__init__(message)
29
33
 
30
34
 
35
+ def invalidate_session_cache() -> None:
36
+ global _session_ok
37
+ _session_ok = None
38
+
39
+
40
+ def clear_session() -> None:
41
+ """Drop stored credentials and in-process session cache."""
42
+ invalidate_session_cache()
43
+ clear_credentials()
44
+
45
+
31
46
  def _not_logged_in() -> None:
32
47
  """Print a login prompt and exit."""
33
48
  from rich.console import Console
@@ -38,17 +53,93 @@ def _not_logged_in() -> None:
38
53
  raise SystemExit(0)
39
54
 
40
55
 
41
- def require_login() -> None:
42
- """Exit early if the user has no stored credentials."""
43
- if not load_credentials() or not load_credentials().get("access_token"):
56
+ def _session_expired() -> None:
57
+ """Print a re-login prompt and exit (credentials already cleared)."""
58
+ from rich.console import Console
59
+ c = Console()
60
+ c.print("[yellow]Session expired.[/yellow] Log in again:\n")
61
+ c.print(" [bold]ops auth login[/bold] Log in to your account")
62
+ raise SystemExit(0)
63
+
64
+
65
+ def _auth_failure() -> None:
66
+ """Clear stale credentials and exit with the appropriate auth prompt."""
67
+ had_creds = has_stored_credentials()
68
+ clear_session()
69
+ if had_creds:
70
+ _session_expired()
71
+ _not_logged_in()
72
+
73
+
74
+ def has_stored_credentials() -> bool:
75
+ creds = load_credentials()
76
+ return bool(creds and creds.get("access_token"))
77
+
78
+
79
+ def _should_refresh_proactively(creds: Dict[str, Any]) -> bool:
80
+ expires_at = creds.get("expires_at")
81
+ if expires_at is None:
82
+ return False
83
+ try:
84
+ import time
85
+ return time.time() >= float(expires_at) - _REFRESH_BUFFER_SEC
86
+ except (TypeError, ValueError):
87
+ return False
88
+
89
+
90
+ def _validate_session_with_me() -> bool:
91
+ """Return True if GET /auth/me succeeds (refreshing access token on 401 if possible)."""
92
+ try:
93
+ resp = httpx.get(_url("/auth/me"), headers=_headers(), timeout=TIMEOUT)
94
+ if resp.status_code == 200:
95
+ return True
96
+ if _needs_auth_refresh(resp) and _try_refresh():
97
+ resp = httpx.get(_url("/auth/me"), headers=_headers(), timeout=TIMEOUT)
98
+ return resp.status_code == 200
99
+ return False
100
+ except Exception:
101
+ return False
102
+
103
+
104
+ def ensure_session() -> bool:
105
+ """Return True when stored credentials represent a valid API session.
106
+
107
+ Refreshes the access token automatically when it is expired or near expiry.
108
+ """
109
+ global _session_ok
110
+ if _session_ok is True:
111
+ return True
112
+ if not has_stored_credentials():
113
+ _session_ok = False
114
+ return False
115
+ creds = load_credentials() or {}
116
+ if _should_refresh_proactively(creds) and not _try_refresh():
117
+ _session_ok = False
118
+ return False
119
+ ok = _validate_session_with_me()
120
+ _session_ok = ok
121
+ return ok
122
+
123
+
124
+ def is_logged_in() -> bool:
125
+ """True when the user has a valid session (same check as ``ops status``)."""
126
+ return ensure_session()
127
+
128
+
129
+ def require_login(*, validate: bool = True) -> None:
130
+ """Exit early if the user has no valid session."""
131
+ if not has_stored_credentials():
44
132
  _not_logged_in()
133
+ if validate and not ensure_session():
134
+ clear_session()
135
+ _session_expired()
45
136
 
46
137
 
47
138
  def require_no_login() -> None:
48
139
  """Exit early if the user is already logged in."""
49
140
  from rich.console import Console
50
- creds = load_credentials()
51
- if creds and creds.get("access_token"):
141
+ if is_logged_in():
142
+ creds = load_credentials() or {}
52
143
  Console().print(
53
144
  f"Already logged in as [bold]{creds.get('email', '')}[/bold]. "
54
145
  "Run [bold]ops auth logout[/bold] first."
@@ -130,11 +221,20 @@ def _me_is_admin_after_token_update() -> Optional[bool]:
130
221
 
131
222
 
132
223
  def _try_refresh() -> bool:
224
+ global _session_ok
133
225
  rt = get_refresh_token()
134
226
  if not rt:
135
227
  return False
136
228
  try:
137
- data = post("/auth/refresh", {"refresh_token": rt}, auth=False)
229
+ resp = httpx.post(
230
+ _url("/auth/refresh"),
231
+ json={"refresh_token": rt},
232
+ headers=_headers(token=""),
233
+ timeout=TIMEOUT,
234
+ )
235
+ if resp.status_code >= 400:
236
+ return False
237
+ data = resp.json()
138
238
  creds = load_credentials() or {}
139
239
  save_credentials(
140
240
  access_token=data["access_token"],
@@ -142,7 +242,9 @@ def _try_refresh() -> bool:
142
242
  id_token=data.get("id_token"),
143
243
  email=creds.get("email"),
144
244
  is_admin=creds.get("is_admin", False),
245
+ expires_in=data.get("expires_in"),
145
246
  )
247
+ invalidate_session_cache()
146
248
  # Source of truth for admin is Cognito groups via /auth/me (fixes stale cached is_admin).
147
249
  fresh_admin = _me_is_admin_after_token_update()
148
250
  if fresh_admin is not None:
@@ -154,6 +256,7 @@ def _try_refresh() -> bool:
154
256
  email=creds.get("email"),
155
257
  is_admin=fresh_admin,
156
258
  )
259
+ _session_ok = True
157
260
  return True
158
261
  except Exception:
159
262
  return False
@@ -179,7 +282,7 @@ def post(path: str, body: Dict[str, Any], auth: bool = True) -> Dict[str, Any]:
179
282
  if _try_refresh():
180
283
  resp = httpx.post(_url(path), json=body, headers=_headers(), timeout=TIMEOUT)
181
284
  else:
182
- _not_logged_in()
285
+ _auth_failure()
183
286
  return _parse(resp)
184
287
 
185
288
 
@@ -190,7 +293,7 @@ def get(path: str, params: Optional[Dict[str, Any]] = None, auth: bool = True) -
190
293
  if _try_refresh():
191
294
  resp = httpx.get(_url(path), params=params, headers=_headers(), timeout=TIMEOUT)
192
295
  else:
193
- _not_logged_in()
296
+ _auth_failure()
194
297
  return _parse(resp)
195
298
 
196
299
 
@@ -1,5 +1,6 @@
1
1
  """Authentication CLI commands."""
2
2
 
3
+ import json
3
4
  import sys
4
5
  from typing import Any, Dict, Optional, Sequence
5
6
 
@@ -257,6 +258,29 @@ def print_quota(q: dict) -> None:
257
258
  console.print(f" Storage left: {st_left_str}")
258
259
 
259
260
 
261
+ def quota_to_json_obj(q: dict) -> Dict[str, Any]:
262
+ """Quota fields as a plain dict (shared by ``ops status --json``)."""
263
+ return {
264
+ "max_concurrent_runs": q.get("max_concurrent_runs"),
265
+ "max_tasks_per_analysis": q.get("max_tasks_per_analysis"),
266
+ "max_task_timeout": q.get("max_task_timeout"),
267
+ "max_storage_per_task": q.get("max_storage_per_task"),
268
+ "max_monthly_runtime": q.get("max_monthly_runtime"),
269
+ "monthly_runtime_used": q.get("monthly_runtime_used"),
270
+ "monthly_runtime_reserved": q.get("monthly_runtime_reserved"),
271
+ "monthly_runtime_remaining": q.get("monthly_runtime_remaining"),
272
+ "next_reset_at": _to_local_date(q["next_reset_at"]) if q.get("next_reset_at") else None,
273
+ "max_monthly_storage": q.get("max_monthly_storage"),
274
+ "storage_used": q.get("storage_used"),
275
+ "storage_remaining": max(0, (q.get("max_monthly_storage") or 0) - (q.get("storage_used") or 0)),
276
+ }
277
+
278
+
279
+ def format_quota_json(q: dict) -> str:
280
+ """Single JSON object for quota fields (legacy helper)."""
281
+ return json.dumps(quota_to_json_obj(q), indent=2) + "\n"
282
+
283
+
260
284
  def print_me(
261
285
  r: Dict[str, Any],
262
286
  *,
@@ -265,8 +289,7 @@ def print_me(
265
289
  """Print a /auth/me response (used by ``ops status``).
266
290
 
267
291
  ``open_sees_py_lines`` are Rich-markup strings without the leading indent;
268
- they are printed after last activity and before the server ``CLI version``
269
- line (when present).
292
+ they are printed after last activity (when present).
270
293
  """
271
294
  console.print(f" Email: [bold]{r.get('email', '')}[/bold]")
272
295
  console.print(f" Admin: {'[yellow]yes[/yellow]' if r.get('is_admin') else 'no'}")
@@ -283,13 +306,50 @@ def print_me(
283
306
  if open_sees_py_lines:
284
307
  for line in open_sees_py_lines:
285
308
  console.print(f" {line}")
286
- if r.get("last_cli_version"):
287
- console.print(f" CLI version: {r['last_cli_version']}")
288
309
 
310
+
311
+ def format_status_plain(
312
+ r: Dict[str, Any],
313
+ *,
314
+ open_seespy_version: str,
315
+ ) -> str:
316
+ """Machine-readable lines: ``key: value`` (split on first ``:`` per line)."""
317
+ lines: list[str] = [
318
+ f"email: {r.get('email', '')}",
319
+ f"admin: {'yes' if r.get('is_admin') else 'no'}",
320
+ f"enabled: {'yes' if r.get('is_enabled') else 'no'}",
321
+ ]
322
+ signup_raw = r.get("signup_at") or r.get("created_at")
323
+ lines.append(f"signup_time: {_to_local(signup_raw) if signup_raw else ''}")
324
+ lines.append(f"last_login: {_to_local(r['last_login_at']) if r.get('last_login_at') else ''}")
325
+ lines.append(f"last_active: {_to_local(r['last_activity_at']) if r.get('last_activity_at') else ''}")
326
+ lines.append(f"open_seespy_version: {open_seespy_version}")
327
+ return "\n".join(lines) + "\n"
328
+
329
+
330
+ def format_status_json(
331
+ r: Dict[str, Any],
332
+ *,
333
+ open_seespy_version: str,
334
+ ) -> str:
335
+ """Single JSON object for ``json.loads``.
336
+
337
+ Keys: email, admin, enabled, signup_time, last_login,
338
+ last_active, open_seespy_version, quota (nested object or null).
339
+ """
340
+ signup_raw = r.get("signup_at") or r.get("created_at")
289
341
  q = r.get("quota")
290
- if q:
291
- console.print()
292
- print_quota(q)
342
+ obj: Dict[str, Any] = {
343
+ "email": r.get("email") or "",
344
+ "admin": bool(r.get("is_admin")),
345
+ "enabled": bool(r.get("is_enabled")),
346
+ "signup_time": _to_local(signup_raw) if signup_raw else None,
347
+ "last_login": _to_local(r["last_login_at"]) if r.get("last_login_at") else None,
348
+ "last_active": _to_local(r["last_activity_at"]) if r.get("last_activity_at") else None,
349
+ "open_seespy_version": open_seespy_version or None,
350
+ "quota": quota_to_json_obj(q) if q else None,
351
+ }
352
+ return json.dumps(obj, indent=2) + "\n"
293
353
 
294
354
 
295
355
  app = typer.Typer(
@@ -297,20 +357,15 @@ app = typer.Typer(
297
357
  )
298
358
 
299
359
 
300
- def _is_logged_in() -> bool:
301
- creds = config.load_credentials()
302
- return bool(creds and creds.get("access_token"))
303
-
304
-
305
360
  def _print_auth_help() -> None:
306
- logged_in = _is_logged_in()
361
+ logged_in = api.is_logged_in()
307
362
  console.print("[bold]ops auth[/bold] — Account management\n")
308
363
 
309
364
  if logged_in:
310
365
  creds = config.load_credentials() or {}
311
366
  console.print(f" Logged in as [green]{creds.get('email', '')}[/green]\n")
312
367
  console.print("[bold]Commands:[/bold]\n")
313
- console.print(" [bold]ops status[/bold] (top-level) Account details & quota")
368
+ console.print(" [bold]ops status[/bold] (top-level) Account details and quota")
314
369
  console.print(" [bold]ops auth change-password[/bold] Change your password")
315
370
  console.print(" [bold]ops auth logout[/bold] Log out")
316
371
  else:
@@ -414,7 +469,9 @@ def login(email: Optional[str] = typer.Option(None, "--email", "-e")):
414
469
  id_token=r.get("id_token"),
415
470
  email=email,
416
471
  is_admin=r.get("is_admin", False),
472
+ expires_in=r.get("expires_in"),
417
473
  )
474
+ api.invalidate_session_cache()
418
475
  console.print(f"[green]Logged in as [bold]{email}[/bold][/green]")
419
476
  except api.ApiError as e:
420
477
  console.print(f"[red]{e.message}[/red]")
@@ -425,23 +482,23 @@ def login(email: Optional[str] = typer.Option(None, "--email", "-e")):
425
482
  def logout():
426
483
  """Log out of your account."""
427
484
  api.require_login()
428
- token = config.get_access_token()
429
- if token:
485
+ refresh = config.get_refresh_token()
486
+ if refresh:
430
487
  try:
431
- api.post("/auth/logout", {"access_token": token}, auth=False)
488
+ api.post("/auth/logout", {"refresh_token": refresh}, auth=False)
432
489
  except Exception:
433
490
  pass
434
- config.clear_credentials()
491
+ api.clear_session()
435
492
  console.print("[green]Logged out.[/green]")
436
493
 
437
494
 
438
495
  @app.command()
439
496
  def status():
440
497
  """Show current login status."""
441
- creds = config.load_credentials()
442
- if not creds or not creds.get("access_token"):
498
+ if not api.is_logged_in():
443
499
  console.print("Not logged in. Run [bold]ops auth login[/bold]")
444
500
  raise typer.Exit(0)
501
+ creds = config.load_credentials() or {}
445
502
  console.print(f"Logged in as [bold]{creds.get('email', 'unknown')}[/bold]")
446
503
 
447
504
 
@@ -12,6 +12,7 @@ import json
12
12
  import os
13
13
  import re
14
14
  import sys
15
+ import time
15
16
  from pathlib import Path
16
17
  from typing import Any, Dict, Optional
17
18
 
@@ -106,15 +107,24 @@ def save_credentials(
106
107
  id_token: Optional[str] = None,
107
108
  email: Optional[str] = None,
108
109
  is_admin: bool = False,
110
+ expires_in: Optional[int] = None,
109
111
  ) -> None:
110
112
  _ensure_dir()
111
- data = {
113
+ existing = load_credentials() or {}
114
+ data: Dict[str, Any] = {
112
115
  "access_token": access_token,
113
116
  "refresh_token": refresh_token,
114
117
  "id_token": id_token,
115
118
  "email": email,
116
119
  "is_admin": is_admin,
117
120
  }
121
+ if expires_in is not None:
122
+ try:
123
+ data["expires_at"] = time.time() + int(expires_in)
124
+ except (TypeError, ValueError):
125
+ pass
126
+ elif existing.get("expires_at") is not None:
127
+ data["expires_at"] = existing["expires_at"]
118
128
  CREDENTIALS_FILE.write_text(json.dumps(data, indent=2))
119
129
  CREDENTIALS_FILE.chmod(0o600)
120
130
 
@@ -152,3 +162,32 @@ def get_refresh_token() -> Optional[str]:
152
162
  def get_api_url() -> str:
153
163
  _maybe_load_dotenv_files()
154
164
  return os.environ.get("OPENSEES_API_URL") or DEFAULT_API_URL
165
+
166
+
167
+ # ---------------------------------------------------------------------------
168
+ # OpenSeesPy version (sticky local preference)
169
+ # ---------------------------------------------------------------------------
170
+
171
+ OPENSEESPY_VERSION_FILE = CONFIG_DIR / "openseespy_version"
172
+
173
+
174
+ def set_openseespy_version(version: str) -> None:
175
+ """Save the sticky OpenSeesPy version preference."""
176
+ _ensure_dir()
177
+ OPENSEESPY_VERSION_FILE.write_text(version.strip())
178
+
179
+
180
+ def get_openseespy_version() -> Optional[str]:
181
+ """Return the sticky OpenSeesPy version, or None if not set."""
182
+ if not OPENSEESPY_VERSION_FILE.exists():
183
+ return None
184
+ try:
185
+ return OPENSEESPY_VERSION_FILE.read_text().strip() or None
186
+ except OSError:
187
+ return None
188
+
189
+
190
+ def clear_openseespy_version() -> None:
191
+ """Clear the sticky OpenSeesPy version preference."""
192
+ if OPENSEESPY_VERSION_FILE.exists():
193
+ OPENSEESPY_VERSION_FILE.unlink()