
    epj)                    r   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mZ ddl	m
Z
mZmZmZmZ ddlmZmZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ  ej         e!          Z"dJdZ#dKdZ$dLdZ%dMdZ&dNdZ'dOd Z(dPd%Z)dQd*Z*dRd,Z+dSd0Z,dTd8Z-e G d9 d:                      Z.	 dUddd;d<dVdIZ/dS )Wu?  Per-turn setup for ``run_conversation`` (the turn prologue).

``run_conversation`` opened with ~470 lines of straight-line setup before the
tool-calling loop ever started: stdio guarding, runtime-main wiring, retry-counter
resets, user-message sanitization, todo/nudge-counter hydration, system-prompt
restore-or-build, session-row creation (before compression, whose DB writes
reference the row), preflight context compression, the ``pre_llm_call`` plugin
hook, external-memory prefetch, and crash-resilience persistence (last, so the
user row is written once with its final ``api_content`` sidecar).

All of that is *prologue* — it runs once per turn, has no back-references into the
loop, and produces a fixed set of values the loop then consumes. ``TurnContext``
captures those produced values; ``build_turn_context`` performs the setup work and
returns one. ``run_conversation`` is left to unpack the context and run the loop,
shrinking the orchestrator by the full prologue.

The builder still mutates ``agent`` heavily (counters, thread id, cached prompt,
session DB) exactly as the inline code did — those side effects are the point. The
``TurnContext`` it returns carries only the *locals* the loop reads back.

Behavior is identical to the original inline prologue; this is a pure
move-and-name refactor with no semantic change.
    )annotationsN)	dataclass)AnyDictListMappingOptional)IDLE_COMPACTION_STATUS_TEMPLATE%PREFLIGHT_COMPRESSION_STATUS_TEMPLATEcompression_skipped_due_to_lock&conversation_history_after_compression#recover_rotated_compression_session)#automatic_compaction_status_message)IterationBudget)build_memory_context_block)is_trivial_prompt)estimate_messages_tokens_roughestimate_request_tokens_roughcontentr   ext_prefetch_cachestrplugin_user_contextreturnOptional[str]c                    t          | t                    sdS g }|r&t          |          }|r|                    |           |r|                    |           |sdS | dz   d                    |          z   S )ue  Compose the API-bound content of the current turn's user message.

    Sources: memory-manager prefetch + ``pre_llm_call`` plugin context with
    target="user_message" (the default). Both are appended to the *API copy*
    of the user message only — the stored content stays clean.

    This is the single source of that composition. The prologue stamps the
    result onto the live message as ``api_content`` (persisted alongside the
    clean content) and the ``api_messages`` build in ``conversation_loop``
    sends the same helper's output, so the persisted sidecar can never drift
    from the bytes on the wire — which is the whole prompt-cache invariant:
    what turn N sends must be what turn N+1 replays.

    Returns ``None`` when nothing is injected (multimodal/non-string content,
    or no ephemeral context), meaning the message is sent as-is.
    N

)
isinstancer   r   appendjoin)r   r   r   
injectionsfenceds        8/home/thesage/.hermes/hermes-agent/agent/turn_context.pycompose_user_api_contentr#   5   s    * gs## tJ &+,>?? 	&f%%% /-... tVfkk*5555    api_msgDict[str, Any]c                    |                      dd          }t          |t                    r|r|                     d          dv r|| d<   |S )a}  Pop the ``api_content`` sidecar and substitute it into ``content``.

    Used at every API-bound message-build site (the ``api_messages`` build in
    ``conversation_loop``, the max-iterations summary in
    ``chat_completion_helpers``, the chat-completions transport). The sidecar
    carries the exact bytes previously sent to the API for this message when
    they differ from the clean stored content; substituting it here keeps the
    provider prompt-cache prefix byte-stable across turns.

    Returns the popped sidecar string (for callers that need the value for
    current-turn composition logic) or ``None`` when absent.
    api_contentNrole)user	assistantr   )popr   r   get)r%   sidecars     r"   substitute_api_contentr/   X   sZ     kk-..G7C  %% KK#888$	Nr$   msgNonec                2    |                      dd           dS )u  Drop the ``api_content`` sidecar from a message whose content was rewritten.

    Called from every content-rewrite path (historical image strip,
    merge-summary-into-tail, consecutive-user repair merge, stale-confirmation
    redaction). Replaying the pre-rewrite sidecar would resend exactly what
    the rewrite removed, so it must be dropped — the cost is one cache
    boundary miss, never wrong content.
    r(   N)r,   )r0   s    r"   drop_stale_api_contentr3   o   s     GGM4     r$   Mapping[str, Any]c                ^    |                      d          }t          |t                    r|ndS )zExtract the ``api_content`` sidecar from a message dict for persistence.

    Shared by the gateway/branch forwarding sites that copy the sidecar into a
    new row. Returns the string sidecar or ``None`` when absent/non-string.
    r(   N)r-   r   r   )r0   vs     r"   extract_api_content_sidecarr7   {   s.     	A1c"",11,r$   agentc                    t          | dd          pd}t          | d          r	 d| _        n# t          $ r Y nw xY wt	          |t
                    r|ndS )aM  Pop the gateway's per-turn must-deliver notes off the agent (one-shot).

    The gateway relocates volatile per-turn facts OUT of the ephemeral system
    prompt (auto-reset notes, the first-contact intro, voice-channel changes)
    and delivers them on the current user message via the api_content sidecar
    instead, so the composed system prompt stays byte-stable turn-over-turn.
    It stages the rendered notes on ``agent._gateway_turn_context_notes``
    right before ``run_conversation``; this consumes them so a cached agent
    can never replay a stale note on a later turn.
    _gateway_turn_context_notes )getattrhasattrr:   	Exceptionr   r   )r8   notess     r"   "consume_gateway_turn_context_notesr@      sw     E8"==CEu344 	02E-- 	 	 	D	uc**2552s   - 
::r?   boolc                    |rt          | t                    sdS 	 |                     d|d           dS # t          $ r Y dS w xY w)u  Deliver must-deliver notes on a multimodal (list) user message.

    ``compose_user_api_content`` returns ``None`` for non-string content, so
    sidecar-borne facts would silently drop on image/attachment turns.  For
    gateway must-deliver notes we instead append a text part to the content
    list in place — the part becomes durable message content (persisted and
    replayed as-is), which keeps the wire and the transcript byte-identical.

    Returns ``True`` when a part was appended.
    Ftext)typerC   T)r   listr   r>   )r   r?   s     r"   "append_notes_to_multimodal_contentrF      sh      
7D11 u66777t   uus   5 
AAmessages	List[Any]user_messageintc                
   d}t          t          |           dz
  dd          D ]^}| |         }t          |t                    r|                    d          dk    s9|dk     r|}|                    d          |k    r|c S _|S )u  Locate this turn's user message after compaction rebuilt ``messages``.

    Compression replaces list entries with fresh copies (and may append a
    todo-snapshot user message or a restored user turn AFTER the surviving
    copy of the current turn's message), so a pre-compression index is
    meaningless. Prefer the LAST user message whose content exactly matches
    this turn's text — the surviving copy in the common case — so the
    injection stamp and the #48677 persist override can't land on a
    todo-snapshot or historical row. Fall back to the last user message when
    no exact match survives (merge-summary-into-tail rewrites the content but
    the trackers still need a live anchor). Returns -1 when the list has no
    user message at all.
       r)   r*   r   r   )rangelenr   dictr-   )rG   rI   fallbackir0   s        r"   reanchor_current_turn_user_idxrS      s     H3x==1$b"--  qk3%% 	#''&//V*C*Ca<<H779--HHH .Or$   orig_lennew_lenorig_tokens
new_tokensc                0    || k     rdS |dk    o||dz  k     S )uF  Return ``True`` if a compression pass materially reduced the request.

    Compression can succeed by summarising message contents — reducing the
    estimated request token count — without reducing the message row
    count.  Treating row count as the sole progress signal false-positives
    on size-only wins and surfaces a misleading "Cannot compress further"
    failure even when post-compression tokens are well below the model
    context window.  See issue #39548 for an observed case: 220 → 220
    messages, ~288k → ~183k tokens on a 1M-context model still triggered
    auto-reset.

    The token reduction must be *material* (>5%) to count as progress — the
    same floor the overflow-handler retry path uses (conversation_loop.py,
    #39550) — so a sub-5% wobble doesn't keep the multi-pass loop spinning.
    Tr   ffffff? )rT   rU   rV   rW   s       r"   _compression_made_progressr[      s-    $ t?>zK$,>>>r$   threshold_tokensc                ,    ||k    o| dk    o|| dz  k     S )aw  Whether an over-threshold request merits another immediate summary.

    Row-count progress is enough to prove that a compression boundary was real,
    but not enough to justify another expensive pass before trying the provider.
    Continue only when the request remains over threshold *and* the previous pass
    materially reduced its estimated token pressure (>5%).
    r   rY   rZ   )rV   rW   r\   s      r"   ,_compression_warrants_another_preflight_passr^      s0     	&& 	,!O	,t++r$   List[Dict[str, Any]]protect_first_nprotect_last_nc                ^    t          |           ||z   dz   k    rdS t          |           |k    S )u  Cheap gate for the (expensive) full preflight token estimate.

    Returns ``True`` when either:
      (a) message count exceeds the protected ranges (the historical gate), or
      (b) a cheap char-based estimate already crosses the configured threshold
          — the few-but-huge case from issue #27405 that the count-only gate
          would silently skip (a handful of very large messages never trips
          the count condition, so compression was never attempted and the
          turn hit a hard context-overflow error).

    Branch (b) uses ``estimate_messages_tokens_rough`` (the shared char-based
    estimator) so a single large base64 image isn't mistaken for ~250K tokens.
    It intentionally undercounts vs. the full request estimate — it omits the
    system prompt and tool schemas — because it is only a *hint* deciding
    whether to pay for the authoritative ``estimate_request_tokens_rough``,
    which (together with ``should_compress``) makes the real decision.
    rM   T)rO   r   )rG   r`   ra   r\   s       r"   _should_run_preflight_estimaterc      s8    . 8}}7!;;;t)(337GGGr$   enabledidle_after_secondsidle_gap_secondsfloattokensfloor_tokenscooldown_activec                :    | r|dk    rdS ||k     rdS |rdS ||k    S )ah  Decide whether an idle-triggered compaction should run this turn.

    Idle compaction is opt-in (``idle_after_seconds <= 0`` disables it). It
    fires when a session resumes after a wall-clock gap of at least
    ``idle_after_seconds`` since its last activity, so a long-lived thread
    that is paused and later resumed compacts its accumulated history up
    front instead of re-reading it on every subsequent turn.

    It is orthogonal to the token-threshold trigger: it does NOT require the
    context to exceed ``threshold_tokens``. It still skips work when the
    context is at or below ``floor_tokens`` (the size compaction would reduce
    *to*), so a small idle thread never pays for a summarisation that saves
    nothing, and it defers to an active compression-failure cooldown.

    Pure predicate so the policy is unit-testable without a live agent.
    r   FrZ   rd   re   rf   rh   ri   rj   s         r"   _should_idle_compactrm     sE    2  (A--u,,,u uL  r$   c                      e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   ded<   ded<   ded<   dZded<   dZded<   dZded<   dZded<   dS )TurnContextzCValues produced by the turn prologue and consumed by the turn loop.r   rI   r   original_user_messager_   rG   Optional[List[Dict[str, Any]]]conversation_historyr   active_system_prompteffective_task_idturn_idrJ   current_turn_user_idxFrA   should_review_memoryr;   r   r   preflight_compression_blockedN)	__name__
__module____qualname____doc____annotations__rw   r   r   rx   rZ   r$   r"   ro   ro   -  s         MM """"8888''''LLL!&&&&&!!!!!     */!//////r$   ro   F)persist_user_display_kindpersist_user_display_metadata
moa_activesystem_messagerr   rq   task_idpersist_user_messageOptional[Any]persist_user_timestampOptional[float]r~   r   Optional[Dict[str, Any]]r   c       
        +   a  |             t                     }|| | j                    |t           dd                                                       	 ddlm}  |t           dd          pdt           dd          pdt           d	d          pdt           d
d          pdt           dd          pdt           dd          pdt           dd          pd           n# t          $ r Y nw xY w	 t           dd          s,ddl}d|j        v rddl	m
}m}  |            r | d           n,# t          $ r t                              dd           Y nw xY wt          |t                    r ||          }t          |t                    r ||          }| _        d _        | _        | _        |pt          t)          j                              }| _        t          t           dd          pd          }|s/ j        pd d| dt)          j                    j        dd          }d _        | _        d _        ddlm}  | |           d _        d _        d _        d _         d _!        d _"        d _#        d _$        d _%        d _&        d _'         j(        )                                 d _*        t           j+        dd          }tY          |          r
 |             d _-         j.        dk    r;	  /                                r 0                    d           n# t          $ r Y nw xY w j1        r 2                                 d _1        tg           j4                   _5         ||          }tm          |          dk    r|dd         d z   n|}|7                    d!d"          }t          8                    d# j        pd$ j9         j:        pd% j;        pd%tm          pg           |           rty                    ng at           d&d          }||n|}t          |tz                    r!|>                    d'          |k    r|}||d'<   n!d(|d)}t          |tz                    rd _?        r. j@        A                                s B                               rV jC        dk    rKt          d* D                       } | dk    r,|  _C         jE        dk    r jF        dk    r|  jE        z   _F        |r||d+<   |	r|	|d,<   aG                    |           tm          a          d-z
  }!|! _         xjC        d-z  c_C        d _H        t           d.d          }"|"|"I                                 t           d/d          }#|#|#I                                 ||n|}$d}% jE        dk    r9d0 jJ        v r0 j+        r) xjF        d-z  c_F         jF         jE        k    r	d}%d _F        t           d1d          }&|&0	 dd2lKmL}'  |'|$          }(|(r |&|(           n# t          $ r Y nw xY w jM        sC ||          }) N                    d3|)dd4          tm          |)          d4k    rd nd d5            jO         |
 |            jO        }*t           d6d          }+	 |+ P                                 n.|+5   P                                 ddd           n# 1 swxY w Y   n4# t          $ r' t          Q                    d7 j        pd$d           Y nw xY wt          |tz                    r|>                    d8          rd _?        n6# t          |tz                    r|>                    d8          rd _?        w xY wt           d9d          }, jR        r|,dk    rart          jS                    t           d:t          jS                              z
  }-|-|,k    r_ jT        }.t          a|*pd jV        pd;          }/t          |.jX        |.jY        z            }0 t          |.d<d=                       }1t           jR        |,|-|/|0t          |1          >          rt          8                    d?t          |-          |,|/d@|0d@ j        pd$           t          |.dAt          j^        t          |-          |/B          |/t          |-           j9        C          }2|2r 0                    |2           a}3 _                    a||/|D          \  a}*a|3ur(t           a          t          a|          }!|! _        d}4d}5d _b        d _c         jR        rt          a jT        je         jT        jf         jT        jX                  rt          a|*pd jV        pd;          }6 jT        }.t          |.dEd          }7tY          |7          r; |7            }8t          |8t                    rt          |8t                    s|8 _c        t          |.dFdG           }9 |9|6          }:t           dd          dHk    o3t          t           dIdJ          pdJ          g                                dKv };|:s|.jh        }<|<dk    r|6|<k    r|6|._h         t          |.d<dL                       }=d}>d}?|:r.t          8                    dM|6d@|.jX        d@|.ji        d@           n|=rlt          8                    dNt          |=>                    dOdP                     j        pd$           |6|.jX        k    r|=>                    dOdP          }@dQ|@dR}?n|;r+t          8                    dSt           dIdJ                     n\|.j                    |6          }>|>sEt          |.dTd          }AtY          |A          r%	  |A|6          d-         }?n# t          $ r d}?Y nw xY w|>r!d}4t           dUd          }BtY          |B          r
 |B             t          8                    dV|6d@|.jX        d@ j9        |.jk        d@           t          |.dWt          j^        |6|.jX        X          |6|.jX        |.jk         j9        Y          }C|Cr 0                    |C           t          d-t          t           dZd[          pd[                    }Dt          |D          D ],}Etm          a          }F|6}Ga}H _                    a||6|D          \  a}*a|Hu r3t                     r$t          8                    d\ j        pd$            nt          a|*pd jV        pd;          }6t          |Ftm          a          |G|6          sd}5 nt           a          d _        d _"        d _$        d _%        d _&        |.j                    |6          s n<t          |G|6|.jX                  s$d}5t          Q                    d]|Gd@|6d@            n.nm|?r r                    |?|6|.jX                   nMt           dUd          }BtY          |B          r
 |B             |=s|:s|;rd}Int          |.d^d          }Id}JtY          |I          rN	 t           |Ia                    }Jn4# t          $ r'}Kt                              d_|K           d}JY d}K~Knd}K~Kww xY w|Jrt          8                    d`t          |.dat          |.          jt                  |6d@t          |.dbd          d@           a}L _                    a||6|D          \  a}*a|Lur5d}4t           a          d _        d _"        d _$        d _%        d _&        |4rt          a|          }!|! _        d}M	 ddclumv}N  |Ndd j        |||$ty          a          t                      j9        t           ded          pdt           dfd          pdt           dgd          pdh          }Og }P	 ddilwmx}Qmy}R  |Q            }Sn# t          $ r d}Rd}SY nw xY w|OD ]}Td}Ut          |Ttz                    r+|T>                    dj          rt          |Tdj                   }Un-t          |Tt                    r|Tz                                r|T}Unq|RH	  |R|U j        dk|Sl          }Un2# t          $ r%}Vt          Q                    dm|V           Y d}V~Vnd}V~Vww xY w|PG                    |U           |Prdn{                    |P          }Mn2# t          $ r%}Wt          Q                    do|W           Y d}W~Wnd}W~Www xY wt                     }X|Xrd|!cxk    rtm          a          k     r9n n6t          a|!         tz                    ra|!         >                    d'          nd}Yt          |Ytx                    rt          |Y|X           n|Mr|Mdnz   |Xz   n|X}Mi  _~        t                       _        d _        d _        t          j                    j         _         |                                d j                    j        r+ |                                d j                   d _        nd _        d _         j        rK	 t          |$t                    r|$nd}Z j                             jC        |Z           n# t          $ r Y nw xY wd}[ j        rW	 t          |$t                    r|$nd}\t          |\          s j                            |\          pd}[n# t          $ r Y nw xY w|s:t           dd          dHk    r$d|!cxk    rtm          a          k     r	n na|!         >                    dp          d(k    ra|!         }]t          |]>                    d'd          |[|M          }^|^|^|]>                    d'          k    r|^|]dq<   |4rt          t           drd                    rxt           dsd          }_|_e	 |_                     j        |]>                    d'          |^           n4# t          $ r' t          Q                    dt j        pd$d           Y nw xY wdz afdw}`	 |+ |`             n$|+5   |`             ddd           n# 1 swxY w Y   n4# t          $ r' t          Q                    dx j        pd$d           Y nw xY wt          |tz                    r|>                    d8          rd _?        n6# t          |tz                    r|>                    d8          rd _?        w xY wt#          ||$a|*|||!|%|M|[|5y          S ){a  Run the once-per-turn setup and return the loop's input context.

    The callables/helpers the original prologue referenced from the
    ``conversation_loop`` module are passed in explicitly to keep this module
    free of an import cycle with ``agent.conversation_loop``.
    N_memory_write_originassistant_toolr   )set_runtime_mainproviderr;   modelrequested_providerbase_urlapi_keyapi_mode	auth_mode)r   r   r   r   r   _skip_mcp_refreshFztools.mcp_tool)has_registered_mcp_toolsrefresh_agent_mcp_toolsT)
quiet_modez&between-turns MCP tool refresh skipped)exc_info_relay_pending_turn_idsession:   )note_turn_startreset_consolidation_failuresanthropic_messagesu~   🔌 Detected stale connections from a previous provider issue — cleaned up automatically. Proceeding with fresh connection.P   z...
 zPconversation turn: session=%s model=%s provider=%s platform=%s history=%d msg=%rnoneunknown_pending_cli_user_messager   r*   )r)   r   c              3  L   K   | ]}|                     d           dk    dV   dS )r)   r*   rM   N)r-   ).0ms     r"   	<genexpr>z%build_turn_context.<locals>.<genexpr>  s?       
 
quuV}}/F/FA/F/F/F/F
 
r$   display_kinddisplay_metadatarM   _stream_context_scrubber_stream_think_scrubbermemoryreaction_callback)detect_reactionu   💬 Starting conversation: '<   '_session_persist_lockz5Turn-start session row creation failed for session=%s_db_persisted&compression_idle_compact_after_seconds_last_activity_ts)system_prompttools'get_active_compression_failure_cooldownc                     d S NrZ   rZ   r$   r"   <lambda>z$build_turn_context.<locals>.<lambda>  s    PT r$   rl   zDIdle compaction: %ss idle >= %ss, ~%s tokens > %s floor (session %s),idle)idle_secondsrh   )phasedefault_messageapprox_tokensr   r   )r   r   !snapshot_preflight_display_tokens$should_defer_preflight_to_real_usagec                    dS )NFrZ   )_tokenss    r"   r   z$build_turn_context.<locals>.<lambda>  s    E r$   codex_app_server codex_app_server_auto_compactionnative>   offr   c                     d S r   rZ   rZ   r$   r"   r   z$build_turn_context.<locals>.<lambda>  s    D r$   zpSkipping preflight compression: rough estimate ~%s >= %s, but last real provider prompt was %s after compressionz`Skipping preflight compression: same-session cooldown active (~%s seconds remaining, session %s)remaining_secondsg        z	cooldown:z.0fzsSkipping Hermes preflight compression for codex app-server (mode=%s); Hermes will not start thread compaction here.should_compress_info_clear_context_overflow_warnzDPreflight compression: ~%s tokens >= %s threshold (model %s, ctx %s)	preflight)rh   	threshold)r   r   r   r\   context_lengthr   max_compression_attempts   zRPreflight compression deferred: compression lock held by another path (session %s)zgPreflight compression made insufficient progress: ~%s -> ~%s request tokens; skipping additional passesshould_compress_preflightzQshould_compress_preflight raised %s; skipping engine-driven preflight maintenancez_Engine-driven preflight maintenance: %s requested compress() at ~%s tokens (below %s threshold)namer\   )invoke_hookpre_llm_callplatform_parent_session_id_user_id)

session_idr   ru   rI   rr   is_first_turnr   r   parent_session_id	sender_id)get_spill_configspill_if_oversizedcontextzplugin hook)r   sourceconfigzhook context spill failed: %sr   zpre_llm_call hook failed: %sr)   r(   _last_compaction_in_place_session_dbz>in-place compaction api_content backfill failed for session=%sr   r1   c                 \                                                                       d S r   )_ensure_db_session_persist_session)r8   rr   rG   s   r"   _ensure_and_persistz/build_turn_context.<locals>._ensure_and_persist  s2      """x)=>>>>>r$   z:Early turn-start session persistence failed for session=%s)rI   rp   rG   rr   rs   rt   ru   rv   rw   r   r   rx   )r   r1   )r   r   r<   _restore_primary_runtimeagent.auxiliary_clientr   r>   sysmodulestools.mcp_toolr   r   loggerdebugr   r   _stream_callback_persist_user_message_idx_persist_user_message_override_persist_user_message_timestampuuiduuid4_current_task_idhexr   _current_turn_id_current_api_request_idagent.agent_runtime_helpersr   _invalid_tool_retries_invalid_json_retries_empty_content_retries_incomplete_scratchpad_retries_codex_incomplete_retries_thinking_prefill_retries_post_tool_empty_retried_last_content_with_tools$_last_content_tools_all_housekeeping_mute_post_response_unicode_sanitization_passes_tool_guardrailsreset_for_turn_tool_guardrail_halt_decision_memory_storecallable_vision_supportedr   _cleanup_dead_connections_emit_status_compression_warning_replay_compression_warningr   max_iterationsiteration_budgetrO   replaceinfor   r   r   rE   rP   r-   r   _todo_store	has_items_hydrate_todo_store_user_turn_countsum_memory_nudge_interval_turns_since_memoryr   _is_user_initiated_turnresetvalid_tool_namesagent.reactionsr   r   _safe_print_cached_system_promptr   warningcompression_enabledtimecontext_compressorr   r   rJ   r\   summary_target_ratiorm   rA   r   r
   format_compress_contextr   rS    _turn_received_provider_response _turn_preflight_display_snapshotrc   r`   ra   lowerlast_prompt_tokenslast_real_prompt_tokensshould_compressr   r   maxrN   r   r[   r^   _warn_context_overflow_blockedrD   ry   hermes_cli.lifecycler   tools.hook_output_spillr   r   stripr   r@   rF   _turn_failed_file_mutationsset_turn_file_mutation_paths_verification_stop_nudges_pre_verify_nudges	threadingcurrent_threadident_execution_thread_id_set_interrupt_interrupt_requested _interrupt_thread_signal_pending_interrupt_message_memory_manageron_turn_startr   prefetch_allr#   set_latest_user_api_contentro   )br8   rI   r   rr   r   stream_callbackr   r   r~   r   restore_or_build_system_promptinstall_safe_stdiosanitize_surrogatessummarize_user_message_for_logset_session_contextset_current_write_originrar   recovered_historyr   _sysr   r   rt   ru   r   _reset_consol_preview_text_msg_previewpending_cli_messageexpected_persist_contentuser_msgprior_user_turnsrv   scrubberthink_scrubberrp   rw   r   r   kind_print_previewrs   persist_lock_idle_after	_idle_gap_compressor_idle_tokens_idle_floor_idle_cooldown_idle_status_idle_input_preflight_compressed_preflight_compression_blocked_preflight_tokens_snapshot_fn_snapshot_val_defer_preflight_preflight_deferred_codex_native_auto_last_compression_cooldown_should_compress_now_compress_block_reason_cooldown_secs_info_clear_warn_preflight_status_max_preflight_passes_pass	_orig_len_orig_tokens_preflight_input_engine_preflight_wants_engine_preflight_preflight_exc_engine_inputr   _invoke_hook_pre_results
_ctx_parts
_spill_cfg_spill_if_oversized_spill_config_cachedr_piece
_spill_excexc_gateway_notes_gw_turn_content	_turn_msgr   _query_turn_user_msg_api_content_dbr   rG   sb   `  `                                                                                             @r"   build_turn_contextr  J  sn   8 
 <EBB$0 ())) WU,BDTUUVVV 
""$$$;;;;;;E:r**0bE7B''-2&u.BBGGM2UJ339rE9b117RUJ339re["55;	
 	
 	
 	
 	
    Nu1599 	D 4<//\\\\\\\\++-- D++EdCCCC N N N=MMMMMN ,$$ 9**<88&,, I223GHH -E&*E#+?E(,BE)43tz||#4#4.E'%!92>>D"EEG 
,9YY/@YY4:<<CSTVUVTVCWYY 	 $(E $E$&E! <;;;;;OE7### #$E"#E#$E +,E(&'E#&'E#%*E"%)E"16E. %E)*E&	))+++*.E'E/1OQUVVM "E ~---	..00 """  
  	 	 	D	 ! *))+++%)" -U-ABBE 32<@@M36}3E3E3J3JM#2#&..P]L''c22L
KKZ"FEK1L9#)S)=)C%D%D	   .BIt()))rH "%)DdKK 4 @l  	&--3##I..2JJJ& +"|<<)400 	3.2E+  8E$5$?$?$A$A 8!!"6777  \ 6! ; ; 
 
+
 
 
 
 
 a%5E"+a//E4MQR4R4R,<u?[,[) ! I#< ( 	I+HH'(OOHMMA-&;E# 
a %)E! u8$??HU$<dCCN! 5I4T00Zf !$q((E222# 3!!Q&!!$(DDD#' ()E%
  ':DAA$	777777"?#899D (!!$''' 	 	 	D	  
77EE<N3B3,? <N++b00uub< < <	
 	
 	
 "*&&un>RSSS 6 5"94@@L3$$&&&& + +((***+ + + + + + + + + + + + + + + 
 
 
C& 	 	
 	
 	
 	
 	

 -t44 	38K8O8OP_8`8` 	3.2E+ -t44 	38K8O8OP_8`8` 	3.2E+2222 %!I1MMK  CL[1___IKK'%1Ddikk"R"RR	##2K828bk)T  L ,{/OO KWF   N $1#.!*#( $^ 4 4   2L #	NN#''"&&$.    C $C$J%(^^L% % % #/!$Y+	  	  	    5&&|444&161H1HnL- 2I 2 2.. ;..+Qx)=, ,( -K ,- -) 7LE3 "%*"-2E*-1E*  h6%C 0 / 1	& & h6 :.4"+%
 
 

 .
 <d
 
 L!! 	G(LNNM --- Gjt7 7 G :G6"2!!
 

 /./@AA E:t,,0BB 	!6  
   egg ! 	 # 	C2Ezz/%771B.!
5L!
 !
 ! !  %!% (	6KKI$((/336::    #  	6KK6)--.A3GGHH *F	   !K$@@@ "7!:!:;NPS!T!T)I^)I)I)I& 	6KKKA8LL    $/#>#>?P#Q#Q ' 6  -CTJJE?? 66167H1I1I!1L..$ 6 6 615...6 A	6$(! "%)GNNK$$ KKV$((/33-11   !D! E L,):! ! ! 0!,!=*9k! ! ! ! 6""#4555 %(3wu&@!DDIJJ% %! 455 > >MM	0#+ 161H1Hn<M- 2I 2 2..
  0007>> 1 KK<(2F  
 E
 %B"6"<"+-% % %!
 2s8}}l<M   6:2E'M8%9( ($ 01,23/15.=B:,1)"223DEE EC %0  
 6:2NNP'++,00	   E $ ]	6 00&!,    "%)GNNK$$ 
 % (; ?Q $(!!$+!<d% %!2 ',#)** 4
4.23D3DX3N3N.O.O++  4 4 4 LL>&  
 /4++++++4 ' 6DKk1B1B1KLL(,,{,>BBFF   !)161H1Hn<M- 2I 2 2.. =00,0)+Qx, ,( 45E067E359E2AFE>05E- @ !?l!
 !
 +@' 2<DDDDDD#|'%.!%h#$8999+UJ55;%e-A4HHNBeZ66<"
 
 
 !#
	(        $.:<<   	( 	( 	("&#'   	(  	& 	&AF!T"" quuY'7'7 Qy\**As## 		 ".P00#(#3,3	  FF ! P P PNN#BJOOOOOOOOPf%%%% 	:"(++j"9"9 < < <5s;;;;;;;;< 8>>N  )9999CMM999998$9:DAA : *+//	::: 	 	 &-- 	./?PPPP '$#f,~==#   )+E%&)eeE#&'E# E "+!9!;!;!AE BDDu9:::! 7
D%"<===16..#' 16.  	1;<QSV1W1W_--]_I!//0F	RRRR 	 	 	D	  	.89NPS.T.T\**Z\F$V,, V%*%:%G%G%O%O%USU" 	 	 	D	* %E:t,,0BBB&6666X66666*+//776AA!"78/y"--/ACV
 
 #8J8J98U8U(U(U,8N=) % :EBB* *  e]D99?77!,*..y99(   
 %   -!,6%)	 '     ? ? ? ? ? ? ? ?3!!!! & &##%%%& & & & & & & & & & & & & & & 
 
 
H& 	 	
 	
 	
 	
 	

 -t44 	38K8O8OP_8`8` 	3.2E+ -t44 	38K8O8OP_8`8` 	3.2E+2222!311+31/-&D   s   BC0 0
C=<C==D? ?&E('E()M 
MM"Y 
YY\ !\6\ \\ 	\
\ ]4 .\?<]4 >\??]4 43^'o& &o54o5z+ +
{5{{%A6AD. @A@/ @.AD. @/AA @=AD. @?AA A A8AD. B9ACCAD. C
AC=CAC8C3AD. C8AC=C=0AD. D.
AED8AEEAEJ)9AK# K#
AK0K/AK0K=AAM M
AMMAMP,/AQ Q.ARRARRAS R(AR?R3AS R?ASSAS SASSAS S
AT1 S.AS<S9AT1 S;AS<S<AT1 T13AU$)r   r   r   r   r   r   r   r   )r%   r&   r   r   )r0   r&   r   r1   )r0   r4   r   r   )r8   r   r   r   )r   r   r?   r   r   rA   )rG   rH   rI   r   r   rJ   )
rT   rJ   rU   rJ   rV   rJ   rW   rJ   r   rA   )rV   rJ   rW   rJ   r\   rJ   r   rA   )
rG   r_   r`   rJ   ra   rJ   r\   rJ   r   rA   )rd   rA   re   rJ   rf   rg   rh   rJ   ri   rJ   rj   rA   r   rA   r   )rI   r   r   r   rr   rq   r   r   r   r   r   r   r~   r   r   r   r   rA   r   ro   )0r|   
__future__r   loggingr8  r#  r   dataclassesr   typingr   r   r   r   r	   agent.conversation_compressionr
   r   r   r   r   agent.context_enginer   agent.iteration_budgetr   agent.memory_managerr   agent.memory_providerr   agent.model_metadatar   r   	getLoggerry   r   r#   r/   r3   r7   r@   rF   rS   r[   r^   rc   rm   ro   r  rZ   r$   r"   <module>r     s   0 # " " " " "        ! ! ! ! ! ! 5 5 5 5 5 5 5 5 5 5 5 5 5 5              E D D D D D 2 2 2 2 2 2 ; ; ; ; ; ; 3 3 3 3 3 3       
 
	8	$	$ 6  6  6  6F   .	! 	! 	! 	!- - - -3 3 3 3(   (   4? ? ? ?.   "H H H H8! ! ! !D 0 0 0 0 0 0 0 0H /3i 04>B 'i i i i i i i ir$   