
    RmjI                       d 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mZmZmZ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" 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#m0Z1 ddl#m2Z3 ddl#m4Z5 erddl6m7Z7 ddlm8Z8  G d de          Z9 G d de9d          Z: G d de          Z;ed         Z<	  G d de          Z= G d de          Z> G d d e          Z?dd!dPd(Z@dQd*ZAdQd+ZB ed,-           G d. d/                      ZC ed,-           G d0 d1                      ZD ed,-           G d2 d3                      ZE ed,-           G d4 d5                      ZF G d6 d7          ZGdRd:ZHdRd;ZIdSd>Z.dTd@ZJed,dAdUdD            ZKdVdFZLdWdHZMdXdLZNdYdMZOg dNZPdOS )Za  Generic plugin configuration and registration helpers.

This module exposes the top-level plugin system used to validate and activate
adaptive and custom plugin components. Component registration names are scoped
per component by the runtime, so end users do not provide instance ids.
    )annotations)asynccontextmanager)	dataclassfieldfieldsis_dataclass)TYPE_CHECKINGAsyncIteratorCallableLiteralProtocolSelf	TypedDictcast)EventSanitizeGuardrailJson
JsonObject LlmConditionalExecutionGuardrailLlmExecutionInterceptLlmRequestInterceptLlmSanitizeRequestGuardrailLlmSanitizeResponseGuardrailLlmStreamExecutionIntercept!ToolConditionalExecutionGuardrailToolExecutionInterceptToolRequestInterceptToolSanitizeGuardrailUnsupportedBehaviorsubscribers)_PluginHostActivation)active_plugin_report)clear_plugin_configuration)deregister_plugin)initialize_plugins)initialize_with_dynamic_plugins)list_plugin_kinds)register_plugin)validate_plugin_config)TracebackType)Eventc                  .    e Zd ZU ded<   ded<   ded<   dS )_ConfigDiagnosticRequiredzLiteral['warning', 'error']levelstrcodemessageN)__name__
__module____qualname____annotations__     Y/home/thesage/.hermes/hermes-agent/venv/lib/python3.11/site-packages/nemo_relay/plugin.pyr,   r,   B   s.         &&&&IIILLLLLr6   r,   c                  (    e Zd ZU dZded<   ded<   dS )ConfigDiagnosticz!One plugin validation diagnostic.r.   	componentr   Nr1   r2   r3   __doc__r4   r5   r6   r7   r9   r9   H   s(         ++NNNJJJJJr6   r9   F)totalc                      e Zd ZU dZded<   dS )ConfigReportz4Validation or activation report for a plugin config.zlist[ConfigDiagnostic]diagnosticsNr;   r5   r6   r7   r?   r?   O   s$         >>''''''r6   r?   )rust_dynamicworkerc                      e 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Zd/dZd0d!Zd1d#Zd2d%Zd&S )3PluginContextzGComponent-scoped registration context passed to custom plugin handlers.namer.   callbackCallable[[Event], None]returnNonec                    dS )z;Register an infallible event subscriber for this component.Nr5   )selfrE   rF   s      r7   register_subscriberz!PluginContext.register_subscriber\       r6   priorityintr   c                    dS )z3Register a mark event sanitizer for this component.Nr5   rK   rE   rN   rF   s       r7    register_mark_sanitize_guardrailz.PluginContext.register_mark_sanitize_guardrail`   rM   r6   c                    dS )z:Register a scope-start event sanitizer for this component.Nr5   rQ   s       r7   'register_scope_sanitize_start_guardrailz5PluginContext.register_scope_sanitize_start_guardraild   	     	r6   c                    dS )z8Register a scope-end event sanitizer for this component.Nr5   rQ   s       r7   %register_scope_sanitize_end_guardrailz3PluginContext.register_scope_sanitize_end_guardrailj   rM   r6   r   c                    dS )z>Register a tool sanitize-request guardrail for this component.Nr5   rQ   s       r7   (register_tool_sanitize_request_guardrailz6PluginContext.register_tool_sanitize_request_guardrailn   rU   r6   c                    dS )z?Register a tool sanitize-response guardrail for this component.Nr5   rQ   s       r7   )register_tool_sanitize_response_guardrailz7PluginContext.register_tool_sanitize_response_guardrailt   rU   r6   r   c                    dS )zCRegister a tool conditional-execution guardrail for this component.Nr5   rQ   s       r7   -register_tool_conditional_execution_guardrailz;PluginContext.register_tool_conditional_execution_guardrailz   rU   r6   r   c                    dS )z>Register an LLM sanitize-request guardrail for this component.Nr5   rQ   s       r7   'register_llm_sanitize_request_guardrailz5PluginContext.register_llm_sanitize_request_guardrail   rU   r6   r   c                    dS )z?Register an LLM sanitize-response guardrail for this component.Nr5   rQ   s       r7   (register_llm_sanitize_response_guardrailz6PluginContext.register_llm_sanitize_response_guardrail   rU   r6   r   c                    dS )zCRegister an LLM conditional-execution guardrail for this component.Nr5   rQ   s       r7   ,register_llm_conditional_execution_guardrailz:PluginContext.register_llm_conditional_execution_guardrail   rU   r6   break_chainboolr   c                    dS )z5Register an LLM request intercept for this component.Nr5   rK   rE   rN   rd   rF   s        r7   register_llm_request_interceptz,PluginContext.register_llm_request_intercept   rU   r6   r   c                    dS )z7Register an LLM execution intercept for this component.Nr5   rQ   s       r7    register_llm_execution_interceptz.PluginContext.register_llm_execution_intercept   rM   r6   r   c                    dS )zARegister an LLM streaming execution intercept for this component.Nr5   rQ   s       r7   'register_llm_stream_execution_interceptz5PluginContext.register_llm_stream_execution_intercept   rU   r6   r   c                    dS )z5Register a tool request intercept for this component.Nr5   rg   s        r7   register_tool_request_interceptz-PluginContext.register_tool_request_intercept   rU   r6   r   c                    dS )z7Register a tool execution intercept for this component.Nr5   rQ   s       r7   !register_tool_execution_interceptz/PluginContext.register_tool_execution_intercept   rM   r6   N)rE   r.   rF   rG   rH   rI   )rE   r.   rN   rO   rF   r   rH   rI   )rE   r.   rN   rO   rF   r   rH   rI   )rE   r.   rN   rO   rF   r   rH   rI   )rE   r.   rN   rO   rF   r   rH   rI   )rE   r.   rN   rO   rF   r   rH   rI   )rE   r.   rN   rO   rF   r   rH   rI   )
rE   r.   rN   rO   rd   re   rF   r   rH   rI   )rE   r.   rN   rO   rF   r   rH   rI   )rE   r.   rN   rO   rF   r   rH   rI   )
rE   r.   rN   rO   rd   re   rF   r   rH   rI   )rE   r.   rN   rO   rF   r   rH   rI   )r1   r2   r3   r<   rL   rR   rT   rW   rY   r[   r]   r_   ra   rc   rh   rj   rl   rn   rp   r5   r6   r7   rD   rD   Y   sF       QQ                                               r6   rD   c                  "    e Zd ZdZddZdd
ZdS )Pluginz Custom plugin callback contract.plugin_configr   rH   list[ConfigDiagnostic] | Nonec                    dS )a(  Validate one component-local config object.

        Args:
            plugin_config: The `config` object from a single component.

        Returns:
            A list of diagnostics, or `None` for no diagnostics.

        Behavior:
            Error diagnostics block `initialize(...)`.
        Nr5   )rK   rs   s     r7   validatezPlugin.validate   s	     	r6   contextrD   rI   c                    dS )a  Install middleware and subscribers for one component instance.

        Args:
            plugin_config: The `config` object from a single component.
            context: Component-scoped registration context used to install
                middleware and subscribers.

        Returns:
            `None`.

        Behavior:
            Any exception aborts the current initialization and triggers
            rollback of partial registrations.
        Nr5   )rK   rs   rw   s      r7   registerzPlugin.register   s	     	r6   N)rs   r   rH   rt   )rs   r   rw   rD   rH   rI   )r1   r2   r3   r<   rv   ry   r5   r6   r7   rr   rr      sB        **        r6   rr   c                      e Zd ZddZdS )_SupportsToDictrH   r   c                    d S Nr5   rK   s    r7   to_dictz_SupportsToDict.to_dict   s      r6   NrH   r   )r1   r2   r3   r   r5   r6   r7   r{   r{      s        ((((((r6   r{   preserve_nullsvalueobjectr   re   rH   r   c                   t           d          r't          t                                                     S t	                     r1t           t                    s fdt                     D             S t           t                    rfd D             S t           t                    r fd 
                                D             S t          t                     S )Nr   c                p    i | ]2}t          |j                  }s||j        t          |          3S )Nr   )getattrrE   
_normalize).0
field_infofield_valuer   r   s      r7   
<dictcomp>z_normalize.<locals>.<dictcomp>   sW     
 
 
 'z ? ?	
 "-!8 OZNSSS "9!8!8r6   c                2    g | ]}t          |           S )r   r   )r   itemr   s     r7   
<listcomp>z_normalize.<locals>.<listcomp>   s&    RRRD
4???RRRr6   c                t    i | ]4\  }}s|	t          t          |          t          |p|dk              5S )Nconfigr   )r   r.   r   )r   keyvalr   s      r7   r   z_normalize.<locals>.<dictcomp>   sU     
 
 
S
 "% cNNJs>;\ST\_]]]!0r6   )hasattrr   r{   r   r   
isinstancetyper   listdictitemsr   )r   r   s   ``r7   r   r      s   ui   6OU++33555E 
:eT#:#: 

 
 
 
 
$Umm
 
 
 	
 % SRRRRERRRR% 

 
 
 
!KKMM
 
 
 	

 er6   r   c                F    t          t          t          |                     S r}   r   r   r   r   s    r7   _normalize_objectr      s    
Ju--...r6   c                J    t          t          t          | d                    S )NTr   r   r   s    r7   _normalize_component_configr      s    
JuTBBBCCCr6   T)slotsc                  F    e Zd ZU dZdZded<   dZded<   dZded<   dd
ZdS )ConfigPolicya  Policy for unsupported plugin configuration.

    Args:
        unknown_component: How to handle unknown component kinds.
        unknown_field: How to handle unknown fields inside known components.
        unsupported_value: How to handle known fields with unsupported values.

    Behavior:
        `"warn"` emits a warning diagnostic, `"error"` emits an error
        diagnostic that blocks initialization, and `"ignore"` suppresses the
        diagnostic entirely.
    warnr   unknown_componentunknown_fielderrorunsupported_valuerH   r   c                ,    | j         | j        | j        dS )z9Serialize this policy to the canonical JSON object shape.r   r   r   r   r~   s    r7   r   zConfigPolicy.to_dict  s%     "&!7!/!%!7
 
 	
r6   Nr   )	r1   r2   r3   r<   r   r4   r   r   r   r5   r6   r7   r   r      sk           .43333)/M////-44444
 
 
 
 
 
r6   r   c                  V    e Zd ZU dZded<   dZded<    ee          Zded	<   ddZ	dS )ComponentSpecaC  One top-level custom plugin component.

    Args:
        kind: Registered plugin kind string.
        enabled: Whether the component should be activated.
        config: Component-local JSON config object.

    Behavior:
        Disabled components are still validated but skipped during runtime
        registration.
    r.   kindTre   enableddefault_factoryr   r   rH   c                F    | j         | j        t          | j                  dS )z<Serialize this component to the canonical JSON object shape.)r   r   r   )r   r   r   r   r~   s    r7   r   zComponentSpec.to_dict  s*     I|1$+>>
 
 	
r6   Nr   )
r1   r2   r3   r<   r4   r   r   r   r   r   r5   r6   r7   r   r     sn         
 
 IIIGt444F4444
 
 
 
 
 
r6   r   c                  n    e Zd ZU dZdZded<    ee          Zded<    ee	          Z
ded	<   ddZdS )PluginConfiga|  Canonical plugin configuration document.

    Args:
        version: Plugin config schema version.
        components: Ordered list of top-level components. This may mix
            `plugin.ComponentSpec(...)` and `adaptive.ComponentSpec(...)`.
        policy: Plugin-level unsupported-config policy.

    Behavior:
        Component order is preserved during initialization.
       rO   versionr   zlist[object]
componentsr   policyrH   r   c                d    | j         d | j        D             | j                                        dS )z;Serialize this config to the canonical JSON document shape.c                ,    g | ]}t          |          S r5   r   )r   r:   s     r7   r   z(PluginConfig.to_dict.<locals>.<listcomp>>  s     RRRY:i00RRRr6   )r   r   r   )r   r   r   r   r~   s    r7   r   zPluginConfig.to_dict:  s<     |RR$/RRRk))++
 
 	
r6   Nr   )r1   r2   r3   r<   r   r4   r   r   r   r   r   r   r5   r6   r7   r   r   (  s         
 
 G$uT:::J:::: 5>>>F>>>>
 
 
 
 
 
r6   r   c                  j    e Zd ZU dZded<   ded<   ded<   dZded	<    ee
          Zded<   ddZ	dS )DynamicPluginActivationSpeca  One dynamic plugin component to load and activate.

    Args:
        plugin_id: Expected plugin identifier from the authored manifest.
        kind: Dynamic plugin execution lane.
        manifest_ref: Path to the authored ``relay-plugin.toml``.
        environment_ref: Optional lifecycle-managed environment path. Python
            workers require the path created by Relay's plugin lifecycle.
        config: Component-local JSON configuration.
    r.   	plugin_idDynamicPluginKindr   manifest_refNz
str | Noneenvironment_refr   r   r   rH   c                x    | j         | j        | j        t          | j                  d}| j        
| j        |d<   |S )zDSerialize this activation specification to its canonical JSON shape.)r   r   r   r   Nr   )r   r   r   r   r   r   )rK   r   s     r7   r   z#DynamicPluginActivationSpec.to_dictV  sK     I -1$+>>	
 
 +'+';E#$r6   r   )
r1   r2   r3   r<   r4   r   r   r   r   r   r5   r6   r7   r   r   C  s         	 	 NNN"&O&&&&t444F4444
 
 
 
 
 
r6   r   c                  f    e Zd ZdZdZddZedd	            Zedd            ZddZ	ddZ
ddZdS )PluginHostActivationa$  Owned lifetime for one process-wide dynamic plugin host.

    Keep this object alive while agent code may invoke callbacks from the
    loaded plugins. Prefer ``async with`` or call :meth:`close` explicitly.
    Native finalization performs best-effort cleanup when an object is dropped.
    _nativenative_NativePluginHostActivationrH   rI   c                    || _         d S r}   r   )rK   r   s     r7   __init__zPluginHostActivation.__init__m  s    r6   r?   c                @    t          t          | j        j                  S )z8Return the validation report captured during activation.)r   r?   r   reportr~   s    r7   r   zPluginHostActivation.reportp  s     L$,"5666r6   re   c                    | j         j        S )zReturn whether this activation handle has not begun teardown.

        ``False`` does not guarantee another process-wide activation can start;
        failed teardown may intentionally retain the activation owner.
        )r   	is_activer~   s    r7   r   zPluginHostActivation.is_activeu  s     |%%r6   c                H   K   | j                                          d{V  dS )z<Clear callbacks and unload plugins; repeated calls are safe.N)r   closer~   s    r7   r   zPluginHostActivation.close~  s2      l  """""""""""r6   r   c                
   K   | S )z7Return this active host when entering an async context.r5   r~   s    r7   
__aenter__zPluginHostActivation.__aenter__  s      r6   exc_typetype[BaseException] | None	exc_valueBaseException | None	tracebackTracebackType | Nonec                D   K   ~~~|                                   d{V  dS )z-Close the host when leaving an async context.N)r   )rK   r   r   r   s       r7   	__aexit__zPluginHostActivation.__aexit__  s5       ijjllr6   N)r   r   rH   rI   )rH   r?   )rH   re   rH   rI   )rH   r   )r   r   r   r   r   r   rH   rI   )r1   r2   r3   r<   	__slots__r   propertyr   r   r   r   r   r5   r6   r7   r   r   c  s          I    7 7 7 X7 & & & X&# # # #        r6   r   r   PluginConfig | JsonObjectc                `    t          t          t          t          |                               S )al  Validate a plugin configuration without changing runtime state.

    Args:
        config: `PluginConfig` or an equivalent JSON object.

    Returns:
        The validation report for the supplied config.

    Behavior:
        Validation checks plugin-level compatibility, unknown component kinds,
        multiplicity rules, and per-plugin validation logic.
    )r   r?   _validate_plugin_configr   r   s    r7   rv   rv     s&     56G6O6OPPQQQr6   c                p   K   t          t          t          t          |                      d{V           S )a  Validate and activate a plugin configuration.

    Args:
        config: `PluginConfig` or an equivalent JSON object.

    Returns:
        The report for the successfully activated configuration.

    Behavior:
        Initialization replaces the current active plugin configuration. Partial
        registration is rolled back on failure, and the previous configuration
        is restored when possible.
    N)r   r?   _initialize_pluginsr   r   s    r7   
initializer     s<       $78I&8Q8Q$R$RRRRRRRSSSr6   dynamic_plugins.list[DynamicPluginActivationSpec | JsonObject]c                   K   d |D             }t          t          |           |           d{V }t          |          S )aS  Initialize registered components with dynamic plugins as one owned host.

    Args:
        config: Base plugin configuration layered over the discovered
            ``plugins.toml`` files before dynamic components are appended. It
            may contain statically registered components.
        dynamic_plugins: Non-empty ordered activation specifications. Dataclass
            instances and equivalent JSON objects may be mixed.

    Returns:
        An owned activation containing the successful validation report.

    Behavior:
        Only one dynamic plugin host may be active in a process. Errors roll
        back partial loads. The returned object must remain alive until agent
        work is complete. This is the owned initialization path when dynamic
        plugins are configured; use :func:`initialize` for static-only config.
    c                ,    g | ]}t          |          S r5   )r   )r   specs     r7   r   z3initialize_with_dynamic_plugins.<locals>.<listcomp>  s!    NNNd+D11NNNr6   N) _initialize_with_dynamic_pluginsr   r   )r   r   normalized_pluginsr   s       r7   r%   r%     sV      , ONoNNN34Ef4M4MOabbbbbbbbF'''r6   rI   c                 "    t                       dS )zClear the active plugin configuration.

    Returns:
        `None`.

    Behavior:
        This removes active component registrations but leaves the plugin kind
        registry intact for future validation or initialization.
    N)_clear_plugin_configurationr5   r6   r7   clearr     s      !!!!!r6   )clear_on_exitr   AsyncIterator[ConfigReport]c                 K   t          |            d{V }	 |W V  t          j                     |rt                       dS dS # t          j                     |rt                       w w xY w)a  Context manager for plugin initialization and cleanup.

    Args:
        config: `PluginConfig` or an equivalent JSON object.
        clear_on_exit: Whether to clear the plugin configuration on exit.

    Yields:
        The `ConfigReport` for the initialized configuration.

    Behavior:
        This context manager initializes the plugin configuration on entry and clears it on exit.
    N)r   r   flushr   )r   r   report_s      r7   pluginr     s       v&&&&&&&&G 	GGGGG	 	 	 	GGGG	s   A &A+ConfigReport | Nonec                 J    t          t          dz  t                                S )aM  Return the last successful plugin report.

    Returns:
        The active `ConfigReport`, or `None` when no plugin configuration is
        currently active.

    Behavior:
        This reports the last successfully activated configuration snapshot. It
        does not revalidate plugin state or inspect pending registrations.
    N)r   r?   _active_plugin_reportr5   r6   r7   r   r     s      t#%:%<%<===r6   	list[str]c                     t                      S )zList registered custom plugin kinds.

    Returns:
        A sorted list of plugin kind strings known to the plugin registry.

    Behavior:
        This reports available plugin kinds, not the currently active
        component set.
    )_list_plugin_kindsr5   r6   r7   
list_kindsr     s     r6   plugin_kindr.   r   c                &    t          | |           dS )a	  Register a custom plugin implementation.

    Args:
        plugin_kind: Unique top-level component kind string.
        plugin: Custom plugin implementation.

    Returns:
        `None`.

    Behavior:
        Registering the same kind twice raises an error.
    N)_register_plugin)r   r   s     r7   ry   ry     s     [&)))))r6   c                     t          |           S )a{  Deregister a custom plugin kind.

    Args:
        plugin_kind: Kind string to remove from the plugin registry.

    Returns:
        `True` if a plugin was removed, otherwise `False`.

    Behavior:
        This affects future validation and initialization only. Active runtime
        registrations remain until `clear()` or the next successful
        `initialize(...)`.
    )_deregister_plugin)r   s    r7   
deregisterr     s     k***r6   )r   r9   r   r?   r   r   r   rD   r   rr   r%   r   r   r   r   ry   r   rv   N)r   r   r   re   rH   r   )r   r   rH   r   )r   r   rH   r?   )r   r   r   r   rH   r   r   )r   r   r   re   rH   r   )rH   r   )rH   r   )r   r.   r   rr   rH   rI   )r   r.   rH   re   )Qr<   
__future__r   
contextlibr   dataclassesr   r   r   r   typingr	   r
   r   r   r   r   r   r   
nemo_relayr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   nemo_relay._nativer    r   r!   r   r"   r   r#   r   r$   r   r%   r   r&   r   r'   r   r(   r   typesr)   r*   r,   r9   r?   r   rD   rr   r{   r   r   r   r   r   r   r   r   rv   r   r   r   r   r   ry   r   __all__r5   r6   r7   <module>r     s    # " " " " " * * * * * * > > > > > > > > > > > > c c c c c c c c c c c c c c c c c c c c                                 " T S S S S S                                          !######          	       0    ( ( ( ( (9 ( ( ( 45  5Q Q Q Q QH Q Q Qh         X      F) ) ) ) )h ) ) ) 9>      */ / / /D D D D 
 
 
 
 
 
 
 
6 
 
 
 
 
 
 
 
4 
 
 
 
 
 
 
 
4        >+ + + + + + + +\R R R R T T T T"( ( ( (6
" 
" 
" 
" MQ      ,> > > >
  
  
  
 * * * * + + + +"  r6   