
    `gj1%                        d 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
 ddlmZ ddlmZ ddlmZ dZd	Zd
efdZd
efdZd
e
eef   fdZde
eef   d
dfdZd
efdZd
efdZd
efdZd
efdZd
efdZd Zd Z d Z!d Z"d Z#y)uy  hermes webhook — manage dynamic webhook subscriptions from the CLI.

Usage:
    hermes webhook subscribe <name> [options]
    hermes webhook list
    hermes webhook remove <name>
    hermes webhook test <name> [--payload '{"key": "value"}']

Subscriptions persist to ~/.hermes/webhook_subscriptions.json and are
hot-reloaded by the webhook adapter without a gateway restart.
    N)Path)Dictdisplay_hermes_home)atomic_replace)cfg_getzwebhook_subscriptions.jsoni  returnc                      ddl m}   |        S )Nr   get_hermes_home)hermes_constantsr   r   s    E/root/.hermes/venv/lib/python3.12/site-packages/hermes_cli/webhook.py_hermes_homer      s    0    c                  $    t               t        z  S )N)r   _SUBSCRIPTIONS_FILENAME r   r   _subscriptions_pathr   $   s    >333r   c                      t               } | j                         si S 	 t        j                  | j	                  d            }t        |t              r|S i S # t        $ r i cY S w xY w)Nutf-8encoding)r   existsjsonloads	read_text
isinstancedict	Exception)pathdatas     r   _load_subscriptionsr"   (   s^     D;;=	zz$..'.:;!$-t525 	s   6A A A%$A%subsc                    t               }|j                  j                  dd       t        j                  d|j
                   dd|j                  d      \  }}t        |      }	 t        j                  |dd      5 }t        j                  | |d	d
       |j                          t        j                  |j                                d d d        t        j                  |t               t!        ||       t        j                  |t               y # 1 sw Y   JxY w# t"        $ r$ 	 |j%                  d        # t&        $ r Y  w xY ww xY w)NT)parentsexist_ok.z.tmp)prefixsuffixdirtextwr   r      F)indentensure_ascii)
missing_ok)r   parentmkdirtempfilemkstempnamer   osfdopenr   dumpflushfsyncfilenochmod_SUBSCRIPTIONS_FILE_MODEr   r   unlinkOSError)r#   r    fdtmp_nametmp_pathfhs         r   _save_subscriptionsrD   3   s#    DKKdT2
 ##499+QKK	LB H~HYYr31 	"RIIdBqu=HHJHHRYY[!	" 	34x& 	/0	" 	"  	OOtO, 	  		sJ   (D"  ADAD" DD" "	E,D?>E?	EE
EEc                  ^    	 ddl m}   |        }t        |ddi       S # t        $ r i cY S w xY w)z;Load webhook platform config. Returns {} if not configured.r   )load_config	platformswebhook)default)hermes_cli.configrF   r   r   )rF   cfgs     r   _get_webhook_configrL   S   s6    1msKB?? 	s    ,,c                  F    t        t               j                  d            S )Nenabled)boolrL   getr   r   r   _is_webhook_enabledrQ   ]   s    #%)))455r   c                      t               j                  di       } | j                  d      }| j                  dd      }|r|dv rdn|}d|v r|j                  d      sd| d	}d
| d| S )Nextrahostporti!  >   ::0.0.0.0	localhost:[]zhttp://)rL   rP   
startswith)whrT   rU   display_hosts       r   _get_webhook_base_urlr_   a   s{    			"	"7B	/B66&>D66&$D&*d6G.G;TL
l<#:#:3#?<.*\N!D6**r   c                  (    t               } d|  d|  dS )Nz
  Webhook platform is not enabled. To set it up:

  1. Run the gateway setup wizard:
     hermes gateway setup

  2. Or manually add to z/config.yaml:
     platforms:
       webhook:
         enabled: true
         extra:
           port: 8644
           secret: "your-global-hmac-secret"

  3. Or set environment variables in z/.env:
     WEBHOOK_ENABLED=true
     WEBHOOK_PORT=8644
     WEBHOOK_SECRET=your-global-secret

  Then start the gateway: hermes gateway run
r   )_dhhs    r   _setup_hintrb   k   s1     D  & '+V , r   c                  @    t               ryt        t                      y)zDCheck webhook is enabled. Print setup guide and return False if not.TF)rQ   printrb   r   r   r   _require_webhook_enabledre      s    	+-r   c                     t        | dd      }|st        d       t        d       yt               sy|dv rt        |        y|dv rt	        |        y|dv rt        |        y|dk(  rt        |        yy)	z,Entry point for 'hermes webhook' subcommand.webhook_actionNz2Usage: hermes webhook {subscribe|list|remove|test}z(Run 'hermes webhook --help' for details.>   add	subscribe>   lslist>   rmremovetest)getattrrd   re   _cmd_subscribe	_cmd_list_cmd_remove	_cmd_test)argssubs     r   webhook_commandrv      sv    
$($
/CBC89#%
""t		$	 	 D	$ 
r   c                 n   | j                   j                         j                         j                  dd      }t	        j
                  d|      st        d| d       y t               }||v }| j                  xs t        j                  d      }| j                  r7| j                  j                  d      D cg c]  }|j                          c}ng }| j                  xs d| ||| j                  xs d	| j                  r7| j                  j                  d      D cg c]  }|j                          c}ng | j                   xs d
t#        j$                  dt#        j&                               d}t)        | dd      r|d   d
k(  rt        d       y d|d<   t)        | dd	      xs d	}	|	j                         r|	j                         |d<   | j*                  rd| j*                  i|d<   |||<   t-        |       t/               }
|rdnd}t        d| d|        t        d|
 d|        t        d|        |rt        ddj1                  |              nt        d       t        d|d           |j3                  d      rt        d        |j3                  d!      rD|d!   d d" t5        |d!         d"kD  rd#nd	z   }|j3                  d      rd$nd%}t        d&| d'|        |j3                  d      rt        d(|d           t        d)       t        d*       t        d+       y c c}w c c}w ),N -z^[a-z0-9][a-z0-9_-]*$zError: Invalid name 'z7'. Use lowercase alphanumeric with hyphens/underscores.    ,zAgent-created subscription:  logz%Y-%m-%dT%H:%M:%SZ)descriptioneventssecretpromptskillsdeliver
created_atdeliver_onlyFr   u|   Error: --deliver-only requires --deliver to be a real target (telegram, discord, slack, github_comment, etc.) — not 'log'.Tscriptchat_iddeliver_extraUpdatedCreated
  z webhook subscription: z
  URL:    
/webhooks/z
  Secret: z
  Events: , z  Events: (all)z  Deliver: z1  Mode: direct delivery (no agent, zero LLM cost)r   P   z...MessagePromptz  z: z
  Script: z3
  Configure your service to POST to the URL above.z6  Use the secret for HMAC-SHA256 signature validation.zF  The gateway must be running to receive events (hermes gateway run).
)r5   striplowerreplacerematchrd   r"   r   secretstoken_urlsafer   splitr~   r   r   r   timestrftimegmtimero   deliver_chat_idrD   r_   joinrP   len)rt   r5   r#   	is_updater   er   srouter   base_urlstatusprompt_previewlabels                 r   rp   rp      s   99??""$,,S#6D88,d3%dV+bcd DI[[5G11"5F<@KK!2!23!78Aaggi8RF ''P-I$+P++#AEdkk&7&7&<=1779=RT<<(5mm$8$++-HE t^U+u$R  $nT8R(.BF||~ ,,.h"+T-A-A!BoDJ$&H#YF	D/v
67	Jxj
4&
12	Jvh
 
499V,-./ 	Ki()
*+yy AByyx"-#eHo:NQS:SY[\"YY~6	H5'N+,-yy
5?+,-	
@A	
BC	
STi 9 >s   9L-!L2c                 j   t               }|st        d       t        d       y t               }t        dt        |       d       |j	                         D ]  \  }}dj                  |j                  dg             xs d}|j                  dd	      }|j                  d
      r| d}|j                  dd      }t        d|        |rt        d|        t        d| d|        t        d|        t        d|        |j                  d      rt        d|d           t                 y )Nz#  No dynamic webhook subscriptions.z2  Create one with: hermes webhook subscribe <name>r   z webhook subscription(s):
r   r   z(all)r   r}   r   u    (direct — no agent)r~   r|   u     ◆ z    z    URL:     r   z    Events:  z    Deliver: r   z    Script:  )r"   rd   r_   r   itemsr   rP   )rt   r#   r   r5   r   r   r   descs           r   rq   rq      s'    D34BC$&H	DT6
78zz| e599Xr23>w))Iu-99^$ 	!78Gyy+tfoD- hZz$89fX&'gY'(99XM%/!234r   c                     | j                   j                         j                         }t               }||vrt	        d| d       t	        d       y ||= t        |       t	        d|        y )N  No subscription named ''.z>  Note: Static routes from config.yaml cannot be removed here.z   Removed webhook subscription: )r5   r   r   r"   rd   rD   )rt   r5   r#   s      r   rr   rr      sh    99??""$D D4)$r23NOT
	,TF
34r   c                 `   | j                   j                         j                         }t               }||vrt	        d| d       y||   }|j                  dd      }t               }| d| }| j                  xs d}ddl}ddl	}	d	|j                  |j                         |j                         |	j                        j                         z   }
t	        d
|        	 ddl}|j                  j!                  ||j                         d|
ddd      }|j                  j#                  |d      5 }|j%                         j'                         }t	        d|j(                   d|        ddd       y# 1 sw Y   yxY w# t*        $ r#}t	        d|        t	        d       Y d}~yd}~ww xY w)z$Send a test POST to a webhook route.r   r   Nr   r|   r   zQ{"test": true, "event_type": "test", "message": "Hello from hermes webhook test"}r   zsha256=z  Sending test POST to zapplication/jsonrn   )zContent-TypezX-Hub-Signature-256zX-GitHub-EventPOST)r!   headersmethod
   )timeoutz  Response (z): z	  Error: z.  Is the gateway running? (hermes gateway run))r5   r   r   r"   rd   rP   r_   payloadhmachashlibnewencodesha256	hexdigesturllib.requestrequestRequesturlopenreaddecoder   r   )rt   r5   r#   r   r   r   urlr   r   r   sigurllibreqrespbodyr   s                   r   rs   rs     s   99??""$D D4)$r23JEYYx$F$&HJj
'CllqqG
dhh)7>>ikC 
#C5
)*@nn$$! 2'*"(
  % 	
 ^^##C#4 	999;%%'DLS78	9 	9 	9  @	!o>??@s7    AF 2:E5,F 5E>:F >F 	F-
F((F-)$__doc__r   r6   r   r   r3   r   pathlibr   typingr   r   r   utilsr   rJ   r   r   r=   r   r   strr   r"   rD   rL   rO   rQ   r_   rb   re   rv   rp   rq   rr   rs   r   r   r   <module>r      s   
  	 	      0   % 7   d 
4T 4T#t)_ d39o $ @T 6T 6+s +S 2$ ,>UB45(@r   