
    .cjM                       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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dl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$d%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)masked_secret_prompt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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tokenz?Rotate the service-account token: validate and store it in .envz@Provide the new token non-interactively (default: masked prompt)z--no-verify
store_truez7Store without probing 1Password first (not recommended))actionr   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--applyzIActually export resolved values into the current shell (default: dry-run)disablez"Turn off the 1Password integrationN)add_subparsers
add_parseradd_argument_DEFAULT_TOKEN_ENVset_defaults	cmd_setup
cmd_status	cmd_tokencmd_set
cmd_removecmd_synccmd_disable)	r   subr   r   r   set_pr#   r$   r%   s	            D/home/ice/.hermes/hermes-agent/hermes_cli/onepassword_secrets_cli.pyregister_clir5   /   s   

&
&,@
&
A
ACNNI   E 
L     
VASVVV     
G     
A     
I&&&^^H+Q^RRF
Z(((NNN   E 
O     
F    
 
I&&&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  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_versionrB   	token_envr)   r   r   osenvironr
   
_op_whoamir   )	r7   consolecfgop_cfgr?   binaryrS   r   whos	            r4   r+   r+   u   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   1r6   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	   rE   rB   r@   rC   r?   rF   F)r      )show_headerboxpaddingboldstyleEnabledAccountz[dim]default[/dim]zToken env varzToken in envzOverride existingrI   TzCache TTL (s)rG   rH   z	op binaryz (r   z[yellow]not found[/yellow]
Referencesz1Password secret sourcer<   )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   rN   boolstrrO   r)   
isinstancedictrT   rU   rP   rQ   r   
add_columnadd_row_ynrR   lenrJ   r   sortedrV   )r7   rW   rX   rY   rE   rB   rS   r?   
references	token_setrZ   table	ref_tablenamer[   s                  r4   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	
 	
 	
 1r6   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]rA   r>   r	   rF   u    [green]✓[/green] mapped [cyan]u   [/cyan] → rE   uy     [yellow]Note: the integration is disabled — run [cyan]hermes secrets onepassword setup[/cyan] to turn it on.[/yellow]r   )r   rP   _validate_referencesr!   r"   rJ   r   rM   rN   rn   ro   r   )r7   rW   validwarningswrX   rY   env_maps           r4   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	
 	
 	
 1r6   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	   rF   z[yellow]z is not mapped.[/yellow]rA   u-   [green]✓[/green] removed mapping for [cyan]r;   r   )	r   r   rM   rN   rn   ro   r!   rJ   r   )r7   rW   rX   rY   r   s        r4   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1r6   c                &   t                      }t                      }|                    d          pi                     d          pi }|                    dt                    }t	          |                    dd          pd                                          }t	          |                    dd          pd                                          }| j        pd                                }|sot          j        	                                s|
                    d           dS |
                    d	           t          d
| d                                          }|s|
                    d           dS | j        st          j        |          }| |
                    dt           d           dS |
                    d           t!          |||          }	|	|
                    d           dS |
                    d|	 d           t#          ||           |t$          j        |<   t          j                     |
                    dt+                       d| d           |                    d          s|
                    d           dS )u-  Rotate the 1Password service-account token without the full setup flow.

    Prompts for (or accepts via ``--token``) a new service-account token,
    verifies it with ``op whoami`` (unless ``--no-verify``), and only then
    persists it to .env — so a bad paste never bricks the working token.
    r>   r	   rC   rB   r@   r?   u2   [red]No TTY — pass the token with --token.[/red]rA   uc   Create a new service-account token at https://my.1password.com → Developer → Service Accounts.
zPaste new token (z): z![red]Empty token, aborting.[/red]Nu&   [red]op CLI not found — install it (z3) or re-run with --no-verify to store anyway.[/red]u   Verifying with `op whoami`…token_valueuD   [red]✗ New token was rejected by op — nothing was changed.[/red]u#   [green]✓ Token accepted[/green] (z).u   [green]✓[/green] stored in rD   z..  Takes effect on the next Hermes invocation.rE   u   [yellow]Note: the 1Password integration is currently disabled — run `hermes secrets onepassword setup` to turn it on.[/yellow]r   )r   r   rN   r)   rm   rO   r   sysstdinisattyrJ   r   	no_verifyrP   rQ   rL   rV   r   rT   rU   clear_cachesr
   )
r7   rW   rX   rY   rS   rB   r?   r   rZ   r[   s
             r4   r-   r-   .  s    iiG
--Cggi  &B++M::@bF

68JKKI&**Y++1r2288::Gfjj339r::@@BBKZ2$$&&E Qy!! 	MMNOOO1M	
 	
 	
 %%G%G%G%GHHNNPP 9:::q> E,,>MMA A A A   15666e<<<;MMV   1CCCCCDDD9e$$$!BJy MM	6 	6 	6I 	6 	6 	6   ::i   
M	
 	
 	
 1r6   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	   rE   zb[yellow]1Password integration is disabled.  Run `hermes secrets onepassword setup` first.[/yellow]rA   rF   us   [yellow]No op:// references configured.  Add one with `hermes secrets onepassword set ENV_VAR "op://…"`.[/yellow]r   rB   r@   rC   r?   TrI   )rE   rF   rB   rC   r?   rI   rG   r{   r|   ra   rh   rj   r<   rb   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)ru   rB   rS   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   rN   rJ   rn   ro   rm   rO   r)   applyrP   apply_onepassword_secretsrl   errorr   rp   rt   appliedrq   skippedr   rs   fetch_onepassword_secretsRuntimeErrorrT   rU   )r7   rW   rX   rY   ru   rB   rS   r?   resultrw   ry   r   r>   r   excoverridealreadys                    r4   r0   r0   l  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	   FrE   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   rM   r   rJ   )r7   rW   rX   rY   s       r4   r1   r1     sq    iiG
--C^^Ir**55mRHHFF9MM	   1r6   brl   rm   c                    | rdndS )Nz[green]yes[/green]z[dim]no[/dim] )r   s    r4   rr   rr     s    #$9/9r6   rZ   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runrm   
returncodestdoutstderrrO   
splitlinesOSErrorTimeoutExpired)rZ   ress     r4   rR   rR     s    
n[[+&	
 
 
 >QJ,#*3355@@BB1EE Z./   s   A)A- -BBr@   r   rB   r   Optional[str]c                  t          |           dg}|r|d|gz  }t          j                                        }|                    dd           |r||d<   	 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 )zReturn a short identity string if op is authenticated, else None.

    ``token_value``, when given, is passed to the child as
    ``OP_SERVICE_ACCOUNT_TOKEN`` so a candidate token can be probed
    without touching the caller's environment.
    whoamir   NO_COLOR1r   T
   )rF   r   r   r   Nr   r@   
 x   authenticated)rm   rT   rU   copyrM   r   r   r   r   r   r   rO   replace)rZ   rB   r   cmdrF   r   outs          r4   rV   rV     s    v;;
!C &W%%
*//

CNN:s### 6*5&'nSD"
 
 
 Z./   tt
~t:
"
"
$
$C;;tS!!$3$':?:s   A1 1B
B)r   r   r   r   )r7   r8   r   r9   )r   rl   r   rm   )rZ   r   r   rm   )rZ   r   rB   rm   r   rm   r   r   )(__doc__
__future__r   argparserT   r   r   pathlibr   typingr   rich.consoler   
rich.panelr   
rich.tabler   agent.secret_sourcesr	   rP   hermes_cli.configr
   r   r   r   hermes_cli.secret_promptr   r)   rL   r5   r+   r,   r.   r/   r-   r0   r1   rr   rR   rV   r   r6   r4   <module>r      s    # " " " " "  				     



                                     6 6 6 6 6 6            : 9 9 9 9 9/ C	>+ >+ >+ >+LN N N Nb8 8 8 8v   >   ; ; ; ;|\ \ \ \~   *: : : :     79; ; ; ; ; ; ; ;r6   