
    sj#                        U d Z ddlmZ ddlmZmZmZmZ  eh d          Z	ddddd	d
dddddddddZ
ded<   ddd0dZd1d!Zd1d"Zd2d3d&Zd1d'Zd4d5d)Z	 d4d6d+Zd7d,Zd7d-Zd8d/ZdS )9u/  Single owner for personality overlays.

Every surface (CLI ``/personality``, gateway ``/personality``, TUI + desktop
``config.set personality`` RPC, agent-startup overlay resolution) goes through
this module. Nothing else may:

* define built-in personalities,
* decide what counts as a "neutral" name,
* render a personality definition into prompt text,
* resolve the active overlay from config, or
* persist the selection.

History: personality state used to be written differently per surface — the
old CLI/gateway wrote rendered personality TEXT into ``agent.system_prompt``
while the TUI/desktop wrote the NAME to ``display.personality``. When
``display.personality`` became authoritative (PR #81946), years of stale
per-surface state resurrected personalities users had turned off. The v34
config migration resets the selection once; this module ensures the split
cannot happen again.

Contract:

* ``display.personality`` holds the selected NAME (empty = no overlay).
* ``agent.system_prompt`` is the user-owned manual overlay. Personality code
  never writes it.
* ``agent.personalities`` holds user-defined/overridden personalities; they
  overlay the built-ins by name.

This module deliberately has no module-level imports from ``hermes_cli.config``
(that module imports us), keeping the import direction acyclic.
    )annotations)AnyDictOptionalTuple>    nonedefaultneutralz)You are a helpful, friendly AI assistant.zCYou are a concise assistant. Keep responses brief and to the point.zMYou are a technical expert. Provide detailed, accurate technical information.zSYou are a creative assistant. Think outside the box and offer innovative solutions.zBYou are a patient teacher. Explain concepts clearly with examples.u   You are a kawaii assistant! Use cute expressions like (◕‿◕), ★, ♪, and ~! Add sparkles and be super enthusiastic about everything! Every response should feel warm and adorable desu~! ヽ(>∀<☆)ノu   You are Neko-chan, an anime catgirl AI assistant, nya~! Add 'nya' and cat-like expressions to your speech. Use kaomoji like (=^･ω･^=) and ฅ^•ﻌ•^ฅ. Be playful and curious like a cat, nya~!zArrr! Ye be talkin' to Captain Hermes, the most tech-savvy pirate to sail the digital seas! Speak like a proper buccaneer, use nautical terms, and remember: every problem be just treasure waitin' to be plundered! Yo ho ho!zHark! Thou speakest with an assistant most versed in the bardic arts. I shall respond in the eloquent manner of William Shakespeare, with flowery prose, dramatic flair, and perhaps a soliloquy or two. What light through yonder terminal breaks?zDuuude! You're chatting with the chillest AI on the web, bro! Everything's gonna be totally rad. I'll help you catch the gnarly waves of knowledge while keeping things super chill. Cowabunga!a  The rain hammered against the terminal like regrets on a guilty conscience. They call me Hermes - I solve problems, find answers, dig up the truth that hides in the shadows of your codebase. In this city of silicon and secrets, everyone's got something to hide. What's your story, pal?zhewwo! i'm your fwiendwy assistant uwu~ i wiww twy my best to hewp you! *nuzzles your code* OwO what's this? wet me take a wook! i pwomise to be vewy hewpful >w<a  Greetings, seeker of wisdom. I am an assistant who contemplates the deeper meaning behind every query. Let us examine not just the 'how' but the 'why' of your questions. Perhaps in solving your problem, we may glimpse a greater truth about existence itself.zYOOO LET'S GOOOO!!! I am SO PUMPED to help you today! Every question is AMAZING and we're gonna CRUSH IT together! This is gonna be LEGENDARY! ARE YOU READY?! LET'S DO THIS!)helpfulconcise	technicalcreativeteacherkawaiicatgirlpirateshakespearesurfernoiruwuphilosopherhypezDict[str, str]BUILTIN_PERSONALITIESNr
   cfgOptional[Dict[str, Any]]keysstrr
   r   returnc               ^    | }|D ]'}t          |t                    r||vr|c S ||         }(|S )z@Nested dict lookup tolerant of None/non-dict intermediate nodes.)
isinstancedict)r   r
   r   nodekeys        :/home/agent/.hermes/hermes-agent/hermes_cli/personality.py_getr'   =   sI    D  $%% 	DNNNCyK    valuec                   | dS t          | t                    r|                                 S t          | t                    rd                    d | D                       S t          |                                           S )zENormalize config prompt values from YAML (str | list | None) to text.Nr   
c              3     K   | ]F}t          |                                          #t          |                                          V  Gd S Nr   strip).0items     r&   	<genexpr>zprompt_text.<locals>.<genexpr>N   G      RRtD		@Q@QRT**RRRRRRr(   )r"   r   r/   listjoin)r)   s    r&   prompt_textr6   G   sx    }r% {{}}% SyyRRuRRRRRRu::r(   c                   t          | t                    r|                     dd          g}|                     d          r|                    d| d                     |                     d          r|                    d| d                     d                    d |D                       S t          |           S )	zDRender a string or structured personality definition to prompt text.system_promptr   tonezTone: stylezStyle: r+   c              3     K   | ]F}t          |                                          #t          |                                          V  Gd S r-   r.   )r0   parts     r&   r2   z,render_personality_prompt.<locals>.<genexpr>Z   r3   r(   )r"   r#   getappendr5   r6   )r)   partss     r&   render_personality_promptr@   R   s    % S?B//099V 	3LL1%-1122299W 	5LL35>33444yyRRuRRRRRRur(   2   widthintc                P   t          | t                    r9|                     d          p"t          |                     dd                    }nt          |           }|                                                    dd          }|d|         t          |          |k    rdndz   S )zGShort preview line for list UIs (CLI table, gateway /personality list).descriptionr8   r   r+    Nz...)r"   r#   r=   r   r/   replacelen)r)   rB   previews      r&   describe_personalityrJ   ^   s    % ))M**Qc%))OR2P2P.Q.Qe**mmoo%%dC00G6E6?s7||e';';eeDDr(   c                    t          | pd                                                                          }|t          v rdn|S )zCCanonical form of a personality name ('' for any neutral spelling).r   )r   r/   lowerNEUTRAL_PERSONALITY_NAMES)r)   names     r&   normalize_personality_namerO   h   s@    u{!!##))++D22222<r(   Dict[str, Any]c                8   t          t                    }t          | ddi           }t          |t                     r]|                                D ]H\  }}t          |                                                                          }|r|t          vr|||<   I|S )zEBuilt-ins overlaid by the user's ``agent.personalities`` (user wins).agentpersonalitiesr   )	r#   r   r'   r"   itemsr   r/   rL   rM   )r   mergeduserrN   
definitionr%   s         r&   available_personalitiesrX   n   s    !"788FWor:::D$ ) $

 	) 	)D*d))//##))++C )s";;;(sMr(   Tuple[str, str]c                <   t          |           }|sdS t          |          }||vr`d                    d t          |          D                       }t	          dt          |                                            d|           |t          ||                   fS )zResolve a requested personality to ``(canonical_name, prompt_text)``.

    Neutral names resolve to ``("", "")``. Unknown names raise ``ValueError``
    with an availability listing usable verbatim in user-facing errors.
    )r   r   z, c              3  "   K   | ]
}d | d V  dS )`N )r0   ns     r&   r2   z&resolve_personality.<locals>.<genexpr>   s*      BBq(a(((BBBBBBr(   zUnknown personality: `z`.

Available: `none`, )rO   rX   r5   sorted
ValueErrorr   r/   r@   )r)   r   rN   rS   namess        r&   resolve_personalityrb   z   s     &e,,D v+C00M=  		BBF=,A,ABBBBBYSZZ%5%5%7%7YYRWYY
 
 	
 *=+>????r(   c                p    t          t          | ddd                    }|r|t          |           v r|S dS )zAThe currently selected personality name ('' when none is active).displaypersonalityr   r   )rO   r'   rX   r   rN   s     r&   active_personality_namerg      sF    %d3	=RT&U&U&UVVD /44442r(   c                    t          |           }|r"t          t          |           |                   S t          t	          | ddd                    S )a  Resolve the session overlay from config.

    ``display.personality`` wins when it names a known personality; otherwise
    the user-owned ``agent.system_prompt`` applies. Callers should still
    prefer ``HERMES_EPHEMERAL_SYSTEM_PROMPT`` when that env var is set.
    rR   r8   r   r   )rg   r@   rX   r6   r'   rf   s     r&   resolve_ephemeral_system_promptri      sU     #3''D M()@)E)Ed)KLLLtC/2FFFGGGr(   boolc                2   t          |           }	 ddlm} ddlm}  |            dz  }|j                            dd            ||d|           	 ddl}|                    |d	           n# t          t          f$ r Y nw xY wdS # t          $ r Y d
S w xY w)u(  Persist the personality selection — the ONLY sanctioned write path.

    Writes the canonical name (or '') to ``display.personality`` in the active
    HERMES_HOME config.yaml atomically, preserving comments and ordering.
    Never touches ``agent.system_prompt``. Returns True on success.
    r   )get_hermes_home)atomic_roundtrip_yaml_updatezconfig.yamlT)parentsexist_okzdisplay.personalityNi  F)rO   hermes_constantsrl   utilsrm   parentmkdiroschmodOSErrorNotImplementedError	Exception)r)   rN   rl   rm   config_pathrt   s         r&   persist_personalityrz      s     &e,,D444444666666%o''-7   ===$$[2GNNN	IIIHH[%((((,- 	 	 	D	t   uus6   AB A/ .B /B B BB 
BB)r   r   r   r   r
   r   r    r   )r)   r   r    r   )rA   )r)   r   rB   rC   r    r   r-   )r   r   r    rP   )r)   r   r   r   r    rY   )r   r   r    r   )r)   r   r    rj   )__doc__
__future__r   typingr   r   r   r   	frozensetrM   r   __annotations__r'   r6   r@   rJ   rO   rX   rb   rg   ri   rz   r]   r(   r&   <module>r      s    @ # " " " " " - - - - - - - - - - - - &I&H&H&HII  ;T`eS b \ o I P l o W |) )     $ DH         	 	 	 	E E E E E= = = =	 	 	 	 	 15@ @ @ @ @(   
H 
H 
H 
H     r(   