
    sjs                    0   d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZmZ ddlmZ ddlmZ ddlmZ d	Zdd
lmZmZmZmZ ddlmZ d Zd6dZd7dZd8dZd8dZ d8dZ!d8dZ"d8dZ#d8dZ$d9d Z%d:d#Z&d$d%d;d+Z'd$d%d<d/Z(d0d1gZ)d=d5Z*dS )>u  CLI handlers for ``hermes secrets bitwarden ...``.

Subcommands:
    setup    — interactive wizard: install bws, prompt for token + project, test fetch
    status   — show current config + binary version + token validation status
    sync     — run a fetch right now and show what would be applied (dry-run friendly)
    disable  — flip ``secrets.bitwarden.enabled`` to False
    install  — just download the bws binary (no token / project required)
    )annotationsN)Path)ListOptional)Console)Panel)Tablez2.0.0)get_env_pathload_configsave_configsave_env_value)masked_secret_promptc                     ddl m}  | S )zHImport ``agent.secret_sources.bitwarden`` on first use (crypto payload).r   )	bitwarden)agent.secret_sourcesr   )_bws    :/home/agent/.hermes/hermes-agent/hermes_cli/secrets_cli.py_load_bwr   1   s    555555J    namestrc                ^    | dk    rt                      S t          dt          d|           )u  PEP 562 module-level lazy resolver.

    Existing callers (and upstream tests) monkeypatch attributes on
    ``hermes_cli.secrets_cli.bw`` directly.  Resolving that attribute at
    module-import time would re-import ``cryptography`` eagerly — the very
    self-lock we are preventing (#86781).  Defer the backend import until
    the first actual attribute access, so ``import hermes_cli.secrets_cli``
    stays crypto-free while ``secrets_cli.bw.find_bws`` still resolves.
    bwzmodule z has no attribute )r   AttributeError__name__)r   s    r   __getattr__r   8   s6     t||zz
I8IIII
J
JJr   parent_parserargparse.ArgumentParserreturnNonec                   |                      d          }|                    dd          }|                    dd           |                    dd	           |                    d
d           |                    t                     |                    dd          }|                    t
                     |                    dd          }|                    dd           |                    ddd           |                    t                     |                    dd          }|                    ddd           |                    t                     |                    dd          }|                    t                     |                    ddt           d          }|                    ddd            |                    t                     d!S )"zAttach the ``bitwarden`` subcommand tree to a parent parser.

    Called from ``hermes_cli.main`` as part of building the top-level
    ``hermes secrets`` parser.
    secrets_bw_command)destsetupzAInteractive wizard: install bws, store access token, pick project)help--project-idz.Pre-select a project UUID instead of prompting--access-tokenzCProvide the access token non-interactively (will be stored in .env)--server-urlzBitwarden region / self-hosted endpoint. Examples: https://vault.bitwarden.com (US, default), https://vault.bitwarden.eu (EU), or your self-hosted URL. Skips the interactive region prompt.)funcstatusz.Show config + binary + token validation statustokenz@Rotate the access token: validate a new one and store it in .envz@Provide the new token non-interactively (default: masked prompt)z--no-verify
store_truez7Store without probing Bitwarden first (not recommended))actionr%   syncz)Fetch secrets now and report what changedz--applyzKActually export the secrets into the current shell's env (default: dry-run)disablez"Turn off the Bitwarden integrationinstallz,Download and verify the pinned bws binary (v)z--forcez1Re-download even if a managed copy already existsN)add_subparsers
add_parseradd_argumentset_defaults	cmd_setup
cmd_status	cmd_tokencmd_synccmd_disable_BWS_VERSIONcmd_install)r   subr$   r*   r+   r.   r/   r0   s           r   register_clir>   L   sp    
&
&,@
&
A
ACNNP   E 
=     
R     
3     
I&&&^^=   F Z(((NNO   E 
O     
F    
 
I&&&>>&'R>SSDZ    
 	8$$$nnY-QnRRGk***nnKLKKK   G @    
 k*****r   argsargparse.Namespaceintc           	        t                      }t                      }|                    t          j        dd                     |                                 |                    d           	 |                    d          }|)|                    d           |                                }t          |          }|                    d| d	| d
           nF# t          $ r9}|                    d| d           |                    d           Y d }~dS d }~ww xY wt          j
                                        sg }| j        r| j                                        s|                    d           | j        r| j                                        sGt           j                            dd                                          s|                    d           | j        r| j                                        s|                    d           |r.|                    dd                    |           d           dS |                                 |                    d           t+                      }|                    di                               di           }|                    dd          }	| j        pd                                }
|
s%t/          d|	 d                                          }
|
s|                    d           dS |
                    d          s|                    d            t3          |	|
           |
t           j        |	<   |                    d!t5                       d"|	            |                                 |                    d#           t7          | ||          }|dS |r|                    d$|            n|                    d%           | j        r4| j                                        r| j                                        }n|                                 |                    d&           d}t9          ||
||'          }|dS |s,|                    d(           |                    d)           dS t;          d*d+,          }|                    d-dd./           |                    d0           |                    d1d23           t?          |d          D ]Q\  }}|                     tC          |          |                    d4d5          |                    d6d5                     R|                    |           	 |"                    d7tG          |           d8                                          }|s<	 tI          |          }n%# tJ          $ r |                    d9           Y nw xY wd|cxk    rtG          |          k    rn n||dz
           d6         }n'|                    d:tG          |           d;           |                                 | j        r| j                                        sd<nd.}|                    d=| d>           	 |&                    |
||d|?          \  }}n1# t          $ r$}|                    d@| d           Y d }~dS d }~ww xY w|s|                    dA           nt;          d*d+,          }|                    d0d3           |                    dB           tO          |          D ]E}||	k    rdC}n$t           j                            |          rdD}ndE}|                     ||           F|                    |           |D ]}|                    dF|            d*|dG<   ||dH<   ||dI<   |                    d|	           |                    dJdK           |                    dLd*           |                    dMd*           tQ          |           |                                 |                    dN           |                    dO           dPS )QNu  [bold]Bitwarden Secrets Manager setup[/bold]

Need an access token? In the Bitwarden web app:
  Secrets Manager → Machine accounts → [your account] →
  Access tokens → Create access token

Copy the token (starts with [cyan]0.[/cyan]…) — it cannot be retrieved later.cyan)border_stylez([bold]Step 1[/bold]  Install the bws CLIFinstall_if_missingu#     No bws on PATH — downloading…u     [green]✓[/green]   (r1   u"     [red]✗ Could not install bws: [/red]z>  Manual install: https://github.com/bitwarden/sdk-sm/releases   r'   BWS_SERVER_URL r(   r&   zP  [red]Non-interactive mode (no TTY) requires all setup flags.[/red]
  Missing: z, z

  Usage:
    hermes secrets bitwarden setup \
      --access-token '0.xxx' \
      --server-url 'https://vault.bitwarden.com' \
      --project-id 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'z.[bold]Step 2[/bold]  Provide your access tokensecretsr   access_token_envBWS_ACCESS_TOKENz  Paste access token (): z#  [red]Empty token, aborting.[/red]0.     [yellow]Warning: token doesn't start with '0.' — usually that means you pasted something other than a BSM access token.  Continuing anyway.[/yellow]u     [green]✓[/green] stored in  as z,[bold]Step 3[/bold]  Pick a Bitwarden regionu     [green]✓[/green] using uN     [green]✓[/green] using bws default (US Cloud, https://vault.bitwarden.com)z#[bold]Step 4[/bold]  Pick a project
server_urlz?  [yellow]No projects visible to this machine account.[/yellow]ur     In the Bitwarden web app, open the machine account → Projects tab and grant it access to at least one project.Tboldshow_headerheader_style#   stylewidthNameIDdimr\   r   ?idz  Select project [1-z]:   [red]Enter a number.[/red]     [red]Out of range — pick 1-.[/red]   z[bold]Step z[/bold]  Test fetch)access_token
project_idbinary	use_cacherT   u     [red]✗ Fetch failed: zB  [yellow]Fetch succeeded but the project has no secrets.[/yellow]Statusu5   [dim]bootstrap token — never overrides itself[/dim]z9[yellow]already set in env (will be overwritten)[/yellow]z[green]new[/green]z  [yellow]warning:[/yellow] enabledri   rT   cache_ttl_seconds,  override_existingauto_installuv   [green]✓ Bitwarden Secrets Manager is enabled.[/green]  Secrets will be pulled at the start of every Hermes process.z  Status:  [cyan]hermes secrets bitwarden status[/cyan]
  Refresh: [cyan]hermes secrets bitwarden sync[/cyan]
  Disable: [cyan]hermes secrets bitwarden disable[/cyan]r   ))r   r   printr   fitfind_bwsinstall_bws_bws_version	Exceptionsysstdinisattyrh   stripappendrT   osenvirongetri   joinr   
setdefaultr   
startswithr   r
   _resolve_server_url_list_projectsr	   
add_column	enumerateadd_rowr   inputlenrA   
ValueErrorfetch_bitwarden_secretssortedr   )r?   r   consolerj   versionexcmissingcfgsecrets_cfg	token_envr+   rT   ri   projectstableipchoiceidxstep_numrL   warningskeyr*   ws                            r   r6   r6      sC	   	BiiGMM	`
  	
 	
 	
	 	 	 MMOOOMM<===66>MM?@@@^^%%Fv&&CfCCCCCDDDD   F3FFFGGG;	
 	
 	
 qqqqq 9 ! 	-d&7&=&=&?&? 	-NN+,,, 	/DO$9$9$;$; 	/:>>"2B77==?? /~... 	+DO$9$9$;$; 	+NN>*** 
	MML"ii00L L L   1 MMOOOMMBCCC
--C>>)R00 jb11  24FGGI$"++--E V$%Li%L%L%LMMSSUU ;<<<qD!! 
_	
 	
 	

 9e$$$!BJyMMSLNNSS	SSTTT MMOOOMM@AAA$T;@@Jq 
@J@@AAAA6	
 	
 	
  %T4?0022 %T_**,,

;<<<
!&%ZPPP1 	MM[\\\MM?   1$V<<<F!444   U+++h** 	H 	HDAqMM#a&&!%%"4"4aeeD#6F6FGGGGe	T]]#L#h--#L#L#LMMSSUUF &kk   <=== C((((3x==(((((%cAg.t4
MMRCMMRRRSSS	T MMOOOLT_-B-B-D-DLqq1HMM====>>>
66!! 7 
 
    =#===>>>qqqqq  Z[[[[$V<<<v..."""'?? 	' 	'CiP$$ .T-MM#v&&&&e : :8Q889999 "K	 *K *K-y999.444.555>4000MMOOOMM	G   MM	C  
 1sC   0A,C 
D '.DD )V9 9WWZ$ $
[.[[c                l   t                      }t                      }t                      }|                    d          pi                     d          pi }t	          |                    d                    }|                    dd          }|                    dd          }t          |                    dd          pd                                          }t          j                            |d                                          }	t	          |	          }
|	                    d	
          }t          |||	|          \  }}t          d	d d          }|                    dd           |                    d           |                    dt          |                     |                    d|           |                    dt          |
                     |                    d|           |                    d|pd           |                    d|pd           |                    dt          t	          |                    dd	                                         |                    dt          |                    dd                               |                    dt          t	          |                    dd                                         |r*|                    d | d!t          |           d"           n|                    d d#           |                    t#          |d$d%&                     |D ]}|                    |           |s|                    d'           d(S |
s|                    d)| d*           |s|                    d+           d(S ),NrL   r   rm   rM   rN   ri   rK   rT   FrE   )rm   rj   r+   rT   r      )rW   boxpaddingrU   ra   EnabledzToken env varzToken in envzToken validationz
Project IDz[dim](unset)[/dim]z
Server URLz:[dim]default (US Cloud, https://vault.bitwarden.com)[/dim]zOverride existingrp   zCache TTL (s)rn   ro   zAuto-installrq   Tz
bws binaryz (r1   z[yellow]not installed[/yellow]zBitwarden Secrets ManagerrC   )titlerD   z=
  Run [cyan]hermes secrets bitwarden setup[/cyan] to enable.r   z
  [yellow]Enabled but uG    is not set — Hermes will skip BSM and warn on next startup.[/yellow]uC   
  [yellow]Enabled but no project_id — nothing to fetch.[/yellow])r   r   r   r   boolr   r{   r}   r~   rt   _token_validation_statusr	   r   r   _ynrv   rr   r   )r?   r   r   r   bw_cfgrm   r   ri   rT   r+   	token_setrj   token_validationvalidation_messagesr   messages                   r   r7   r7   Z  s   	BiiG
--Cggi  &B++K88>BF6::i(())G

-/ABBIL"--JVZZb117R88>>@@JJNN9b))//11EUI[[E[22F,D	- - -)) ev>>>E	Rv&&&	R	MM)S\\222	MM/Y///	MM.S^^444	MM$&6777	MM,Z%G3GHHH	MMRR   
MM%s4

;NPU0V0V+W+W'X'XYYY	MM/S4G)M)M%N%NOOO	MM.Sfjj.N.N)O)O%P%PQQQ Gl%I%I,v2F2F%I%I%IJJJJl%EFFFMM%%@vVVVWWW&  g VWWWq 
1y 1 1 1	
 	
 	
  
R	
 	
 	
 1r   c                   t                      }t                      }t                      }|                    d          pi                     d          pi }|                    dd          }t	          |                    dd          pd                                          }| j        pd                                }|sot          j        	                                s|
                    d           dS |
                    d	           t          d
| d                                          }|s|
                    d           dS |                    d          s|
                    d           | j        s|                    d          }||
                    d           dS |
                    d           t          ||||          }	|	|
                    d           dS |
                    dt!          |	           dt!          |	          dk    rdnd d           t	          |                    dd          pd          }
|
r)|	r'|
d |	D             vr|
                    d|
 d           t#          ||           |t$          j        |<   |                                 |
                    dt+                       d| d            |                    d!          s|
                    d"           d#S )$u-  Rotate the BSM access token without re-running the whole setup wizard.

    Prompts for (or accepts via ``--access-token``) a new machine-account
    token, probes Bitwarden with it (unless ``--no-verify``), and only then
    persists it to .env — so a bad paste never bricks the working token.
    rL   r   rM   rN   rT   rK   u9   [red]No TTY — pass the token with --access-token.[/red]rI   u   Create a new token in the Bitwarden web app:
  Secrets Manager → Machine accounts → [your account] → Access tokens → Create access token
zPaste new access token (rO   z![red]Empty token, aborting.[/red]rP   u   [yellow]Warning: token doesn't start with '0.' — usually that means you pasted something other than a BSM access token.[/yellow]TrE   Nu`   [red]bws binary not available — cannot verify.  Re-run with --no-verify to store anyway.[/red]u   Verifying against Bitwarden…rS   u>   [red]✗ New token was rejected — nothing was changed.[/red]u#   [green]✓ Token accepted[/green] (z projectsz
 visible).ri   c                    h | ]
}|d          S rc    .0r   s     r   	<setcomp>zcmd_token.<locals>.<setcomp>  s    9T9T9Ta!D'9T9T9Tr   z$[yellow]Warning: configured project z is not visible to this machine account.  Grant it access in the Bitwarden web app or re-run `hermes secrets bitwarden setup` to pick a different project.[/yellow]u   [green]✓[/green] stored in rR   z..  Takes effect on the next Hermes invocation.rm   u   [yellow]Note: the Bitwarden integration is currently disabled — run `hermes secrets bitwarden setup` (or set secrets.bitwarden.enabled: true) to turn it on.[/yellow]r   )r   r   r   r   r   r{   rh   rx   ry   rz   rr   r   r   	no_verifyrt   r   r   r   r}   r~   clear_cachesr
   )r?   r   r   r   r   r   rT   r+   rj   r   ri   s              r   r8   r8     s    
BiiG
--Cggi  &B++K88>BF

-/ABBIVZZb117R88>>@@J$"++--E Xy!! 	MMK   16	
 	
 	

 %%N	%N%N%NOOUUWW 9:::qD!! 
K	
 	
 	

 > 55>MMA   16777!&%ZPPPMMP   1UHU U.1(mmq.@.@ssbU U U	
 	
 	
 L"55;<<
 	( 	z9T9T89T9T9T'T'TMM.z . . .   9e$$$!BJy OOMM	6 	6 	6I 	6 	6 	6   ::i   
G	
 	
 	

 1r   c                   t                      }t                      }t                      }|                    d          pi                     d          pi }|                    d          s|                    d           dS |                    dd          }t
          j                            |d                                          }|s|                    d	| d
           dS |                    dd          }|s|                    d           dS t          |                    dd          pd                                          }	 |	                    ||d|          \  }	}
n1# t          $ r$}|                    d| d           Y d }~dS d }~ww xY w|	s|                    d           dS t          |                    dd                    p| j        }t          dd          }|                    dd           |                    d           d}t          |	          D ]}||k    r|                    |d           t          t
          j                            |                    }|r|s|                    |d           f| j        r8|	|         t
          j        |<   |dz  }|                    |d|rdndz              |                    |d |rd!ndz              |                    |           |
D ]}|                    d"|            | j        s|                    d#           n|                    d$| d%           dS )&NrL   r   rm   z`[yellow]Bitwarden integration is disabled.  Run `hermes secrets bitwarden setup` first.[/yellow]rI   rM   rN   rK   z[red]z is not set.[/red]ri   z$[red]No project_id configured.[/red]rT   F)rh   ri   rk   rT   z[red]Fetch failed: rH   z'[yellow]No secrets in project.[/yellow]r   rp   TrU   rV   r^   rC   ra   Actionz![dim]skip (bootstrap token)[/dim]z[dim]skip (already set)[/dim]z[green]exported[/green]z (overrode)z[green]would export[/green]z (overrides)z[yellow]warning:[/yellow] u   
  This was a dry-run — secrets are picked up automatically on the next [cyan]hermes[/cyan] invocation.  Re-run with [cyan]--apply[/cyan] to export into the current shell instead.z
  [green]Exported z( secret(s) into current process.[/green])r   r   r   r   rr   r}   r~   r{   r   r   rw   r   applyr	   r   r   r   )r?   r   r   r   r   r   r+   ri   rT   rL   r   r   overrider   appliedr   alreadyr   s                     r   r9   r9     s   	BiiG
--Cggi  &B++K88>BF::i   ?	
 	
 	
 q

-/ABBIJNN9b))//11E ;i;;;<<<qL"--J <===qVZZb117R88>>@@J	66!!	 7 
 
    7C777888qqqqq  ?@@@qFJJ2E::;;ItzHd888E	V6***	XGg d d)MM#BCCCrz~~c**++ 	8 	MM#>???: 	d%clBJsOqLGMM#8W<\MMZ\]^^^^MM#<RY@a_abccccMM% 8 861667777: `8	
 	
 	
 	
 	^W^^^___1s   E, ,
F6FFc                    t                      }t                      }|                    di                               di           }d|d<   t          |           |                    d           dS )NrL   r   Frm   u   [green]Disabled.[/green]  Bitwarden secrets will NOT be pulled on the next Hermes invocation.
  Your access token is left in .env — remove it manually if you also want to revoke the credential.r   )r   r   r   r   rr   )r?   r   r   r   s       r   r:   r:   3  ss    iiG
--CnnY++K,, F9MM	$   1r   c                D   t                      }t                      }	 |                    t          | j                            }|                    d| dt          |           d           dS # t          $ r$}|                    d| d           Y d }~dS d }~ww xY w)	N)forceu   [green]✓[/green] rG   r1   r   z[red]Install failed: rH   rI   )r   r   ru   r   r   rr   rv   rw   )r?   r   r   pathr   s        r   r<   r<   C  s    	BiiG~~D$4$4~55JDJJ\$5G5GJJJKKKq   9c999:::qqqqqs   AA1 1
B;BBbr   c                    | rdndS )Nz[green]yes[/green]z[dim]no[/dim]r   )r   s    r   r   r   T  s    #$9/9r   rj   r   c                   	 t          j        t          |           dgddddd          }|j        dk    r8|j        p|j                                                                        d         S n# t          t           j	        f$ r Y nw xY wdS )	Nz	--versionTutf-8replacerg   )capture_outputtextencodingerrorstimeoutr   zversion unknown)

subprocessrunr   
returncodestdoutstderrr{   
splitlinesOSErrorTimeoutExpired)rj   ress     r   rv   rv   X  s    
n[[+&		
 
 
 >QJ,#*3355@@BB1EE Z./   s   A+A/ /BBrK   rS   rm   Optional[Path]r+   rT   tuple[str, list[str]]c                   | sdg fS |sdg fS |dg fS g }|                     d          s|                    d           t          j                    }t	          |dd          }t          ||||	          }|_|                    d
                                          }|r1|                    d |	                                D                        d|fS d|fS )Nz-[dim]not checked[/dim] (integration disabled)z&[dim]not checked[/dim] (token missing)z*[dim]not checked[/dim] (bws not installed)rP   rQ   T   )filerecordr]   rS   F)stylesc              3  >   K   | ]}|                                 V  d S )N)rstrip)r   lines     r   	<genexpr>z+_token_validation_status.<locals>.<genexpr>  s*      KKdDKKMMKKKKKKr   z[red]failed[/red]z[green]passed[/green])
r   r|   ioStringIOr   r   export_textr{   extendr   )	rm   rj   r+   rT   messagescaptureprobe_consoler   detailss	            r   r   r   g  s     C>BB <7;;~;R??HD!! 
_	
 	
 	

 kmmGSAAAMfe]zRRRH++5+99??AA 	LOOKKg6H6H6J6JKKKKKK"H,,"H,,r   r   r   Optional[List[dict]]c          	     j   ddl m}  |dd          }||d<   |                    dd           |r||d<   	 t          j        t          |           d	d
ddg|ddddd          }n=# t          t          j        f$ r$}|                    d| d           Y d}~dS d}~ww xY w|j	        dk    r|j
        p|j                                        dd         }|                    d| d           |                                }	d|	v sd|	v r|                    d           nd|	v sd|	v r|                    d           dS 	 t          j        |j        pd          }
n6# t          j        $ r$}|                    d| d           Y d}~dS d}~ww xY wt#          |
t$                    sg S d |
D             S ) zICall ``bws project list`` and return the parsed list, or None on failure.r   )build_subprocess_envF)scrub_secretsinherit_profile_homerN   NO_COLOR1rJ   projectlistz--outputjsonTr   r      )envr   r   r   r   r   z  [red]Couldn't list projects: rH   Nro   z   [red]bws project list failed: invalid_clientz400 bad requesta$    [yellow]'invalid_client' from the US identity endpoint usually means the token is for a different Bitwarden region.  Re-run [cyan]hermes secrets bitwarden setup[/cyan] and pick EU or self-hosted at the region prompt, or set [cyan]secrets.bitwarden.server_url[/cyan] in config.yaml.[/yellow]authorizationinvalidzu  [yellow]This usually means the access token is wrong or revoked. Double-check it in the Bitwarden web app.[/yellow]z[]z  [red]bws returned non-JSON: c                f    g | ].}t          |t                    |                    d           ,|/S r   )
isinstancedictr   r   s     r   
<listcomp>z"_list_projects.<locals>.<listcomp>  s6    CCC!z!T22CquuT{{CACCCr   )tools.environments.localr   r   r   r   r   r   r   rr   r   r   r   r{   lowerr   loadsJSONDecodeErrorr   r   )rj   r+   r   rT   r   r   r   r   errlowereddatas              r   r   r     sV    >=====

U
O
O
OC#CNN:s### + *
n[[)VZ@	
 
 
 Z./   CCCCDDDttttt ~z'SZ..00#6DDDDEEE))++w&&*;w*F*FMM=    ''9+?+?MME   tz#*,--   BsBBBCCCttttt dD!! 	CCtCCCCs/   -A% %B;BB E F+F

F)u7   US Cloud  (https://vault.bitwarden.com — bws default)rK   )z&EU Cloud  (https://vault.bitwarden.eu)zhttps://vault.bitwarden.eur   r   Optional[str]c                "   | j         r2| j                                         r| j                                         S t          j                            dd                                          }|r|                    d| d           |S t          |                    dd          pd                                          }|r|                    d| d           t          dd	d
d          }|                    ddd           |                    d           t          t          d          D ]+\  }\  }}|                    t          |          |           ,|                    t          t          t                    dz             d           |                    |           t          t                    dz   }		 d|	 d}
|r|
dz  }
|
dz  }
|                    |
                                          }|s|r|S |                    d           V	 t          |          }n%# t          $ r |                    d           Y w xY wd|cxk    rt          t                    k    rn nt          |dz
           d         S ||	k    rl|                    d                                          }|s|                    d           d
S |                    d          s|                    d           |S |                    d|	 d           P)a  Pick a Bitwarden server URL for setup.

    Resolution order:
      1. ``--server-url`` CLI flag (non-interactive)
      2. ``BWS_SERVER_URL`` env var (so users running with that already set
         in their shell don't have to re-enter it)
      3. Existing ``secrets.bitwarden.server_url`` value (for re-runs)
      4. Interactive menu: US / EU / self-hosted

    Returns the chosen URL as a string (empty string = bws default,
    i.e. US Cloud).  Returns None if the user aborted with an empty
    custom URL.
    rJ   rK   z'  Detected [cyan]BWS_SERVER_URL[/cyan]=u    in your shell — using it.rT   z  Existing config: [cyan]z?[/cyan]. Press Enter to keep, or pick a different option below.TrU   Nr   )rW   rX   r   r   rY   rC   rZ   r[   zRegion / endpointrI   zSelf-hosted / custom URLz  Select region [1-]z (Enter to keep current)z: rd   zD  Enter your Bitwarden server URL (e.g. https://vault.example.com): z!  [red]Empty URL, aborting.[/red])zhttp://zhttps://u]     [yellow]Warning: URL doesn't start with http:// or https:// — bws may reject it.[/yellow]re   rf   )rT   r{   r}   r~   r   rr   r   r	   r   r   _REGION_PRESETSr   r   r   rA   r   r   )r?   r   r   env_urlexistingr   r   label_url
custom_idxpromptr   r   customs                 r   r   r     su   $  '4?0022 '$$&&&jnn-r2288::G [g[[[	
 	
 	
 ;??<44:;;AACCH 
E E E E	
 	
 	

 dT6RRRE	Sa000	()))%oq99 % %=E4c!ffe$$$$	MM#c/**Q.//1KLLLMM%_%%)J M4z444 	100F$v&&,,.. 	  MM8999	f++CC 	 	 	MM8999H	 ++++s?+++++++"37+A..*]]5  egg   ABBBt$$%<== ?   MK
KKKLLLA Ms   H' 'I	I	)r   r   )r   r   r   r    )r?   r@   r   rA   )r   r   r   r   )rj   r   r   r   )
rm   r   rj   r   r+   r   rT   r   r   r   )
rj   r   r+   r   r   r   rT   r   r   r   )r?   r@   r   r   r   r   r   r  )+__doc__
__future__r   argparser   r   r}   r   rx   pathlibr   typingr   r   rich.consoler   
rich.panelr   
rich.tabler	   r;   hermes_cli.configr
   r   r   r   hermes_cli.secret_promptr   r   r   r>   r6   r7   r8   r9   r:   r<   r   rv   r   r   r  r   r   r   r   <module>r     s    # " " " " "  				  				     



       ! ! ! ! ! ! ! !                                     : 9 9 9 9 9  K K K K(H+ H+ H+ H+`{ { { {|9 9 9 9xO O O OdH H H HV    	 	 	 	": : : :   ( - - - - - -B FH2D 2D 2D 2D 2D 2Dr DLLM LM LM LM LM LMr   