
    `gjlj                        d Z ddlmZ ddlZddlZddlmZmZmZm	Z	 ddl
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZ ddlm Z  d	 Z!dd
Z"dZ#ddZ$dddZ%dddZ&ddZ'ddZ(g dZ)y)u@  System-prompt assembly for :class:`AIAgent`.

The agent's system prompt is built once per session and reused across all
turns — only context compression triggers a rebuild.  This keeps the
upstream prefix cache warm.  See ``hermes-agent-dev``'s
``references/system-prompt-invariant.md`` for the invariants and
``references/self-improvement-loop.md`` for how the background-review
fork inherits the cached prompt verbatim.

Three tiers are joined with ``\n\n``:

* ``stable``   — identity (SOUL.md or DEFAULT_AGENT_IDENTITY), tool
  guidance, computer-use guidance, nous subscription block, tool-use
  enforcement guidance + per-model operational guidance, skills prompt,
  alibaba model-name workaround, environment hints, platform hints.
* ``context``  — caller-supplied ``system_message`` plus context files
  (AGENTS.md / .cursorrules / etc.) discovered under ``TERMINAL_CWD``.
* ``volatile`` — memory snapshot, USER.md profile, external memory
  provider block, timestamp/session/model/provider line.

Pure helpers that read the agent's state.  AIAgent keeps thin forwarders.
    )annotationsN)AnyDictListOptional)DEFAULT_AGENT_IDENTITY!GOOGLE_MODEL_OPERATIONAL_GUIDANCEHERMES_AGENT_HELP_GUIDANCEKANBAN_GUIDANCEMEMORY_GUIDANCEOPENAI_MODEL_EXECUTION_GUIDANCEPARALLEL_TOOL_CALL_GUIDANCEPLATFORM_HINTSSESSION_SEARCH_GUIDANCESKILLS_GUIDANCESTEER_CHANNEL_NOTETASK_COMPLETION_GUIDANCETELEGRAM_RICH_MESSAGES_HINTTOOL_USE_ENFORCEMENT_GUIDANCETOOL_USE_ENFORCEMENT_MODELSdrain_truncation_warnings)resolve_context_cwd)get_hermes_home)is_truthy_valuec                     ddl } | S )a  Lazy reference to the ``run_agent`` module.

    Helpers like ``load_soul_md``, ``build_environment_hints``,
    ``build_context_files_prompt``, ``build_nous_subscription_prompt``,
    ``build_skills_system_prompt`` and ``get_toolset_for_tool`` are
    imported into ``run_agent``'s namespace.  Many tests
    ``patch("run_agent.load_soul_md", ...)``; if we imported them
    directly here those patches would not reach us.  Looking them up
    through ``run_agent`` on every call preserves the patch contract.
    r   N	run_agentr   s    F/root/.hermes/venv/lib/python3.12/site-packages/agent/system_prompt.py_rar   5   s         c                @   |s|S t        | dd      }t        |t              r|s|S |j                  |      }||S t        |t              r)|j                         }|r| d| j                         S |S t        |t              s|S |j                  d      }t        |t              r!|j                         r|j                         }n|}|j                  d      }t        |t              r3|j                         r#| d|j                          j                         S |S )u  Apply a per-platform prompt-hint override to the default hint.

    Reads ``agent._platform_hint_overrides`` (populated from
    ``config.yaml`` ``platform_hints`` by ``agent_init``) and resolves the
    effective hint for *platform_key*:

      * ``replace`` — substitute the default hint entirely.
      * ``append``  — keep the default and append the extra text.
      * a bare string value — treated as ``append`` (convenience shorthand).

    Precedence: ``replace`` wins over ``append`` if both are present.
    Override text is added on top of (not instead of) the SOUL/context/
    memory tiers — it only affects the platform-hint segment, so other
    platforms are unaffected and general system instructions still apply.

    Defensive: any malformed entry falls back to the unmodified default so
    a bad config value can never break prompt assembly or leak across
    platforms.
    _platform_hint_overridesN

replaceappend)getattr
isinstancedictgetstrstrip)	agentplatform_keydefault_hint	overridesspecextrareplace_textbaseappend_texts	            r   _resolve_platform_hintr5   D   s   ( 94@Ii&i==&D| $

7<,tE7+113N,NdD!88I&L,$););)=!!#((8$K+s#(9(9(;tK--/017799Kr    u    You're in its embedded terminal pane, beside the GUI chat — the user can select your output (Option-drag on macOS, Shift-drag elsewhere) and press Cmd/Ctrl+L to send it to the chat composer.c                p    | s| S t         | v r| S t        t        j                  d            s| S | t         z   S )u  Append the desktop-embedded-terminal-pane clarifier to a tui hint.

    Triggered by ``HERMES_DESKTOP_TERMINAL=1`` (set by ``main.cjs`` only on the
    shell env of the desktop's embedded TUI PTY — never on the chat backend).
    This is a runtime-surface qualifier, not a config override, so it lives at
    the resolution site rather than inside ``_resolve_platform_hint`` (which
    is purely the config-platform_hints override applier). Byte-stable for the
    cache: called once per session build, deterministically from env state.

    Idempotent and empty-safe: re-applying on an already-augmented hint is a
    no-op, and an empty input returns empty (we never synthesize the
    clarifier without its tui framing).
    HERMES_DESKTOP_TERMINAL)_TUI_EMBEDDED_PANE_CLARIFIERr   osgetenv)hints    r   _tui_embedded_pane_clarifierr<   |   s<     #t+299%>?@...r    c                   -. t               -d}t         dd      }|$t        |dd      }t        |t              r|dkD  r|}g }d} j                  s j
                  s&-j                  |      }|r|j                  |       d}|s|j                  t               |j                  t               t         dd      r! j                  r|j                  t               t         dd      r! j                  r|j                  t               g }d	 j                  v r|j                  t               d
 j                  v r|j                  t               d j                  v r|j                  t               t         dd      }	|	r|j                  |	       n%|	#d j                  v r|j                  t                |r |j                  dj#                  |              j                  r|j                  t$               d j                  v rddlm}
 |j                   |
              -j+                   j                        }|r|j                  |        j                  rL j,                  }d}|du s"t        |t.              r|j1                         dv rd}n|du s"t        |t.              r|j1                         dv rd}nyt        |t2              r3 j4                  xs dj1                         .t7        .fd|D              }n6 j4                  xs dj1                         .t7        .fdt8        D              }|rq|j                  t:                j4                  xs dj1                         }d|v sd|v r|j                  t<               d|v sd|v sd|v r|j                  t>               t7         fddD              }|rt-fd j                  D        D ch c]  }|r| }}tA               }	 ddl!m"}  | jF                  tI                     }-jM                   j                  ||xs d       }nd}|r|j                  |        jN                  d!k(  rZd" j4                  v r j4                  jQ                  d"      d#   n j4                  }|j                  d$| d% j4                   d&       -jS                         }|r|j                  |        j                  r=	 dd'l!m*} |jW                   | jF                  tI                j4                  (             t         d)d      r!	 dd*l,m-}  |       }|r|j                  |       	 dd+l.m/}  |       }|d,k(  r)|j                  d-t/        ta                     z   d.z          nO|j                  d/| d0ta                d1| d2ta                d3ta                d4ta                d5ta                d6        jF                  xs dj1                         jc                         }d}|td        v r
td        |   }n4|r2	 dd7l3m4} |jk                  |      }|r|jl                  r|jl                  }|d8k(  rv|rt	 dd9l7m8}   |        }!|!jk                  d:      xs i jk                  d8      xs i jk                  d;      xs i }"|"jk                  d<      r|js                         dz   tt        z   }tw         ||      }#|d=k(  r|#rty        |#      }#|#r|j                  |#       g }$||$j                  |        j
                  s<-j{                  tI               || jF                  d>v ?      }%|%r|$j                  |%       g }& j|                  rt j~                  r. j|                  j                  d	      }'|'r|&j                  |'        j                  r. j|                  j                  d@      }(|(r|&j                  |(        j                  r.	  j                  j                         })|)r|&j                  |)       ddAlDmE}*  |*       }+dB|+j                  dC       }, j                  r j                  r|,dD j                   z  }, j4                  r|,dE j4                   z  }, jN                  r|,dF jN                   z  },|&j                  |,       dGj#                  dH |D              dGj#                  dI |$D              dGj#                  dJ |&D              dKS c c}w # tJ        $ r tA               }Y w xY w# tJ        $ r Y w xY w# tJ        $ r Y w xY w# tJ        $ r d,}Y w xY w# tJ        $ r Y w xY w# tJ        $ r Y w xY w# tJ        $ r Y ]w xY w)Lu  Assemble the system prompt as three ordered parts.

    Returns a dict with three keys:
      * ``stable``   — identity, tool guidance, skills prompt,
        environment hints, platform hints, model-family operational
        guidance.
      * ``context``  — context files (AGENTS.md, .cursorrules, etc.)
        and caller-supplied system_message.
      * ``volatile`` — memory snapshot, user profile, external
        memory provider block, timestamp line.

    Joined into a single string by :func:`build_system_prompt` and
    cached on ``agent._cached_system_prompt`` for the lifetime of the
    AIAgent.  Hermes never re-renders parts of this string mid-
    session — that's the only way to keep upstream prompt caches
    warm across turns.
    Ncontext_compressorcontext_lengthr   FT_task_completion_guidance_parallel_tool_call_guidancememorysession_searchskill_manage_kanban_worker_guidancekanban_show computer_use)computer_use_guidance>   onyestruealways>   noofffalsenever c              3  d   K   | ]'  }t        |t              s|j                         v  ) y wN)r'   r*   lower.0pmodel_lowers     r   	<genexpr>z,build_system_prompt_parts.<locals>.<genexpr>  s'     [q
STVYHZ!''){2[s   00c              3  &   K   | ]  }|v  
 y wrT    rV   s     r   rZ   z,build_system_prompt_parts.<locals>.<genexpr>  s     Pq!{*Ps   geminigemmagptcodexgrokc              3  :   K   | ]  }|j                   v   y wrT   )valid_tool_names)rW   namer,   s     r   rZ   z,build_system_prompt_parts.<locals>.<genexpr>&  s     td45#9#99ts   )skills_list
skill_viewrD   c              3  @   K   | ]  }j                  |        y wrT   )get_toolset_for_tool)rW   	tool_name_rs     r   rZ   z,build_system_prompt_parts.<locals>.<genexpr>*  s!      7@''	2s   )coding_compact_skill_categories)platformcwd)available_toolsavailable_toolsetscompact_categoriesalibaba/z#You are powered by the model named z. The exact model ID is zt. When asked what model you are, always answer based on this information, not on any model name returned by the API.)coding_system_blocks)rl   rm   model_environment_probe)get_environment_probe_line)_resolve_active_profile_namedefaultzCActive Hermes profile: default. Other profiles (if any) live under z/profiles/<name>/. Each profile has its own skills/, plugins/, cron/, and memories/ that affect a different session than this one. Do not modify another profile's skills/plugins/cron/memories unless the user explicitly directs you to.zActive Hermes profile: z . This session reads and writes z
/profiles/z'/. The default profile's data lives at z
/skills/, z/plugins/, z/cron/, u/  /memories/ — those belong to a different session run from a different shell. Do NOT modify another profile's skills/plugins/cron/memories unless the user explicitly directs you to. The cross-profile write guard will refuse such writes by default; pass cross_profile=True only after explicit direction.)platform_registrytelegram)load_config_readonly	platformsr1   rich_messagestui)clir   )rm   	skip_soulr?   allow_install_tree_fallbackuser)nowzConversation started: z%A, %B %d, %Yz
Session ID: z
Model: z
Provider: r#   c              3  d   K   | ](  }|s|j                         s|j                          * y wrT   r+   rW   rX   s     r   rZ   z,build_system_prompt_parts.<locals>.<genexpr>	        UaQ1779	U   000c              3  d   K   | ](  }|s|j                         s|j                          * y wrT   r   r   s     r   rZ   z,build_system_prompt_parts.<locals>.<genexpr>
  r   r   c              3  d   K   | ](  }|s|j                         s|j                          * y wrT   r   r   s     r   rZ   z,build_system_prompt_parts.<locals>.<genexpr>  r   r   )stablecontextvolatile)Ir   r&   r'   intload_soul_identityskip_context_filesload_soul_mdr%   r   r
   rc   r   r   r   r   r   r   joinr   agent.prompt_builderrI   build_nous_subscription_prompt_tool_use_enforcementr*   rU   listru   anyr   r   r	   r   	frozensetagent.coding_contextrk   rl   r   	Exceptionbuild_skills_system_promptprovidersplitbuild_environment_hintsrt   extendtools.env_proberw   agent.file_safetyrx   r   r+   r   gateway.platform_registryrz   r)   platform_hinthermes_cli.configr|   rstripr   r5   r<   build_context_files_prompt_memory_store_memory_enabledformat_for_system_prompt_user_profile_enabled_memory_managerbuild_system_prompthermes_timer   strftimepass_session_id
session_id)/r,   system_message_ctx_len_cc_cc_lenstable_parts_soul_loaded_soul_contenttool_guidance_kanban_guidancerI   nous_subscription_prompt_enforce_inject_model_lowerhas_skills_toolstoolsetavail_toolsets_compact_catsrk   skills_prompt_model_short
_env_hintsrt   rw   _probe_linerx   active_profiler-   _default_hintrz   _entryr|   _cfg	_tg_extra_effective_hintcontext_partscontext_files_promptvolatile_parts	mem_block
user_block_ext_mem_block_hermes_nowr   timestamp_linerj   rY   s/   `                                            @@r   build_system_prompt_partsr      s4	   * 
B #H
%-t
4C
#/6gs#!H !L
 Lu'?'?1.L23 23 u148U=S=S45 u4d;@V@V78 M5)))_-511145///_-
 u&?F-.		!mu7M7M&M_-CHH]34 ./ ///>134!@@AWAWX45 ..t
8S 9hnn>NRq>qG:h#<AQUtAtG$' ;;,"335K[H[[G !;;,"335KP4OPPG =>!KK-2446L <'7l+B##$EF $<(?6\CY##$CDtFsttDIDZDZ
 	 
 
 "	(L;-@-BM
 55!22-,4 6 
 M* ~~"58EKK5Gu{{((-b1U[[1, @%%*[[M 29:	
 ++-JJ' 	A$"^^+-++$ u*D1	B46K##K0#B57 "?,-.1	
 	%n%5 6)+,J~6F G''6'8&9ODUCVVa !/*;)< =()
	
 NN(b//1779L M~%&|4		C&**<8F&.. & 4 4 z!m	>')D((;/52:::FL"QQRYZ`^`I}}_- - 4 4 6 <?Z Z -UL-POu6GO,  "M !^,##  "<<#%#(-.(H  =  J    !56 !#N  ++DDXNI%%i0&&,,EEfMJ%%j1 	"22FFHN%%n5 /
-C .cll?.K-LMN!1!1N5+;+;*<=={{Iekk]33~~L(899.) KKU<UUKKU=UUKKU>UU A
$  	(%KM	(b  		"  		  #"#J  		  		n  		s   c97"c> *<d 4 d( d8 "1e
 A3e ,-e* >dd	d%$d%(	d54d58ee
	ee	e'&e'*	e76e7c                    t        | |      }dj                  d |d   |d   |d   fD              }t               D ]  }| j                  |        |S )u  Assemble the full system prompt from all layers.

    Called once per session (cached on ``agent._cached_system_prompt``) and
    only rebuilt after context compression events. This ensures the system
    prompt is stable across all turns in a session, maximizing prefix cache
    hits.

    Layers are ordered cache-friendly: stable identity/guidance first,
    then session-stable context files, then per-call volatile content
    (memory, USER profile, timestamp).  The whole string is treated as
    one cached block — Hermes never rebuilds or reinjects parts of it
    mid-session, which is the only way to keep upstream prompt caches
    warm across turns.
    )r   r#   c              3  &   K   | ]	  }|s|  y wrT   r\   r   s     r   rZ   z&build_system_prompt.<locals>.<genexpr>  s     `q^_`s   r   r   r   )r   r   r   _emit_status)r,   r   partsjoinedwarnings        r   r   r     sb     &eNKE[[`U8_eI6FjHY$Z``F -. $7#$ Mr    c                `    d| _         | j                  r| j                  j                          yy)zInvalidate the cached system prompt, forcing a rebuild on the next turn.

    Called after context compression events. Also reloads memory from disk
    so the rebuilt prompt captures any writes from this session.
    N)_cached_system_promptr   load_from_disk)r,   s    r   invalidate_system_promptr   )  s,     #'E**, r    c                    | j                   syg }| j                   D ]B  }|d   }|d   |j                  dd      |j                  di       dd}|j                  |       D t        j                  |d	
      S )zFormat tool definitions for the system message in the trajectory format.

    Returns:
        str: JSON string representation of tool definitions
    z[]functionrd   descriptionrR   
parametersN)rd   r   r   requiredF)ensure_ascii)toolsr)   r%   jsondumps)r,   formatted_toolstoolfuncformatted_tools        r   format_tools_for_system_messager   4  s     ;; O /JL88M26((<4	
 	~./ ::oE::r    )r   r   r   r   )r,   r   r-   r*   r.   r*   returnr*   )r;   r*   r   r*   rT   )r,   r   r   Optional[str]r   zDict[str, str])r,   r   r   r   r   r*   )r,   r   r   None)r,   r   r   r*   )*__doc__
__future__r   r   r9   typingr   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   agent.runtime_cwdr   hermes_constantsr   utilsr   r   r5   r8   r<   r   r   r   r   __all__r\   r    r   <module>r      sv   . #  	 , ,    $ 2 , !.d2 /.yx4-;0r    