
    Jjt                   X   d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	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 ddlmZ ddlmZ ddl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#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ddl<m=Z= ddl>m?Z?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddlGmHZHmIZI  ejJ        eK          ZLdZMdOdZNdPd#ZOd$ ZPdQd'ZQdRd)ZRdSd,ZSdTd.ZTdUd/ZUdVd0ZVd1 ZWdWd3ZXdXdYd7ZYd8ZZdZd?Z[d@ Z\	 	 	 	 	 	 	 d[d\dMZ]dNgZ^dS )]u  The agent conversation loop — extracted from ``run_agent.AIAgent``.

This is the biggest single chunk pulled out of ``run_agent.py``: the
roughly 3,900-line :func:`run_conversation` body that drives one user
turn through the agent (model call, tool dispatch, retries, fallbacks,
compression, post-turn hooks, background memory/skill review nudges).

The function takes the parent ``AIAgent`` instance as its first
argument (``agent``) and accesses its state via attribute lookup.
``_ra().AIAgent.run_conversation`` is now a thin forwarder.

Symbols that production code or tests patch on ``run_agent`` directly
(``handle_function_call``, ``_set_interrupt``, ``OpenAI``, ...) are
resolved through :func:`_ra` so those patches keep working.
    )annotationsN)AnyDictListOptional)_summarize_user_message_for_log)&conversation_history_after_compression)KawaiiSpinner)FailoverReasonclassify_api_error)IterationBudget)build_turn_context)TurnRetryState)build_memory_context_block)
close_interrupted_tool_sequence_repair_tool_call_arguments_sanitize_messages_non_ascii_sanitize_messages_surrogates_sanitize_structure_non_ascii_sanitize_structure_surrogates_sanitize_surrogates_sanitize_tools_non_ascii_strip_images_from_messages_strip_non_ascii)MINIMUM_CONTEXT_LENGTHestimate_messages_tokens_roughestimate_request_tokens_rough&get_context_length_from_provider_erroris_output_cap_error(parse_available_output_tokens_from_errorsave_context_length)_install_safe_stdio)apply_anthropic_cache_control)adaptive_rate_limit_backoffjittered_backoff)has_incomplete_scratchpad)estimate_usage_costnormalize_usage)PARTIAL_STREAM_STUB_ID)set_session_context)set_current_write_origin)base_url_host_matchesenv_var_enabledz3Operation interrupted: waiting for model response (error	ExceptionreturnOptional[int]c                   g }| t          | dd          t          | dd          fD ]8}|r4	 |                    t          |                     (# t          $ r Y 4w xY w9d                    |                                          }d|vsd|vsd|vrdS t          j        d|          }|sdS 	 t          |	                    d	                    }n# t          $ r Y dS w xY wd
|cxk    rdk    rn n|S dS )z@Extract a provider-reported image dimension ceiling, if present.messageNbody image	dimensionzmax allowed sizez8max allowed size(?:\s+for [^:]+)?:\s*(\d{3,5})\s*pixels?   i   @  )getattrappendstrr/   joinlowerresearchintgroup
ValueError)r.   partsvaluetextmatchmax_dimensions         =/home/rurouni/.hermes/hermes-agent/agent/conversation_loop.py_image_error_max_dimensionrJ   M   sX   Ey$''vt$$ 	 	
  	SZZ((((   	
 88E??  ""Ddk559KSW9W9WtIQSWXXE tEKKNN++   tt
m####t#####4s#   "A
AA."C 
CCagentr   request_tokensrA   Optional[str]c                   t          | dd          sdS t          | dd          }t          |t                    r|dk    rdS |t          k    rdS t          | dd          pd}t          | dd          pd	}t          | d
d          pd}t	          t          | dd          pg           }t
                              d||||t          ||t          | dd          pd	  	         d| d|ddt          ddS )zIReturn a user-facing error when Ollama is loaded with too little context.toolsN_ollama_num_ctxr   model the selected modelbase_urlzunknown base URLproviderunknownzOllama runtime context too small for Hermes tool use: model=%s provider=%s base_url=%s runtime_context=%d minimum_context=%d estimated_request_tokens=%d tool_count=%d session=%s
session_idnonezOllama loaded `z` with only ,z6 tokens of runtime context, but Hermes needs at least a   tokens for reliable tool use.

Increase the Ollama context for this model and restart/reload the model before trying again. A known-good starting point is 65,536 tokens. In Hermes config, set `model.ollama_num_ctx: 65536` (and `model.context_length: 65536` if you also override the displayed model context). If you manage the model through an Ollama Modelfile, set `PARAMETER num_ctx 65536` there instead.)r:   
isinstancerA   r   lenloggerwarning)rK   rL   runtime_ctxrQ   rT   rU   
tool_counts          rI   _ollama_context_limit_errorr`   j   sA   5'4(( t%!2D99Kk3'' ;!+;+;t,,,tE7B''?+?Euj"--C1CHuj"--:HWUGT228b99J
NN	 	|T**4f   	7% 	7 	7[O 	7 	7.DP	7 	7 	7
    c                     ddl } | S )zLazy reference to ``run_agent`` so callers can patch
    ``run_agent.handle_function_call`` / ``run_agent._set_interrupt`` /
    ``run_agent.OpenAI`` and have those patches reach this code path.
    r   N	run_agentrc   s    rI   _rare      s    
 ra   
capabilityr<   c                p    	 ddl m}m}  |d          } |||           }|pdS # t          $ r Y dS w xY w)Nr   )&format_nous_portal_entitlement_messageget_nous_portal_account_infoTforce_fresh)rf   rR   )hermes_cli.nous_accountrh   ri   r/   )rf   rh   ri   account_infor3   s        rI   _nous_entitlement_messagern      s    	
 	
 	
 	
 	
 	
 	
 	

 43EEE88!
 
 
 }"   rrs   $' 
55boolc                    t          |          }|sdS |                                D ]#}|                     | j         d| d           $dS )NF      💡 Tforce)rn   
splitlines_vprint
log_prefix)rK   rf   r3   lines       rI    _print_nous_entitlement_guidancerx      sh    '
33G u""$$ G G)99499FFFF4ra   rU   rT   c                    | pd                                                                 } | dk    rdS t          |pd          }t          |d          pt          |d          S )NrR   nousTzinference-api.nousresearch.comzinference.nousresearch.com)stripr>   r<   r,   )rU   rT   bases      rI   _is_nous_inference_router}      sk    B%%''--//H6tx~2Dd$DEE 	E 'CDDra   rQ   c                   t          ||          rt          |           S |pd                                pd}|pd                                pd}|pd                                                                dk    r | d| dddg}d	                    |          S | d
| ddg}t          t          |pd          d          r|                    d           |                    d           d	                    |          S )NrR   zthe selected providerrS   	anthropicz? reported that your Claude subscription usage is exhausted for z( (included quota + extra-usage credits).zdOptions: wait for the billing cycle to reset, or add extra usage at https://claude.ai/settings/usagezjYou can also switch to an Anthropic API key or another provider with /model <model> --provider <provider>.
zI reported that billing, credits, or account entitlement is exhausted for .z=Add credits or update billing with that provider, then retry.openrouter.aiz:OpenRouter credits: https://openrouter.ai/settings/creditszOYou can switch providers temporarily with /model <model> --provider <provider>.)r}   rn   r{   r>   r=   r,   r<   r;   )rf   rU   rT   rQ   provider_labelmodel_labelliness          rI   _billing_or_entitlement_messager      sU     (33 5(444n"++--H1HN;B%%''?+?K 	B%%'';66 " W W!,W W W/4	
 yy  ; ;,7; ; ; 	HE SR00/BB SQRRR	LLbccc99Ura   c                   t          ||||          }|sdS |                                D ]#}|                     | j         d| d           $dS )Nrf   rU   rT   rQ   Frq   Trr   )r   rt   ru   rv   )rK   rf   rU   rT   rQ   r3   rw   s          rI   &_print_billing_or_entitlement_guidancer      s     .	  G  u""$$ G G)99499FFFF4ra   c                    	 ddl m}  |d          }|j        durdS |                     d          S # t          $ r Y dS w xY w)zFRefresh Nous runtime credentials after a fresh paid-entitlement check.r   )ri   Trj   Frr   )rl   ri   paid_service_access$_try_refresh_nous_client_credentialsr/   )rK   ri   rm   s      rI   ._try_refresh_nous_paid_entitlement_credentialsr     s    
HHHHHH33EEE+477599 : 
 
 	
    uus   5 5 
AAc           
        d}d}|r| j         r	 | j                             | j                  }|'|                    d          }|d}n|dk    rd}n|}d}n8# t          $ r+}t
                              d| j        |           Y d}~nd}~ww xY w|rt          | |          r	|| _        dS |rFd	}t
          	                    d
| j        t          | dd          pdt          | dd          pd           |r%|dv r!t
                              d| j        |           |                     |          | _        	 ddlm}  |d| j        | j        t          | dd          pd           n2# t          $ r%}t
                              d|           Y d}~nd}~ww xY w	 ddlm}	  |	|            n,# t          $ r t
                              dd           Y nw xY w| j         ra	 | j                             | j        | j                   dS # t          $ r,}t
                              d| j        |           Y d}~dS d}~ww xY wdS )u_  Restore the cached system prompt from the session DB or build it fresh.

    Mutates ``agent._cached_system_prompt`` and persists a freshly-built
    prompt back to the session DB on first build.  Extracted from
    ``run_conversation`` so the prefix-cache restore path can be tested in
    isolation.

    Three-way state distinction for the stored row, surfaced via logs so
    silent prefix-cache misses are visible in ``agent.log``:

      * ``missing`` — no session row yet (legitimate first turn).
      * ``null``   — row exists, ``system_prompt`` column is NULL.
        Legacy session predating system-prompt persistence, or a migration
        leftover.  Warns when ``conversation_history`` is non-empty.
      * ``empty``  — row exists, ``system_prompt`` column is the empty
        string.  Indicates a previous-turn write that ran but stored
        nothing (silent persistence bug).  Always warns.
      * ``present`` — row exists with a usable prompt → reused verbatim.

    Read or write failures against the session DB log at WARNING (not
    DEBUG) so persistent issues (disk full, schema drift, lock contention)
    surface without needing verbose mode.  This used to be a debug-level
    log that silently broke prefix-cache reuse on the gateway path
    (which constructs a fresh ``AIAgent`` per turn and depends on this
    DB roundtrip).
    Nmissingsystem_promptnullrR   emptypresentu   Session DB get_session failed for system-prompt restore (session=%s): %s. Falling back to fresh build — prefix cache will miss for this turn.stale_runtimezdStored system prompt for session %s has stale runtime identity; rebuilding for model=%s provider=%s.rQ   rU   )r   r   zStored system prompt for session %s is %s; rebuilding from scratch this turn. Prefix cache will miss until the rebuild persists. Investigate the previous turn's update_system_prompt write path.r   )invoke_hookon_session_startplatform)rW   rQ   r   z on_session_start hook failed: %s)seed_credits_at_session_startz*cold-start credits seed failed (fail-open)Texc_infozSession DB update_system_prompt failed for session %s: %s. Subsequent turns will rebuild the system prompt and miss the prefix cache.)_session_dbget_sessionrW   getr/   r\   r]   _stored_prompt_matches_runtime_cached_system_promptinfor:   _build_system_prompthermes_cli.pluginsr   rQ   agent.credits_trackerr   debugupdate_system_prompt)
rK   system_messageconversation_historystored_promptstored_statesession_row
raw_promptexc_invoke_hookr   s
             rI   _restore_or_build_system_promptr     s]   6 ML  1 	+778HIIK&(___==
%#)LL2%%#*LL$.M#,L 	 	 	NN1  #	       	  7}MM  '4# 
&3E7B''-2E:r**0b	
 	
 	
  
0A A A
 	/ l	
 	
 	
 #("<"<^"L"LE
	@BBBBBB'+UJ55;		
 	
 	
 	
 	
  @ @ @93????????@RGGGGGG%%e,,,, R R RADQQQQQR  		2253CUE`aaaaa 	 	 	NN)  #	        		 	sZ   AA 
B"!BB50E& &
F0FFF+ +&GG%H 
H<!H77H<promptc                8   dfd} |d          }t          t          | dd          pd                                          }|r
|r||k    rdS  |d	          }t          t          | d
d          pd                                          }|r
|r||k    rdS dS )z?Return False when the persisted Model/Provider lines are stale.labelr<   r0   c                    |  d}d}                                 D ]@}|                    |          r)|t          |          d                                          }A|S )N:rR   )rt   
startswithr[   r{   )r   prefixrE   rw   r   s       rI   
line_valuez2_stored_prompt_matches_runtime.<locals>.line_value  sh    %%'' 	3 	3Dv&& 3S[[\\*0022ra   ModelrQ   rR   FProviderrU   T)r   r<   r0   r<   )r<   r:   r{   )rK   r   r   stored_modelcurrent_modelstored_providercurrent_providers    `     rI   r   r     s          :g&&Lw339r::@@BBM  ,-*G*Gu j,,O75*b99?R@@FFHH + CS0S0Su4ra   is_partial_stubdropped_toolsOptional[List[str]]c                `    | r%|r#d                     |d d                   }d| dS | r	 dS 	 dS )N,    z"[System: Your previous tool call (aF  ) was too large and the stream timed out before it could be delivered. Do NOT retry the same tool call with the same large content. Instead, break the content into multiple smaller tool calls (e.g. use multiple patch calls or write smaller files). Each tool call's arguments must be under ~8K tokens to avoid stream timeouts.]z[System: The previous response was cut off by a network error mid-stream. Continue exactly where you left off. Do not restart or repeat prior text. Finish the answer directly.]z[System: Your previous response was truncated by the output length limit. Continue exactly where you left off. Do not restart or repeat prior text. Finish the answer directly.])r=   )r   r   	tool_lists      rI   _get_continuation_promptr     sp     
= 
IImBQB/00	
0
0 
0 
0	
 
 
+	
 	
I	
 	
ra   zlTry rephrasing the request, narrowing the context, or adding a fallback provider with `hermes fallback add`.messages
List[Dict]api_call_countfinal_responseerror_detailDict[str, Any]c                   || |ddd| dS )u  Build the terminal turn result for a content-policy block.

    A content-policy refusal is deterministic for the unchanged prompt, so the
    turn ends here (no retry). Both the HTTP-200 refusal handler and the
    exception-path handler return the identical shape — a failed, non-completed
    turn carrying the user-facing message and a ``content_policy_blocked:``
    prefixed error — so they funnel through this one builder.
    FTzcontent_policy_blocked: r   r   	api_calls	completedfailedr.    )r   r   r   r   s       rI   _content_policy_blocked_resultr     s-      )#:L::  ra   c                   t          | dd          }t          |t                    r|s|S |rR|d                             d          dk    r3|}| j        r|dz   | j        z                                   }||d         d<   |S )u  Refresh the in-flight system message after a provider failover.

    ``try_activate_fallback`` rewrites the ``Model:``/``Provider:`` identity
    lines on ``agent._cached_system_prompt`` (see
    ``rewrite_prompt_model_identity``) so the agent reports the model that is
    actually answering.  But the current call block's ``api_messages`` were
    built from the pre-failover prompt, and the retry loop rebuilds
    ``api_kwargs`` from that list each iteration — without this sync the
    whole turn (and every gateway turn, since fallback re-activates per
    message while the primary is down) ships the stale identity.

    Mutates ``api_messages[0]`` in place and returns the prompt to use as
    ``active_system_prompt`` for subsequent call-block rebuilds.
    r   Nr   rolesystem

content)r:   rZ   r<   r   ephemeral_system_promptr{   )rK   api_messagesactive_system_promptsp	effectives        rI   _sync_failover_system_messager     s     
/	6	6Bb# $b $## /Q++F33x??	( 	U"V+e.KKRRTTI%.Q	"Ira   user_messager   r   List[Dict[str, Any]]task_idstream_callbackOptional[callable]persist_user_messagepersist_user_timestampOptional[float]
moa_configOptional[dict[str, Any]]c	                @  opqrstuvw |0	 ddl m}	  |	|          \  }
}||
}|}||
}n# t          $ r Y nw xY wt           |||||||t          t
          t          t          t          t          t                    }|j        }|j        }|j        }|j        }|j        }|j        }|j        }|j        }|j        }|j        }|j        }d}d}d}d}d}d}d}g }d}d}i  _         j        dk    r                     |||||          S | j        k     r j        j        dk    s j        rE j                                          j        r"d	}d
} j         s !                    d           n|dz  }| _"         #                    d|             j        rd _        nT j        $                                s;d} j         s0 !                    d j        j%         d j        j&         d           n| j'        "	 g } tQ          tS          |                    D ]\  }!}"|"*                    d          dk    r|"*                    d          rtW          |          |!z
  }#i q||#d         D ]N}$|$*                    d          dk    r n2|$*                    d          }%|%r|$*                    dd          q|%<   Oqfd|"d         D             }  n '                    ||            n3# t          $ r&}&tX          -                    d||&           Y d}&~&nd}&~&ww xY w j.        dk    rd j/        v r xj0        dz  c_0         1                                }'|'rud}(te          tW          |          dz
  dd          D ]})||)         }*tg          |*th                    r|**                    d          dk    rddl5m6}+  |+|'          },|**                    dd          }-tg          |-tn                    r	|-|,z   |*d<   nB	 |-rtq          |-          ng }.|.9                    d|,d           |.|*d<   n# t          $ r Y nw xY wd	}(tX          -                    d |)            n|(sqtu           d!d          }/|/<|/5   j;        r j;        d"z   |'z    _;        n|' _;        ddd           n# 1 swxY w Y   n"tu           d#d          }-|-r|-d"z   |'z   n|' _;        tu           d$d          pty          j=        t|                    }0 ?                    ||0 j@        %          }1|1dk    r|0A                    d&|1 j@        pd'           dd(lBmC}2  |2 |          }3|3dk    r|0A                    d)|3 j@        pd'           g }4tQ          |          D ]h\  }5}6|6D                                }7|5|k    r|6*                    d          d*k    rg }8|r&t          |          }9|9r|89                    |9           |r|89                    |           |8rI|7*                    dd          }:tg          |:tn                    r|:d+z   d+F                    |8          z   |7d<    G                    |6|7           d,|7v r|7H                    d,           d-|7v r|7H                    d-           |7H                    d.d            I                                r J                    |7 jK        /           |49                    |7           j|pd}; jL        r|;d+z    jL        z   M                                };|;r	d0|;d1g|4z   }4|r(	 dd2lNmO}<mP}=  |=tg          |tn                    r|nto          |          |4|*                    d3          pg |*                    d4          pi  |<|d5           |<|d6          |*                    d7          8          }>|>rctS          |4          D ]S}?|?*                    d          d*k    r8|?*                    dd          }:tg          |:tn                    r|:d+z   |>z   |?d<    nTn2# t          $ r%}@tX          Q                    d9|@           Y d}@~@nd}@~@ww xY w jR        rj|4r!|4d         *                    d          d0k    rdnd}AtQ           jR                  D ]0\  }5}B|4S                    |A|5z   |BD                                           1 jT        rt          |4 jV         jW        :          }4 X                    |4          }4 Y                    |4 j        d;k    <          }4|4D ]G}Ctg          |C*                    d          tn                    r|Cd         M                                |Cd<   H|4D ]}C|C*                    d          }D|Dsg }E|DD ]Րvtg          vth                    rd=vv r	 t          j[        vd=         d>                   }Fi vd=i vd=         d>t          j\        |Fd?d	@          iivnR# t          $ rE t          vd=         d>         vd=         *                    dAdB                    vd=         d><   Y nw xY w|E9                    v           |E|Cd<   t          |4           t          dC |4D                       }Gt          |4          }Ht          |4 jb        pdD          }It           |I          }J|Jrl|J}d	}dE}|9                    d|d1            d                    dF           |dz  }| _"        	  j        e                                 n# t          $ r Y nw xY wznJ jf        }Ktu          |KdGdH           }L tu          |KdIdJ                       }M jg        rHtW          |          dk    r4|dKk     r- |L|I          s!|Ms|Kh                    |I          r|dz  }tX          A                    dL|IdMt          tu          |KdNd          pd          dMtu          |KdOd          r"t          tu          |KdOd          pd          dMnd|            d                    dP|IdMdQ            j                    |||I|R          \  }}d _k        d _l        d _m        d _n        d _o        t           |          }|dz  }| _"         j        e                                 dw j         s q                    d" jr         dS| d j         dT            q                     jr         dUtW          |4           dV|HdMdW|GdMdX            q                     jr         dY jb        rtW           jb                  nd            nt          jt        t          jv                              }Nt          jt        t          jw                              }O jx        r x                    |N dZ|O dT           nq y                                s] z                                rIt          jt        g d[          }Pt          |N dZ|O dT|P j{        \          ww|                                  j}        rty          j-        d] jK         d^tW          |           d_ jb        rtW           jb                  nd            ty          j-        d`|r|d         d         nda            ty          j-        db|HdMdc           t          j~                    }Qd}R j        }St                      }TdK}Udd}Vd}Wd}X| de| }Y|Y _        |R|Sk     Trm j        dfk    r	 ddglm}Zm}[  |Z            }\|\|\dk    rdh |[|\           di}]                     dj|] dk                                dj|]                                             rt           |4|          }d}Rd}d|T_                                                               ||           dj|] dl||dd	|]dmS n# t          $ r Y nt          $ r Y nw xY w	                                                        |4                                |4          }X j        rt%          |X            j        d;k    r)                                                     |Xdn          }Xtu           dod          rI                                 r5ti          |X*                    dp          pi           }^d*|^dq<   |^|Xdp<   d _        	 ddrlm}_  |_|X|||Y j@        pd j        pd jK         j         j         j        |s          }`|`j        }X|`j        }a|`j        }bn!# t          $ r ti          |X          }ag }bY nw xY w	 ddtlm}cm}d  |cdu          r8|X*                    dv          }etg          |etp                    s|X*                    dw          }etg          |etp                    s|4}e                     |X          }f |d	 di dx|dy|dz|Yd{ j@        pdd||d}tq          |          d~ j        pdd jK        d j        d j        d j        d|dtg          |etp                    rtq          |e          ng dtW          |4          dtW           jb        pg           d|Hd|Gd j        d|Qdtq          |b          d|f n# t          $ r Y nw xY wtG          d          r                     |Xd            wfdrd	stu           dd          rdsn j        dv svto           j        pd                                                              d          s;to           j        pd                                                              d          rdsn_ j        dk    r y                                sdsn< y                                s(ddlm}g tg          tu           dd          |g          rdsrs fd}hddlm}i  |i|X|h|a|||Y j@        pd j        pd jK         j         j         j        |tq          |b                    }Wt          j~                    |Qz
  }jwrw                    d           dw jx        r x                    d            j         s! q                     jr         d|jdd            j}        rG|Wrtu          |Wdd          nd}kty          j-        d|k dtW          |Wd          r|Wj        nd            d}lg }m j        d;k    r                                 }n|n                    |W          s|Wd	}l|m9                    d           n.to          tu          |Wdd          pd          M                                                                }o|odv rtu          |Wdd          }ptg          |pth                    r|p*                    d          n|prto          |p          nd|o d}qtX          Q                    d|o|q                                            d	}l|m9                    d|o d|q            nFtu          |Wdd          }rtg          |rtn                    r|rM                                nd}s|sr*tX          -                    dtW          |s                     ntu          |Wdd          }ttu          |Wdd          }utX          Q                    d|t|utu          |Wdd          d j         d j                    d	}l|m9                    d           nf j        dk    r[                                 }v|v                    |W          s0d	}l|W|m9                    d           n|m9                    d           n  j        dk    rY                                 }w|w                    |W          s/d	}l|W|m9                    d           n|m9                    d           n                                 }x|x                    |W          ssd	}l|W|m9                    d           nYtW          |Wd          s|m9                    d           n2|Wj        |m9                    d           n|m9                    d           |lr                     |||Y||Q|XddF                    |m          pdtu          tu          |Wdd          dd          |R|Sd	d           wrw                    d           dw jx        r x                    d           |Rdz  }R j        tW           j                  k     r                     d                                            rt           |4|          }d}Rd}d|T_        
ldtd}y|WrptW          |Wd          r_|Wj        rXto          |Wj                  ttW          |Wj        dæ          r,|Wj        j        r |Wj        j        *                    dd¦          }yn/|Wr-tW          |Wd          r|Wj        rto          |Wj                  t|ydk    r$|Wr"tW          |Wd          r|WjK        r
d|WjK         }y|ydk    rL|WrJdƄ tm          |W                                          D             }z j}        rty          j-        d|z            d}{|WrtW          |Wd          r|Wj        rxtu          |Wj        dd          }|||4tg          |Wj        th                    r|Wj        *                    d          }|||*	 t          ||          }{n# tp          tr          f$ r Y nw xY w|{dk    rd|jdʛd˝}}na|{dk    rd|jdʛd˝}}nS|{dk    rd}}nJ|{dv rd|{ d|jdʛd˝}}n;|{dv rd|{ dԝ}}n0|{d|{ d|jdʛd˝}}n#|jdk     rd|jd؛dٝ}}n|jdk    rd|jdʛdܝ}}nd|jd؛d}}                     d|R d|S ddF                    |m                                           d|y                                 t          }~                     d|~                                 d|}            |R|Sk    rى                                 r                     d|S d                                            rt           |4|          }d}Rd}d|T_                                           d                    d|S d           tX                               jr         d|S d                                ||           d|S d|} }||d||d	dS ty          |Rdd          }                     d|d؛d|} d           tX          Q                    d|R d|S ddF                    |m           d|y            t          j~                    |z   }d}t          j~                    |k     r j        rn q                     jr         dd	           d|} d|R d|S d}t{          ||                                ||                                             |||dd	dS t          j        d           |dz  }|dz  dk    r@ #                    d|R d|S dt          |t          j~                    z
             d           t          j~                    |k      j        d;k    rqtu          |Wdd          }tu          |Wdd          }d}tg          |th                    r|*                    d          }ntu          |dd          }|dk    r|d v rd}Vndd}Vn j        dk    r/                                 }|                    |Wj                  }Vn j        dk    r1                                 }|                    |W          }|j        }Vnl                                 }|                    |W          }|j        }V|}                     |V||          r# q                     jr         dd	           d}V|Vdk    rI                                 } j        dk    r|                    |W j                  }n|                    |W          }tu          |dd          pdM                                }|s)                     |          pdM                                }                     |||Y||Q|Xd|pdd|R|Sdt          j        j                   wrw                    d           dw jx        r x                    d                                            r                     d                                            rt           |4|          }d}Rd}d|T_        Z                                  tW          |          dk    r|dd         dTz   n|}tX          Q                    d	 jr         jK         j        |pd
            d                    d           |rd| nd}d| d+t           }                     |                                ||           t          ||||pd          S |Vdk    rtu          |Wdd          t          k    r! q                     jr         dd	           n  q                     jr         dd	           d}                                 } j        dk    r|                    |W j                  }n|                    |W          }|}|rtu          |dd          nd}|rt          tu          |dd                    nd}t          |o"t          j        d|t          j                            }| o|o|dur                     |           p|du }|r[d} q                     jr         dd	           d}                     |                                ||           |||dd	|dS  j        dv r|}tu          |Wdd          }|r j        tW           j                  k     r q                     jr         dd	            d                    d                                            r6|r                     |          }| _        d}g }d}Rd}d|T_        d	|T_        >nډ q                     jr         dd	           ||s|dz  }                     ||V          }|9                    |           |j        r|9                    |j                   |dk     rtu          |Wdd          t          k    }tu          |Wdd          }|rF|rDdF                    |ddK                   } q                     jr         d | d!| d"           nG|r# q                     jr         d#| d"           n" q                     jr         d$| d"           t          ||          }d*|d1}|9                    |           | _        d	|T_        =nd                     dF                    |                    M                                }                     |                                ||           |pd||dd	d%dS  j        dv rk|}|f|rctu          |Wdd          t          k    }|dk     r|dz  }|r                     d&| d"           n                     d'| d"            j        r j        nd(}|d)|z  z  }                     |X          }|t          ||          }t          d*|pd          }t          ||           _        d                                  |r! q                     jr         d+d	           n  q                     jr         d,d	                                |                                ||           |rd-nd.}|||dd	|dS tW          |          dk    rj q                     jr         d/                                |          }                     |                                ||           d.||dd	d.dS                                    q                     jr         d0d	                                ||           d1||dd	d1dmS tW          |Wd          r
|Wj        rt          |Wj         j         j        2          }|}d}tu           dd          }|etW          |d3          rS	 |                                \  }}|||z   }n3# t          $ r&}tX          -                    d4|           Y d}~nd}~ww xY w|ztW          |d5          rh	 tu           d6d          pd}|                     j@        |pd7           n3# t          $ r&}tX          -                    d8|           Y d}~nd}~ww xY w|j        }|j        }|j        }||||j        |j        |j        |j        |j        d9} jf                            |           tu           jf        d:d          r jf        j        }tu           jf        d;d          rFt           jK         j        |            !                     jr         d<|dMd= jK                    d jf        _        d jf        _         xj        |z  c_         xj        |z  c_         xj        |z  c_         xj        dz  c_         xj        |j        z  c_         xj        |j        z  c_         xj        |j        z  c_         xj        |j        z  c_         xj        |j        z  c_        d}|j        r#|r!d>|j         d| d?d@|j        z  |z  dʛdA}tX          A                    dB j         jK         j        pd||||j|	  	          jK        } j        } j        }|tu          |dCd          nd}|rU|*                    d          r@|d         }|*                    d          p j        }|*                    d          p j        }t          ||||tu           dDd          E          }|j        # xj        t          |j                  z  c_        |9	  xj        t          |          z  c_        n# tp          tr          f$ r Y nw xY w|j         _        |j         _         j        r" j@        r	  j         s                                  d}|j        t          |j                  }|1	 |pdFt          |          z   }n# tp          tr          f$ r Y nw xY w j                             j@        |j        |j        |j        |j        |j        ||j        |j         j         j        |j        dGk    rdHnd jK        dI           n:# t          $ r-}tX          -                    dJ j@        ||           Y d}~nd}~ww xY w j}        r8ty          j-        dK|dL         dMdM|dN         dMdO|dP         dM           |j        }|j        }|dL         }|s|rI j         sB|dk    r	||z  d@z  nd} q                     jr         dQ|dMd|dMdR|dʛdS|dMdT
           d|T_         j        dfk    r$	 ddUlm}  |æ             n# t          $ r Y nw xY w #                    dV| dW           4n:# t
          $ r wrw                    d           dw jx        r x                    d           t          j~                    |Qz
  }ĉ q                     jr         dXd	           d	}                     tu           d6d          pd          M                                }|r|9                    d|d1           |}nt           |d؛dY}                     ||           Y 3nAt          $ 3r-}Ɛwrw                    d           dw jx        r x                    d           tg          |Ɛt                    r;tu           dZd          d)k     r#to          |Ʀ                                          }ǐd[|v pd\|v }Ȑd]|v pd^|v o| }t          |          }tg          |4tp                    rt          |4          rd	}tg          |Xth                    rt          |X          rd	}tg          tu           d_d          tp                    rt           jR                  rd	}|s|rG xj	        dz  c_	        |r                     d`           n                     da           Y d}~Ɛ"|Ȑrd	 _        t          |          }tg          |4tp                    rt          |4           tg          |Xth                    rt%          |X           d}tg          tu           d_d          tp                    rt           jR                  }d}tg          tu           dbd          tp                    rt           jb                  }d}tg          |tn                    r"t          |          }||k    r|}|ω _        d	}tg          tu           dcd          tn                    r)t           jL                  }|Љ jL        k    r	|Љ _L        d	}d}tg          tu           ddd          th                    r j        *                    de          nd}tg          |th                    rt%          |Ҧ          }d}tu           dDd          pd}|rtg          |tn                    rt          |Ԧ          }||k    r|Չ _        tg          tu           ddd          th                    r|Չ j        dD<   tu           dd          &tW           j        dD          r|Չ j        _        d	}Ӊ q                     jr         dfd	            xj	        dz  c_	        |p	|p|p|p|p|}|r! q                     jr         dgd	           n  q                     jr         dhd	           Y d}~Ɛ%d}	 to          tu          |Ɛdid          ptu          |dd          pto          |Ʀ                    }n# t          $ r Y nw xY wtu          |Ɛdjd          }ؐdk}|נ                                pt#          pfdl|D                       }|du pdmt          |ئ          cxk    odk     nc }tu           dnd	          ro|rm|rkd _        t'          |          }tg          |4tp                    rt'          |4            q                     jr         do|rdpndiz   d	           Y d}~Ɛ'tu          |Ɛdjd          }݉                     |Ʀ          }tu           dqd          }K|Krtu          |KdOdr          ndr}ߐt+          |tu           dd          pdtu           dd          pd|H||4rtW          |4          nds          }tX          -                    dt|j        j        |j        |j        |jh        |j        |j                                        |||Y||Q|Xt7          |Ʀ          j>        to          |Ʀ          ||R|S|j        |j        j                   |j        t          j        k    ryt;          tu           dd          pdtu           dd          pd          rF|Tj        s>d	|T_        t?                     r& q                     jr         dud	           Y d}~Ɛ(Ή                      ||Tj        |j        |ސv          \  }|T_        |rY d}~Ɛ)|j        t          j!        k    r}|Tj"        sud	|T_"        tG          |Ʀ          pdw} $                    |4|x          r& q                     jr         dyd	           Y d}~Ɛ)tX          A                    dz           |j        t          j%        k    rg|Tj&        s_d	|T_&         '                    |4          r& q                     jr         d{d	           Y d}~Ɛ)tX          A                    d|           |j        t          j(        k    r j        dk    r j        r|Tj)        sd	|T_)        tu           d}d          spd	 _*        	  j+        ,                                 n# t          $ r Y nw xY w -                                  q                     jr         d~d	           Y d}~Ɛ*։ j        d;k    rk j        dv ra|ݐdk    rZ|Tj.        sRd	|T_.         /                    d	          r3 j        dk    rdnd}                     d| d           Y d}~Ɛ+L j        dk    rT j        dk    rH|ݐdk    rA|Tj0        s9d	|T_0         1                                r                     d           Y d}~Ɛ+ j        dk    r j        dfk    r|ݐdk    r|Tj2        sd	|T_2         3                    d	          rti           jr         d           Y d}~Ɛ,ddl5m6}  |            }d}	 tu          |Ɛdid          ptu          |Ɛdd          }|to          |          dd         }n# t          $ r Y nw xY wti           jr         d           |rti           jr         d|            to           d          sti           jr         d           ti           jr         d           ti           jr         d           ti           jr         d           ti           jr         d| d           ti           jr         d            j        dk    rH|ݐdk    rA|Tj8        s9d	|T_8         9                                r                     d           Y d}~Ɛ- j        dk    r9|ݐdk    r1tW           d          r|Tj:        sd	|T_:        ddl;m<} ddl=m>}  ?                                rti           jr         d           Y d}~Ɛ.- j@        }ti           jr         d            ||          rLti           jr         d           ti           jr         d           ti           jr         d           n ||          rdnd}ti           jr         d|            ti          tg          |tn                    r+tW          |          dk    r jr         d|dd          dTn
 jr         d           ti           jr         d           ddl5m6}  |            }ti           jr         d| d           ti           jr         d| d           ti           jr         d           ti           jr         d           ti           jr         d           ti           jr         d           |j        t          jA        k    r|TjB        sd	|T_B        d}|4D ]8}"tg          |"th                    r!d|"v r|"H                    dd           |dz  }9 q                     jr         dd	           tX          Q                    d jr        |           Y d}~Ɛ0|j        t          jC        k    r|TjD        sω j        d;k    rĐt          tu           dd	                    rt#          d |D                       rd	|T_D         E                    |          } q                     jr         d|d          d|dv          dd	           tX          Q                    d jr        |d         |dv                    Y d}~Ɛ1|j        t          jF        k    r|TjG        sd	|T_G        	 ddlHmI}  | jb                  \  }}n;# t          $ r.}tX          Q                    d jr        |           d}Y d}~nd}~ww xY w|rL q                     jr         d| dd	           tX          Q                    d jr        |           Y d}~Ɛ2_tX          Q                    d jr                   |Rdz  }Rt          j~                    |Qz
  } #                    d|R d|S dԝ           t7          |Ʀ          j>        }to          |Ʀ                                          t J                    |Ʀ          }tX          Q                    d|R|S|                                 |           tu           dd          }tu           dd          }:tu           dd          }|rd|ݛ dnd}                     d|R d|S d| |                                 d| d|                                 d|:                                 d|            |rP|ݐdk     rItu          |Ɛdid          }|rto          |צ          ddȅ         nd}|r                     d|                                 d|ddtW          |4           d|HdMdc            K                                rnd͐tv rh                     d| dϝ            jL        r,                     dЦ                                dѦ                                d|             j        r q                     jr         dӝd	           d| d                     to          |Ʀ                     d}t{          ||                                ||                                             |||dd	dcY d}~S tu          |Ɛdjd          }ݐt          jM        t          jN        t          jO        h}|j        |v rtu           dd	          s                                   q                     jr         d֝d	            q                     jr         dםd	           tX                               jr         d|j        j         dٝ                                ||           d}||d||d	d	d	dۜcY d}~S |j        t          jM        k    r;dr} jf        }|j        }||k    r|P                     jK        | j        tu           dDd           j         j        ܦ           tW          |d:          rd	|_        d|_                             d|dMd|dMdc           |dz  }||Uk    rtW          |          } j                    |||H|R          \  }}t           |          }tW          |          |k     s||k    rD                     d|dMd|dMd           t          j        d)           d	|T_Q        Y d}~Ɛn|j        t          jR        t          j        t          jS        hv }|j        t          jT        t          jU        hv }|p|o|Rd)k    } | rE j        tW           j                  k     r'|j        t          jS        k    }|rdn't                      V                     jW                  }|sݐ|r=|jX        pi *                    dd4          }                     d| d           n^|j        t          j        k    r                     d           n/|r                     d           n                     d                                |j                  r#t           |4|          }d}Rd}d|T_        Y d}~Ɛ9|jY        r|TjZ        sz j        tW           j                  k     r]d	|T_Z                             d                                |j                  r#t           |4|          }d}Rd}d|T_        Y d}~Ɛ:|r։ j        dfk    r|j        t          jR        k    r|sd}	 ddlm[}m\} tu          |Ɛdd          }|rtu          |dd          nd} || j]                  }|r |||ސ           ntX          A                    d           n# t          $ r Y nw xY w|rt          d|Sdz
            }RY d}~Ɛ:|j        t          jN        k    }	|ݐdk    rtg           j        tn                    rd j        v r q                     jr         dd	            q                     jr         dd	            q                     jr         dd	            q                     jr         dd	            q                     jr         dd	           |	r|dz  }||Uk    r                                   q                     jr         d|U dd	            q                     jr         dd	           tX                               jr         d|U d                                ||           d|U d}||d||d	d	d	dcY d}~S                      d| d|U dT           tW          |          }t          |          }
 j                    |||H|R          \  }}t           |          }t          |          }|}HtW          |          |k     s|dk    r||
dz  k     rtW          |          |k     r-                     d| dtW          |           d            n#                     d|
dMd|dMd           t          j        d)           d	|T_Q        Y d}~Ɛn '                    |4d          r                     d           Y d}~Ɛ=                                   q                     jr         dd	            q                     jr         dd	           tX                               jr         d                                ||           d}||d||d	d	d	dcY d}~S |j        t          jO        k    }|r" jf        }|j        }t          t          }|t          d|d	z
            }| _                             d
|dMd|dMd|dMdԝ           |dz  }||Uk    r                                   q                     jr         d|U dd	            q                     jr         dd	           tX                               jr         d|U d                                ||           d|U d}||d||d	d	d	dcY d}~S d	|T_Q        Y d}~Ɛnt          t          r                                   q                     jr         dd	            q                     jr         dd	           tX                               jr         dtdd                                          ||           d}||d||d	d	dcY d}~S t          t|          }tu           dd          pd                                }tu           dd          pda                    d                                          }|dv p|                    d          }|o
|du odtv }|                     d|dMd|dMdԝ           |P                     jK        | j        tu           dDd           j         j        ܦ           tW          |d:          rd	|_        d	|_                             d|dMdސ|dMdc           n<|r                     d|dMd           n                     d|dMd           |dz  }||Uk    r                                   q                     jr         d|U dd	            q                     jr         dd	           tX                               jr         d|U d                                ||           d|U d}||d||d	d	d	dcY d}~S                      d|HdMd| d|U d           tW          |          }t          |          }
 j                    |||H|R          \  }}t           |          }t          |          }|}HtW          |          |k     s|dk    r||
dz  k     s
|r||k     rtW          |          |k     r-                     d| dtW          |           d            n6|dk    r/||
dz  k     r#                     d|
dMd|dMd           t          j        d)           d	|T_Q        Y d}~ƐnY                                   q                     jr         dd	            q                     jr         dd	           tX                               jr         d |dMd!                                ||           d"|dMd#}||d||d	d	d	dcY d}~S tg          |Ɛtr          tp          f          otg          |Ɛt          t          jb        f           o{tg          |Ɛt          jd                   o^tg          |Ɛtp                    oGd$to          |Ʀ                                          v o#d%to          |Ʀ                                          v  }|ph|j         o_|jh         oW|j        t          jR        t          jU        t          jO        t          jN        t          jM        t          jA        hvo| }|r                                 rx|j        t          j        k    r                     d&           nJ|j        t          je        k    r                     d'           n                     d(|ݛ d)                                            r#t           |4|          }d}Rd}d|T_        Y d}~ƐF|X                     |Xd*|Ɛ+                                              J                    |Ʀ          }|j        t          j        k    r d                    d,|            nP|j        t          je        k    r d                    d-|            n d                    d.|ݛ dߐ|             q                     jr         d/|ݛ d0d	            q                     jr         d| d| d	            q                     jr         d|: d	           |jY        s|j        t          j        k    r|j        t          j        k    r&t           d1|to          |:          |2          rn|dfk    rto           d          rn|d3v r|ݐdk    r|d4k    r q                     jr         d5d	            q                     jr         d6d	            q                     jr         d7d	            q                     jr         d8d	           n!|dk    rB q                     jr         d9d	            q                     jr         d:d	           n؉ q                     jr         d;d	            q                     jr         d<d	            q                     jr         d=d	            q                     jr         d>d	           tg          |tn                    r|g                    d?          rh q                     jr         d@| dAd	            q                     jr         dBd	            q                     jr         dC| dDd	           nÉ q                     jr         dEd	            q                     jr         dFd	            q                     jr         dG| dBd	           t          to          |:          dH          r  q                     jr         dId	           n  q                     jr         dJd	           |j        t          j        k    r q                     jr         dKd	            q                     jr         dLd	            q                     jr         dMd	            q                     jr         dNd	           |j        t          je        k    r  q                     jr         dOd	            q                     jr         dPd	            q                     jr         dQd	            q                     jr         dRd	            q                     jr         dSd	            q                     jr         dTd	            q                     jr         dUd	            q                     jr         dVd	           tX                               jr         dW|ƛ            |ݐdmk    r<|HdXk    stW          |4          dYk    r! q                     jr         dZd	           n                     ||           |j        t          j        k    r-d[| d+t           }t          ||||          cY d}~S |||dd	|dmcY d}~S |R|Sk    r|Tj        s@ i                    ||R|S\          r&d	|T_        d}Rd|T_        d _        d _j        Y d}~ƐM                                 r                     d|S d]                                            r#t           |4|          }d}Rd}d|T_        Y d}~ƐN[                                   J                    |Ʀ          }d}|j        t          j        k    rc d                    d^|            t          d1|to          |:          |2          }t           d1|to          |:          |2           n?|r d                    d_|S d`|            n d                    da|S d`|             q                     jr         db| d	           tu          |Ɛdjd           ot#          tfdcddD                       }|r@ q                     jr         ded	            q                     jr         dfd	           ddgllmm}  |||t          }|r q                     jr         dhd	            q                     jr         did	            q                     jr         dj| dk| dld	            q                     jr         dmd	            q                     jr         dnd	           tX                              do jr        |S|||tW          |4          |HdM           |X                     |Xdp|Ɛ+                                ||           |j        t          j        k    rdq| }|r	|d+| z  }n
dr|S d| }|rddsllmn} | |||t          z  }n	|r|duz  }|||dd	||j        j        dvcY d}~S d}|rtu          tu          |Ɛdd          dd          }|rtW          |dw          ro|*                    dx          p|*                    dy          } | r=	 t          t          |           dz          }n# tp          tr          f$ r Y nw xY w|r|nty          |Rd{d|          }d}!|r*|s't          |Rto          |:          |||}          \  }}!|rid}"|!d~k    rd}"n|!dk    rd}"d|d؛d|Rdz    d|S dԐ|" dT	}#|!d~k    r d                    |#           n8                     |#           n!                     d|d؛d|R d|S d           tX          Q                    d||R|S                                 |!pd|Ʀ           t          j~                    |z   }d}t          j~                    |k     r j        rq q                     jr         dd	           d|R d|S d}t{          ||                                ||                                             |||dd	dcY d}~S t          j        d           |dz  }|dz  dk    rA #                    d|R d|S dt          |t          j~                    z
             d           t          j~                    |k     Y d}~nd}~ww xY w|R|Sk     Tm|rd}!n|TjQ        r-|dz  } j        e                                 |Rdz  }Rd|T_Q        b|Tj        r'|dz  } j        e                                 d|T_        b|Tj        rz j        r j        nd(}$|$d)|z  z  }%                     |X          }&|&t          |%|&          }%t          d*|&pd          }'t          |%|'           _        cS|W4d}ti           jr         d                                ||            n	                                  }(i }) j        dk    r j        |)d<    |(j        |Wfi |)}*|*}|*j        }V|j        tg          |j        tn                    s|j        }+tg          |+th                    rJ|+*                    dd          p+|+*                    dd          pt          j\        |+          |_        n!tg          |+tp                    rg },|+D ]Ӑ}-tg          |-tn                    r|,9                    |-           1tg          |-th                    rG|-*                    d          dk    r,|,9                    |-*                    dd                     tg          |-th                    r/d|-v r*|,9                    to          |-d                              d"F                    |,          |_        nto          |+          |_        	 ddtlm}cm}d  |cd          rtu          |dd          pg }.|j        pd}/|Q|jz   }0 |d	 di dx|dy|dz|Yd{ j@        pdd~ j        pdd jK        d j        d j        d j        d|d|jd|Qd|0d-|VdtW          |4          dtu          |Wdd          d p                    |W||V          d q                    |W          d|dtW          |/          dtW          |.           n# t          $ r Y nw xY w|j        r j         sx j}        r& q                     jr         d|j                    nK q                     jr         d|j        dd@          tW          |j                  d@k    rdTnd            |j        r jr        r|j        M                                }1t          js        dd|1          M                                }1|1r&|1t                    d"          d         ddY         nd}2|2rAtu           dd          dk    r+	  r                    d|2           nJ# t          $ r Y n>w xY w|1r7	  r                    dd|1dd         d           n# t          $ r Y nw xY wt          |j        pd          r xjv        dz  c_v                             d            jv        d)k    r#                     d jv         d           h                                   q                     jr         dd	           d _v                             |          }                     |                                ||           d||dd	ddS d _v         j        d;k    r|Vdk    r xjw        dz  c_w                             ||V          }t          |*                    d          pdM                                          }3tg          |*                    d,          tn                    r6t          |*                    d,d          M                                          nd}4t          |*                    d                    }5t          |*                    d                    }6|3s
|4s|5s|6r|r|d         nd}7tg          |7th                    r|7*                    d          nd}8|*                    d          }9tg          |7th                    r|7*                    d          nd}:|*                    d          };tg          |7th                    o|7*                    d          dk    o|7*                    d-          dk    oq|7*                    d          pd|*                    d          pdk    o@|7*                    d,          pd|*                    d,          pdk    o|8|9k    o|:|;k    }<|<s+|9                    |            x                    |            jw        dKk     r8 j         s( q                     jr         d jw         d           | _        ld _w                             ||           d||dd	ddS tW           d          rd _w        |jy        
r} j         s5 q                     jr         dtW          |jy                   d            j}        rL|jy        D ]Cvty          j-        dvjz        j{         dvjz        j|        dd          dT           D|jy        D ]~vvjz        j{         j/        vre }                    vjz        j{                  }=|=r>ti           jr         dvjz        j{         d|= d           |=vjz        _{         fd|jy        D             }>|>r xj~        dz  c_~        dF                    t           j/                            }?|>d         }@tW          |@          dYk    r|@ddY         dTz   n|@}A                     d|A d j~         d            j~        dKk    rc                                   q                     jr         dd	           d _~                             ||           d|A }|||dd	|dS                      ||V          }B|9                    |B           |jy        D ]{vvjz        j{        }C|C j/        vr*|CpdM                                sd}Dnd|C d|? }Dnd}D|9                    dvjz        j{        vj        |Dd           |oLd _~        g u|jy        D ](vvjz        j|        }Etg          |Eth          tp          f          r#t          j\        |E          vjz        _|        T|ECtg          |Etn                    s-to          |E          vjz        _|        vjz        j|        }E|Er|EM                                sdvjz        _|        	 t          j[        |E           # t          jb        $ r=}u9                    vjz        j{        to          |          f           Y d}~"d}~ww xY wurҐt#          ufd|jy        D                       }F|Frc q                     jr         d|Vdd	           d _                             |                                ||           d.||dd	d.dS  xj        dz  c_        ud         \  }Gt                     d|G dt             j        dKk     r#                     d j         d           q                     d           d _                             ||V          }H|9                    |H           d uD             }I|jy        D ]tvvjz        j{        |Iv r+t          vfduD                       }Jd|J d}Knd}K|9                    dvjz        j{        vj        |Kd           ur_d _                             |jy                  |_y                             |jy                  |_y                             ||V          }B|j        pd}L|Lrى                     |L          rÐ|L _m        t          h d£          ot          ofdÄ|jy        D                       }M|M _n        |Mr y                                rd	 _o        n[                                 rF                     |L          M                                }N|Nr q                    dĐ|N            d}O|rtg          |d         th                    rj|d         *                    d.          rO|H                                 d	}O|r6tg          |d         th                    r|d         *                    d.          O|Ord _l        d _k        d _        |9                    |B            x                    |B           	                      ||           nA# t          $ r4}PtX          Q                    dŉ j@        pda|P           Y d}P~Pn
d}P~Pww xY w j        r(	                      d           n# t          $ r Y nw xY w                     ||||            j        ȉ j        }Qd}                     |Q          } d                    dǐ|Qj         d|Qj                    |9                    d|d1           |r_ !                    d"| d"            j        r>	                      |                                d           n# t          $ r Y nw xY wn}d}d	 _        dȄ |jy        D             }R|Rdhk    r j        e                                  jf        }K|Kj        dk    r
|Kj        }Sn)|Kj        dk    rd}Snt          | jb        pdD          }S jg        rc|Kh                    |S          rM !                    dʦ            j                    || jf        j        |R          \  }}t           |          }| _        v|j        pd}d _o                             |          stu           d6d          pd}T                     |T          ryd}                     |T          M                                }UtX          A                    dtW          |U                      d                    dͦ           |U}d _        ntu           dd          }V|Vrtu           dd          r{d}tX          A                    dѦ            d                    dҦ           d _m        d _n        d _k                             |V          M                                }d	 _        nt#          dӄ |dd         D                       }Wt          t          j        d|pdt          j                            }X|Wrtu           dd          s|Xsd	 _        d _m        d _n        tX          A                    dצ                                dئ                                ||V          }Ydِ|Yd<   d	|Yd<   |9                    |Y           |9                    d*dd	dܜ           yat          tu          |d,d          p&tu          |dd          ptu          |dd          p|X          }Z|Zr jl        d)k     r xjl        dz  c_l        tX          A                    dމ jl                                        d߉ jl         d                                |d          }d	|d.<   |9                    |           | _        zA                     |          M                                 }[|Zo jl        d)k    }\|[rj|Zr|\rd jk        dKk     rY xjk        dz  c_k        tX          Q                    d jk         jK                                        d jk         d           z|[rȉ j        rtX          Q                    d jk         jK         j                                        d                                            rjt           |4|          }d _k                             d jK         d? j         dԝ           tX          A                    d jK         j                   {                                  d}                     |          }]                     |                                ||V          }Bdِ|Bd<   d	|Bd<   |9                    |B           |]r\tW          |]          dk    r|]dd         dTz   n|]}^tX          Q                    d|^            d                    d           nQtX          Q                    d jk         jK         j                    d                    d j        rdndz              d}nd _k        d _l                                          ddlBm}_  |_           }`|`dk    r j/        r|d)k     r                     ||||`dk              rj|dz  }                     |d          }|9                    |            x                    |           d*dd1}|9                    |           | _        }d}|rdF                    |          |z   }g }d}                     |          M                                }                     ||V          }a|rtg          |d         th                    r|d         *                    d.          s8|d         *                    dڦ          s|d         *                    d          r|H                                 |rntg          |d         th                    rS|d         *                    d.          L|d         *                    dڦ          h|d         *                    d          	 ddlm}bm}c  |c            rN |btu           d{d          tu           dt5                                tu           dd                    }dnd}dn1# t          $ r$ tX          -                    dd	           d}dY nw xY w|drtu           dd          dz    _        d|ad-<   d	|ad<   |9                    |a           |9                    d*|dd	d           | _        tX          -                    d j                   6d}et          tu           dt5                                pg           }ftu           dd          }g	 ddlm}h dd lm}im}c |fr |cd          r|g |h            k     rtu           dd          }j|jAddlm}k t           |ktu           d~d          pd                    }j|j _         |itu           d{d          pdtu           d~d          pdtu           dd          pd|j|g||f          }en1# t          $ r$ tX          -                    dd	           d}eY nw xY w|erv|gdz    _        d|ad-<   d	|ad<   |9                    |a           |9                    d*|ed	d	           | _        tX          -                    d
 j                   |9                    |a           d|V dԝ} j         s !                    d| d           n)# t          $ r}d| dto          |           t	 ti          dt            n4# tF          tr          f$ r tX                              t           Y nw xY wtX                              d|           te          tW          |          dz
  dd          D ]}5||5         }6tg          |6th                    s n|6*                    d          dk    r<|6*                    d          dk    r|6*                    d          rd ||5dz   d         D             }l|6d         D ]}vvrtg          vth                    svd         |lvrSdt                      j                            v          vd         dt d}m|9                    |m           ~ | j        dz
  k    r5dtddY          dԝ}dt }|9                    d|d1           Y d}~n1Y d}~nd}~ww xY w| j        k     r j        j        dk    = j        Eddlm}n  |n ||||||||||||          S (  a  
    Run a complete conversation with tool calling until completion.

    Args:
        user_message (str): The user's message/question
        system_message (str): Custom system message (optional, overrides ephemeral_system_prompt if provided)
        conversation_history (List[Dict]): Previous conversation messages (optional)
        task_id (str): Unique identifier for this task to isolate VMs between concurrent tasks (optional, auto-generated if not provided)
        stream_callback: Optional callback invoked with each text delta during streaming.
            Used by the TTS pipeline to start audio generation before the full response.
            When None (default), API calls use the standard non-streaming path.
        persist_user_message: Optional clean user message to store in
            transcripts/history when user_message contains API-only
            synthetic prefixes.
        persist_user_timestamp: Optional platform event timestamp to store
            as metadata on that persisted user message.
                or queuing follow-up prefetch work.

    Returns:
        Dict: Complete conversation result with final response and message history
    Nr   )decode_moa_turn)restore_or_build_system_promptinstall_safe_stdiosanitize_surrogatessummarize_user_message_for_logr*   r+   raFrV   codex_app_server)r   original_user_messager   effective_task_idshould_review_memoryTinterrupted_by_useru2   
⚡ Breaking out of tool loop due to interrupt...r8   zstarting API call #budget_exhaustedu%   
⚠️  Iteration budget exhausted (/z iterations used)r   	assistant
tool_callstooltool_call_idr   rR   c                    g | ]h}t          |t                    |d          d                             |                    d                    |d                              d          diS )functionnameid	arguments)r   resultr   rZ   dictr   ).0tc_results_by_ids     rI   
<listcomp>z$run_conversation.<locals>.<listcomp>  s~     & & & !#)"d33&(*:v(>*8*<*<RVVD\\*J*J-/
^-?-?-L-L & & &ra   z&step_callback error (iteration %s): %sskill_manage)format_steer_markerrF   )typerF   z<Pre-API-call steer drain: injected into tool msg at index %d_pending_steer_lockr   _pending_steerr\   )r\   rW   zFSanitized %s corrupted tool_call arguments before request (session=%s)-)#repair_message_sequence_with_cursorzFRepaired %s message-alternation violations before request (session=%s)userr   	reasoningfinish_reason_thinking_prefill)rQ   r   )r   r   )_preset_temperatureaggregate_moa_contextreference_models
aggregatorreference_temperatureaggregator_temperaturereference_max_tokens)user_promptr   r  r  temperaturer  
max_tokensz"MoA context aggregation failed: %s)	cache_ttlnative_anthropiccodex_responses)drop_codex_reasoning_itemsr   r   )rY   r   )
separators	sort_keysr   ?c              3  N   K   | ] }t          t          |                    V  !d S N)r[   r<   )r  msgs     rI   	<genexpr>z#run_conversation.<locals>.<genexpr>  s.      @@C#c#hh--@@@@@@ra   )rO    ollama_runtime_context_too_smallu;   ❌ Ollama runtime context is too small for Hermes tool use$should_defer_preflight_to_real_usagec                    dS )NFr   )_ts    rI   <lambda>z"run_conversation.<locals>.<lambda>  s    E ra   'get_active_compression_failure_cooldownc                     d S r#  r   r   ra   rI   r*  z"run_conversation.<locals>.<lambda>  s    D ra   r   zRPre-API compression: ~%s request tokens >= %s threshold (context=%s, attempt=%s/3)rY   threshold_tokenscontext_lengthu   📦 Pre-API compression: ~zM tokens near the context/output limit. Compacting before the next model call.)approx_tokensr   u   🔄 Making API call #z...u      📊 Request size: z messages, ~z
 tokens (~z chars)u      🔧 Available tools: r5   )brainsparklepulsemoonstar)spinner_typeprint_fnzAPI Request - Model: z, Messages: z	, Tools: zLast message role: rX   zTotal message size: ~z tokensstopz:api:rz   )nous_rate_limit_remainingformat_remainingu,   Nous Portal rate limit active — resets in r   u   ⏳ z Trying fallback...zg

No fallback provider available. Try again after the reset, or add a fallback provider in config.yaml.r   )allow_stream_is_user_initiated_turnextra_headerszx-initiator)apply_llm_request_middleware)
r   turn_idapi_request_idrW   r   rQ   rU   rT   api_moder   )has_hookr   pre_api_requestr   inputr   r>  r?  rW   r   r   r   rQ   rU   rT   r@  r   request_messagesmessage_countr_   approx_input_tokensrequest_char_countr  
started_atmiddleware_tracerequestHERMES_DUMP_REQUESTS	preflight)reasonc                 v    r                     d           d  j        r                     d           d S d S )NrR   )r7  thinking_callback)rK   thinking_spinners   rI   _stop_spinnerz'run_conversation.<locals>._stop_spinner  sT    ' 0(--b111+/(. 4//333334 4ra   _disable_streaming>   copilot-acpzacp://copilotz
acp+tcp://moa)Mockclientc                `    r                     |           S                     |           S )N)on_first_delta)!_interruptible_streaming_api_call_interruptible_api_call)next_api_kwargsrQ  _use_streamingrK   s    rI   _perform_api_callz+run_conversation.<locals>._perform_api_call  sD    % $FF+M  G      !88IIIra   )run_llm_execution_middleware)original_requestr   r>  r?  rW   r   rQ   rU   rT   r@  r   rI  u   ⏱️  API call completed in z.2fszN/AzAPI Response received - Model: z	, Usage: usagezresponse is Nonestatus>   r   	cancelledr.   r3   zResponses API returned status ''z>Codex response status='%s' (error=%s). Routing to fallback. %szresponse.status=z: output_textzaCodex response.output is empty but output_text is present (%d chars); deferring to normalization.incomplete_detailszeCodex response.output is empty after stream backfill (status=%s, incomplete_details=%s, model=%s). %sz	api_mode=z
 provider=zresponse.output is emptyanthropic_messagesz/response.content invalid (not a non-empty list)bedrock_conversez/Bedrock response invalid (no output or choices)choicesz#response has no 'choices' attributezresponse.choices is Nonezresponse.choices is emptyInvalidAPIResponser   zInvalid API responsecodeinvalid_response)r   r>  r?  r   api_start_time
api_kwargs
error_typeerror_messagestatus_coderetry_countmax_retries	retryablerM  u<   ⚠️ Empty/malformed response — switching to fallback...Unknownmetadataprovider_namezmodel=c                n    i | ]2\  }}|                     d           |t          |          dd         3S )_Nd   )r   r<   )r  kvs      rI   
<dictcomp>z$run_conversation.<locals>.<dictcomp>  sA    %r%r%r$!Q`a`l`lmp`q`q%raQ%r%r%rra   z*Response attributes for invalid response: i  z-upstream provider timed out (Cloudflare 524, z.0fzs)i  zupstream gateway timeout (504, i  z'rate limited by upstream provider (429)>       zupstream server error (>       zupstream provider overloaded ()zupstream error (code 
   zfast response (z.1fu   s) — likely rate limited<   zslow response (u   s) — likely upstream timeoutzresponse time u&   ⚠️  Invalid API response (attempt z): u      🏢 Provider: u      📝 Provider message: u      ⏱️  u   ⚠️ Max retries (u.   ) for invalid responses — trying fallback...u   ❌ Max retries (z,) exceeded for invalid responses. Giving up.zInvalid API response after z	 retries.z
 retries: )r   r   r   r   r.   r   g      @g      ^@)
base_delay	max_delayu   ⏳ Retrying in zs (z)...zInvalid API response (retry z | Provider: u3   ⚡ Interrupt detected during retry wait, aborting.rr   z$Operation interrupted during retry (z
, attempt z).)r   r   r   r   interruptedg?   zretry backoff (z), zs remainingrM  
incomplete>   lengthmax_output_tokensuA   ⚠️  Treating suspicious Ollama/GLM stop response as truncatedr  content_filter)strip_tool_prefixContentPolicyBlockedz*model declined to respond (content_filter)uH   ⚠️ Model declined to respond (safety refusal) — trying fallback...r  z[%sModel declined to respond (finish_reason=content_filter). model=%s provider=%s refusal=%sz	(no text)uF   ⚠️ The model declined to respond to this request (safety refusal).zModel's explanation: z"The model returned no explanation.uj   ⚠️  The model declined to respond to this request (safety refusal — not a Hermes/gateway failure).

zmodel declined (content_filter))r   r   r   u[   ⚠️  Stream interrupted by network error (finish_reason='length' on partial-stream-stub)uQ   ⚠️  Response truncated (finish_reason='length') - model hit max output tokensz8<(?:think|thinking|reasoning|REASONING_SCRATCHPAD)[^>]*>zModel used all output tokens on reasoning with none left for the response. Try lowering reasoning effort or increasing max_tokens.uV   💭 Reasoning exhausted the output token budget — no visible response was produced.u  ⚠️ **Thinking Budget Exhausted**

The model used all its output tokens on reasoning and had none left for the actual response.

To fix this:
→ Lower reasoning effort: `/thinkon low` or `/thinkon minimal`
→ Or switch to a larger/non-reasoning model with `/model`)r   r   r   r   partialr.   >   rh  chat_completionsrg  _content_filter_terminateduM   🛡️  Content filter terminated stream — activating fallback provider...z:Content filter terminated stream; switching to fallback...u^   ⚠️  No fallback provider configured — retrying with same provider (may re-hit filter)...   _dropped_tool_namesu&   ↻ Stream interrupted mid tool-call (u    ) — requesting chunked retry (z/4)...u4   ↻ Stream interrupted — requesting continuation (u   ↻ Requesting continuation (z9Response remained truncated after 4 continuation attemptsu7   ⚠️  Stream interrupted mid tool-call — retrying (u<   ⚠️  Truncated tool call detected — retrying API call (i      i   u[   ⚠️  Stream kept dropping mid tool-call after 4 retries — the action was not executed.uf   ⚠️  Truncated tool call response detected again — refusing to execute incomplete tool arguments.zLStream repeatedly dropped mid tool-call (network); the tool was not executedz-Response truncated due to output length limitu3      ⏪ Rolling back to last complete assistant turnu-   ❌ First response truncated - cannot recoverz3First response truncated due to output length limit)rU   r@  consume_reference_usagez)MoA reference usage accounting failed: %sconsume_and_save_trace _current_streamed_assistant_text)aggregator_output_fallbackzMoA trace flush failed: %s)prompt_tokenscompletion_tokenstotal_tokensinput_tokensoutput_tokenscache_read_tokenscache_write_tokensreasoning_tokens_context_probed_context_probe_persistableu   💾 Cached context length: z tokens for z cache=z (rz  z%)zHAPI call #%d: model=%s provider=%s in=%d out=%d total=%d latency=%.1fs%slast_aggregator_slotapi_key)rU   rT   r  g        includedsubscription_included)r  r  r  r  r  estimated_cost_usdcost_statuscost_sourcebilling_providerbilling_base_urlbilling_moderQ   r   z4Token persistence failed (session=%s, tokens=%d): %szToken usage: prompt=r  z, completion=r  z, total=r  u      💾 Cache: z	 tokens (z% hit, z	 written))clear_nous_rate_limitz
API call #z
 completedu    ⚡ Interrupted during API call.zs elapsed)._unicode_sanitization_passesz'ascii'ascii	surrogatez'utf-8'prefill_messagesuH   ⚠️  Stripped invalid surrogate characters from messages. Retrying...uP   ⚠️  Surrogate encoding error — retrying after full-payload sanitization...rO   r   _client_kwargsdefault_headersu   ⚠️  API key contained non-ASCII characters (bad copy-paste?) — stripped them. If auth fails, re-copy the key from your provider's dashboard.ud   ⚠️  System encoding is ASCII — stripped non-ASCII characters from request payload. Retrying...uT   ⚠️  System encoding is ASCII — enabling full-payload sanitization for retry...r4   rq  )z%only 'text' content type is supportedz#only text content type is supportedzimage_url is not supportedzimage content is not supportedzmultimodal is not supportedz#multimodal content is not supportedz!multimodal input is not supportedzvision is not supportedzvision input is not supportedzdoes not support imageszdoes not support image inputzdoes not support multimodalzdoes not support visionzmodel does not support imagezimage_url'. expectedz,unknown variant `image_url`, expected `text`z(unknown variant image_url, expected textz+no endpoints found that support image inputc              3      K   | ]}|v V  	d S r#  r   )r  p
_err_lowers     rI   r%  z#run_conversation.<locals>.<genexpr>	  s8       2 2()AO2 2 2 2 2 2ra   i  _vision_supporteduV   ⚠️  Server rejected image content — switching to text-only mode for this sessionz,. Stripped images from history and retrying.context_compressori@ )rU   rQ   r/  r.  num_messageszTError classified: reason=%s status=%s retryable=%s compress=%s rotate=%s fallback=%suX   🔐 Nous paid access verified — refreshed runtime credentials and retrying request...)rq  has_retried_429classified_reasonerror_contextr9   )rH   uE   📐 Image(s) exceeded provider size limit — shrank and retrying...zlimage-shrink recovery: no data-URL image parts found or shrink didn't reduce size; surfacing original error.u`   📐 Provider rejected list-type tool content — downgraded screenshots to text and retrying...znmultimodal-tool-content recovery: no list-type tool messages with image parts found; surfacing original error._oauth_1m_beta_disabledui   🔕 OAuth subscription doesn't support the 1M-context beta — disabled for this session and retrying...>   	xai-oauthopenai-codexi  r  z	xAI OAuthCodexu   🔐 z. auth refreshed after 401. Retrying request...r  vertexu=   🔐 Vertex AI token refreshed after 401. Retrying request...u<   🔐 Nous agent key refreshed after 401. Retrying request...)display_hermes_homeresponse   u/   🔐 Nous 401 — Portal authentication failed.z   Response: zNous model accesszS   Most likely: Portal OAuth expired, account out of credits, or agent key revoked.z   Troubleshooting:u.        • Re-authenticate: hermes auth add nousuA        • Check credits / billing: https://portal.nousresearch.comu$        • Verify stored credentials: z
/auth.jsonuK        • Switch providers temporarily: /model <model> --provider openroutercopilotuA   🔐 Copilot credentials refreshed after 401. Retrying request..._anthropic_api_key)_is_oauth_token)is_token_provideruC   🔐 Anthropic credentials refreshed after 401. Retrying request...u-   🔐 Anthropic 401 — authentication failed.z5   Auth method: Microsoft Entra ID (httpx event hook)z;   Run `hermes doctor` for credential-chain diagnostics, orz0   `az login` if your developer session expired.zBearer (OAuth/setup-token)zx-api-key (API key)z   Auth method:    z   Token prefix: z   Token: (empty or short)u"        • Check ANTHROPIC_TOKEN in z+/.env for Hermes-managed OAuth/setup tokensu$        • Check ANTHROPIC_API_KEY in z)/.env for API keys or legacy token valuesuJ        • For API keys: verify at https://platform.claude.com/settings/keysuD        • For Claude Code: run 'claude /login' to refresh, then retryu=        • Legacy cleanup: hermes config set ANTHROPIC_TOKEN ""uA        • Clear stale keys: hermes config set ANTHROPIC_API_KEY ""reasoning_detailsuc   ⚠️  Thinking block signature invalid, stripped reasoning_details from api_messages for retry...zs%sThinking block signature recovery: stripped reasoning_details from %d api_messages (canonical messages unchanged)_codex_reasoning_replay_enabledc              3     K   | ]o}t          |t                    oU|                    d           dk    o<t          |                    d          t                    o|                    d          V  pdS )r   r   codex_reasoning_itemsN)rZ   r   r   list)r  _ms     rI   r%  z#run_conversation.<locals>.<genexpr>:  s        
 	 #2t,, <FF6NNk9<&rvv.E'F'FMM< FF#:;;	     ra   ua   ⚠️  Encrypted reasoning replay was rejected by the provider — disabled replay and stripped itemsz item(s) from z message(s), retrying...z^%sInvalid encrypted reasoning recovery: disabled replay and stripped %d items from %d messages)strip_pattern_and_formatz5%sllama.cpp grammar recovery: strip helper failed: %su<   ⚠️  llama.cpp rejected tool schema grammar — stripped z' pattern/format keyword(s), retrying...zU%sllama.cpp grammar recovery: stripped %d pattern/format keyword(s) from tool schemasue   %sllama.cpp grammar error but no pattern/format keywords to strip — falling through to normal retryzAPI error recovery (attempt z;API call failed (attempt %s/%s) error_type=%s %s summary=%sz [HTTP ]u!   ⚠️  API call failed (attempt u      🔌 Provider: z	  Model: u      🌐 Endpoint: u      📝 Error: i,  u      📋 Details: u      ⏱️  Elapsed: zs  Context: z msgs, ~zsupport tool useu$      💡 No OpenRouter providers for z1 support tool calling with your current settings.zU      Your provider_routing.only restriction is filtering out tool-capable providers.zY      Try removing the restriction or adding providers that support tools for this model.zH      Check which providers support tools: https://openrouter.ai/models/u?   ⚡ Interrupt detected during error handling, aborting retries.z+Operation interrupted: handling API error (compression_enableduS   ❌ Context overflow, but auto-compaction is disabled (compression.enabled: false).ux      💡 Run /compress to compact manually, /new to start fresh, switch to a larger-context model, or reduce attachments.zContext overflow (u4   ) with auto-compaction disabled — not compressing.zContext overflow and auto-compaction is disabled (compression.enabled: false). Run /compress to compact manually, /new to start fresh, or switch to a larger-context model.)r   r   r   r   r.   r  r   compaction_disabled)rQ   r.  rT   r  rU   r@  uO   ⚠️  Anthropic long-context tier requires extra usage — reducing context: u    → u   🗜️ Context reduced to z tokens (was z), retrying...upstream_provideru   ⚠️ Upstream u0    rate-limited — switching to fallback model...uI   ⚠️ Billing or credits exhausted — switching to fallback provider...uA   ⚠️ Provider unreachable — switching to fallback provider...u9   ⚠️ Rate limited — switching to fallback provider...u[   🔐 Authentication failed and could not be refreshed — switching to fallback provider...)is_genuine_nous_rate_limitrecord_nous_rate_limitheaders)r  last_known_state)r  r  zNous 429 looks like upstream capacity (no exhausted bucket in headers or last-known state) -- not tripping cross-session breaker.i  zmodels.inference.ai.azure.comuJ      💡 GitHub Models free tier (models.inference.ai.azure.com) caps everyzJ      request at ~8K tokens. Hermes' system prompt + tool schemas baselinezF      exceeds that floor, so this endpoint cannot run an agentic loop.zK      Use the `copilot` provider with a Copilot subscription token (`hermesu=         setup` → GitHub Copilot), or pick any other provider.u   ❌ Max compression attempts (z&) reached for payload-too-large error.uR      💡 Try /new to start a fresh conversation, or /compress to retry compression.z413 compression failed after z
 attempts.z5Request payload too large: max compression attempts (z
) reached.)r   r   r   r   r.   r  r   compression_exhaustedu@   ⚠️  Request payload too large (413) — compression attempt gffffff?u   🗜️ Compressed z messages, retrying...u   🗜️ Compressed ~u    → ~z tokens, retrying...)remember_modeluj   📐 Compression could not reduce the request further — removed retained vision payloads and retrying...u2   ❌ Payload too large and cannot compress further.z/413 payload too large. Cannot compress further.z9Request payload too large (413). Cannot compress further.@   uM   ⚠️  Output cap too large for current prompt — retrying with max_tokens=z (available_tokens=z; context_length unchanged at z!Context compression failed after z3Context length exceeded: max compression attempts (u_   ❌ The provider rejected the request because max_tokens exceeds its output cap for this model.u      💡 Lower model.max_tokens in your config.yaml to at or below the model's max-output limit. (This is an output-cap error, not a context overflow — compression cannot fix it.)zMOutput-cap error not routed into compression (max_tokens over provider cap): zcmax_tokens exceeds the provider's output cap for this model. Lower model.max_tokens in config.yaml.)r   r   r   r   r.   r  r   >   
minimax-cnminimax)z https://api.minimax.io/anthropicz"https://api.minimaxi.com/anthropiczcontext window exceeds limit (z!Context limit detected from API: u:   ⚠️  Context length exceeded — using provider limit: zBProvider reported overflow amount only; keeping context_length at z tokens and compressing.um   ⚠️  Context length exceeded, but provider did not report a max context length; keeping context_length at u   🗜️ Context too large (~u    tokens) — compressing (u8   ❌ Context length exceeded and cannot compress further.u      💡 The conversation has accumulated too much content. Try /new to start fresh, or /compress to manually trigger compression.zContext length exceeded: z! tokens. Cannot compress further.zContext length exceeded (z" tokens). Cannot compress further.nonetypeznot iterableuI   ⚠️ Provider safety filter blocked this request — trying fallback...uA   ⚠️ TLS certificate verification failed — trying fallback...u!   ⚠️ Non-retryable error (HTTP u   ) — trying fallback...non_retryable_client_error)rM  r.   u1   ❌ Provider safety filter blocked this request: u)   ❌ TLS certificate verification failed: u   ❌ Non-retryable error (HTTP u%   ❌ Non-retryable client error (HTTP z). Aborting.zmodel accessr   >   rz   r  r  r  uK      💡 Codex OAuth token was rejected (HTTP 401). Your token may have beenz?      refreshed by another client (Codex CLI, VS Code). To fix:z?      1. Run `codex` in your terminal to generate fresh tokens.z3      2. Then run `hermes auth` to re-authenticate.u8      💡 xAI OAuth token was rejected (HTTP 401). To fix:zU      re-authenticate with xAI Grok OAuth (SuperGrok / Premium+) from `hermes model`.uJ      💡 Nous Portal OAuth token was rejected (HTTP 401). Your token may bezF      expired, revoked, or your account may be out of credits. To fix:z'      1. Re-authenticate: hermes portalzC      2. Check your portal account: https://portal.nousresearch.comz:freeu         ⚠️  Note: `z1` looks like an OpenRouter slug (`:free` suffix).zH         Nous Portal won't recognize that model name. Either switch to az7         Nous catalog model, or run `/model openrouter:z` to use OpenRouter.u9      💡 Your API key was rejected by the provider. Check:u-         • Is the key valid? Run: hermes setupu+         • Does your account have access to r   u?         • Check credits: https://openrouter.ai/settings/creditsu6      💡 This type of error won't be fixed by retrying.uC      💡 The provider's safety filter rejected this specific prompt.u]         • Try rephrasing the request, narrowing the context, or splitting into smaller steps.uM         • Configure a fallback provider so future blocks route automatically:uM           hermes fallback add   (interactive picker — same as `hermes model`)uL      💡 The TLS certificate chain could not be verified. This fails the sameuA         way on every retry — fix the environment, then try again:uH         • Corporate TLS-inspecting proxy? Point Python at its CA bundle:zL        export SSL_CERT_FILE=/path/to/corp-ca.pem  (also REQUESTS_CA_BUNDLE)u<         • Missing/stale system CA store? Install/refresh it:zS        pip install --upgrade certifi   (macOS: run 'Install Certificates.command')uN         • Self-signed local endpoint (llama.cpp, LM Studio, vLLM)? Use http://zD        for localhost, or add the server's cert to your trust store.zNon-retryable client error: iP  P   uU   ⚠️  Skipping session persistence for large failed session to prevent growth loop.us   ⚠️  The model provider's safety filter blocked this request (not a Hermes/gateway failure).

Provider message: )rr  rs  u"   ) exhausted — trying fallback...u%   ❌ Billing or credits exhausted — u   ❌ Rate limited after u    retries — u   ❌ API failed after u      💀 Final error: c              3      K   | ]}|v V  	d S r#  r   )r  r  	error_msgs     rI   r%  z#run_conversation.<locals>.<genexpr>e  s7          1Y            ra   )zconnection lostzconnection resetzconnection closedznetwork connectionznetwork error
terminatedu      💡 The provider's stream connection keeps dropping. This often happens when the model tries to write a very large file in a single tool call.z~      Try asking the model to use execute_code with Python's open() for large files, or to write the file in smaller sections.)is_thinking_timeoutu      💡 The model's thinking phase exceeded the upstream proxy's idle timeout before the first content token arrived. This is a known issue with reasoning models behind cloud gateways (NVIDIA NIM, OpenAI, Anthropic, DeepSeek).z$      Workarounds in priority order:z      1. Set `providers.z.models.u   .stale_timeout_seconds: 900` in `~/.hermes/config.yaml` to extend the per-call timeout. (Hermes's built-in floor is 600s for known reasoning models — if you still see this after raising, the upstream cap is even shorter.)zn      2. Lower `reasoning_budget` or set `reasoning_effort: medium` on this model if the provider supports it.zZ      3. Use a smaller / faster reasoning model if the task doesn't require deep thinking.zP%sAPI call failed after %s retries. %s | provider=%s model=%s msgs=%s tokens=~%smax_retries_exhaustedzBilling or credits exhausted: zAPI call failed after )build_thinking_timeout_guidance)rU   rQ   u  

The provider's stream connection keeps dropping — this often happens when generating very large tool call responses (e.g. write_file with long content). Try asking me to use execute_code with Python's open() for large files, or to write in smaller sections.)r   r   r   r   r   r.   failure_reasonr   zretry-afterzRetry-AfteriX  g       @g      N@)rT   rQ   r.   default_waitzai_coding_overload_longz- (Z.AI Coding overload adaptive long backoff)zai_coding_overload_shortz# (Z.AI Coding overload short retry)u   ⏱️ Rate limited. Waiting zs (attempt z>Retrying API call in %ss (attempt %s/%s) %s policy=%s error=%sdefaultz<Operation interrupted: retrying API call after error (retry zerror retry backoff (interrupted_during_api_call!all_retries_exhausted_no_responseu:   ❌ All API retries exhausted with no successful response.r  r  post_api_requestapi_durationended_atresponse_model)r  assistant_messageassistant_content_charsassistant_tool_call_countu   🤖 Assistant: z,</?(?:REASONING_SCRATCHPAD|think|reasoning)>_delegate_depth	_thinkingzreasoning.availableuL   ⚠️  Incomplete <REASONING_SCRATCHPAD> detected (opened but never closed)u   🔄 Retrying API call (z/2)...uA   ❌ Max retries (2) for incomplete scratchpad. Saving as partial.z/Incomplete REASONING_SCRATCHPAD after 2 retriesr  codex_message_itemsu0   ↻ Codex response incomplete; continuing turn (z/3)z@Codex response remained incomplete after 3 continuation attempts_codex_incomplete_retriesu   🔧 Processing z tool call(s)...zTool call: z with args: u   🔧 Auto-repaired tool name: 'z' -> 'c                N    g | ]!}|j         j        j        v|j         j        "S r   )r   r   valid_tool_names)r  r  rK   s     rI   r  z$run_conversation.<locals>.<listcomp>B  s;     & & &)+{'u/EEE K$EEEra   u   ⚠️  Unknown tool 'u3   ' — sending error to model for agent-correction (uI   ❌ Max retries (3) for invalid tool calls exceeded. Stopping as partial.z#Model generated invalid tool call: u   Tool call rejected: the tool name was empty. If tool-call XML or JSON appeared in file contents or tool output, that is data — do not re-emit it as a tool call. To call a tool, use a valid name from your tool list; otherwise reply in plain text.zTool 'z#' does not exist. Available tools: zZSkipped: another tool call in this turn used an invalid name. Please retry this tool call.)r   r   r   r   z{}c              3     K   | ]P}|j         j        d  D             v |j         j        pd                                                    d           V  QdS )c                    h | ]\  }}|S r   r   )r  nry  s      rI   	<setcomp>z-run_conversation.<locals>.<genexpr>.<setcomp>  s    /P/P/Pda/P/P/Pra   rR   )}r  N)r   r   r   rstripendswith)r  r  invalid_json_argss     rI   r%  z#run_conversation.<locals>.<genexpr>  sv       % %;+/P/P>O/P/P/PPP  [28b@@BBKKJWWWPPPP% %ra   u>   ⚠️  Truncated tool call arguments detected (finish_reason=u   ) — refusing to execute.u1   ⚠️  Invalid JSON in tool call arguments for 'z': z/3)...u;   ⚠️  Injecting recovery tool results for invalid JSON...c                    h | ]\  }}|S r   r   )r  r   ry  s      rI   r  z#run_conversation.<locals>.<setcomp>  s    (O(O(O'$(O(O(Ora   c              3  B   K   | ]\  }}|j         j        k    |V  d S r#  r   r   )r  r  er  s      rI   r%  z#run_conversation.<locals>.<genexpr>  s8      *d*dAaSUS^ScNcNc1NcNcNcNc*d*dra   zError: Invalid JSON arguments. z_. For tools with no required parameters, use an empty object: {}. Please retry with valid JSON.z;Skipped: other tool call in this response had invalid JSON.>   todomemoryr  session_searchc              3  4   K   | ]}|j         j        v V  d S r#  r  )r  r  _HOUSEKEEPING_TOOLSs     rI   r%  z#run_conversation.<locals>.<genexpr>  sB       , , (,??, , , , , ,ra   u     ┊ 💬 zJIncremental tool-call persistence failed before execution (session=%s): %sguardrail_haltu   ⚠️ Tool guardrail halted c                &    h | ]}|j         j        S r   r  )r  r  s     rI   r  z#run_conversation.<locals>.<setcomp>g  s    UUU"R[-UUUra   execute_codeu     ⟳ compacting context…partial_stream_recoveryuG   Partial stream content delivered (%d chars) — using as final responseuD   ↻ Stream interrupted — using delivered content as final response_last_content_with_tools$_last_content_tools_all_housekeepingfallback_prior_turn_contentuO   Empty follow-up after tool calls — using prior turn content as final responseuM   ↻ Empty response after tool calls — using earlier content as final answerc              3  H   K   | ]}|                     d           dk    V  dS )r   r   N)r   r  ms     rI   r%  z#run_conversation.<locals>.<genexpr>  sE       * * f/* * * * * *ra   z<think>|<thinking>|<reasoning>_post_tool_empty_retrieduH   Empty response after tool calls — nudging model to continue processinguD   ⚠️ Model returned empty after tool calls — nudging to continuez(empty)_empty_recovery_syntheticz~You just executed tool calls but returned an empty response. Please process the tool results above and continue with the task.)r   r   r  reasoning_contentuM   Thinking-only response (no visible content) — prefilling to continue (%d/2)u7   ↻ Thinking-only response — prefilling to continue (z/2)uB   Empty response (no content or reasoning) — retry %d/3 (model=%s)u/   ⚠️ Empty response from model — retrying (uO   Empty response after %d retries — attempting fallback (model=%s, provider=%s)uL   ⚠️ Model returning empty responses — switching to fallback provider...u   ↻ Switched to fallback: z<Fallback activated after empty responses: now using %s on %sempty_response_exhausted_empty_terminal_sentinelzaReasoning-only response (no visible content) after exhausting retries and fallback. Reasoning: %su[   ⚠️ Model produced reasoning but no visible response after all retries. Returning empty.zfEmpty response (no content or reasoning) after %d retries. No fallback available. model=%s provider=%su/   ❌ Model returned no content after all retriesz and fallback attempts.z#. No fallback providers configured.)intent_ack_continuation_modeoff
codex_only)r   assistant_contentr   require_workspacezr[System: Continue now. Execute the required tool calls and only send your final answer after completing the task.])build_verify_on_stop_nudgeverify_on_stop_enabled_turn_file_mutation_paths_verification_stop_nudges)rW   changed_pathsattemptsz#verification stop-loop check failedr   verification_required_verification_stop_synthetic)r   r   r)  z0verification stop-loop nudge issued (attempt %d)_pre_verify_nudges)max_verify_nudges)get_pre_verify_continue_messagerA  
pre_verify_resolved_is_coding)is_coding_context)r   )rW   r   rQ   codingattemptr   r&  zpre_verify hook check failedverify_hook_continue_pre_verify_synthetic)r   r   r3  z$pre_verify nudge issued (attempt %d)ztext_response(finish_reason=u"   🎉 Conversation completed after z OpenAI-compatible API call(s)z)Error during OpenAI-compatible API call #u   ❌ z Outer loop error in API call #%dc                z    h | ]8}t          |t                    r!|                    d           dk    0|d         9S )r   r   r   r   r  s     rI   r  z#run_conversation.<locals>.<setcomp>x  sP     $ $ $%a..$ 4555==F3J3J .)3J3J3Jra   zError executing tool: zerror_near_max_iterations(z0I apologize, but I encountered repeated errors: )finalize_turn)r   r   r  r   r   r   r   r>  r   r   _should_review_memory_turn_exit_reason)rB  )r  (  hermes_cli.moa_configr   r/   r   r   r"   r   r   r*   r+   re   r   r   r   r   r   r   r>  current_turn_user_idxr   plugin_user_contextext_prefetch_cache_auth_pool_refresh_countsr@  _run_codex_app_server_turnmax_iterationsiteration_budget	remaining_budget_grace_call_checkpoint_mgrnew_turn_interrupt_requested
quiet_mode_safe_print_api_call_count_touch_activityconsumeused	max_totalstep_callback	enumeratereversedr   r[   r\   r   _skill_nudge_intervalr  _iters_since_skill_drain_pending_steerrangerZ   r   agent.prompt_builderr  r<   r  r;   r:   r
  logging	getLogger__name___sanitize_tool_call_argumentsrW   r   agent.agent_runtime_helpersr  copyr   r=   _copy_reasoning_content_for_apipop_should_sanitize_tool_calls#_sanitize_tool_calls_for_strict_apirQ   r   r{   agent.moa_loopr  r  r]   r  insert_use_prompt_cachingr#   
_cache_ttl_use_native_cache_layout_sanitize_api_messages#_drop_thinking_only_and_merge_usersjsonloadsdumpsr   r   sumr   r   rO   r`   _emit_statusrefundr  r  should_compressrA   _compress_context_empty_content_retries_thinking_prefill_retriesr  r  _mute_post_responser	   ru   rv   randomchoicer
   get_thinking_facesget_thinking_verbsrO  _has_stream_consumers_should_start_quiet_spinner	_print_fnstartverbose_loggingtime_api_max_retriesr   _current_api_request_idrU   agent.nous_rate_guardr8  r9  _buffer_vprint_buffer_status_try_activate_fallbackr   primary_recovery_attempted_flush_status_buffer_persist_sessionImportError_reset_stream_delivery_tracking$_reapply_reasoning_echo_for_provider_build_api_kwargs_force_ascii_payloadr   _get_transportpreflight_kwargs_is_copilot_urlr;  hermes_cli.middlewarer=  r   rT   payloadoriginal_payloadtracer   rA  r   _api_request_payload_for_hookr  r-   _dump_api_request_debugr>   r   unittest.mockrU  r^  r7  hasattrra  validate_response_client_log_contextri  _invoke_api_request_error_hook_fallback_index_fallback_chainr.   rv  r3   varsr  	TypeErrorrC   _clean_error_message_has_pending_fallbackr%   r   clear_interruptsleepmap_finish_reasonstop_reasonnormalize_responser  _should_treat_stop_as_truncated_is_anthropic_oauth_extract_reasoningr   content_policy_blockedrE   _CONTENT_POLICY_RECOVERY_HINT_cleanup_task_resourcesr   r)   ro   r?   r@   
IGNORECASE_has_content_after_think_block"_get_messages_up_to_last_assistant_session_messagesrestart_with_rebuilt_messages_build_assistant_messager   r    restart_with_length_continuation_strip_think_blocks%_requested_output_cap_from_api_kwargsmaxmin_ephemeral_max_output_tokensr(   r  r  r  r  r  r  r  r  r  update_from_responser.  r!   r  r  session_prompt_tokenssession_completion_tokenssession_total_tokenssession_api_callssession_input_tokenssession_output_tokenssession_cache_read_tokenssession_cache_write_tokenssession_reasoning_tokensr'   
amount_usdsession_estimated_cost_usdfloatrb  session_cost_statussourcesession_cost_sourcer   _session_db_created_ensure_db_sessionupdate_token_countsr  r  InterruptedError"INTERRUPT_WAITING_FOR_MODEL_PREFIXUnicodeEncodeErrorr   r  r   r   r   r   r  r  rV  anyr  r   _extract_api_error_contextr   rM  rq  rt  should_rotate_credentialshould_fallbackr  billingr}   'nous_paid_entitlement_refresh_attemptedr   _recover_with_credential_poolimage_too_largeimage_shrink_retry_attemptedrJ   #_try_shrink_image_parts_in_messages#multimodal_tool_content_unsupported'multimodal_tool_content_retry_attempted)_try_strip_image_parts_from_tool_messages!oauth_long_context_beta_forbiddenoauth_1m_beta_retry_attemptedr  _anthropic_clientclose_rebuild_anthropic_clientcodex_auth_retry_attempted%_try_refresh_codex_client_credentialsvertex_auth_retry_attempted&_try_refresh_vertex_client_credentialsnous_auth_retry_attemptedr   printhermes_constantsr  rx   copilot_auth_retry_attempted'_try_refresh_copilot_client_credentialsanthropic_auth_retry_attemptedagent.anthropic_adapterr  agent.azure_identity_adapterr  )_try_refresh_anthropic_client_credentialsr  thinking_signaturethinking_sig_retry_attemptedinvalid_encrypted_content)invalid_encrypted_content_retry_attempted_disable_codex_reasoning_replayllama_cpp_grammar_pattern!llama_cpp_grammar_retry_attemptedtools.schema_sanitizerr  _summarize_api_error_is_openrouter_urlproviders_allowedlong_context_tierpayload_too_largecontext_overflowupdate_model restart_with_compressed_messages
rate_limitupstream_rate_limittimeout
overloaded!_pool_may_recover_from_rate_limit_credential_poolr  is_authauth_failover_attemptedr  r  _rate_limit_stater    r   r   r  JSONDecodeErrorsslSSLErrorssl_cert_verificationr   r  r,   _try_recover_primary_transport_fallback_activatedr   agent.thinking_timeout_guidancer  r  r$   _api_response_payload_for_hook#_usage_summary_for_api_request_hooktool_progress_callbacksubsplitr&   _incomplete_scratchpad_retriesr  _emit_interim_assistant_messager   r   r   r   _repair_tool_call_invalid_tool_retriessortedr   _invalid_json_retriesnext_cap_delegate_task_calls_deduplicate_tool_calls	frozensetall _should_emit_quiet_tool_messagesr  _flush_messages_to_session_dbstream_delta_callback_execute_tool_calls_tool_guardrail_halt_decision#_toolguard_controlled_halt_response	tool_namerk  _stream_needs_breaklast_prompt_tokens_response_was_previewed)_drop_trailing_empty_response_scaffolding_clear_status_bufferr  "_looks_like_codex_intermediate_ackagent.verification_stopr"  r#  setr%  agent.verify_hooksr+  r,  agent.coding_contextr/  r.  r*  OSError	exceptionAIAgent_get_tool_call_name_staticagent.turn_finalizerr5  (x  rK   r   r   r   r   r   r   r   r   r   _decoded_message_decoded_moa_config_ctxr   r   r   r   r>  r9  r6  _plugin_user_context_ext_prefetch_cacher   r   r  r   codex_ack_continuationslength_continue_retriestruncated_tool_call_retriestruncated_response_partscompression_attemptsr7  
prev_tools_idxr  
_fwd_start_tm_tcid	_step_err_pre_api_steer	_injected_si_smr  markerexistingblocks_lockrequest_loggerrepaired_tool_callsr  repaired_seqr   idxr$  api_msg_injections_fenced_baseeffective_systemr  r  _moa_context_msg_moa_exc
sys_offsetpfmamtcsnew_tcsargs_objtotal_charsr/  request_pressure_tokens_runtime_context_error_compressor_defer_preflight_compression_cooldownfaceverbr5  rm  rr  rs  _retrymax_compression_attemptsr  r  rn  r?  r8  _fmt_nous_remaining_nous_remaining	_nous_msg_xhr=  _llm_request_mw_original_api_kwargs_llm_middleware_tracerA  r   rD  _request_payloadrU  r]  r^  r  
resp_modelresponse_invaliderror_details_ct_v_codex_resp_status_codex_error_obj_codex_error_msg	_out_text_out_text_stripped_resp_status_resp_incomplete_tv_btv_ctvrw  
resp_attrs_resp_error_code	_code_raw_failure_hintcleaned_provider_error_final_response	wait_time	sleep_end_backoff_touch_counter_interrupt_textrb  rf  incomplete_reason_tfr_bt_fr_bedrock_result_cc_fr_finish_resultr  _refusal_transport_refusal_result_refusal_text_refusal_log_refusal_detail_refusal_response
_trunc_msg_trunc_transport_trunc_result_trunc_content_trunc_has_tool_calls_has_think_tags_thinking_exhausted_exhaust_error_exhaust_response_cf_terminatedinterim_msg_is_partial_stream_stub_dropped_tools
_tool_list_continue_contentcontinue_msgpartial_response_is_stub_stall_tc_boost_base	_tc_boost_tc_requested_cap_tc_boost_caprolled_back_messagescanonical_usageaggregator_usage_moa_ref_cost_moa_client
_ref_usage_moa_acct_exc_agg_streamed_text_moa_trace_excr  r  r  
usage_dictctx
_cache_pct_agg_cost_model_agg_cost_provider_agg_cost_base_url	_agg_slotcost_result_cost_deltar  cachedwrittenr   hit_pctr  api_elapsed_partial	api_error_err_str_is_ascii_codec_is_surrogate_error_surrogates_found_messages_sanitized_prefill_sanitized_tools_sanitized_system_sanitized_sanitized_system_sanitized_ephemeral_headers_sanitized_default_headers_credential_sanitized_raw_key
_clean_key_any_sanitized	_err_body_err_status_IMAGE_REJECTION_PHRASES_looks_like_image_rejection
_status_ok_imgs_removedrq  r  _ctx_len
classifiedrecovered_with_poolimage_max_dimension_label_dhh_fn_dhh
_body_text_bodyr  r  keyauth_method_api_strippedreplay_statsr  ry  	_stripped
_strip_excelapsed_timero  _error_summary	_provider_model_status_code_str_err_body_str_overflow_reasons_reduced_ctx
compressorold_ctxoriginal_lenis_rate_limited_is_transport_failure_should_fallback_is_upstreampool_may_recover_upstream_name_genuine_nous_rate_limitr  r  	_err_resp	_err_hdrsis_payload_too_largeoriginal_tokens
new_tokensis_context_length_erroravailable_outsafe_outnew_ctx_provider_lower_base_loweris_minimax_providerminimax_delta_only_overflowis_local_validation_erroris_client_error_nonretryable_summary_policy_response_final_summary_billing_guidance_is_stream_dropr  _is_thinking_timeoutr  _retry_after_resp_headers_ra_raw_backoff_policy_policy_note_rate_limit_status_boost_base_boost_requested_cap
_boost_cap
_transport_normalize_kwargs
normalizedrawrD   part_assistant_tool_calls_assistant_text_api_ended_at_think_text
first_lineinterim_has_contentinterim_has_reasoninginterim_has_codex_reasoninginterim_has_codex_message_itemslast_msglast_codex_itemsinterim_codex_itemslast_codex_message_itemsinterim_codex_message_itemsduplicate_interimrepairedinvalid_tool_calls	availableinvalid_nameinvalid_previewassistant_msg_tc_namer   args
_truncatedr  recovery_assistantinvalid_nameserrtool_resultturn_content_all_housekeepingclean_had_prefillr   decision	_tc_names_real_tokens_partial_streamed
_recoveredfallback_prior_was_tool_has_inline_thinking
_nudge_msg_has_structured_truly_empty_prefill_exhaustedreasoning_textreasoning_previewr  	_ack_mode	final_msgr"  r#  _verify_nudge_verify_nudge2_edited_attemptr+  r,  r0  r/  answered_idserr_msgr5  r  r  r  rQ  r\  r  r  r  rP  sx  `                                                                                                                                                                                                                                                                                                                                                                              @@@@@@@@@rI   run_conversationrM    sͱ   @ 
	======4COL4Q4Q11"./0
'/+;( 	 	 	D	 'F.0'F/!9  D" $L 6}H44.lG 6 531 NNKF"#*,! ')E# ~+++//%"7/!6 0 
 
 	
 E000U5K5UXY5Y5Y^c^v5Y&&((( % 	K 5# Y!!"WXXX! .DNDDEEE
 # 	',E$$'//11 	 2# ^!!  #]5KaKf  #]  #]ini  jJ  #]  #]  #]  ^  ^  ^ *b
 )(8*<*< = =  HD"vvf~~449M9M4%(]]T%9
)+#+JKK#8 O OC"wwv&88 %$'GGN$;$;E$ O8;	28N8Nu 5& & & & ')&6& & &
 ##NJ???? b b bE~W`aaaaaaaab
 '!++"e&<<<$$)$$ 3355 $	nIS]]Q.B77  smc4(( SWWV__-F-FHHHHHH00@@F"wwy"55H!(C00 	!)1F):I!7?%GT(^^^RF"MM66*J*JKKK-3C	NN( ! ! ! D! $ILLV   E n  '<dCC$ B B / B383G$3NQ_3_E003AE0	B B B B B B B B B B B B B B B  'u.>EEHQY+mHtOn,L,L_mE( !$77V7;LX;V;V#AA!' B 
 

 ""X# 'C    	TSSSSS::5(KK!X 'C   !(++ *	) *	)HChhjjG +++60I0I & 489LMMG 4#**7333' =&&';<<< W#KK	266E!%-- W-2V^fkk+>V>V-V	* 11#w??? g%%K((('))O,,,KK+T222
 0022 V99'9UUU ((((" 052( 	c 06 9E<Y Y``bb 	\%-:JKKL|[L 	OOUUUUUUUU449CDY[^9_9_  5 5ehi~ee!-%/^^4F%G%G%M2)~~l;;Ar 3 3J@W X X+>+>zKc+d+d)~~.DEE        " ( 6 6 " "88F++v55$(HHY$;$;E)%55 P27&.<2OY!E	 6
  O O OCXNNNNNNNNO
 ! 	B+_Q0C0CF0K0Kx0W0W^_J%e&<== B BS##J$4chhjjAAAA $ 	8*!&!?  L 33LAA @@',~9J'J A 
 
  	6 	6B"&&++S11 6 "9 3 3 5 59 	' 	'B&&&&C G # #b$'' J",<,<#':bn[.I#J#J J 1 n1' (Z*.* * *1 1   %   6QzN;7zN..vs;;7 7:{333
 r""""&B| 	&l333 @@<@@@@@6|DD"? 3t#
 #
 #
 "=*"
 "
 " 	3NF BOO[^LLMMM\]]]aN$2E!&--////   & ."?AQAQ
 
!
BLL!
 !
 ! ! %3	H!!$q(($$%<== )) ) ++,CDD )
 !A% KK-*..w{,>BBGaHHLL;(8!<<L3w{,<a@@EAFFJJJBK$   Y.EQ Y Y Y   .3-D-D5)	 .E . .*H* ,-E(./E+-1E*9>E6(-E% $Jx$ $  aN$2E!"))+++   	)MMqu/qq~qqX]XlqqqrrrMMU-  V  VSEVEV  V  Vdq  V  V  V  @K  V  V  V  V  W  W  WMMU-pp\a\gHnEKHXHXHXmnppqqqq =!A!C!CDDD=!A!C!CDDD& 	) ''4(;(;$(;(;(;<<<<0022 )u7X7X7Z7Z )  &}-Z-Z-Z[[#0D1D1D41D1D1DS_jojy#z#z#z  &&(((   	LM  L%+  L  L3x==  L  Lw|  xC  dJcfglgrcscscs  IJ  L  L  M  M  MM^0\V0D0DV\^^___MJ-JJJJKKK,!!#$ 
#::.::(6%K'' ~''*        '@&?&A&AO&27J7JQ)<)<_)M)MQ Q Q " ,,A9AAA   ,,-?I-?-?@@@ 7799 %3P %|5I4K 4K0*+K340@EF=$ 22444..x9MNNN!Dy !D !D !D
 )1)7).&*%.     #   D    D@/55777 ::<HHH"44\BB
- >1*===>%666!&!5!5!7!7!H!Hbg!H!h!hJ 5";UCC :H]H]H_H_ :z~~o>>D"EEC)/C&25J/49E1/RRRRRR&B&B" 1 ''5#(#3#9r!&!52#k!&!&!&'5' ' 'O "1!8J+:+K(,;,A))  / / /+/
+;+;(,.)))/7         x 122 0+5>>*+E+E()*:DAA G/9~~g/F/F,)*:DAA </;," ,1+N+Nz+Z+Z($-  $5$5 %,G ,:>	
 (-'7'=2 *?)> 26h &+^%9r #(++ &+^^ &+^^ &+^^ ,:>  **:DAA.$T2B-C-C-C!#!" +.l*;*;*;#$ (+5;+<"'='='=%& 1>'( 0;{)* (-'7'7+, (6~-. .22G-H-H-H/0 %5$41 4 !   D ##9:: R11*[1QQQ4 4 4 4 4 4 "& 5"6>> /%*NN No555>/R006688CCOTT 65>/R006688CCLQQ 6 &+NN ^u,,U5P5P5R5R,%*NN4466 / 322222!'%4"@"@$GG /).J J J J J J J ONNNNN77%%9-##1$/52"^1r+"^"^"^#1%)*?%@%@  "  $y{{^; $ ,$))"---'+$* 0++B///' jMMU%5"h"hUa"h"h"h"hiii( TFN!Y7E!B!B!BTYJM  #SJ  #S  #Skrs{  ~E  lF  lF  ZQYaYgYg  LQ  #S  #S  T  T  T $)  ">%666!0022E 228<< -U#+/3,)001CDDDD
 25WXxQS5T5T5ZXZ1[1[1a1a1c1c1i1i1k1k.15LLL3:8Wd3S3S 0GQRbdhGiGi %a$4$8$8$C$C$CBR *a-=)>)>)>)`K])`)`)` !1
 !'$d$68H$)$=$=$?$?!" !" !"
 48 0 - 4 45pHZ5p5p^n5p5p q q q q -4HmT,R,R	JTU^`cJdJd5lY__5F5F5Fjl 2#5 !U$*LL)R(+,>(?(?%& %& %& %& 4;8Xt3T3TL7>xI]_c7d7d$4$*NN)[(46F(/'4(H(H(^EN(^(^en(^(^%& %& %& 8<$4$1$8$89S$T$T$T^';;;..00C00:: d+/(#+)001CDDDD)001bccc^'999 //11D11(;; d+/(#+)001CDDDD)001bccc //11D11(;; 	N+/(#+)001CDDDD!(9!=!= N)001VWWWW%-5)001KLLLL)001LMMM# _88 1 ''5'5'5#-#7&*ii&>&>&XBX$+GHgt,L,LfVZ$[$[$/$/"&1 9   " ( 0(--b111+/(. 4//333  1$K
 ,s53H/I/III,,-klll3355 !/L!<1E0G 0G,&'/0,<A9  !*I$-M :GHg$>$> :8> :$'$7$7	"8>:>> d8>CZ d,4N,C,G,GYb,c,cM! :gh	&B&B :xGW :$'(8$9$9	 %	11h178U\C]C]1bjbp1(A(A(A %	11h1%r%r$x..BVBVBXBX%r%r%r
 0 e#M*cWa*c*cddd (,$ %GHg$>$> %8> %$+HNFD$I$I	$,HND1Q1Q,(0(:(:6(B(BI$0%36y>> 0 0$-z#: % % % $%
 (3..(lXd(l(l(l(l)S00(^,(^(^(^(^)S00(Q)Z77(jBR(j(jVb(j(j(j(j)Z77(\IY(\(\(\)5(h@P(h(hT`(h(h(h(h%**(f,(f(f(f(f%**(j,(j(j(j(j(L(L(L(L(L((  *KR]  *K  *K`k  *K  *Kptpypy  {H  qI  qI  *K  *K  L  L  L(()Mm)M)MNNN-2-G-G	-R-R*(()^F\)^)^___(()F})F)FGGG"k11 6688 E!00  2D  2D  2D  2D  E  E  E 7799 %3P %|5I4K 4K0*+K340@EF=$22444**+x{+x+x+xyyy(8%k%kU`%k%k%klll..x9MNNN*n*n*n_l*n*n.=(0).)7%4&*     !1X] ^ ^ ^I(()aI)a)a)am)a)a)abbbNN  $W+  $W  $WP[  $W  $W`d`i`ijw`x`x  $W  $W  HU  $W  $W  X  X  X !%	i 7I-.*)++	11 5 !MMU-=*r*r*rz~M /LUb  /L  /Lny  /L  /L  }H  /L  /L  /LO;HoVVV!228=QRRR!113332A,4-;-2/3$ $  
3 /!3.1C71<<!11!M+ !M !M !M !M#&y49;;'>#?#?!M !M !M  ' )++	11.  >%666$Xx>>F)0;OQU)V)V&(,%!"4d;; X,>,B,B8,L,L)),34FRV,W,W)--2CGf2f2f )5(.^';;; //11D$($:$:8;O$P$PMM^'999"1133F&,&?&?&I&IO$3$AMM"1133F%+%>%>x%H%HN$2$@M(6%<<%)   	1
 $/rrr"& &    )1  !$444).)=)=)?)?&~)===*<*O*O$8Q +P + + +=*O*OPX*Y*Y%,_i%N%N%TRT$[$[$]$]M ) b).)A)A/)R)R)XVX(_(_(a(a88 1 ''5'5'5#-#9&3&c7c$($/$/"'-DJ 9     ( 0(--b111+/(. 4//333
 2244 ,,f   3355 !/L!<1E0G 0G,&'/0,<A9 ..000 }--33 &dsd+e33* !
 NN:(%+u~$3	   &&`   )B????A $;*; ; 9; ; & 112CDDD**85IJJJ9 &'8%2%W6W	    !H,,xr226LLL$/ O O O"& &     $/ V V V"& &    "&J',';';'='=$~)===(8(K(K$8Q )L ) ) )9(K(KH(U(U!.JMW%aWZD%I%I%I]aN]g,rD\SW1X1X,Y,Y,Ymr) '+& 29W*M, ,' 'O 21 + ,47t@d@des@t@t<t 6-5 ( + 5 '
 $/ A A A"& &   Z * 556GHHH..x9MNNN.?(0)7).'+%3     ~)ggg,6) *1$&BE* * +" % 5E<Q8R8R R R!MM#(#3 !N !N !N&* *   
 ".. \    %;;== &
 $< !b/4/W/WX`/a/aH:B 7:; 7;= 8./78 4DI AGK D % "MM#(#3 !: !: !: '+	 *    -8AV83q83*/*H*HIZ\i*j*jK$OOK88808 [ 8 ? ?@Q@Y Z Z Z6::$+HdB$?$?CY$Y !8 29$,.CT2" 2" $; !&~ !&15>"1";M1N1NJ$)MM+0+; )L )L6@)L )L -D)L )L )L%& %& %& %& &= 
!&$)MM+0+; )L )L,C)L )L )L%& %& %& %& %*MM+0+; )L )L,C)L )L )L%& %& %&
 5M$;^5" 5" 1 -3/@0" 0" !) = = =:B 7JN G %/4/H/HQiIjIj/k/k/q/q/s/s,!99:KLLL!228=QRRR2B2Jd,4-;-2+/)d$ $  ~)ggg,6),8=R8 '$ ; ;?U U +  ;Q>> ;q @ ;#1 !& %*$8$8)Y5P)Y )Y )Y%& %& %& %&
 %*$8$8)P,G)P )P )P%& %& %& FKEU1_1A1A[_,:aC^>^,_	494_4_`j4k4k 1#4#@03I?P0Q0QI03E;L;QPQ0R0REHTaEbEb B !)!66888- 	" %','7  %U  %U  %U*. !. !" !" !" !"
 !&','7  %`  %`  %`*. !. !" !" !" "99:KLLL!228=QRRR $2!U !< !< &U	 , 3B,4-;-2+/)8$ $  8}}q(()9&n&n&nooo/4/W/WX`/a/a,556GHHH..x9MNNN /^(<)7).'+%T     22444)9&h&h&hptuuu..x9MNNN.c(0)7).&*%Z     8W-- P(. P&5 !&!&' ' 'O (7$ %)M")%4"@"@K".7;Ha3b3b.e8C8[8[8]8]5J)52AJ2N( e e e"LL)TVcdddddddde #.7;H`3a3a.	W '/QSU V V \Z\ / (>> % 0;M;UQU ?      ) W W W"LL)E~VVVVVVVVW$3$AM(7(E%#2#?L *7->(4(7(D)8)F-<-N.=.P,;,L	" 	"J ,AA*MMM
 u79JERR T#6E"5#;=Y[`aa A/U^SQQQ!--1A.._b...rwr}..  A  A  ACH0@NS0K//=@//337HH33..,>..++q0++../2NN..//?3PP//337XX33448ZZ4422o6VV22 "$J&8 `] ` &`/P  &`  &`S`  &`  &`dghw  iJ  eJ  KX  eX  &`  &`  &`  &`
KKb/en>YPY%'8,$j	   ',kO).&).&VaVm5KT R R RswI  YY]]7%;%; Y*3G*<-6]]:-F-F-X%.*-6]]:-F-F-X%.*"5'(!3!3 'y" = =# # #K #-988E+BX<Y<YY88 %0!!<<m@T@TT<<< ):6 ! ! ! D!0;0BE-0;0BE- ( .U-= .- $)#< ; % 8 8 : : :
 +/K*5A.3K4J.K.K,8!)3>3E#}I]I]2]KK(1:'> !) !) !)$(D!)!-AA % 0-<-I.=.K2A2S3B3U1@1Q3>,7,>,7,>1616#.#5#C#C .E-DIM&+k/0 B    "  )    #LL V % 0,       	 , t  'sZ=X  's  's  'sis  uH  jI  's  's  's  U_  `n  Uo  's  's  's  t  t  t ->F-@G'8F ' 53C =CaZZ6F?S#8#8Q$/ I I%<I I*0<I I 'HI I4;HI I I   */& >V++OOOOOO--////$   %%&M>&M&M&MNNN#   # ,$))"---'+$* 0++B///"ikkN:!1SSS[_```" !44E#ErJJPb %''   iOO[X$N$NOOO%-NN(J%hK%h%h%h%hN&&x1EFFF E E E $ ,$))"---'+$* 0++B/// i);<< Y!PnpqArAruvAvAv"9~~3355H&/8&;&Rw(?RO $x/ K%1I/6I ( )Fh(O(O%!,55 58FF 504-!*d33 59*EE 504-!'%1CT"J"JDQQ 589OPP 504- ) 
!,? 
!::a?::, !00 j    "00 r   !& j!592 /K8.T.T+%lD99 G8FFF
 &j$77 F9*EEE-2*%ge5G&N&NPTUU f1MeNd1e1e.+0(%geWd&C&CTJJ V/H/U/U,,1)%&:C@@ 90@AU0V0V-04HHH7H 4>O ;48 1%ge5NPT&U&UWZ[[ 93CEDa3b3b03u7TTT@T =48 1-2*  *'%9I4*P*PRVWW&E0445FGGG!% )
 &&6== a1NO_1`1`. 16-#*5)T#B#B#Hb
 $ "
8S(A(A ")9()C)CJ)X550:#-ge=Mt.T.TVZ#[#[ !QFPE$8$C $+5(D#A#A#MRYZ_ZfhqRrRr#M;EEL$88< 5 %','7 %W %W %W +/	 !. !" !" !" ::a?::/ 515/5  15  2	5
  5 ' * 	!MM#(#3  !Z  !Z  !Z&* *    
 "MM#(#3  !J  !J  !J&* *    ! 	 #GIvt$D$D %3$+Iy$$G$G%3$'	NN!4 !4II !   D%iEE,,(Z '__..
.1 2 2 2 2-E2 2 2 / /+ )D0SSC<L<L5R5R5R5Rs5R5R5R5R
E#6==3 #
 /4E+$?$I$IM!,55 B3LAAAMM + H H HMZcII`ce #	 "    HHHH%iEE % @ @ K K &e-A4HHMXd7;0@&III^d/$UJ;;Ar!%"55;"/#+6B!I\!2!2!2  
 j%+Z-C(**D79S	   44-##1#1#1)#I7"%i.. + + +(2%,2 5   " %)???0z266<"z266<"  @
 #J @ FJFBEeLL !$/ T T T"& &   
 !>C>a>a +$*$:&0&7"/	 ?b ? ?;#V%; ' HHHH %)GGG"? H ;?F7*DY*O*O*WSW'@@$&9 A    $/ 6 6 6"& &   
 !V   %)[[["J \ FJFBFF|TT $/ N N N"& &   
 !Y   %)YYY*>>>1 ?"@ ? <@F8"5*CUKK !8<5!!399;;;;( ! ! ! D!77999$/ a a a"& &   
 ! N&777*GGG#s**"= + 9=F5BBBNN !05+0M0MSZ,,-kV-k-k-klll N&888(22#s**"> + :>F6CCEE !,,-lmmm N&888&00#s**"< + 8<F4AAAMM !!1oooppp  POOOOO"799D!#J '	64 @ @ hGIWacgDhDh ,),UDSD)9J$   U-^^^___! N!1LL
LLMMM;ECVWW H!1  G  G  G  H  H  HU-BBBCCCU-]]]^^^U-pppqqqU-ccSWcccdddU-zzz{{{Ni//#s**"? + ;?F7DDFF !,,-pqqq N&:::#s**';<< +"A + =AF9GGGGGGNNNNNNFFHH !!1vvvwww 2CU-\\\]]]((-- r !1hhhiii!1nnnooo!1cccddddFUoVYFZFZ&u&B&B`u!1PP;PPQQQU_`cehUiUi  qnqrunvnvy{n{n{!1QQCHQQQQ  EJ  EU  Bq  Bq  Bq  r  r  rU-BBBCCCOOOOOO"799DU-  C  CQU  C  C  C  D  D  DU-  C  CSW  C  C  C  D  D  DU-yyyzzzU-ssstttU-nnnoooU-rrrsss> %)JJJ"? K ;?F7$%M* / /%b$// /4G24M4MFF#6===)Q.MMM + U U U" "   
 NN9 (-	   HHHH" %)QQQ"L R*;;;WU,MtTTUU <  
 #+     < HLFD#(#H#H#R#RLMM + N N8DW8MN N'
3N N N #	 "    NNx($W-$Z0	   HHHH %)QQQ"D R @DF<&SSSSSS'?'?'L'L99$ & & &S!,j   %&						& ! !$/ [ [(1[ [ ["& &   
 J!,i  
 ! NNP(   q #y{{^;%%O;OOOOO   ")__5
	NN0022	!&!;!;I!F!FQ--//"   $E:yAA	z9== ;;?J#R#;[#;#;#;#;PR $$  &F  &F  &FWb  &F  &Fgq  &F  tD  &F  &F  G  G  G$$%V)%V%Vf%V%VWWW$$%A%%A%ABBB$$%G~%G%GHHH R;#4#4 '	64 @ @I<E$OC	NN4C4$8$84M$ R,,-P-P-PQQQ$$  &NL  &N  &N  &NZ]^jZkZk  &N  &N  vC  &N  &N  &N  &N  O  O  O ,,..*i77((xvxxx   . ,,s   ,,w   ((kcikk  
 - MMU%5"v"v"v  CM  D  D  D 'QT^  'Q  'Qbgb|b|  ~A  BK  ~L  ~L  cM  cM  'Q  'Q  'QO3HoNNN**85IJJJ))+++*9$,%3%*'+        &iEE& #4"4"3%! %):::#E+@$GG ; ..000MM + 9 9 9" "   
 MM + T T T" "   
 LL + I Iz?P?V I I I   **85IJJJT $ +:$,%*%3!0#'"&/3	 	 	 	 	 	 	 	$ $(HHH#)L!&!9J(7G--"//"'++7%*^$+E9b$A$A%*^%*^ 0    #:/@AA J9=J6
 EJJA,,G&FG G/;FG G G   )A-(+/GGG'*8}}9>9P9P$n*7$5 :Q : :6"6
 0V!80 0, x==<777\;Q;Q!00!Bl V !B !B(/ A!B !B !B   !JqMMMFJFC!EEEE #-"3"-"*"68 #
 )3(9"*"-> )%
 $ D-B+2B ! $ )%(=EDY@Z@Z(Z(Z $.#48Z#ZL!-  UUDD!2  % , %' n.8.F.L"-Q-Q 3\. .N "00!A> !A !A !A    (..2HHH!00 k    3 n!00 c    "001lmmm 77z?P7QQ %3P %|5I4K 4K0*+K340@EF=$HHHH$ &!":! -E4I0J0JJJ59F2((<   33:;L3MM !/L!<1E0G 0G,&'/0,<A9 . $+!&00")^-FFF/ G 05,        %,Iz4$H$H	  )3GIy$???.2 " 4N3M$--2-D4 4 40 4 22(1.;    
 #KK!9   %   / ! '*![1_&=&=  %)II %  3&&"5>377 '75>IIMM +www" "    MM +www" "    MM +sss" "    MM +xxx" "    MM +jjj" "   
 ( K(A-(+.FFF22444)9  'Z  'ZYq  'Z  'Z  'Z  bf  g  g  g)9  'N  'N  'N  VZ  [  [  [(8%{%{Wo%{%{%{|||..x9MNNN +Gbz  +G  +G  +G.=(0).)7%4'+&*59	  	  	 	 	 	 	 	 ((  *a  mA  *a  *a  D\  *a  *a  *a  b  b  b#&x==L&DX&N&NO5:5L5L . 1 6M 6 62H2 ,Rx, ,( "@!I!IJ$.M8}}|33
Q:XgjnXnKnKnx==<77!001|11Z]^fZgZg111  A  A  A  A!00  2D  2D  2D  2Dak  2D  2D  2D  2D  E  E  E
1BF? JJ(+0 K   % "00!S   %HHHH 22444)9&m&m&muyzzz)9  'N  'N  'N  VZ  [  [  [(8%i%i%ijjj..x9MNNN*e.=(0).)7%4'+&*59	  	  	 	 	 	 	 	  %)HH ( + J!&!9J(7G %MY$W$WM$0 $'q-"*<#=#==E:,,m8@Em m1>lm m`glm m m   -1,/2JJJ!66888!MMU-=  +B  +B]u  +B  +B  +B  JNM  O  O  O!MMU-=  +R  +R  +R  Z^M  _  _  _"LLE,<  *D  *D_w  *D  *D  *D  E  E  E!228=QRRR /Id|  /I  /I  /IO2A,4-2-;)8+/*.9=	$ 	$ 	 	 	 	 	 	 CG? +955 22444$/ Q Q Q"& &   
 $/ ; ; ; #' &    $/ Q Q?H#Q Q   ..x9MNNNE (
 />(0).)7%4'+&*           EYPWXXG'.uj"'E'E'K&R&R&T&TO#*5*b#A#A#GR"O"OPS"T"T"Z"Z"\"\K'+DD &11 3   ( , J#tOJ<	I 0 *,,-uQX-u-u-uip-u-u-u-uvvv"//"'++2%*^$+E9b$A$A%*^%*^ 0    #:/@AA I9=J6DHJA,,  .Mjq  .M  .M  .M  {B  .M  .M  .M  .M  N  N  N  N4 	,,]9@\] ] ]   
 ,,]9@\] ] ]  
 )A-(+.FFF22444)9&}&}Yq&}&}&}  FJ  K  K  K)9  'N  'N  'N  VZ  [  [  [(8%%[s%%%  A  A  A..x9MNNN +E`x  +E  +E  +E.=(0).)7%4'+&*59	  	  	 	 	 	 	 	 ((  *i  *i  *i  *i  tH  *i  *i  Kc  *i  *i  *i  j  j  j#&x==L&DX&N&NO5:5L5L . 1 6M 6 62H2 ,Rx, ,( "@!I!IJ$.M8}}|33
Q:XgjnXnKnKnt{Kn  AH  KR  AR  ARx==<77!001|11Z]^fZgZg111  A  A  A  A'!^^
_t=S0S0S!00  2D  2D  2D  2Dak  2D  2D  2D  2D  E  E  E
1BF? 22444)9&s&s&s{  A  A  A)9  '}  '}  '}  EI  J  J  J(8  &C  &CS]  &C  &C  &C  &C  D  D  D..x9MNNN*vj*v*v*v*v.=(0).)7%4'+&*59	  	  	 	 	 	 	 	. y:y*ABB &!$68L#M   'y#,???. #9i88 E&#i..*>*>*@*@@E*c)nn.B.B.D.DD/ *Z . &00 	 * ::	&-*5*5*;*<*<*=6 #2 21    # } 2244 |%,0UUU!001|}}}}'..2VVV!001tuuuu!001zU`1z1z1z{{{3355 !/L!<1E0G 0G,&'/0,<A9 !-55&/KS\ 6   
 ..000 -2,F,Fy,Q,Q)!(N,QQQ**747 7    $*n.RRR**747 7   
 **7[ 7 747 7   MMU%5"u"u\g"u"u"u  ~BM  C  C  CMMU%5"e"e"e"e]c"e"emqMrrrMMU%5"P"P"P"PX\M]]]!) )Z->.BX-X-X%,0FFFKq!'5%.%(ZZ"(L L LF !&&005U!/6 60 !&*OOOT_cfTfTf(N:: %1A  /O  /O  /O  W[  !\  !\  !\ %1A  /C  /C  /C  KO  !P  !P  !P %1A  /C  /C  /C  KO  !P  !P  !P %1A.v.v.v  C  !D  !D  !D  !D!*k!9!9 %1A.{.{.{  DH  !I  !I  !I %1A  /Y  /Y  /Y  ae  !f  !f  !f  !f %1A  /N  /N  /N  VZ  ![  ![  ![ %1A  /J  /J  /J  RV  !W  !W  !W %1A.j.j.jrv w w w %1A  /G  /G  /G  OS  !T  !T  !T $.fc#:#: !hvw?W?W !h$)MMU5E  3V  3V\b  3V  3V  3V  ^bM  %c  %c  %c$)MMU5E  3P  3P  3P  X\M  %]  %]  %]$)MMU5E  3[  3[  E  3[  3[  3[  cgM  %h  %h  %h!MMU-=*x*x*x  AEM  F  F  F!MMU-=*l*l*ltxMyyy!MMU-=*s*sjp*s*s*s{M  A  A  A4SZZQQ P %1A  /C  /C  /C  KO  !P  !P  !P)9&q&q&qy}~~~ "(N,QQQ$/ttt"& &    $/  O  O  O"& &    $/~~~"& &    $/~~~"& &    "(N,PPP$/}}}"& &    $/rrr"& &    $/yyy"& &    $/}}}"& &    $/mmm"& &    $/  E  E  E"& &    $/"& &    $/uuu"& &    LLE$4!]!]R[!]!]^^^ #c))}u/D/DLHYHY\^H^H^$/ P P P"& &     ..x9MNNN!(N,QQQ?1F? ?  =? ? )  >$*+;)>	            +@$,%3%*"&!6        +--
 "< !AeAe!{ Bf B B ! =A9&'
 27.01-491 2244 u,,-sK-s-s-sttt3355 !/L!<1E0G 0G,&'/0,<A9 ..000%*%?%?	%J%JN(*%!(N,BBB**+cSa+c+cddd,K'5%.%(ZZ"(	- - -) ?!'5%.%(ZZ"(     ) o**+o[+o+o_m+o+opppp**+m;+m+m]k+m+mnnnMMU%5"\"\N"\"\dhMiii $I}dCCC          9         $ ' $/ ; ; ; #' &    $/ ) ) ) #' &   2      ,?+>"!, ,(
 ,  $/ J J J #' &    $/UUU"& &    $/ Q Q*3Q Q=CQ Q Q #' &    $/ e e e"& &   
 $/ P P P"& &    LLj(+~!63|+<+<>R>R  
 "-55&/Fi 6    **85IJJJ!(N,BBB*[>*[*[, J+/I6G/I/IIO*j;*j*jZh*j*j+       (+J+J%."(, , ,  ) 'F +:$,%3%*"&!/ +5*;*A          $" %$+GIz4,P,PR[]a$b$bM$ %)F)F %"/"3"3M"B"B"fmFWFWXeFfFf" 	%% 035>>3/G/G$-z#: % % % $%,8{LL>N{gjvz>{>{>{	"&" < 1L#!$U$'%.2 2 2.I # w#%L&*DDD'V(,GGG'L *U  *U  *U  *Ucnqrcr  *U  *U  vA  *U  *U  DP  *U  *U  *U& '*DDD**+=>>>>,,-?@@@@(()uI)u)u)uVa)u)udo)u)u)uvvvT--//#0y   !IKK)3	)*&ikkI--1 )9&n&n&nvz{{{ +Git  +G  +G  xC  +G  +G  +G7/RRR..x9MNNN--///.=(0)7).+/          JsOOO +a/*-3q88--IK I I+ I I"9ty{{#:;;I I I  ' ikkI--_9E]% K''l_  	 =2 	aN"))+++ 1K6;F3/ 		 aN"))+++38F02 	 /4.>H%**DK A)@$@AF"HHTTN)V^44UN$7a88J14VZ1H1HE.
  CU%aaabbb""8-ABBBf	--//J "~!5559>9R!"5666xUUCTUUJ *&4M
 !(4ZHYHacf=g=g4'/c4(( 9030C0C0pswwyZ\G]G]0paeakloapap%--T** 9E # < <%dC00 <!LL....'d33 <8H8HF8R8R!LL&")=)=>>>>'d33 <$!LLT&\):):;;;04		%0@0@%--03C%-(        8.// ! 1<FFL" * '8&?&E2O$2\$AM L*   1 1 !( (6~	
 $)#3#9r "'!52 $kk "' "' "' (6~ &2\ $2> "/ '4m  '*,&7&7&7!" (/x$'G'G'G#$ "'!E!E$-*7 "F " " "%. $GGQQQ/0 +<*;12 14O0D0D0D34 366K2L2L2L5 8     !( a1A a( aMMU%5"b"bGXG`"b"bccccMMU%5  #`  #`GXG`aebeaeGf  #`qt  vG  vO  rP  rP  SV  rV  rVhmhm  \^  #`  #`  a  a  a ") e.J /7==?? fCR %'' 
 ALS[..t44Q7<<QS
 	'%1BA"F"F"J"J44[*MMMM$     445JKYdeifieiYjlpqqqq$   
 )):)B)HbII 44944$$%sttt71<<(()pEDh)p)p)pqqq ..000MMU%5"x"x"x  AEM  F  F  F;<E8+0+S+ST\+]+](112CDDD**85IJJJ +\$8%3%*#'!R   45E0~!222}7T7T//14//#<<=NP]^^&*KOOI,F,F,L"+S+S+U+U&V&V#Zdepetet  vA  fB  fB  DG  [H  [H  )S[__["-M-M-S-S-U-U(V(V(V  NS%.2;??CZ3[3[.\.\+26{G\7]7]2^2^/ (K,K 3K 7	K 08Ax||TH Q[[ceiPjPj'tx||4K'L'L'Lpt$*5//:Q*R*R'V`aikoVpVp/zx||<Q/R/R/Rvz,2=//BW2X2X/"8T22 T$LL00K?T$LL99\IT &\\)44:PY@Z@Z@`^`aT &\\+66<"+//R]B^B^Bdbde	T
 -0CCT 58SS & - K 444==kJJJ2Q66 + Q)9  'P  'Pkp  lK  'P  'P  'P  Q  Q  Q.6E+23/&&x1EFFF&h (!/!&#_    ;<< 423/ !+ k' |MMU%5"z"zsK\KgGhGh"z"z"z{{{( t/: t t&rBK4D&r&rRTR]RghlilhlRm&r&r&rssss ,6 8 8B{'u/EEE#(#:#:2;;K#L#L# 8!U%5"y"yVXVaVf"y"ynv"y"y"yzzz/7BK,& & & &/@/K& & &" & <//14// !%		&1G*H*H I II#5a#8LCF|CTCTWYCYCYl3B3&7%&?&?_kO((  *g/  *g  *g  GL  Gb  *g  *g  *g  h  h  h2a7722444)9  'E  'E  'E  MQ  R  R  R673..x9MNNN*aP_*a*a.=(0)7).'+%4     %*$B$BCTVc$d$dMOOM222/:    #%;#3#5+AAA %-N#9#9#;#; 
l%E !( +l8*k*k`i*k*k 'CG $*$&K$4,.E'.	) )     ./+ %'!+6 M MB;0D!$t55 !04
40@0@- '
40E0E'03D		-!{4 !tzz|| !04- M
4((((/ M M M)00"+2BCFF1KLLLLLLLLM % D! "% % % % %"3">% % % " "J
 " $/ Z Z.;Z Z Z"& &   
 783556GHHH..x9MNNN.](0)7).'+%T     //14//+<Q+?(Iy(()v]f)v)vkt)v)vwww2Q66,,-kHc-k-k-klll  ,,-jkkk673 .3-K-KL]_l-m-m* (:;;; )P(O=N(O(O(O"3">  B!{/=@@&**d*d*d*d9J*d*d*d&d&d%Ec %E %E %E !, /l$OO(.(*(802+6	- -     ! /0+ 05/M/M%00 0!, 05/L/L%00 0!, !& > >?PR_ ` `  18>B AE$H$H$V$V A5AE2 +4 5 5 5 + +' ), , , , ,"3">, , , ) )% BSE>( AU-H-H-J-J A4811??AA A % 9 9, G G M M O O  A!MM*?*?*?@@@  %("8B<66( !(()<==(
 LLNNN#'L ("8B<66( !(()<==(   567E334E0 27....55mDDD
 77BVWWWW    NN+(2F	        . 33D9999$    ))*;XGXZhiii6B$BH(8%%*%N%Nx%X%XN&&]8J]]hm]]   OO[^$T$TUUU & %))*A~*A*A*ABBB 6 %% % ; ;N K K K % ; ;D A A A A#, % % % $%
 /0+ -1)
 VU8I8TUUU	 000*11333  $61A55 $/#ALL 3r99 $%LL $A (;t$ $ $L , 	1L1L\1Z1Z 	%%&CDDD5:5L5L .&+&>&Q 1 6M 6 62H2
 ,Rx, ,(
 +3'  "3!:!@b -2) ;;NKK F  'I2NNTRT & ;;<MNN ,E)%*%>%>?P%Q%Q%W%W%Y%Y
:
OO  
 **0   *4
 9>5  'u.H$OOH GE3Y[`$a$a ,I)$uvvv**+z{{{9=6EJB784
 */)B)B8)L)L)R)R)T)T8<5 '* * *!)"##* * * ' 'O ,0	=*0bM , ,( ($! '/I5 Q Q$! !5$!
 :>6 :>6EJB5   ,,2   &+%C%CDUWd%e%e
09
9-BF
#>? 
333 $*!L :>) )    ! '+ 1;EE 0"#46I4PP0"#46I4PP0 0	' 'O ' !5+JQ+N+N771<77<!;  
 ,,E % ?E E E   ',&D&D-|' ' <@$78 4442:/  (-'@'@&( (egg$L ( A!;q@ ' $ !_ !@R !X]XtwxXxXx449444!8%+  
 ,,B % <B B B   ! $ %(= %J!8%+!N	   ,,@   !7799 %3P %|5I4K 4K0;<E8!00!6U[ !6 !6$)N!6 !6 !6   #KK!5 %U^  
 % ..000(B%%*%=%=>O%P%PNCCHMMM$)$B$BCTVc$d$dM/8M), AEM"<=OOM222% LOP^L_L_beLeLeN4C4,@5,H,Hky),->  
 **K   
 3 "8%+!N   **M<A<Q  E88DF   &/N 01,23/ **,,,      98??	&&. '/!33@@%1*8!)+4+D	 A   4 ,q0+"'"@"@ART`"a"aKOOK00099+FFF !'Q$ $L OOL111.6E+*+'+ 0%'WW-E%F%F%WN/1,./+!&!:!:>!J!J!P!P!R!R!::;Lm\\	 	#"8B<66	# !(()<==		#
 $B<++,GHH	# $B<++,FGG	# LLNNN 	#"8B<66	# !(()<==		#
 $B<++,GHH	# $B<++,FGG	#)       
 .-// -(B(B'.ulD'I'I*1%9TVYV[V[*\*\%,U4OQR%S%S) ) ) )-  ) ) )LL!FQULVVV$(MMM) ! 'BAFFJ 3 2IIo.@DI<=OOI... OO &#08<% %   
 /7E+ LL!S!&!@B B B "& 0KSUU!S!S!YWYZZ"5*>BB*DDDDDD\\\\\\\\ 88L#9#9 hIZIZI\I\>\>\!(0Et!L!L!>NNNNNN%)*;*;WUT^`bEcEcEigi*j*j*j%k%kF8>E5)H)H'.ulD'I'I'OR%,UJ%C%C%Ir")%""="="C#)$,+9*1* * * ! * * *LL!?$LOOO%)NNN* " /7!|E,1GIo.9=I56
 OOI...OO &#115% %   
 /7E+LL!G!&!9; ; ;	***$S=$S$S$S!' {%%&y>&y&y&yzzz 7	 7	 7	^N^^VYZ[V\V\^^I((Y(())))Z( ( ( (Y'''''( ?PPP
 S]]Q.B77  sm!#t,, E776??f,,776??k11cggl6K6K1$ $!)#'((!3$ $ $L
 ",/ 	5 	5!GB)=)=Gxd8<77(.(+(P(PQS(T(T024+OI+O+O	' 'G %OOG444 !5!999$R3B3$R$R$R!!_T]!_!_  P PQQQ :9999c7	MO E000U5K5UXY5Y5Y^c^v5YDQ 322222=%%1+!33+   s  6 
AA	C-K7 7
L'L""L'0P77
QQ>"R,,R03R0/C4`$ $
a.aa(Ag66Aiil   
l-,l-B '6 8,	878<C#B} C AAD4 D3B} D4AEEB} EAEEB} EEAJ# J"B} J#
AJ0J-B} J/AJ0J0[B} e4FB} lAl lB} lAl'l$B} l&Al'l'E%B} rA8B} tDB} xA9B} zKB} E"CB} H>F%B} O$B<B} R"E4B} XA1B} Z
C B} ],BB} ` A<B} a=AB} cA&B} d9Be eB} e
Bfe"Bfe>B} fBffB} f 3Bg gB} g
BhgBg?g:B} g?BhhKB} sBs0 s/B} s0BttB} tBtt+B} t2=Bx u0Bv vBx vBvvBx vBvvA3Bx xB} x
Byx#Byx>B} yByyB9B} |B| |B} |
B|"|B} |!B|"|"B} }C6FM2@;
FM2AE;FM-GLFM-SFM-S?CTTFM-T
CTTFM-TCTTC)FM-XGFM-_2FM-`A4FM-bA9FM-dA/FM-e7CffFM-f
Cf fFM-fCf f 8FM-gA0FM-iAFM-j4A"FM-lFM-l2>Cm1m0FM-m1
Cm>m;FM-m=Cm>m>D3FM-r7A8FM-t5I.FM-~)C)FM-B(FM-CDCCFM-C
DDC($DDDFM-DDDDAFM-E'L FM-RFM2RDFM-VFM2VEFM-[(F$FM-bBFM-d*FM-eA?DggFM-g
DggFM-gDggFM-g4FFM-nFM2nD!FM-r</FM-s1BFM-vFM2vD:FM-{FM2{FM-{ B7FM-~FM2~H7FM-GFM2GEFM-L#B(FM-OFM2OG1FM-W[FM-rFM2r 
FM-r*FM2r0AFM-s>AFM-u#L$FM-BFM2BA0FM-C>"FD!D FM-D!FD7D4FM-D6FD7D7F1FM-K(FM2K.A:FM-M-FM2RG7HM ZDF^$ ^#HM ^$
F^1^.HM ^0F^1^1D$HM cFc0 c/HM c0
Fc=c:HM c<Fc=c=HM d%Fd* d)HM d*
Fd7d4HM d6Fd7d7A0HM f)BHM h1K;HM t.)HM uIHM ~-B1HM A CHM D7GEEHM EGFE2GFFHM FGFFBHM H,A,HM JCHM M3HHM VGV% V$HM V%GW#V0%GWWHM WGW#W#HM W/GX XHM X
GXXHM XGXXB,HM [ ,G[- [,HM [-
G[:[7HM [9G[:[:HM [?C7HM _8CHM cB!HM e%DHM i5CHM mB$HM o;C	HM sD1HM w9CHM {EHM @&A*HB BHM B+HB?B<HM B>HB?B?B	HM E
AHM FCHI( I'HM I(+HJJHM JHJJA:HM L?HM MHUMHUM6HNNHUN.HN=N:HUN<HN=N=F	HUUHUrM  )r.   r/   r0   r1   )rK   r   rL   rA   r0   rM   )rf   r<   r0   r<   )rf   r<   r0   ro   )rU   r<   rT   r<   r0   ro   )
rf   r<   rU   r<   rT   r<   rQ   r<   r0   r<   )
rf   r<   rU   r<   rT   r<   rQ   r<   r0   ro   )r0   ro   )r   r<   r0   ro   r#  )r   ro   r   r   r0   r<   )
r   r   r   rA   r   r<   r   r<   r0   r   )NNNNNNN)r   r<   r   r<   r   r   r   r<   r   r   r   rM   r   r   r   r   r0   r   )___doc__
__future__r   re  rT  osrp  r?   r  	threadingry  uuidtypingr   r   r   r   agent.codex_responses_adapterr   agent.conversation_compressionr	   agent.displayr
   agent.error_classifierr   r   agent.iteration_budgetr   agent.turn_contextr   agent.turn_retry_stater   agent.memory_managerr   agent.message_sanitizationr   r   r   r   r   r   r   r   r   r   agent.model_metadatar   r   r   r   r   r    r!   agent.process_bootstrapr"   agent.prompt_cachingr#   agent.retry_utilsr$   r%   agent.trajectoryr&   agent.usage_pricingr'   r(   r  r)   hermes_loggingr*   tools.skill_provenancer+   utilsr,   r-   rU  rV  r\   r  rJ   r`   re   rn   rx   r}   r   r   r   r   r   r   r  r   r   rM  __all__r   ra   rI   <module>rg     s=     # " " " " "   				  				 



       , , , , , , , , , , , , I I I I I I Q Q Q Q Q Q ' ' ' ' ' ' E E E E E E E E 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 ; ; ; ; ; ;                                         8 7 7 7 7 7 > > > > > > K K K K K K K K 6 6 6 6 6 6 D D D D D D D D 3 3 3 3 3 3 . . . . . . ; ; ; ; ; ; 8 8 8 8 8 8 8 8		8	$	$
 &[ "   :) ) ) )X     "      * * * *Z   *   y y yx   0
 
 
 
 
J=    2  : 15*.*..2+/dJ dJ dJ dJ dJPU 
ra   