
    *3j                        d Z ddlmZ ddlZddlmZ ddlmZmZmZ  ej	        d          Z
 ej	        d          ZdddZdddZdddZdddZdddZdddZdS ) a  Helpers for rendering gateway message timestamps exactly once.

Gateway messages need timestamps in the LLM context for temporal awareness, but
persisted message content should stay clean so replay does not accumulate
``[timestamp] [timestamp] ...`` prefixes across turns.
    )annotationsN)datetime)AnyOptionalTuplezv^\[(?P<dow>[A-Z][a-z]{2}) (?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2})(?: (?P<tz>[A-Za-z0-9_+\-/:]+))?\]\s*z)^\[(?P<iso>\d{4}-\d{2}-\d{2}T[^\]]+)\]\s*ts_valuer   returnOptional[float]c                "   | dS t          | t          t          f          rt          |           S t          | d          r3	 t          |                                           S # t
          $ r Y dS w xY wt          | t                    r|                                 }|sdS t          ||          }||S 	 t          |          S # t          t          f$ r Y nw xY w	 t          j        |          }nG# t          t          f$ r3 	 t          j        |d          }n# t          t          f$ r Y Y dS w xY wY nw xY w|j        -||                    |          }n|                                }t          |                                          S dS )zCoerce a timestamp-like value to Unix epoch seconds.

    Accepts Unix epoch numbers, datetime objects, ISO strings, and the gateway's
    bracketed human-readable timestamp format. Returns ``None`` when the value
    cannot be interpreted.
    N	timestamptz%Y-%m-%dT%H:%M:%S%ztzinfo)
isinstanceintfloathasattrr   	Exceptionstrstrip_parse_timestamp_prefix	TypeError
ValueErrorr   fromisoformatstrptimer   replace
astimezone)r   r   textparseddts        @/home/rurouni/.hermes/hermes-agent/gateway/message_timestamps.pycoerce_message_timestampr$      s    t(S%L)) Xx%% 	++--... 	 	 	44	 (C   %~~ 	4("555M	;;:& 	 	 	D		'--BB:& 	 	 	&t-BCCz*   ttt 	
 9~ZZrZ**]]__R\\^^$$$4sZ    A" "
A0/A07C CCC3 3D7DD7D1,D70D11D76D7r   c                    t          | |          }|dS |t          j        ||          }n&t          j        |                                          }d|                    d          z   dz   S )z?Format a timestamp value as ``[Tue 2026-04-28 13:40:53 CEST]``.r   N [z%a %Y-%m-%d %H:%M:%S %Z])r$   r   fromtimestampr   strftime)r   r   epochr"   s       r#   format_message_timestampr,   L   ss    $X"555E}r	~#Eb111#E**55776777#==    contentTuple[str, Optional[float]]c                   t          | t                    r| s| dfS | }d}	 t                              |          pt                              |          }|sn2t          ||          }||}||                                d         }i||fS )aw  Strip one or more leading gateway timestamp prefixes from ``content``.

    Returns ``(clean_content, embedded_epoch)``.  If multiple timestamp prefixes
    are present, the timestamp closest to the actual message text wins.  That
    preserves the original platform-send time for legacy contaminated rows like
    ``[processing time] [platform time] [sender] message``.
    NTr   )r   r   _HUMAN_TIMESTAMP_REmatch_ISO_TIMESTAMP_RE_parse_timestamp_matchend)r.   r   r    embedded_epochr2   r!   s         r#    strip_leading_message_timestampsr7   X   s     gs## 7 }D&*N"#))$//P3D3J3J43P3P 	'"555#NEIIKKLL!" r-   c                v    t          | |          \  }}||n|}t          ||          }|s|S |r| d| S |S )aY  Render a user message for LLM context with exactly one timestamp prefix.

    Existing leading timestamp prefixes are removed first.  If such a prefix was
    present, its parsed time wins over ``ts_value``; otherwise ``ts_value`` is
    formatted and prepended.  If no timestamp is available, the cleaned content is
    returned unchanged.
    r   N )r7   r,   )r.   r   r   clean_contentr6   effective_tsprefixs          r#   "render_user_content_with_timestampr=   r   sl     %EWQS$T$T$T!M>%3%?>>XL%lr:::F  +**=***Mr-   r    c                    t                               |           pt                              |           }|sd S t          ||          S )Nr   )r1   r2   r3   r4   )r    r   r2   s      r#   r   r      sI    %%d++L/@/F/Ft/L/LE t!%B////r-   r2   re.Matchc                   d|                                  v r|                     d          r|                     d          }	 t          j        |          }n9# t          $ r, 	 t          j        |d          }n# t          $ r Y Y d S w xY wY nw xY w|j        -||                    |          }n|                                }t          |
                                          S |                     d          }|                     d          }	 t          j        | d| d          }n# t          $ r Y d S w xY w||                    |          }n|                                }t          |
                                          S )Nisor   r   datetimer9   z%Y-%m-%d %H:%M:%S)	groupdictgroupr   r   r   r   r   r   r   r   r   )r2   r   iso_textr"   	date_part	time_parts         r#   r4   r4      s   !!!!ekk%&8&8!;;u%%	'11BB 	 	 	&x1FGG   ttt 	
 9~ZZrZ**]]__R\\^^$$$F##IF##I)99i99;NOO   tt	~ZZrZ""]]__   sH   A 
B"A87B8
BBBBBD+ +
D98D9)N)r   r   r	   r
   )r   r   r	   r   )r.   r   r	   r/   )NN)r.   r   r   r   r	   r   )r    r   r	   r
   )r2   r?   r	   r
   )__doc__
__future__r   rer   typingr   r   r   compiler1   r3   r$   r,   r7   r=   r   r4    r-   r#   <module>rO      s1    # " " " " " 				       ' ' ' ' ' ' ' ' ' ' !bj-   BJ0  
, , , , ,^	> 	> 	> 	> 	>         4    $0 0 0 0 0! ! ! ! ! ! !r-   