glaip-sdk 0.6.2__py3-none-any.whl → 0.6.4__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.
@@ -0,0 +1,187 @@
1
+ """CLI rendering utilities: Rich console helpers, viewer launchers, renderer builders.
2
+
3
+ Authors:
4
+ Raymond Christopher (raymond.christopher@gdplabs.id)
5
+ Putu Ravindra Wiguna (putu.r.wiguna@gdplabs.id)
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import sys
12
+ from contextlib import AbstractContextManager, contextmanager, nullcontext
13
+ from typing import Any
14
+
15
+ from rich.console import Console
16
+
17
+ from glaip_sdk.branding import ACCENT_STYLE
18
+ from glaip_sdk.cli.context import _get_view, get_ctx_value
19
+ from glaip_sdk.utils.rendering.renderer import (
20
+ CapturingConsole,
21
+ RendererFactoryOptions,
22
+ RichStreamRenderer,
23
+ make_default_renderer,
24
+ make_verbose_renderer,
25
+ )
26
+
27
+ # Export console for backward compatibility
28
+ console = Console()
29
+
30
+
31
+ def _can_use_spinner(ctx: Any | None, active_console: Console) -> bool:
32
+ """Check if spinner output is allowed in the current environment."""
33
+ if ctx is not None:
34
+ tty_enabled = bool(get_ctx_value(ctx, "tty", True))
35
+ view = (_get_view(ctx) or "rich").lower()
36
+ if not tty_enabled or view not in {"", "rich"}:
37
+ return False
38
+
39
+ if not active_console.is_terminal:
40
+ return False
41
+
42
+ return _stream_supports_tty(getattr(active_console, "file", None))
43
+
44
+
45
+ def _stream_supports_tty(stream: Any) -> bool:
46
+ """Return True if the provided stream can safely render a spinner."""
47
+ target = stream if hasattr(stream, "isatty") else sys.stdout
48
+ try:
49
+ return bool(target.isatty())
50
+ except Exception:
51
+ return False
52
+
53
+
54
+ def update_spinner(status_indicator: Any | None, message: str) -> None:
55
+ """Update spinner text when a status indicator is active."""
56
+ if status_indicator is None:
57
+ return
58
+
59
+ try:
60
+ status_indicator.update(message)
61
+ except Exception: # pragma: no cover - defensive update
62
+ pass
63
+
64
+
65
+ def stop_spinner(status_indicator: Any | None) -> None:
66
+ """Stop an active spinner safely."""
67
+ if status_indicator is None:
68
+ return
69
+
70
+ try:
71
+ status_indicator.stop()
72
+ except Exception: # pragma: no cover - defensive stop
73
+ pass
74
+
75
+
76
+ # Backwards compatibility aliases for legacy callers
77
+ _spinner_update = update_spinner
78
+ _spinner_stop = stop_spinner
79
+
80
+
81
+ def spinner_context(
82
+ ctx: Any | None,
83
+ message: str,
84
+ *,
85
+ console_override: Console | None = None,
86
+ spinner: str = "dots",
87
+ spinner_style: str = ACCENT_STYLE,
88
+ ) -> AbstractContextManager[Any]:
89
+ """Return a context manager that renders a spinner when appropriate."""
90
+ active_console = console_override or console
91
+ if not _can_use_spinner(ctx, active_console):
92
+ return nullcontext()
93
+
94
+ status = active_console.status(
95
+ message,
96
+ spinner=spinner,
97
+ spinner_style=spinner_style,
98
+ )
99
+
100
+ if not hasattr(status, "__enter__") or not hasattr(status, "__exit__"):
101
+ return nullcontext()
102
+
103
+ return status
104
+
105
+
106
+ def _register_renderer_with_session(ctx: Any, renderer: RichStreamRenderer) -> None:
107
+ """Attach renderer to an active slash session when present."""
108
+ try:
109
+ ctx_obj = getattr(ctx, "obj", None)
110
+ session = ctx_obj.get("_slash_session") if isinstance(ctx_obj, dict) else None
111
+ if session and hasattr(session, "register_active_renderer"):
112
+ session.register_active_renderer(renderer)
113
+ except Exception:
114
+ # Never let session bookkeeping break renderer creation
115
+ pass
116
+
117
+
118
+ def build_renderer(
119
+ _ctx: Any,
120
+ *,
121
+ save_path: str | os.PathLike[str] | None,
122
+ verbose: bool = False,
123
+ _tty_enabled: bool = True,
124
+ live: bool | None = None,
125
+ snapshots: bool | None = None,
126
+ ) -> tuple[RichStreamRenderer, Console | CapturingConsole]:
127
+ """Build renderer and capturing console for CLI commands.
128
+
129
+ Args:
130
+ _ctx: Click context object for CLI operations.
131
+ save_path: Path to save output to (enables capturing console).
132
+ verbose: Whether to enable verbose mode.
133
+ _tty_enabled: Whether TTY is available for interactive features.
134
+ live: Whether to enable live rendering mode (overrides verbose default).
135
+ snapshots: Whether to capture and store snapshots.
136
+
137
+ Returns:
138
+ Tuple of (renderer, capturing_console) for streaming output.
139
+ """
140
+ # Use capturing console if saving output
141
+ working_console = CapturingConsole(console, capture=True) if save_path else console
142
+
143
+ # Configure renderer based on verbose mode and explicit overrides
144
+ live_enabled = bool(live) if live is not None else not verbose
145
+ cfg_overrides = {
146
+ "live": live_enabled,
147
+ "append_finished_snapshots": bool(snapshots) if snapshots is not None else False,
148
+ }
149
+ renderer_console = (
150
+ working_console.original_console if isinstance(working_console, CapturingConsole) else working_console
151
+ )
152
+ factory = make_verbose_renderer if verbose else make_default_renderer
153
+ factory_options = RendererFactoryOptions(
154
+ console=renderer_console,
155
+ cfg_overrides=cfg_overrides,
156
+ verbose=verbose if factory is make_default_renderer else None,
157
+ )
158
+ renderer = factory_options.build(factory)
159
+
160
+ # Link the renderer back to the slash session when running from the palette.
161
+ _register_renderer_with_session(_ctx, renderer)
162
+
163
+ return renderer, working_console
164
+
165
+
166
+ @contextmanager
167
+ def with_client_and_spinner(
168
+ ctx: Any,
169
+ spinner_message: str,
170
+ *,
171
+ console_override: Console | None = None,
172
+ ) -> Any:
173
+ """Context manager for commands that need client and spinner.
174
+
175
+ Args:
176
+ ctx: Click context.
177
+ spinner_message: Message to display in spinner.
178
+ console_override: Optional console override.
179
+
180
+ Yields:
181
+ Client instance.
182
+ """
183
+ from glaip_sdk.cli.core.context import get_client # noqa: PLC0415
184
+
185
+ client = get_client(ctx)
186
+ with spinner_context(ctx, spinner_message, console_override=console_override):
187
+ yield client
@@ -9,20 +9,27 @@ Authors:
9
9
 
10
10
  from __future__ import annotations
11
11
 
12
- import os
13
12
  import sys
14
13
  from collections.abc import Iterable
14
+ from getpass import getpass
15
15
  from typing import TYPE_CHECKING, Any
16
16
 
17
17
  from rich.console import Console
18
+ from rich.prompt import Prompt
18
19
 
19
20
  from glaip_sdk.branding import ERROR_STYLE, INFO_STYLE, SUCCESS_STYLE, WARNING_STYLE
20
21
  from glaip_sdk.cli.account_store import AccountStore, AccountStoreError, get_account_store
21
22
  from glaip_sdk.cli.commands.common_config import check_connection_with_reason
22
23
  from glaip_sdk.cli.masking import mask_api_key_display
23
- from glaip_sdk.cli.slash.accounts_shared import build_account_status_string
24
+ from glaip_sdk.cli.validators import validate_api_key
25
+ from glaip_sdk.cli.slash.accounts_shared import (
26
+ build_account_rows,
27
+ build_account_status_string,
28
+ env_credentials_present,
29
+ )
24
30
  from glaip_sdk.cli.slash.tui.accounts_app import TEXTUAL_SUPPORTED, AccountsTUICallbacks, run_accounts_textual
25
31
  from glaip_sdk.rich_components import AIPPanel, AIPTable
32
+ from glaip_sdk.utils.validation import validate_url
26
33
 
27
34
  if TYPE_CHECKING: # pragma: no cover
28
35
  from glaip_sdk.cli.slash.session import SlashSession
@@ -46,7 +53,7 @@ class AccountsController:
46
53
  def handle_accounts_command(self, args: list[str]) -> bool:
47
54
  """Handle `/accounts` with optional `/accounts <name>` quick switch."""
48
55
  store = get_account_store()
49
- env_lock = bool(os.getenv("AIP_API_URL") or os.getenv("AIP_API_KEY"))
56
+ env_lock = env_credentials_present(partial=True)
50
57
  accounts = store.list_accounts()
51
58
 
52
59
  if not accounts:
@@ -63,7 +70,7 @@ class AccountsController:
63
70
  if self._should_use_textual():
64
71
  self._render_textual(rows, store, env_lock)
65
72
  else:
66
- self._render_rich(rows, env_lock)
73
+ self._render_rich_interactive(store, env_lock)
67
74
 
68
75
  return self.session._continue_session()
69
76
 
@@ -90,24 +97,13 @@ class AccountsController:
90
97
  env_lock: bool,
91
98
  ) -> list[dict[str, str | bool]]:
92
99
  """Normalize account rows for display."""
93
- rows: list[dict[str, str | bool]] = []
94
- for name, account in sorted(accounts.items()):
95
- rows.append(
96
- {
97
- "name": name,
98
- "api_url": account.get("api_url", ""),
99
- "masked_key": mask_api_key_display(account.get("api_key", "")),
100
- "active": name == active_account,
101
- "env_lock": env_lock,
102
- }
103
- )
104
- return rows
100
+ return build_account_rows(accounts, active_account, env_lock)
105
101
 
106
102
  def _render_rich(self, rows: Iterable[dict[str, str | bool]], env_lock: bool) -> None:
107
103
  """Render a Rich snapshot with columns matching TUI."""
108
104
  if env_lock:
109
105
  self.console.print(
110
- f"[{WARNING_STYLE}]Env credentials detected (AIP_API_URL/AIP_API_KEY); switching is disabled.[/]"
106
+ f"[{WARNING_STYLE}]Env credentials detected (AIP_API_URL/AIP_API_KEY); add/edit/delete are disabled.[/]"
111
107
  )
112
108
 
113
109
  table = AIPTable(title="AIP Accounts")
@@ -129,21 +125,43 @@ class AccountsController:
129
125
 
130
126
  self.console.print(table)
131
127
 
128
+ def _render_rich_interactive(self, store: AccountStore, env_lock: bool) -> None:
129
+ """Render Rich snapshot and run linear add/edit/delete prompts."""
130
+ if env_lock:
131
+ rows = self._build_rows(store.list_accounts(), store.get_active_account(), env_lock)
132
+ self._render_rich(rows, env_lock)
133
+ return
134
+
135
+ while True: # pragma: no cover - interactive prompt loop
136
+ rows = self._build_rows(store.list_accounts(), store.get_active_account(), env_lock)
137
+ self._render_rich(rows, env_lock)
138
+ action = self._prompt_action()
139
+ if action == "q":
140
+ break
141
+ if action == "a":
142
+ self._rich_add_flow(store)
143
+ elif action == "e":
144
+ self._rich_edit_flow(store)
145
+ elif action == "d":
146
+ self._rich_delete_flow(store)
147
+ elif action == "s":
148
+ self._rich_switch_flow(store, env_lock)
149
+ else:
150
+ self.console.print(f"[{WARNING_STYLE}]Invalid choice. Use a/e/d/s/q.[/]")
151
+
132
152
  def _render_textual(self, rows: list[dict[str, str | bool]], store: AccountStore, env_lock: bool) -> None:
133
153
  """Launch the Textual accounts browser."""
134
154
  callbacks = AccountsTUICallbacks(switch_account=lambda name: self._switch_account(store, name, env_lock))
135
155
  active = next((row["name"] for row in rows if row.get("active")), None)
136
156
  run_accounts_textual(rows, active_account=active, env_lock=env_lock, callbacks=callbacks)
137
- # Exit snapshot: show active account + host after closing the TUI
157
+ # Exit snapshot: surface a success banner when a switch occurred inside the TUI
138
158
  active_after = store.get_active_account() or "default"
139
- host_after = ""
140
- account_after = store.get_account(active_after) if hasattr(store, "get_account") else None
141
- if account_after:
142
- host_after = account_after.get("api_url", "")
143
- host_suffix = f" • {host_after}" if host_after else ""
144
- self.console.print(f"[dim]Active account: {active_after}{host_suffix}[/]")
145
- # Surface a success banner when a switch occurred inside the TUI
146
159
  if active_after != active:
160
+ host_after = ""
161
+ account_after = store.get_account(active_after) if hasattr(store, "get_account") else None
162
+ if account_after:
163
+ host_after = account_after.get("api_url", "")
164
+ host_suffix = f" • {host_after}" if host_after else ""
147
165
  self.console.print(
148
166
  AIPPanel(
149
167
  f"[{SUCCESS_STYLE}]Active account ➜ {active_after}[/]{host_suffix}",
@@ -215,3 +233,268 @@ class AccountsController:
215
233
  code, _, detail = reason.partition(":")
216
234
  return code.strip(), detail.strip()
217
235
  return reason.strip(), ""
236
+
237
+ def _prompt_action(self) -> str:
238
+ """Prompt for add/edit/delete/quit action."""
239
+ try:
240
+ choice = Prompt.ask("(a)dd / (e)dit / (d)elete / (s)witch / (q)uit", default="q")
241
+ except Exception: # pragma: no cover - defensive around prompt failures
242
+ return "q"
243
+ return (choice or "").strip().lower()[:1]
244
+
245
+ def _prompt_yes_no(self, prompt: str, *, default: bool = True) -> bool:
246
+ """Prompt a yes/no question with a default."""
247
+ default_str = "Y/n" if default else "y/N"
248
+ try:
249
+ answer = Prompt.ask(f"{prompt} ({default_str})", default="y" if default else "n")
250
+ except Exception: # pragma: no cover - defensive around prompt failures
251
+ return default
252
+ normalized = (answer or "").strip().lower()
253
+ if not normalized:
254
+ return default
255
+ return normalized in {"y", "yes"}
256
+
257
+ def _prompt_account_name(self, store: AccountStore, *, for_edit: bool) -> str | None:
258
+ """Prompt for an account name, validating per store rules."""
259
+ while True: # pragma: no cover - interactive prompt loop
260
+ name = self._get_name_input(for_edit)
261
+ if name is None:
262
+ return None
263
+ if not name:
264
+ self.console.print(f"[{WARNING_STYLE}]Name is required.[/]")
265
+ continue
266
+ if not self._validate_name_format(store, name):
267
+ continue
268
+ if not self._validate_name_existence(store, name, for_edit):
269
+ continue
270
+ return name
271
+
272
+ def _get_name_input(self, for_edit: bool) -> str | None:
273
+ """Get account name input from user."""
274
+ try:
275
+ prompt_text = "Account name" + (" (existing)" if for_edit else "")
276
+ name = Prompt.ask(prompt_text)
277
+ return name.strip() if name else None
278
+ except Exception:
279
+ return None
280
+
281
+ def _validate_name_format(self, store: AccountStore, name: str) -> bool:
282
+ """Validate account name format."""
283
+ try:
284
+ store.validate_account_name(name)
285
+ return True
286
+ except Exception as exc:
287
+ self.console.print(f"[{ERROR_STYLE}]{exc}[/]")
288
+ return False
289
+
290
+ def _validate_name_existence(self, store: AccountStore, name: str, for_edit: bool) -> bool:
291
+ """Validate account name existence based on mode."""
292
+ account_exists = store.get_account(name) is not None
293
+ if not for_edit and account_exists:
294
+ self.console.print(
295
+ f"[{WARNING_STYLE}]Account '{name}' already exists. Use edit instead or choose a new name.[/]"
296
+ )
297
+ return False
298
+ if for_edit and not account_exists:
299
+ self.console.print(f"[{WARNING_STYLE}]Account '{name}' not found. Try again or quit.[/]")
300
+ return False
301
+ return True
302
+
303
+ def _prompt_api_url(self, existing_url: str | None = None) -> str | None:
304
+ """Prompt for API URL with HTTPS validation."""
305
+ placeholder = existing_url or "https://your-aip-instance.com"
306
+ while True: # pragma: no cover - interactive prompt loop
307
+ try:
308
+ entered = Prompt.ask("API URL", default=placeholder)
309
+ except Exception:
310
+ return None
311
+ url = (entered or "").strip()
312
+ if not url and existing_url:
313
+ return existing_url
314
+ if not url:
315
+ self.console.print(f"[{WARNING_STYLE}]API URL is required.[/]")
316
+ continue
317
+ try:
318
+ return validate_url(url)
319
+ except Exception as exc:
320
+ self.console.print(f"[{ERROR_STYLE}]{exc}[/]")
321
+
322
+ def _prompt_api_key(self, existing_key: str | None = None) -> str | None:
323
+ """Prompt for API key (masked)."""
324
+ mask_hint = "leave blank to keep current" if existing_key else None
325
+ while True: # pragma: no cover - interactive prompt loop
326
+ try:
327
+ entered = getpass(f"API key ({mask_hint or 'input hidden'}): ")
328
+ except Exception:
329
+ return None
330
+ if not entered and existing_key:
331
+ return existing_key
332
+ if not entered:
333
+ self.console.print(f"[{WARNING_STYLE}]API key is required.[/]")
334
+ continue
335
+ try:
336
+ return validate_api_key(entered)
337
+ except Exception as exc:
338
+ self.console.print(f"[{ERROR_STYLE}]{exc}[/]")
339
+
340
+ def _rich_add_flow(self, store: AccountStore) -> None:
341
+ """Run Rich add prompts and save."""
342
+ name = self._prompt_account_name(store, for_edit=False)
343
+ if not name:
344
+ return
345
+ api_url = self._prompt_api_url()
346
+ if not api_url:
347
+ return
348
+ api_key = self._prompt_api_key()
349
+ if not api_key:
350
+ return
351
+ should_test = self._prompt_yes_no("Test connection before save?", default=True)
352
+ self._save_account(store, name, api_url, api_key, should_test, True, is_edit=False)
353
+
354
+ def _rich_edit_flow(self, store: AccountStore) -> None:
355
+ """Run Rich edit prompts and save."""
356
+ name = self._prompt_account_name(store, for_edit=True)
357
+ if not name:
358
+ return
359
+ existing = store.get_account(name) or {}
360
+ api_url = self._prompt_api_url(existing.get("api_url"))
361
+ if not api_url:
362
+ return
363
+ api_key = self._prompt_api_key(existing.get("api_key"))
364
+ if not api_key:
365
+ return
366
+ should_test = self._prompt_yes_no("Test connection before save?", default=True)
367
+ self._save_account(store, name, api_url, api_key, should_test, False, is_edit=True)
368
+
369
+ def _rich_switch_flow(self, store: AccountStore, env_lock: bool) -> None:
370
+ """Run Rich switch prompt and set active account."""
371
+ name = self._prompt_account_name(store, for_edit=True)
372
+ if not name:
373
+ return
374
+ self._switch_account(store, name, env_lock)
375
+
376
+ def _save_account(
377
+ self,
378
+ store: AccountStore,
379
+ name: str,
380
+ api_url: str,
381
+ api_key: str,
382
+ should_test: bool,
383
+ set_active: bool,
384
+ *,
385
+ is_edit: bool,
386
+ ) -> None:
387
+ """Validate, optionally test, and persist account changes."""
388
+ if should_test and not self._run_connection_test_with_retry(api_url, api_key):
389
+ return
390
+
391
+ try:
392
+ store.add_account(name, api_url, api_key, overwrite=is_edit)
393
+ except AccountStoreError as exc:
394
+ self.console.print(f"[{ERROR_STYLE}]Save failed: {exc}[/]")
395
+ return
396
+ except Exception as exc:
397
+ self.console.print(f"[{ERROR_STYLE}]Unexpected error while saving: {exc}[/]")
398
+ return
399
+
400
+ self.console.print(f"[{SUCCESS_STYLE}]Account '{name}' saved.[/]")
401
+ if set_active:
402
+ try:
403
+ store.set_active_account(name)
404
+ except Exception as exc:
405
+ self.console.print(f"[{WARNING_STYLE}]Account saved but could not set active: {exc}[/]")
406
+ else:
407
+ self._announce_active_change(store, name)
408
+
409
+ def _confirm_delete_prompt(self, name: str) -> bool:
410
+ """Ask for delete confirmation; return True when confirmed."""
411
+ self.console.print(f"[{WARNING_STYLE}]Type '{name}' to confirm deletion. This cannot be undone.[/]")
412
+ while True: # pragma: no cover - interactive prompt loop
413
+ confirmation = Prompt.ask("Confirm name (or blank to cancel)", default="")
414
+ if confirmation is None or not confirmation.strip():
415
+ self.console.print(f"[{WARNING_STYLE}]Deletion cancelled.[/]")
416
+ return False
417
+ if confirmation.strip() != name:
418
+ self.console.print(f"[{WARNING_STYLE}]Name does not match; type '{name}' to confirm.[/]")
419
+ continue
420
+ return True
421
+
422
+ def _delete_account_and_notify(self, store: AccountStore, name: str, active_before: str | None) -> None:
423
+ """Remove account with error handling and announce active change."""
424
+ try:
425
+ store.remove_account(name)
426
+ except AccountStoreError as exc:
427
+ self.console.print(f"[{ERROR_STYLE}]Delete failed: {exc}[/]")
428
+ return
429
+ except Exception as exc:
430
+ self.console.print(f"[{ERROR_STYLE}]Unexpected error while deleting: {exc}[/]")
431
+ return
432
+
433
+ self.console.print(f"[{SUCCESS_STYLE}]Account '{name}' deleted.[/]")
434
+ # Announce active account change if it changed
435
+ active_after = store.get_active_account()
436
+ if active_after is not None and active_after != active_before:
437
+ self._announce_active_change(store, active_after)
438
+ elif active_after is None and active_before == name:
439
+ self.console.print(f"[{WARNING_STYLE}]No account is currently active. Select an account to activate it.[/]")
440
+
441
+ def _rich_delete_flow(self, store: AccountStore) -> None:
442
+ """Run Rich delete prompts with name confirmation."""
443
+ name = self._prompt_account_name(store, for_edit=True)
444
+ if not name:
445
+ return
446
+
447
+ # Check if this is the last remaining account before prompting for confirmation
448
+ accounts = store.list_accounts()
449
+ if len(accounts) <= 1 and name in accounts:
450
+ self.console.print(f"[{WARNING_STYLE}]Cannot remove the last remaining account.[/]")
451
+ return
452
+
453
+ if not self._confirm_delete_prompt(name):
454
+ return
455
+
456
+ # Re-check after confirmation prompt (race condition guard)
457
+ accounts = store.list_accounts()
458
+ if len(accounts) <= 1 and name in accounts:
459
+ self.console.print(f"[{WARNING_STYLE}]Cannot remove the last remaining account.[/]")
460
+ return
461
+
462
+ active_before = store.get_active_account()
463
+ self._delete_account_and_notify(store, name, active_before)
464
+
465
+ def _format_connection_failure(self, code: str, detail: str, api_url: str) -> str:
466
+ """Build a user-facing connection failure message."""
467
+ detail_suffix = f": {detail}" if detail else ""
468
+ if code == "connection_failed":
469
+ return f"Connection test failed: cannot reach {api_url}{detail_suffix}"
470
+ if code == "api_failed":
471
+ return f"Connection test failed: API error{detail_suffix}"
472
+ return f"Connection test failed{detail_suffix}"
473
+
474
+ def _run_connection_test_with_retry(self, api_url: str, api_key: str) -> bool:
475
+ """Run connection test with retry/skip prompts."""
476
+ skip_prompt_shown = False
477
+ while True:
478
+ ok, reason = check_connection_with_reason(api_url, api_key, abort_on_error=False)
479
+ if ok:
480
+ return True
481
+ code, detail = self._parse_error_reason(reason)
482
+ message = self._format_connection_failure(code, detail, api_url)
483
+ self.console.print(f"[{WARNING_STYLE}]{message}[/]")
484
+ retry = self._prompt_yes_no("Retry connection test?", default=True)
485
+ if retry:
486
+ continue
487
+ if not skip_prompt_shown:
488
+ skip_prompt_shown = True
489
+ skip = self._prompt_yes_no("Skip connection test and save?", default=False)
490
+ if skip:
491
+ return True
492
+ self.console.print(f"[{WARNING_STYLE}]Cancelled save after failed connection test.[/]")
493
+ return False
494
+
495
+ def _announce_active_change(self, store: AccountStore, name: str) -> None:
496
+ """Print active account change announcement."""
497
+ account = store.get_account(name) or {}
498
+ host = account.get("api_url", "")
499
+ host_suffix = f" • {host}" if host else ""
500
+ self.console.print(f"[{SUCCESS_STYLE}]Active account ➜ {name}{host_suffix}[/]")
@@ -6,14 +6,70 @@ Authors:
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ import os
9
10
  from typing import Any
10
11
 
12
+ from glaip_sdk.cli.masking import mask_api_key_display
13
+
11
14
 
12
15
  def build_account_status_string(row: dict[str, Any], *, use_markup: bool = False) -> str:
13
- """Build status string for an account row (active/env-lock)."""
16
+ """Build status string for an account row (active/env-lock).
17
+
18
+ When `use_markup` is True, returns Rich markup strings for Textual/Rich rendering;
19
+ when False, returns plain text for console output.
20
+
21
+ Example:
22
+ build_account_status_string({"active": True, "env_lock": True}, use_markup=True)
23
+ returns "[bold green]● active[/] · [yellow]🔒 env-lock[/]"
24
+ use_markup=False returns "● active · 🔒 env-lock"
25
+ """
14
26
  status_parts: list[str] = []
15
27
  if row.get("active"):
16
28
  status_parts.append("[bold green]● active[/]" if use_markup else "● active")
17
29
  if row.get("env_lock"):
18
30
  status_parts.append("[yellow]🔒 env-lock[/]" if use_markup else "🔒 env-lock")
19
31
  return " · ".join(status_parts)
32
+
33
+
34
+ def env_credentials_present(*, partial: bool = False) -> bool:
35
+ """Return True when env credentials are present.
36
+
37
+ Args:
38
+ partial: When True, treat either AIP_API_URL or AIP_API_KEY as present
39
+ (used by UIs that should lock on any env override). When False,
40
+ require both to be non-empty (used for context display).
41
+ """
42
+ api_url = (os.getenv("AIP_API_URL") or "").strip()
43
+ api_key = (os.getenv("AIP_API_KEY") or "").strip()
44
+ if partial:
45
+ return bool(api_url or api_key)
46
+ return bool(api_url and api_key)
47
+
48
+
49
+ def build_account_rows(
50
+ accounts: dict[str, dict[str, str]],
51
+ active_account: str | None,
52
+ env_lock: bool,
53
+ ) -> list[dict[str, str | bool]]:
54
+ """Build account rows for display from accounts dict.
55
+
56
+ Args:
57
+ accounts: Dictionary mapping account names to account data.
58
+ active_account: Name of the currently active account.
59
+ env_lock: Whether environment credentials are locking account switching.
60
+
61
+ Returns:
62
+ List of account row dictionaries with name, api_url, masked_key, active, and env_lock.
63
+ """
64
+ rows: list[dict[str, str | bool]] = []
65
+ for name, account in sorted(accounts.items()):
66
+ rows.append(
67
+ {
68
+ "name": name,
69
+ "api_url": account.get("api_url", ""),
70
+ "masked_key": mask_api_key_display(account.get("api_key", "")),
71
+ "active": name == active_account,
72
+ "env_lock": env_lock,
73
+ }
74
+ )
75
+ return rows