
    .cj+                    ^   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 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dFdZ dGdZ!dHdZ"dIdZ#dJdZ$dKdZ%dLd$Z&dMd)Z'dNd+Z(dOd/Z)dPd7Z*e G d8 d9                      Z+	 dQd:d;dRdEZ,dS )Su?  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)#automatic_compaction_status_message)IterationBudget)build_memory_context_block)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        4/home/ice/.hermes/hermes-agent/agent/turn_context.pycompose_user_api_contentr!   3   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-   V   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*   )r.   s    r    drop_stale_api_contentr1   m   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   )r.   vs     r    extract_api_content_sidecarr5   y   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hasattrr8   	Exceptionr   r   )r6   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)typerA   T)r   listr   r<   )r   r=   s     r    "append_notes_to_multimodal_contentrD      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+   )rE   rG   fallbackir.   s        r    reanchor_current_turn_user_idxrQ      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? )rR   rS   rT   rU   s       r    _compression_made_progressrY      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   rW   rX   )rT   rU   rZ   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.
    rK   T)rM   r   )rE   r^   r_   rZ   s       r    _should_run_preflight_estimatera      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   FrX   rb   rc   rd   rf   rg   rh   s         r    _should_idle_compactrk   	  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   rG   r   original_user_messager]   rE   Optional[List[Dict[str, Any]]]conversation_historyr   active_system_prompteffective_task_idturn_idrH   current_turn_user_idxFr?   should_review_memoryr9   r   r   preflight_compression_blockedN)	__name__
__module____qualname____doc____annotations__ru   r   r   rv   rX   r"   r    rm   rm   +  s         MM """"8888''''LLL!&&&&&!!!!!     */!//////r"   rm   F)
moa_activesystem_messagerp   ro   task_idpersist_user_messageOptional[Any]persist_user_timestampOptional[float]r|   c               .*   ^  |	              | 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                              }| _         j         pd d| dt'          j                    j        dd          }| _        d _        ddlm}  | |           d _        d _        d _        d _        d _        d _         d _!        d _"        d _#        d _$        d _%         j&        '                                 d _(        t           j)        dd          }tU          |          r
 |             d _+         j,        dk    r;	  -                                r .                    d           n# t
          $ r Y nw xY w j/        r 0                                 d _/        tc           j2                   _3         ||          }ti          |          dk    r|dd         dz   n|}|5                    d d!          }t          6                    d" j         pd# j7         j8        pd$ j9        pd$ti          pg           |           rtu                    ng ^t           d%d          }||n|}t          |tv                    r!|<                    d&          |k    r|}||d&<   n!d'|d(}t          |tv                    rd _=        r. j>        ?                                s @                               rV jA        dk    rKt          d) D                       }|dk    r,| _A         jC        dk    r jD        dk    r| jC        z   _D        ^E                    |           ti          ^          d*z
  }| _         xjA        d*z  c_A        d _F        t           d+d          }||G                                 t           d,d          } | | G                                 ||n|}!d}" jC        dk    r9d- jH        v r0 j)        r) xjD        d*z  c_D         jD         jC        k    r	d}"d _D        t           d.d          }#|#0	 dd/lImJ}$  |$|!          }%|%r |#|%           n# t
          $ r Y nw xY w jK        sC ||          }& L                    d0|&dd1          ti          |&          d1k    rdnd d2            jM         | |            jM        }'t           d3d          }(	 |( N                                 n.|(5   N                                 ddd           n# 1 swxY w Y   n4# t
          $ r' t          O                    d4 j         pd#d           Y nw xY wt          |tv                    r|<                    d5          rd _=        n6# t          |tv                    r|<                    d5          rd _=        w xY wt           d6d          }) jP        r|)dk    r^rt          jQ                    t           d7t          jQ                              z
  }*|*|)k    r_ jR        }+t          ^|'pd jT        pd8          },t          |+jV        |+jW        z            }- t          |+d9d:                       }.t           jP        |)|*|,|-t          |.          ;          rt          6                    d<t          |*          |)|,d=|-d= j         pd#           t          |+d>t          j\        t          |*          |,?          |,t          |*           j7        @          }/|/r .                    |/           ^}0 ]                    ^||,|A          \  ^}'^|0ur(t           ^          t          ^|          }| _        d}1d}2d _`        d _a         jP        rt          ^ jR        jc         jR        jd         jR        jV                  rt          ^|'pd jT        pd8          }3 jR        }+t          |+dBd          }4tU          |4          r; |4            }5t          |5t                    rt          |5t                    s|5 _a        t          |+dCdD           }6 |6|3          }7t           dd          dEk    o3t          t           dFdG          pdG          e                                dHv }8|7s|+jf        }9|9dk    r|3|9k    r|3|+_f         t          |+d9dI                       }:d};d}<|7r.t          6                    dJ|3d=|+jV        d=|+jg        d=           n|:rlt          6                    dKt          |:<                    dLdM                     j         pd#           |3|+jV        k    r|:<                    dLdM          }=dN|=dO}<n|8r+t          6                    dPt           dFdG                     n\|+h                    |3          };|;sEt          |+dQd          }>tU          |>          r%	  |>|3          d*         }<n# t
          $ r d}<Y nw xY w|;r!d}1t           dRd          }?tU          |?          r
 |?             t          6                    dS|3d=|+jV        d= j7        |+ji        d=           t          |+dTt          j\        |3|+jV        U          |3|+jV        |+ji         j7        V          }@|@r .                    |@           t          d*t          t           dWdX          pdX                    }At          |A          D ],}Bti          ^          }C|3}D^}E ]                    ^||3|A          \  ^}'^|Eu r3t                     r$t          6                    dY j         pd#            nt          ^|'pd jT        pd8          }3t          |Cti          ^          |D|3          sd}2 nt           ^          d _        d _         d _"        d _#        d _$        |+h                    |3          s n<t          |D|3|+jV                  s$d}2t          O                    dZ|Dd=|3d=            n.nm|<r p                    |<|3|+jV                   nMt           dRd          }?tU          |?          r
 |?             |:s|7s|8rd}Fnt          |+d[d          }Fd}GtU          |F          rN	 t           |F^                    }Gn4# t
          $ r'}Ht                              d\|H           d}GY d}H~Hnd}H~Hww xY w|Grt          6                    d]t          |+d^t          |+          jr                  |3d=t          |+d_d          d=           ^}I ]                    ^||3|A          \  ^}'^|Iur5d}1t           ^          d _        d _         d _"        d _#        d _$        |1rt          ^|          }| _        d}J	 dd`lsmt}K  |Kda j         |||!tu          ^          t                      j7        t           dbd          pdt           dcd          pdd
  
        }Lg }M	 ddelumv}Nmw}O  |N            }Pn# t
          $ r d}Od}PY nw xY w|LD ]}Qd}Rt          |Qtv                    r+|Q<                    df          rt          |Qdf                   }Rn-t          |Qt                    r|Qx                                r|Q}Rnq|OH	  |O|R j         dg|Ph          }Rn2# t
          $ r%}St          O                    di|S           Y d}S~Snd}S~Sww xY w|ME                    |R           |Mrdjy                    |M          }Jn2# t
          $ r%}Tt          O                    dk|T           Y d}T~Tnd}T~Tww xY wt                     }U|Urd|cxk    rti          ^          k     r9n n6t          ^|         tv                    r^|         <                    d&          nd}Vt          |Vtt                    rt          |V|U           n|Jr|Jdjz   |Uz   n|U}Ji  _|        t                       _~        d _        d _        t          j                    j         _         |                                d j                    j        r+ |                                d j                   d _        nd _        d _         j        rK	 t          |!t                    r|!nd}W j                             jA        |W           n# t
          $ r Y nw xY wd}X j        rG	 t          |!t                    r|!nd}Y j                            |Y          pd}Xn# t
          $ r Y nw xY w|s:t           dd          dEk    r$d|cxk    rti          ^          k     r	n n^|         <                    dl          d'k    r^|         }Zt          |Z<                    d&d          |X|J          }[|[|[|Z<                    d&          k    r|[|Zdm<   |1rt          t           dnd                    rxt           dod          }\|\e	 |\                     j         |Z<                    d&          |[           n4# t
          $ r' t          O                    dp j         pd#d           Y nw xY wdv ^fds}]	 |( |]             n$|(5   |]             ddd           n# 1 swxY w Y   n4# t
          $ r' t          O                    dt j         pd#d           Y nw xY wt          |tv                    r|<                    d5          rd _=        n6# t          |tv                    r|<                    d5          rd _=        w xY wt          ||!^|'||||"|J|X|2u          S )wa  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``.
    _memory_write_originassistant_toolr   )set_runtime_mainproviderr9   modelrequested_providerbase_urlapi_keyapi_mode	auth_mode)r   r   r   r   r   _skip_mcp_refreshFNztools.mcp_tool)has_registered_mcp_toolsrefresh_agent_mcp_toolsT)
quiet_modez&between-turns MCP tool refresh skipped)exc_info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(   rK   N)r+   ).0ms     r    	<genexpr>z%build_turn_context.<locals>.<genexpr>	  s?       
 
quuV}}/F/FA/F/F/F/F
 
r"   rK   _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 NrX   rX   r"   r    <lambda>z$build_turn_context.<locals>.<lambda>  s    PT r"   rj   zDIdle compaction: %ss idle >= %ss, ~%s tokens > %s floor (session %s),idle)idle_secondsrf   )phasedefault_messageapprox_tokensr   r   )r   r~   !snapshot_preflight_display_tokens$should_defer_preflight_to_real_usagec                    dS )NFrX   )_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   rX   rX   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)rf   	threshold)r   r   r   rZ   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)namerZ   )invoke_hookpre_llm_callplatform_user_id)	
session_idr~   rs   rG   rp   is_first_turnr   r   	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   r/   c                 \                                                                       d S r   )_ensure_db_session_persist_session)r6   rp   rE   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)rG   rn   rE   rp   rq   rr   rs   rt   ru   r   r   rv   )r   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hex_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_budgetrM   replaceinfor   r   r   rC   rN   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   rH   rZ   summary_target_ratiork   r?   r   r
   format_compress_contextr   rQ    _turn_received_provider_response _turn_preflight_display_snapshotra   r^   r_   lowerlast_prompt_tokenslast_real_prompt_tokensshould_compressr   r   maxrL   r   rY   r\   _warn_context_overflow_blockedrB   rw   hermes_cli.pluginsr   tools.hook_output_spillr   r   stripr   r>   rD   _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_startprefetch_allr!   set_latest_user_api_contentrm   )_r6   rG   r}   rp   r~   stream_callbackr   r   restore_or_build_system_promptinstall_safe_stdiosanitize_surrogatessummarize_user_message_for_logset_session_contextset_current_write_originrar|   r   _sysr   r   rr   rs   r   _reset_consol_preview_text_msg_previewpending_cli_messageexpected_persist_contentuser_msgprior_user_turnsrt   scrubberthink_scrubberrn   ru   r   r   kind_print_previewrq   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   rE   s_   `  `                                                                                          @r    build_turn_contextr  H  s   4  ())) 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!.Y[[1B[[TZ\\EUVXWXVXEY[[G$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?[,[)
 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!
 !
 +@' 1<BBBBBB#|'%.!%h#$8999+UJ55;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!&!6!C!CF!K!K!Qr 	 	 	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C 
C*)C*.=D, ,&EE)L 
LLW7 7
XX>[ Z8,[ 8Z<<[ ?Z< [ \* .[52\* 4[55\* *3]
n n+*n+y! !
z+zzA$AC   AC $!AC #$$A8AC AAA2A1AC A2
AB!A<ABBAC BAB!B!0AC C
ADCAC<C<ADI9AJ J
AJJAJJ!5AK K
AK$K#AK$O /AO0 O0.AP!P AP!P-AQ P<AQQAQ QAQQAQ QAQQAQ QAS Q.ARRAS RARRAS S3AS8)r   r   r   r   r   r   r   r   )r#   r$   r   r   )r.   r$   r   r/   )r.   r2   r   r   )r6   r   r   r   )r   r   r=   r   r   r?   )rE   rF   rG   r   r   rH   )
rR   rH   rS   rH   rT   rH   rU   rH   r   r?   )rT   rH   rU   rH   rZ   rH   r   r?   )
rE   r]   r^   rH   r_   rH   rZ   rH   r   r?   )rb   r?   rc   rH   rd   re   rf   rH   rg   rH   rh   r?   r   r?   r   )rG   r   r}   r   rp   ro   r~   r   r   r   r   r   r|   r?   r   rm   )-rz   
__future__r   loggingr.  r  r   dataclassesr   typingr   r   r   r   r	   agent.conversation_compressionr
   r   r   r   agent.context_enginer   agent.iteration_budgetr   agent.memory_managerr   agent.model_metadatar   r   	getLoggerrw   r   r!   r-   r1   r5   r>   rD   rQ   rY   r\   ra   rk   rm   r  rX   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 ; ; ; ; ; ;       
 
	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" #I I I I I I I Ir"   