
    NQj@                        d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZ dZdZd%dZd&dZd&dZd&dZd&dZd&dZd&dZ d'dZ!d(d!Z"d)d$Z#dS )*u  CLI handlers for ``hermes secrets onepassword ...``.

Subcommands:
    setup    — verify the op CLI, set account / token env var, enable
    status   — show config + op binary + auth + configured references
    set      — map an env var to an ``op://…`` reference
    remove   — drop a mapping
    sync     — resolve references now and show what would be applied (dry-run)
    disable  — flip ``secrets.onepassword.enabled`` to False

Unlike Bitwarden, the ``op`` binary is NOT auto-installed: 1Password publishes
the CLI through OS package managers and signed installers, so Hermes expects
an already-installed, already-authenticated ``op`` and never downloads one.
    )annotationsN)Path)Optional)Console)Panel)Table)onepassword)get_env_pathload_configsave_configsave_env_valueOP_SERVICE_ACCOUNT_TOKENz5https://developer.1password.com/docs/cli/get-started/parent_parserargparse.ArgumentParserreturnNonec                   |                      d          }|                    dd          }|                    dd           |                    dd	t           d
           |                    dd           |                    dd           |                    t
                     |                    dd          }|                    t                     |                    dd          }|                    dd           |                    dd           |                    t                     |                    dd          }|                    dd           |                    t                     |                    dd          }|                    ddd            |                    t                     |                    d!d"          }|                    t                     d#S )$z>Attach the ``onepassword`` subcommand tree to a parent parser.secrets_op_command)destsetupz:Verify the op CLI, set account / token env var, and enable)help	--accountz=1Password account shorthand or sign-in address (op --account)z--token-envz1Env var holding a service-account token (default )z--tokenz8Service-account token to store in .env non-interactivelyz--binary-pathz2Absolute path to the op binary (skips PATH lookup))funcstatusz$Show config + op binary + referencessetz$Map an env var to an op:// referenceenv_varz.Environment variable name, e.g. OPENAI_API_KEY	referencez51Password reference, e.g. op://Private/OpenAI/api keyremoveu'   Remove an env-var → reference mappingz"Environment variable name to unmapsyncz.Resolve references now and report what changedz--apply
store_truezIActually export resolved values into the current shell (default: dry-run))actionr   disablez"Turn off the 1Password integrationN)add_subparsers
add_parseradd_argument_DEFAULT_TOKEN_ENVset_defaults	cmd_setup
cmd_statuscmd_set
cmd_removecmd_synccmd_disable)r   subr   r   set_pr   r    r#   s           F/home/alina/.hermes/hermes-agent/hermes_cli/onepassword_secrets_cli.pyregister_clir2   -   sM   

&
&,@
&
A
ACNNI   E 
L     
VASVVV     
G     
A     
I&&&^^H+Q^RRF
Z(((NN5'MNNNE	y'WXXX	{)`aaa	G$$$^^H+T^UUF
	(LMMM
Z(((>>&'W>XXDX    
 	8$$$nnY-QnRRGk*****    argsargparse.Namespaceintc                d   t                      }|                    t          j        dt           dd                     t                      }|                    di                               di           }|                                 |                    d           | j        p|                    dd	          pd		                                }t          j        |          }|P|r|                    d
| d           n|                    d           |                    dt                      dS |                    d| dt          |           d           |r||d<   | j        rT| j        	                                r;| j        	                                |d<   |                    d|d          d           |                                 |                    d           | j        p|                    d          pt          	                                }||d<   | j        pd		                                }|rGt#          ||           |t$          j        |<   |                    dt)                       d|            nt$          j                            |          r|                    d|            nYt+          ||                    dd	                    }|r|                    d| d           n|                    d| d           d|d<   |                    di            |                    dd            |                    d!d           t-          |           |                                 |                    d"           |                    d#           d$S )%Nz[bold]1Password secret source setup[/bold]

Hermes resolves [cyan]op://vault/item/field[/cyan] references through your
already-installed, already-authenticated 1Password CLI (`op`).

Don't have it yet? Install + sign in: [cyan][/cyan]cyan)border_stylesecretsr	   z&[bold]Step 1[/bold]  Locate the op CLIbinary_path u     [red]✗ z& is not an executable op binary.[/red]u&     [red]✗ op not found on PATH.[/red]z  Install the 1Password CLI:    u     [green]✓[/green] z  (r   accountz  Account: [cyan]z#[bold]Step 2[/bold]  Authenticationservice_account_token_envu5     [green]✓[/green] service-account token stored in z as u6     [green]✓[/green] using service-account token from u0     [green]✓[/green] using existing op session (z  [yellow]No service-account token and no active op session detected.[/yellow]
  Either run [cyan]op signin[/cyan] (desktop/interactive) or set a service-account token in z, then re-run status.Tenabledenvcache_ttl_seconds,  override_existingu6   [green]✓ 1Password secret source is enabled.[/green]z  Map credentials:  [cyan]hermes secrets onepassword set OPENAI_API_KEY "op://Private/OpenAI/api key"[/cyan]
  Preview:          [cyan]hermes secrets onepassword sync[/cyan]
  Status:           [cyan]hermes secrets onepassword status[/cyan]r   )r   printr   fit	_DOCS_URLr   
setdefaultr<   getstripop_srcfind_op_op_versionr?   	token_envr'   tokenr   osenvironr
   
_op_whoamir   )	r4   consolecfgop_cfgr<   binaryrO   rP   whos	            r1   r)   r)   d   s   iiGMM	N <EN N N  	
 	
 	
   --C^^Ir**55mRHHF MMOOOMM:;;;#Jvzz-'D'DJQQSSK^K((F~ 	DMM[[[[\\\\MMBCCCAiAABBBqMMK&KK[5H5HKKKLLL , +} | F**,, F L..00yD&*;DDDEEE MMOOOMM7888 '6::.I#J#J '& *3F&'Z2$$&&E y%((( %
9 9%9 9-69 9 	: 	: 	: 	:			"	" ZyZZ[[[[Ir!:!:;; 	MMSSSSSTTTTMMM -6M M M   F9
eR   
)3///
)4000MMOOOMMJKKKMM	M   1r3   c                   t                      }t                      }|                    d          pi                     d          pi }t          |                    d                    }t	          |                    dd          pd                                          }|                    dt                    }t	          |                    dd          pd                                          }t          |                    d          t                    r|                    d          ni }t          t          j
                            |                    }	t          j        |          }
t          d	d d
          }|                    dd           |                    d           |                    dt!          |                     |                    d|pd           |                    d|           |                    dt!          |	                     |                    dt!          t          |                    dd                                         |                    dt	          |                    dd                               |
r*|                    d|
 dt#          |
           d           n|                    dd           |                    dt	          t%          |                               |                    t)          |dd                      |rt          dd!          }|                    d"d           |                    d#           t+          |          D ]+}|                    |t	          ||                              ,|                    |           |s|                    d$           d%S |
rF|	sDt-          |
|          }|r|                    d&|            n|                    d'| d(           |s|                    d)           d%S )*Nr;   r	   rA   r?   r=   r@   r<   rB   F)r      )show_headerboxpaddingboldstyleEnabledAccountz[dim]default[/dim]zToken env varzToken in envzOverride existingrE   TzCache TTL (s)rC   rD   z	op binaryz (r   z[yellow]not found[/yellow]
Referencesz1Password secret sourcer9   )titler:   r[   header_styleEnv var	Referencez?
  Run [cyan]hermes secrets onepassword setup[/cyan] to enable.r   z%
  [green]Active op session:[/green] z$
  [yellow]No active op session and uK    is unset — Hermes will warn and skip 1Password on next startup.[/yellow]uv   
  [yellow]No references mapped yet.[/yellow]  Add one: [cyan]hermes secrets onepassword set ENV_VAR "op://…"[/cyan])r   r   rJ   boolstrrK   r'   
isinstancedictrQ   rR   rL   rM   r   
add_columnadd_row_ynrN   lenrF   r   sortedrS   )r4   rT   rU   rV   rA   r?   rO   r<   
references	token_setrW   table	ref_tablenamerX   s                  r1   r*   r*      s
   iiG
--Cggi  &B++M::@bF6::i(())G&**Y++1r2288::G

68JKKIfjj339r::@@BBK&0E1B1BD&I&IQE"""rJRZ^^I..//I^K((Fev>>>E	Rv&&&	R	MM)S\\***	MM)W<(<===	MM/9---	MM.#i..111	MM%s4

;NPT0U0U+V+V'W'WXXX	MM/3vzz2Es'K'K#L#LMMM Akf#F#FF0C0C#F#F#FGGGGk#?@@@	MM,C
OO 4 4555MM%%>VTTTUUU !d@@@	Yf555[))):&& 	; 	;DdC
4(8$9$9::::i    XYYYq i )) 	MMH3HHIIIIMMP	 P P P    
O	
 	
 	
 1r3   c                ~   t                      }t          j        | j        | j        i          \  }}| j        |vr |D ]}|                    d| d           dS t                      }|                    di                               di           }|                    d          }t          |t                    si }||d<   || j                 || j        <   t          |           |                    d| j         d|| j                             |                    d	          s|                    d
           dS )N[red][/red]r>   r;   r	   rB   u    [green]✓[/green] mapped [cyan]u   [/cyan] → rA   uy     [yellow]Note: the integration is disabled — run [cyan]hermes secrets onepassword setup[/cyan] to turn it on.[/yellow]r   )r   rL   _validate_referencesr   r   rF   r   rI   rJ   rk   rl   r   )r4   rT   validwarningswrU   rV   env_maps           r1   r+   r+      s`   iiG 14<2PQQOE8|5   	- 	-AMM+!+++,,,,q
--C^^Ir**55mRHHFjjGgt$$  u!$,/GDLMM	!4< 	! 	!	! 	!   ::i   
T	
 	
 	
 1r3   c                   t                      }t                      }|                    di                               di           }|                    d          }t	          |t
                    r	| j        |vr |                    d| j         d           dS || j        = t          |           |                    d| j         d           d	S )
Nr;   r	   rB   z[yellow]z is not mapped.[/yellow]r>   u-   [green]✓[/green] removed mapping for [cyan]r8   r   )	r   r   rI   rJ   rk   rl   r   rF   r   )r4   rT   rU   rV   r~   s        r1   r,   r,     s    iiG
--C^^Ir**55mRHHFjjGgt$$ G(C(CGGGGHHHqMMW$,WWWXXX1r3   c                   t                      }t                      }|                    d          pi                     d          pi }|                    d          s|                    d           dS t	          |                    d          t
                    r|                    d          ni }|s|                    d           dS t          |                    d	d
          pd
                                          }|                    dt                    }t          |                    dd
          pd
                                          }| j	        r^t          j        d||||t          |                    dd                    d          }|j        r |                    d|j         d           dS t          dd          }	|	                    dd           |	                    d           t!          |j                  D ]}
|	                    |
d           t!          |j                  D ]}
|	                    |
d           |                    |	           |j        D ]}|                    d|            |                    dt+          |j                   d           dS 	 t          j        ||||d          \  }}n1# t.          $ r$}|                    d| d           Y d }~dS d }~ww xY wt          |                    dd                    }t          dd          }	|	                    dd           |	                    d           t!          |          D ]}
|
|k    r|	                    |
d           |
|vr|	                    |
d            :t0          j                            |
          r|s|	                    |
d!           rt          t0          j                            |
                    }|	                    |
d"|rd#nd
z              |                    |	           |D ]}|                    d|            |                    d$           dS )%Nr;   r	   rA   zb[yellow]1Password integration is disabled.  Run `hermes secrets onepassword setup` first.[/yellow]r>   rB   us   [yellow]No op:// references configured.  Add one with `hermes secrets onepassword set ENV_VAR "op://…"`.[/yellow]r   r?   r=   r@   r<   TrE   )rA   rB   r?   r@   r<   rE   rC   rx   ry   r^   re   rg   r9   r_   Actionz[green]exported[/green]z,[dim]skipped (already set / token var)[/dim]z[yellow]warning:[/yellow] z
  [green]Exported z( secret(s) into current process.[/green]F)rr   r?   rO   r<   	use_cachez[dim]skip (token var)[/dim]z$[red]unresolved (see warnings)[/red]z[dim]skip (already set)[/dim]z[green]would export[/green]z (overrides)u   
  This was a dry-run — references resolve automatically on the next [cyan]hermes[/cyan] invocation.  Re-run with [cyan]--apply[/cyan] to export into the current shell instead.)r   r   rJ   rF   rk   rl   rj   rK   r'   applyrL   apply_onepassword_secretsri   errorr   rm   rq   appliedrn   skippedr|   rp   fetch_onepassword_secretsRuntimeErrorrQ   rR   )r4   rT   rU   rV   rr   r?   rO   r<   resultrt   rv   r}   r;   r|   excoverridealreadys                    r1   r-   r-     s   iiG
--Cggi  &B++M::@bF::i   A	
 	
 	
 q&0E1B1BD&I&IQE"""rJ N	
 	
 	
 q&**Y++1r2288::G

68JKKIfjj339r::@@BBK z 1&/#"6::.A4#H#HII
 
 
 < 	MM6&,6667771$V<<<&111"""6>** 	; 	;DMM$ 9::::6>** 	P 	PDMM$ NOOOOe 	< 	<AMM:q::;;;;3v~#6#6   	
 	
 	
 q
"<!#
 
 
    )c)))***qqqqq FJJ2D99::Hd888E	Yf---	Xz""  9MM$ =>>>>  MM$ FGGGGZ^^D!! 	( 	MM$ ?@@@@2:>>$//00GMM-71RPRS    MM% 8 861667777MM	*  
 1s   =K 
L$LLc                    t                      }t                      }|                    di                               di           }d|d<   t          |           |                    d           dS )Nr;   r	   FrA   u   [green]Disabled.[/green]  1Password references will NOT be resolved on the next Hermes invocation.
  Your reference mappings are left in config.yaml — remove them with [cyan]hermes secrets onepassword remove ENV_VAR[/cyan] if you no longer need them.r   )r   r   rI   r   rF   )r4   rT   rU   rV   s       r1   r.   r.   |  sq    iiG
--C^^Ir**55mRHHFF9MM	   1r3   bri   rj   c                    | rdndS )Nz[green]yes[/green]z[dim]no[/dim] )r   s    r1   ro   ro     s    #$9/9r3   rW   r   c                   	 t          j        t          |           dg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   capture_outputtexttimeoutr   zversion unknown)

subprocessrunrj   
returncodestdoutstderrrK   
splitlinesOSErrorTimeoutExpired)rW   ress     r1   rN   rN     s    
n[[+&	
 
 
 >QJ,#*3355@@BB1EE Z./   s   A)A- -BBr?   Optional[str]c                4   t          |           dg}|r|d|gz  }	 t          j        |ddd          }n# t          t          j        f$ r Y dS w xY w|j        dk    rdS |j        pd                                }|                    d	d
          dd         pdS )zAReturn a short identity string if op is authenticated, else None.whoamir   T
   r   Nr   r=   
 x   authenticated)	rj   r   r   r   r   r   r   rK   replace)rW   r?   cmdr   outs        r1   rS   rS     s    v;;
!C &W%%nSD"MMMZ./   tt
~t:
"
"
$
$C;;tS!!$3$':?:s   5 AA)r   r   r   r   )r4   r5   r   r6   )r   ri   r   rj   )rW   r   r   rj   )rW   r   r?   rj   r   r   )$__doc__
__future__r   argparserQ   r   pathlibr   typingr   rich.consoler   
rich.panelr   
rich.tabler   agent.secret_sourcesr	   rL   hermes_cli.configr
   r   r   r   r'   rH   r2   r)   r*   r+   r,   r-   r.   ro   rN   rS   r   r3   r1   <module>r      s    # " " " " "  				                                         6 6 6 6 6 6            0 C	/+ /+ /+ /+nN N N Nb8 8 8 8v   >   \ \ \ \~   *: : : :   ; ; ; ; ; ;r3   