
    Rmj1                       d 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 ddl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  G d
 de          Z G d ded          Z G d de          Z G d de
          ZdJdZdKdZ ed           G d d                      Z ed           G d d                       Z  ed           G d! d"                      Z! ed           G d# d$                      Z" ed           G d% d&                      Z# ed           G d' d(                      Z$ ed           G d) d*                      Z% ed           G d+ d,                      Z& ed           G d- d.                      Z'd/Z( ed           G d0 d1                      Z)dLd4Z*d5d5d5d6dMdDZdNdHZg dIZ+d5S )OzAdaptive plugin configuration helpers.

Adaptive is configured as a single flat top-level plugin component. Hosted
plugins remain separate top-level components managed through ``nemo_relay.plugin``.
    )annotations)	dataclassfieldfieldsis_dataclass)LiteralProtocol	TypedDictcast)Json
JsonObjectUnsupportedBehavior)AdaptiveRuntime)build_cache_telemetry_event)set_latency_sensitivity)validate_adaptive_configc                  .    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__     [/home/thesage/.hermes/hermes-agent/venv/lib/python3.11/site-packages/nemo_relay/adaptive.pyr   r      s.         &&&&IIILLLLLr   r   c                  (    e Zd ZU dZded<   ded<   dS )ConfigDiagnosticz#One adaptive validation diagnostic.r   	componentr   Nr   r   r   __doc__r   r   r   r   r!   r!      s(         --NNNJJJJJr   r!   F)totalc                      e Zd ZU dZded<   dS )ConfigReportz-Validation report for adaptive configuration.zlist[ConfigDiagnostic]diagnosticsNr#   r   r   r   r'   r'   #   s$         77''''''r   r'   c                      e Zd ZddZdS )_SupportsToDictreturnr   c                    d S Nr   selfs    r   to_dictz_SupportsToDict.to_dict*   s      r   Nr+   r   )r   r   r   r0   r   r   r   r*   r*   )   s        ((((((r   r*   valueobjectr+   r   c                    t           d          r't          t                                                     S t	                     r1t           t                    s fdt                     D             S t           t                    rd  D             S t           t                    rd  
                                D             S t          t                     S )Nr0   c                h    i | ].}t          |j                  x|j        t                    /S r-   )getattrname
_normalize).0
field_infofield_valuer2   s     r   
<dictcomp>z_normalize.<locals>.<dictcomp>1   sF     
 
 
&ujo>>>K OZ44KKKr   c                ,    g | ]}t          |          S r   )r8   )r9   items     r   
<listcomp>z_normalize.<locals>.<listcomp>7   s     333T
4  333r   c                ^    i | ]*\  }}|t          t          |          t          |          +S r-   )r   r   r8   )r9   keyvals      r   r<   z_normalize.<locals>.<dictcomp>9   s2    aaaHCQTQ`S#
3Q`Q`Q`r   )hasattrr   r*   r0   r   
isinstancetyper   listdictitemsr   )r2   r;   s   `@r   r8   r8   -   s    ui   6OU++33555E 
:eT#:#: 

 
 
 
 
$Umm
 
 
 	

 % 433U3333% baaaaaaer   r   c                F    t          t          t          |                     S r-   )r   r   r8   )r2   s    r   _normalize_objectrJ   =   s    
Ju--...r   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 adaptive configuration.

    Args:
        unknown_component: How to handle unknown component kinds.
        unknown_field: How to handle unknown adaptive config fields.
        unsupported_value: How to handle known fields with unsupported values.
    warnr   unknown_componentunknown_fielderrorunsupported_valuer+   r   c                ,    | j         | j        | j        dS )z9Serialize this policy to the canonical JSON object shape.rO   rP   rR   rT   r.   s    r   r0   zConfigPolicy.to_dictO   s%     "&!7!/!%!7
 
 	
r   Nr1   )	r   r   r   r$   rO   r   rP   rR   r0   r   r   r   rM   rM   A   sk           .43333)/M////-44444
 
 
 
 
 
r   rM   c                  z    e Zd ZU dZded<    ee          Zded<   edd	            Z	eddd            Z
ddZdS )BackendSpeczAdaptive state backend selection.

    Args:
        kind: Backend kind string such as ``"in_memory"`` or ``"redis"``.
        config: Backend-specific JSON object.
    r   kinddefault_factoryr   configr+   'BackendSpec'c                 "    t          d          S )z*Return an in-memory adaptive backend spec.	in_memory)rW   rV   r   r   r   r]   zBackendSpec.in_memoryd   s     ,,,,r   nemo_relay:url
key_prefixc                *    t          d| |d          S )z%Return a Redis adaptive backend spec.redisr`   ra   rW   rZ   r^   rd   s     r   rc   zBackendSpec.redisi   s     :0V0VWWWWr   c                :    | j         t          | j                  dS )z?Serialize this backend spec to the canonical JSON object shape.re   )rW   rJ   rZ   r.   s    r   r0   zBackendSpec.to_dictn   s    	->t{-K-KLLLr   N)r+   r[   )r_   )r`   r   ra   r   r+   r[   r1   )r   r   r   r$   r   r   rG   rZ   staticmethodr]   rc   r0   r   r   r   rV   rV   X   s           IIIt444F4444- - - \- X X X X \XM M M M M Mr   rV   c                  &    e Zd ZU dZded<   ddZdS )	StateConfigzAdaptive state configuration.

    Args:
        backend: State backend selection for adaptive features that persist or
            learn over time.
    rV   backendr+   r   c                .    dt          | j                  iS )z?Serialize this state config to the canonical JSON object shape.rj   )rJ   rj   r.   s    r   r0   zStateConfig.to_dict~   s    ,T\::;;r   Nr1   )r   r   r   r$   r   r0   r   r   r   ri   ri   s   sB           < < < < < <r   ri   c                  L    e Zd ZU dZdZded<    ee          Zded<   dd
Z	dS )TelemetryConfigzBuilt-in adaptive telemetry subscriber settings.

    Args:
        subscriber_name: Optional subscriber registration name override.
        learners: Enabled learner identifiers.
    N
str | Nonesubscriber_namerX   z	list[str]learnersr+   r   c                :    t          | j        | j        d          S )zCSerialize this telemetry config to the canonical JSON object shape.)ro   rp   )rJ   ro   rp   r.   s    r   r0   zTelemetryConfig.to_dict   s)     #'#7 M 
 
 	
r   r1   )
r   r   r   r$   ro   r   r   rF   rp   r0   r   r   r   rm   rm      se           #'O&&&&%555H5555
 
 
 
 
 
r   rm   c                  T    e Zd ZU dZdZded<   dZded<   dZded	<   d
Zded<   ddZ	dS )AdaptiveHintsConfigaa  Built-in adaptive hints injection settings.

    Args:
        priority: Intercept priority. Lower values run first.
        break_chain: Whether to stop later request intercepts after this one.
        inject_header: Whether to inject the adaptive hints HTTP header.
        inject_body_path: JSON body path used when injecting request-body hints.
    d   intpriorityFboolbreak_chainTinject_headerznvext.agent_hintsr   inject_body_pathr+   r   c                R    t          | j        | j        | j        | j        d          S )zHSerialize this adaptive-hints config to the canonical JSON object shape.)rv   rx   ry   rz   )rJ   rv   rx   ry   rz   r.   s    r   r0   zAdaptiveHintsConfig.to_dict   s5      M#/!%!3$($9	 
 
 	
r   Nr1   )
r   r   r   r$   rv   r   rx   ry   rz   r0   r   r   r   rs   rs      s{           HKM/////	
 	
 	
 	
 	
 	
r   rs   c                  8    e Zd ZU dZdZded<   dZded<   dd
ZdS )ToolParallelismConfiga.  Built-in adaptive tool scheduling settings.

    Args:
        priority: Intercept priority. Lower values run first.
        mode: Scheduling mode. ``"observe_only"`` records signals without
            changing behavior, while other modes enable stronger adaptive
            scheduling behavior.
    rt   ru   rv   observe_onlyz3Literal['observe_only', 'inject_hints', 'schedule']moder+   r   c                :    t          | j        | j        d          S )zJSerialize this tool-parallelism config to the canonical JSON object shape.)rv   r   )rJ   rv   r   r.   s    r   r0   zToolParallelismConfig.to_dict   s     dmTY!O!OPPPr   Nr1   )r   r   r   r$   rv   r   r   r0   r   r   r   r}   r}      s^           H@NDNNNNQ Q Q Q Q Qr   r}   c                  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 )AcgStabilityThresholdsaL  Prompt-stability classification thresholds for ACG.

    Args:
        stable_threshold: Minimum effective score classified as stable.
        semi_stable_threshold: Minimum effective score classified as semi-stable.
        min_observations_for_full_confidence: Observation count required to
            reach full confidence.
    gffffff?floatstable_thresholdg      ?semi_stable_threshold   ru   $min_observations_for_full_confidencer+   r   c                F    t          | j        | j        | j        d          S )zLSerialize these ACG stability thresholds to the canonical JSON object shape.)r   r   r   )rJ   r   r   r   r.   s    r   r0   zAcgStabilityThresholds.to_dict   s0     $($9)-)C8<8a 
 
 	
r   Nr1   )	r   r   r   r$   r   r   r   r   r0   r   r   r   r   r      sl           #""""#'''''02(2222
 
 
 
 
 
r   r   c                  h    e Zd ZU dZdZded<   dZded<   dZded	<    ee	
          Z
ded<   ddZdS )	AcgConfiga#  Adaptive Cache Governor settings.

    Args:
        provider: Provider cache plugin name.
        observation_window: Rolling PromptIR observation window size.
        priority: LLM execution intercept priority.
        stability_thresholds: Prompt-stability classification thresholds.
    passthroughz-Literal['anthropic', 'openai', 'passthrough']providerrt   ru   observation_window2   rv   rX   zAcgStabilityThresholds | Nonestability_thresholdsr+   r   c                l    t          | j        | j        | j        t	          | j                  d          S )z=Serialize this ACG config to the canonical JSON object shape.)r   r   rv   r   )rJ   r   r   rv   r8   r   r.   s    r   r0   zAcgConfig.to_dict   s<      M&*&= M(243L(M(M	 
 
 	
r   Nr1   )r   r   r   r$   r   r   r   rv   r   r   r   r0   r   r   r   r   r      s           ?LHKKKK!!!!!H:?%Pf:g:g:ggggg	
 	
 	
 	
 	
 	
r   r   c                      e Zd ZU dZdZded<   dZded<   dZded	<   dZd
ed<   dZ	ded<   dZ
ded<   dZded<    ee          Zded<   ddZdS )AdaptiveConfiga  Canonical config document for the top-level adaptive component.

    Args:
        version: Adaptive config schema version.
        agent_id: Optional explicit agent identifier for learned state.
        state: Adaptive state backend configuration.
        telemetry: Built-in adaptive telemetry settings.
        adaptive_hints: Built-in LLM hint-injection settings.
        tool_parallelism: Built-in tool scheduling settings.
        acg: Adaptive Cache Governor settings.
        policy: Unsupported-config policy applied within the adaptive config.

    Behavior:
        This document configures only the adaptive component. Plugins are
        configured separately through top-level plugin components.
       ru   versionNrn   agent_idzStateConfig | NonestatezTelemetryConfig | None	telemetryzAdaptiveHintsConfig | Noneadaptive_hintszToolParallelismConfig | Nonetool_parallelismzAcgConfig | NoneacgrX   rM   policyr+   r   c           	        | j         | j        t          | j                  t          | j                  t          | j                  t          | j                  t          | j                  | j        	                                dS )zBSerialize this adaptive config to the canonical JSON object shape.)r   r   r   r   r   r   r   r   )
r   r   r8   r   r   r   r   r   r   r0   r.   s    r   r0   zAdaptiveConfig.to_dict  sq     |
++#DN33()<== *4+@ A Adh''k))++	
 	
 		
r   r1   )r   r   r   r$   r   r   r   r   r   r   r   r   r   rM   r   r0   r   r   r   r   r      s          " GH $E$$$$(,I,,,,15N5555599999 C     5>>>F>>>>
 
 
 
 
 
r   r   adaptivec                  4    e Zd ZU dZded<   dZded<   dd	Zd
S )ComponentSpeczTop-level adaptive component wrapper.

    Args:
        config: ``AdaptiveConfig`` or an equivalent JSON object.
        enabled: Whether the adaptive component should be activated.

    Behavior:
        The component kind is always ``"adaptive"``.
    AdaptiveConfig | JsonObjectrZ   Trw   enabledr+   r   c                F    t           | j        t          | j                  dS )z7Serialize this component to the canonical plugin shape.)rW   r   rZ   )ADAPTIVE_PLUGIN_KINDr   rJ   rZ   r.   s    r   r0   zComponentSpec.to_dict:  s(     )|'44
 
 	
r   Nr1   )r   r   r   r$   r   r   r0   r   r   r   r   r   +  sS           ('''G
 
 
 
 
 
r   r   rZ   r   c                `    t          t          t          t          |                               S )zDValidate an adaptive config document without constructing a runtime.)r   r'   _validate_adaptive_configrJ   )rZ   s    r   validate_configr   C  s$    78I&8Q8QRRSSSr   N)usagerequest_facts	timestampr   r   
request_idr   JsonObject | Noner   r   template_versiontoolset_hashmodel_familytenant_scoper   rn   c        
        `    t          t          dz  t          | |||||||||	
  
                  S )zHBuild one canonical cache telemetry event from usage plus request facts.N
r   r   r   r   r   r   r   r   r   r   )r   r   _build_cache_telemetry_eventr   s
             r   r   r   H  sN     T$!'-%%%	
 	
 	
  r   r   ru   Nonec                $    t          |            dS )a  Set a request-local latency-sensitivity hint.

    Args:
        level: Positive integer sensitivity value for the current execution
            context.

    Returns:
        `None`.

    Behavior:
        This is an execution-time hint for the current request/scope context,
        not persistent adaptive configuration. The native adaptive layer stores
        this as a positive integer.
    N)_set_latency_sensitivity)r   s    r   r   r   g  s     U#####r   )r   r   r   rs   r   rV   r!   rM   r'   r   ri   rm   r}   r   r   )r2   r3   r+   r   )r2   r3   r+   r   )rZ   r   r+   r'   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rn   r+   r   )r   ru   r+   r   ),r$   
__future__r   dataclassesr   r   r   r   typingr   r	   r
   r   
nemo_relayr   r   r   nemo_relay._nativer   r   r   r   r   r   r   r   r!   r'   r*   r8   rJ   rM   rV   ri   rm   rs   r}   r   r   r   r   r   r   __all__r   r   r   <module>r      s    # " " " " " > > > > > > > > > > > > 5 5 5 5 5 5 5 5 5 5 5 5 < < < < < < < < < < A A A A A A Z Z Z Z Z Z R R R R R R T T T T T T    	       0    ( ( ( ( (9 ( ( () ) ) ) )h ) ) )    / / / / 
 
 
 
 
 
 
 
, M M M M M M M M4 < < < < < < < < 
 
 
 
 
 
 
 
* 
 
 
 
 
 
 
 
6 Q Q Q Q Q Q Q Q$ 
 
 
 
 
 
 
 
2 
 
 
 
 
 
 
 
6 &
 &
 &
 &
 &
 &
 &
 &
R "  
 
 
 
 
 
 
 
.T T T T  $'+ !     >$ $ $ $$  r   