
    i              	       X   d 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mZmZ ddlmZ  ej        e          ZdZd	Zd
ZdZdZdZdZdZeez  Z dZ!dede"fdZ#dede$fdZ%dddede$de&defdZ'd%de$de"de$fdZ(de$d e$d!e$de$fd"Z) G d# d$e          Z*dS )&a  Automatic context window compression for long conversations.

Self-contained class with its own OpenAI client for summarization.
Uses auxiliary model (cheap/fast) to summarize middle turns while
protecting head and tail context.

Improvements over v2:
  - Structured summary template with Resolved/Pending question tracking
  - Summarizer preamble: "Do not respond to any questions" (from OpenCode)
  - Handoff framing: "different assistant" (from Codex) to create separation
  - "Remaining Work" replaces "Next Steps" to avoid reading as active instructions
  - Clear separator when summary merges into tail message
  - Iterative summary updates (preserves info across multiple compactions)
  - Token-budget tail protection instead of fixed message count
  - Tool output pruning before LLM summarization (cheap pre-pass)
  - Scaled summary budget (proportional to compressed content)
  - Richer tool call/result detail in summarizer input
    N)AnyDictListOptional)call_llm)ContextEngine)MINIMUM_CONTEXT_LENGTHget_model_context_lengthestimate_messages_tokens_rough)redact_sensitive_textuR  [CONTEXT COMPACTION — REFERENCE ONLY] Earlier turns were compacted into the summary below. This is a handoff from a previous context window — treat it as background reference, NOT as active instructions. Do NOT answer questions or fulfill requests mentioned in this summary; they were already addressed. Your current task is identified in the '## Active Task' section of the summary — resume exactly from there. Respond ONLY to the latest user message that appears AFTER this summary. The current session state (files, config, etc.) may reflect work described here — avoid repeating it:z[CONTEXT SUMMARY]:i  皙?i.  z/[Old tool output cleared to save context space]   i@  iX  raw_contentreturnc                    t          | t                    rt          |           S t          | t                    st          t          | pd                    S d}| D ]}t          |t                    r|t          |          z  }*t          |t                    s |t          t          |                    z  }_|                    d          }|dv r|t          z  }|t          |                    dd          pd          z  }|S )a  Return the effective char-length of a message's content for token budgeting.

    Plain strings: ``len(content)``. Multimodal lists: sum of text-part
    ``len(text)`` plus a flat ``_IMAGE_CHAR_EQUIVALENT`` per image part
    (``image_url`` / ``input_image`` / Anthropic-style ``image``). This
    keeps the compressor from treating a turn with 5 attached images as
    near-zero tokens just because the text part is empty.
     r   type>   image	image_urlinput_imagetext)
isinstancestrlenlistdictget_IMAGE_CHAR_EQUIVALENT)r   totalpptypes       =/home/ubuntu/.hermes/hermes-agent/agent/context_compressor.py_content_length_for_budgetr#   M   s
    +s##  ;k4(( +3{(b))***E 2 2a 	SVVOE!T"" 	SQ[[ Ef999++EE
 Svr**0b111EEL    contentc                    | dS t          | t                    r| S t          | t                    rg }| D ]}t          |t                    r|                    |           -t          |t                    r?|                    d          }t          |t                    r|                    |           d                    d |D                       S t          |           S )zReturn a best-effort text view of message content.

    Used only for substring checks when we need to know whether we've already
    appended a note to a message. Keeps multimodal lists intact elsewhere.
    Nr   r   
c              3      K   | ]}||V  	d S N ).0parts     r"   	<genexpr>z-_content_text_for_contains.<locals>.<genexpr>   s'      88$48888888r$   )r   r   r   appendr   r   join)r%   partsitemr   s       r"   _content_text_for_containsr2   n   s     r'3 '4   	9 	' 	'D$$$ 'T""""D$'' 'xx''dC(( 'LL&&&yy88%888888w<<r$   Fprependr   r4   c                    | |S t          | t                    r|r|| z   n| |z   S t          | t                    rd|d}|r|g| ng | |S t          |           }|r||z   n||z   S )a  Append or prepend plain text to message content safely.

    Compression sometimes needs to add a note or merge a summary into an
    existing message. Message content may be plain text or a multimodal list of
    blocks, so direct string concatenation is not always safe.
    Nr   )r   r   )r   r   r   )r%   r   r4   
text_blockrendereds        r"   _append_text_to_contentr8      s     '3 =!(<tg~~gn<'4   M$d33
)0L
%W%%6L6L6LL7||H%:4(??8d?:r$      args
head_charsc                     	 t          j        |           }n# t          t          f$ r | cY S w xY wdt          dt          ffd |          }t          j        |d          S )u  Shrink long string values inside a tool-call arguments JSON blob while
    preserving JSON validity.

    The ``function.arguments`` field on a tool call is a JSON-encoded string
    passed through to the LLM provider; downstream providers strictly
    validate it and return a non-retryable 400 when it is not well-formed.
    An earlier implementation sliced the raw JSON at a fixed byte offset and
    appended ``...[truncated]`` — which routinely produced strings like::

        {"path": "/foo/bar", "content": "# long markdown
        ...[truncated]

    i.e. an unterminated string and a missing closing brace. MiniMax, for
    example, rejects this with ``invalid function arguments json string``
    and the session gets stuck re-sending the same broken history on every
    turn. See issue #11762 for the observed loop.

    This helper parses the arguments, shrinks long string leaves inside the
    parsed structure, and re-serialises. Non-string values (paths, ints,
    booleans) are preserved intact. If the arguments are not valid JSON
    to begin with — some model backends use non-JSON tool arguments — the
    original string is returned unchanged rather than replaced with
    something neither we nor the backend can parse.
    objr   c                 &   t          | t                    r"t          |           k    r| d          dz   S | S t          | t                    r fd|                                 D             S t          | t
                    rfd| D             S | S )Nz...[truncated]c                 .    i | ]\  }}| |          S r*   r*   )r+   kv_shrinks      r"   
<dictcomp>zB_truncate_tool_call_args_json.<locals>._shrink.<locals>.<dictcomp>   s'    :::daAwwqzz:::r$   c                 &    g | ]} |          S r*   r*   )r+   rA   rB   s     r"   
<listcomp>zB_truncate_tool_call_args_json.<locals>._shrink.<locals>.<listcomp>   s!    ,,,1GGAJJ,,,r$   )r   r   r   r   itemsr   )r=   rB   r;   s    r"   rB   z._truncate_tool_call_args_json.<locals>._shrink   s    c3 	3xx*$$;J;'*:::Jc4   	;::::ciikk::::c4   	-,,,,,,,,
r$   F)ensure_ascii)jsonloads
ValueError	TypeErrorr   dumps)r:   r;   parsedshrunkenrB   s    `  @r"   _truncate_tool_call_args_jsonrO      s    2D!!	"   	S 	S 	 	 	 	 	 	 	 wvH:hU3333s    //	tool_name	tool_argstool_contentc           	      
   	 |rt          j        |          ni }n# t           j        t          f$ r i }Y nw xY w|pd}t	          |          }|                                r|                    d          dz   nd}| dk    rp|                    dd          }t	          |          dk    r|dd	         d
z   }t          j	        d|          }|r|
                    d          nd}	d| d|	 d| dS | dk    r9|                    dd          }
|                    dd          }d|
 d| d|ddS | dk    rb|                    dd          }
|                    d          r,|                    dd                              d          dz   nd}d|
 d| dS | dk    r|                    dd          }|                    dd          }
|                    d d          }t          j	        d!|          }|r|
                    d          nd}d"| d#| d$|
 d%| d&	S | d'k    r9|                    dd          }
|                    d(d)          }d*| d+|
 d|dd,S | d-v rI|                    d.d          }|                    d/d          }|rd0| n|rd1| nd}d2|  d3| d|ddS | d4k    r |                    d5d          }d6| d7|dd,S | d8k    r|                    d9g           }t          |t                    r
|r|d         nd}t          |t                    r,t	          |          dk    r|d:t	          |          dz
   d;z  }d<| d|ddS | d=k    r@|                    d>d          }t	          |          d?k    r|dd@         d
z   }dA| d7|dd,S | dBk    rh|                    dC          pddd?                             dd0          }t	          |                    dCd                    d?k    r|d
z  }dD| dE| dFS | dGv r#|                    dHd          }d2|  dI| d|ddS | dJk    r(|                    dKd          ddL         }dM| d7|ddS | dNk    r4|                    dOd          }|                    d d          }dP| dQ| S | dRk    rdSS | dTk    rdUS | dVk    rdW|ddS | dXk    r|                    dOd          }dY| S | dZk    r4|                    dOd          }|                    d[d          }d\| d]| S d}t          |                                          dd^         D ]'\  }} t          |           dd_         }!|d0| d`|! z  }(d2|  d3| d|dd,S )aa  Create an informative 1-line summary of a tool call + result.

    Used during the pre-compression pruning pass to replace large tool
    outputs with a short but useful description of what the tool did,
    rather than a generic placeholder that carries zero information.

    Returns strings like::

        [terminal] ran `npm test` -> exit 0, 47 lines output
        [read_file] read config.py from line 1 (1,200 chars)
        [search_files] content search for 'compress' in agent/ -> 12 matches
    r   r'      r   terminalcommandP   NM   ...z"exit_code"\s*:\s*(-?\d+)?z[terminal] ran `z
` -> exit z, z lines output	read_filepathoffsetz[read_file] read z from line z (,z chars)
write_filer%   z[write_file] wrote to z lines)search_filespattern.targetz"total_count"\s*:\s*(\d+)z[search_files] z search for 'z' in z -> z matchespatchmodereplacez[patch] z in z chars result))browser_navigatebrowser_clickbrowser_snapshotbrowser_typebrowser_scrollbrowser_visionurlref z ref=[]
web_searchqueryz[web_search] query='z' (web_extracturlsz (+z more)z[web_extract] delegate_taskgoal<   9   z[delegate_task] 'execute_codecodez[execute_code] `z` (z lines output))
skill_viewskills_listskill_managenamez] name=vision_analyzequestion2   z[vision_analyze] 'memoryactionz	[memory] z on todoz[todo] updated task listclarifyz[clarify] asked user a questiontext_to_speechz"[text_to_speech] generated audio (cronjobz
[cronjob] process
session_idz
[process] z	 session=   (   =)rH   rI   JSONDecodeErrorrK   r   stripcountr   researchgroupr   r   rf   rF   r   )"rP   rQ   rR   r:   r%   content_len
line_countcmd
exit_match	exit_coder\   r]   written_linesra   rc   match_countr   re   rm   rn   detailrs   ru   url_descrw   code_previewr   r   r   sid	first_argr@   rA   svs"                                     r"   _summarize_tool_resultr      s   (19tz)$$$r ),     bGg,,K,3MMOOBt$$q((JJhhy"%%s88b==crc(U"CY;WEE
+5>J$$Q'''3	W#WWWWjWWWWKxx$$(A&&T4TTFTTkTTTTTL  xx$$CG88ICVCV_B//55d;;a??\_FFFFFFFN""((9c**xx$$(I..i <gFF(3<!!!$$$]]]g]]D]]e]]]]Gxx$$xx	**I$IIDIIKIIIII I I Ihhub!!hhub!!!ES(D"?9??v???????L  #&&MeMMMMMMMM!!xx##(t44FF4773dD!! 	4c$ii!mm3c$ii!m3333HBBBKBBBBBO##xx##t99r>>9u$DI4IIKIIIIIN""((.B4<<T3GGtxx##$$r))E!LM,MM:MMMMAAAxx$$C9CCTCC[CCCCC$$$88J++CRC0GHGGGGGGGH(C(((C((/6//v///F))I00$$$JKJJJJJI(C(($F$$$I(C((hh|S))2F22S222 ITZZ\\""2A2& " "1VVCRC[\\\R\\!		EyEE9EEEEEEEs    66c                   
    e Zd ZdZedefd            Zd= fdZ	 	 	 	 d>deded	ed
edededdfdZ		 	 	 	 	 	 	 	 	 	 	 d?dede
dedede
deded	ed
ededz  dedefdZdeeef         fdZd@dedefdZ	 d@deeeef                  d ed!edz  deeeeef                  ef         fd"Zd#eeeef                  defd$Zd%Zd&Zd'Zd'Zd(Zd)eeeef                  defd*Zd@d#eeeef                  d+edee         fd,Zed-edefd.            Zedefd/            Zdeeeef                  deeeef                  fd0Z deeeef                  d1edefd2Z!deeeef                  d1edefd3Z"deeeef                  d4edefd5Z#deeeef                  d6ed4edefd7Z$	 d@deeeef                  d4ed8edz  defd9Z%deeeef                  defd:Z&dAdeeeef                  d;ed+edeeeef                  fd<Z' xZ(S )BContextCompressoru  Default context engine — compresses conversation context via lossy summarization.

    Algorithm:
      1. Prune old tool results (cheap, no LLM call)
      2. Protect head messages (system prompt + first exchange)
      3. Protect tail messages by token budget (most recent ~20K tokens)
      4. Summarize middle turns with structured LLM prompt
      5. On subsequent compactions, iteratively update the previous summary
    r   c                     dS )N
compressorr*   )selfs    r"   r   zContextCompressor.nameJ  s    |r$   Nc                     t                                                       d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _	        d| _
        d| _        dS )z/Reset all per-session state for /new or /reset.FNr         Y@)superon_session_reset_context_probed_context_probe_persistable_previous_summary_last_summary_error_last_summary_dropped_count_last_summary_fallback_used_last_aux_model_failure_error_last_aux_model_failure_model_last_compression_savings_pct_ineffective_compression_count)r   	__class__s    r"   r   z"ContextCompressor.on_session_resetN  so      """$*/'!%#' +,(+0(-1*-1*-2*./+++r$   r   modelcontext_lengthbase_urlapi_keyproviderapi_modec                 R   || _         || _        || _        || _        || _        || _        t          t          || j        z            t                    | _
        t          | j
        | j        z            }|| _        t          t          |dz            t                    | _        dS )z>Update model info after a model switch or fallback activation.皙?N)r   r   r   r   r   r   maxintthreshold_percentr	   threshold_tokenssummary_target_ratiotail_token_budgetmin_SUMMARY_TOKENS_CEILINGmax_summary_tokens)r   r   r   r   r   r   r   target_tokenss           r"   update_modelzContextCompressor.update_model\  s     
   , #!7788"!
 !
 D1D4MMNN!."%%&&(?#
 #
r$         ?      r   Fr   protect_first_nprotect_last_nr   
quiet_modesummary_model_overrideconfig_context_lengthc                 J   || _         || _        |	| _        || _        || _        || _        || _        || _        t          dt          |d                    | _
        || _        t          |||	|
|          | _        t          t          | j        |z            t                    | _        d| _        t          | j        | j
        z            }|| _        t          t          | j        dz            t&                    | _        |s@t*                              d|| j        | j        |dz  | j
        dz  | j        |pd|pd	  	         d	| _        d| _        d| _        |pd
| _        d | _        d| _        d| _        d| _        d | _        d| _         d	| _!        d | _"        d | _#        d S )Ng?g?)r   r   r   r   r   r   zContext compressor initialized: model=%s context_length=%d threshold=%d (%.0f%%) target_ratio=%.0f%% tail_budget=%d provider=%s base_url=%sd   noneFr   r           )$r   r   r   r   r   r   r   r   r   r   r   r   r
   r   r   r	   r   compression_countr   r   r   loggerinfor   last_prompt_tokenslast_completion_tokenssummary_modelr   r   r   _summary_failure_cooldown_untilr   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                 r"   __init__zContextCompressor.__init__x  s    
   !2.,$'c2F.M.M$N$N!$6Hg"7
 
 
 !$#&7788"!
 !
 "# D1D4MMNN!."%#d*++-D#
 #
  		KK* t*D,A!C')BS)H&"FH$6    %"#&'#39r 1549*34+69,26  12(16(
 =A*<@***r$   usagec                 r    |                     dd          | _        |                     dd          | _        dS )z-Update tracked token usage from API response.prompt_tokensr   completion_tokensN)r   r   r   )r   r   s     r"   update_from_responsez&ContextCompressor.update_from_response  s5    "'))OQ"?"?&+ii0CQ&G&G###r$   r   c                     ||n| j         }|| j        k     rdS | j        dk    r)| j        s t                              d| j                   dS dS )a  Check if context exceeds the compression threshold.

        Includes anti-thrashing protection: if the last two compressions
        each saved less than 10%, skip compression to avoid infinite loops
        where each pass removes only 1-2 messages.
        NFr   u   Compression skipped — last %d compressions saved <10%% each. Consider /new to start a fresh session, or /compress <topic> for focused compression.T)r   r   r   r   r   warning)r   r   tokenss      r"   should_compressz!ContextCompressor.should_compress  so     #0";AXD)))5.!33? / 7	   5tr$   messagesprotect_tail_countprotect_tail_tokensc                 
   |s|dfS d |D             }d}i }|D ]}|                     d          dk    r|                     d          pg D ]}t          |t                    r\|                     dd          }	|                     di           }
|
                     d	d
          |
                     dd          f||	<   st          |dd          pd}	t          |dd          }
|
rt          |
d	d
          nd
}|
rt          |
dd          nd}||f||	<   Ɍ|R|dk    rKd}t	          |          }t          |t	          |                    }t          t	          |          dz
  dd          D ]}||         }|                     d          pd}t          |          }|t          z  dz   }|                     d          pg D ][}t          |t                    rD|                     di                                dd          }|t	          |          t          z  z  }\||z   |k    rt	          |          |z
  |k    r|} n||z  }|}t          |t	          |          |z
            }nt	          |          |z
  }i }t          t	          |          dz
  dd          D ]}||         }|                     d          dk    r$|                     d          pd}t          |t                    rQt	          |          dk     ret          j        |                    dd                                                    dd         }||v ri |ddi||<   |dz  }||                     dd          f||<   t          |          D ]}||         }|                     d          dk    r$|                     dd          }t          |t                    rP|r|t          k    r^|                    d          rtt	          |          dk    rP|                     dd          }|                     |d          \  }}t#          |||          }i |d|i||<   |dz  }t          |          D ]}||         }|                     d          dk    s|                     d          s9g }d}|d         D ]}t          |t                    rh|                     di                                dd          }t	          |          dk    r+t%          |          }||k    ri |di |d         d|ii}d}|                    |           |ri |d|i||<   ||fS )az  Replace old tool result contents with informative 1-line summaries.

        Instead of a generic placeholder, generates a summary like::

            [terminal] ran `npm test` -> exit 0, 47 lines output
            [read_file] read config.py from line 1 (3,400 chars)

        Also deduplicates identical tool results (e.g. reading the same file
        5x keeps only the newest full copy) and truncates large tool_call
        arguments in assistant messages outside the protected tail.

        Walks backward from the end, protecting the most recent messages that
        fall within ``protect_tail_tokens`` (when provided) OR the last
        ``protect_tail_count`` messages (backward-compatible default).
        When both are given, the token budget takes priority and the message
        count acts as a hard minimum floor.

        Returns (pruned_messages, pruned_count).
        r   c                 6    g | ]}|                                 S r*   )copy)r+   ms     r"   rE   z=ContextCompressor._prune_old_tool_results.<locals>.<listcomp>  s     ---q!&&((---r$   role	assistant
tool_callsidr   functionr   unknown	argumentsNrT   r%   
   toolr9   zutf-8rf   )errors   u>   [Duplicate tool output — same content as a more recent call]tool_call_idrZ   z[Duplicate tool output)r   r   Fi  T)r   r   r   getattrr   r   ranger#   _CHARS_PER_TOKENr   r   hashlibmd5encode	hexdigest_PRUNED_TOOL_PLACEHOLDER
startswithr   rO   r.   ) r   r   r   r   resultprunedcall_id_to_toolmsgtccidfnr   args_straccumulatedboundarymin_protectir   r   
msg_tokensr:   prune_boundarycontent_hashesr%   hcall_idrP   rQ   summarynew_tcsmodifiednew_argss                                    r"   _prune_old_tool_resultsz)ContextCompressor._prune_old_tool_results  s   .  	Q;--H--- -/ 	@ 	@Cwwv+--'',//52 
@ 
@B!"d++ 	@ ffT2..VVJ3302vy0I0I266R]_aKbKb/c,,%b$339r$RT::ACRwr69===CE#M72{B#?#?#?204h/?,, */BQ/F/FK6{{H0#f++>>K3v;;?B33  Qi!ggi006B8EE(,<<rA
'',//52 D DB!"d++ D!vvj"5599+rJJ"c$ii3C&CC
+.AAAs6{{UV[fFfFf HEz) 3v;;+DEENN [[+==N
  "s6{{QB// 	F 	FA)Cwwv&((ggi((.BG'4(( 7||c!!GNN79NEEFFPPRRSVTVSVWAN""pspI/oppq	!%&(D(D$Eq!! ~&& 	 	A)Cwwv&((ggi,,G'4((  g)AAA!!":;; 7||c!!''."55'6':':7O'T'T$	90IwOO7s7Iw77q	! ~&& 	; 	;A)Cwwv+--SWW\5J5J-GH,' # #b$'' ,66*b1155k2FFD4yy3#@#F#F#t++!^B!^
4]r*~4]{T\4]4]!^!^B'+Hr"""" ;:s:L'::q	v~r$   turns_to_summarizec                     t          |          }t          |t          z            }t          t          t          || j                            S )a+  Scale summary token budget with the amount of content being compressed.

        The maximum scales with the model's context window (5% of context,
        capped at ``_SUMMARY_TOKENS_CEILING``) so large-context models get
        richer summaries instead of being hard-capped at 8K tokens.
        )r   r   _SUMMARY_RATIOr   _MIN_SUMMARY_TOKENSr   r   )r   r  content_tokensbudgets       r"   _compute_summary_budgetz)ContextCompressor._compute_summary_budget|  sB     88JKK^n455&FD4K(L(LMMMr$   ip  i  i  i  turnsc           	      p   g }|D ]}|                     dd          }t          |                     d          pd          }|dk    rm|                     dd          }t          |          | j        k    r#|d| j                 dz   || j         d         z   }|                    d	| d
|            |dk    r}t          |          | j        k    r#|d| j                 dz   || j         d         z   }|                     dg           }|rg }|D ]}	t          |	t                    r|	                     di           }
|
                     dd          }t          |
                     dd                    }t          |          | j	        k    r|d| j
                 dz   }|                    d| d| d           t          |	dd          }
|
rt          |
dd          nd}|                    d| d           |dd                    |          z   dz   z  }|                    d|            4t          |          | j        k    r#|d| j                 dz   || j         d         z   }|                    d|                                 d
|            d                    |          S )a  Serialize conversation turns into labeled text for the summarizer.

        Includes tool call arguments and result content (up to
        ``_CONTENT_MAX`` chars per message) so the summarizer can preserve
        specific details like file paths, commands, and outputs.

        All content is redacted before serialization to prevent secrets
        (API keys, tokens, passwords) from leaking into the summary that
        gets sent to the auxiliary model and persisted across compactions.
        r   r   r%   r   r   r   Nz
...[truncated]...
z[TOOL RESULT z]: r   r   r   r   rZ   r   rY   z  ()z(...)z
[Tool calls:
r'   z
]z[ASSISTANT]: rp   

)r   r   r   _CONTENT_MAX_CONTENT_HEAD_CONTENT_TAILr.   r   r   _TOOL_ARGS_MAX_TOOL_ARGS_HEADr   r/   upper)r   r   r0   r  r   r%   tool_idr   tc_partsr  r	  r   r:   s                r"   _serialize_for_summaryz(ContextCompressor._serialize_for_summary  s     '	9 '	9C7769--D+CGGI,>,>,D"EEG v~~''."55w<<$"333%&9t'9&9:=TTW^`d`r_r_s_sWttGBWBBBBCCC {""w<<$"333%&9t'9&9:=TTW^`d`r_r_s_sWttG WW\266
 P!H( > >%b$// >!#
B!7!7B#%66&##6#6D#8R9P9P#Q#QD"4yy4+>>>'+,AT-A,A'BU'J$OO,?,?,?,?,?,?@@@@!(Z!>!>B?A#J72vs#;#;#;sD$OO,<,<,<,<====1DIIh4G4GG%OOG6W66777 7||d///!"54#5"569PPSZ\`\n[n[o[oSppLL7TZZ\\77g778888{{5!!!r$   focus_topicc                 	   t          j                    }|| j        k     r%t                              d| j        |z
             dS |                     |          }|                     |          }d}d| d}| j        r| d| j         d| d| }n
| d	| d
| }|r|d| d| dz  }	 d| j        | j	        | j
        | j        | j        dd|dgt          |dz            d}	| j        r
| j        |	d<   t          d+i |	}
|
j        d         j        j        }t'          |t(                    s|rt)          |          nd}t+          |                                          }|| _        d| _        d| _        d| _        |                     |          S # t4          $ rE t          j                    t6          z   | _        d| _        t9          j        dt6                     Y dS t<          $ r}t?          |dd          pt?          t?          |dd          dd          }t)          |                                           }|dv pd|v pd|v pd |v }|r| j        r| j        | j        k    rt?          | d!d          sd"| _        t9          j        d#| j        || j                   t)          |                                          p|j!        j"        }tG          |          d$k    r|dd%         $                                d&z   }|| _%        | j        | _&        d| _        d| _        | '                    ||'          cY d}~S | j        r| j        | j        k    rt?          | d!d          sd"| _        t9          j        d(| j        || j                   t)          |                                          p|j!        j"        }tG          |          d$k    r|dd%         $                                d&z   }|| _%        | j        | _&        d| _        d| _        | '                    ||'          cY d}~S d)}t          j                    |z   | _        t)          |                                          p|j!        j"        }tG          |          d$k    r|dd%         $                                d&z   }|| _        t9          j        d*||           Y d}~dS d}~ww xY w),uW  Generate a structured summary of conversation turns.

        Uses a structured template (Goal, Progress, Decisions, Resolved/Pending
        Questions, Files, Remaining Work) with explicit preamble telling the
        summarizer not to answer questions.  When a previous summary exists,
        generates an iterative update instead of summarizing from scratch.

        Args:
            focus_topic: Optional focus string for guided compression.  When
                provided, the summariser prioritises preserving information
                related to this topic and is more aggressive about compressing
                everything else.  Inspired by Claude Code's ``/compact``.

        Returns None if all attempts fail — the caller should drop
        the middle turns without a summary rather than inject a useless
        placeholder.
        z:Skipping context summary during cooldown (%.0fs remaining)Nu  You are a summarization agent creating a context checkpoint. Your output will be injected as reference material for a DIFFERENT assistant that continues the conversation. Do NOT respond to any questions or requests in the conversation — only output the structured summary. Do NOT include any preamble, greeting, or prefix. Write the summary in the same language the user was using in the conversation — do not translate or switch to English. NEVER include API keys, tokens, passwords, secrets, credentials, or connection strings in the summary — replace any that appear with [REDACTED]. Note that the user had credentials present, but do not preserve their values.u  ## Active Task
[THE SINGLE MOST IMPORTANT FIELD. Copy the user's most recent request or
task assignment verbatim — the exact words they used. If multiple tasks
were requested and only some are done, list only the ones NOT yet completed.
The next assistant must pick up exactly here. Example:
"User asked: 'Now refactor the auth module to use JWT instead of sessions'"
If no outstanding task exists, write "None."]

## Goal
[What the user is trying to accomplish overall]

## Constraints & Preferences
[User preferences, coding style, constraints, important decisions]

## Completed Actions
[Numbered list of concrete actions taken — include tool used, target, and outcome.
Format each as: N. ACTION target — outcome [tool: name]
Example:
1. READ config.py:45 — found `==` should be `!=` [tool: read_file]
2. PATCH config.py:45 — changed `==` to `!=` [tool: patch]
3. TEST `pytest tests/` — 3/50 failed: test_parse, test_validate, test_edge [tool: terminal]
Be specific with file paths, commands, line numbers, and results.]

## Active State
[Current working state — include:
- Working directory and branch (if applicable)
- Modified/created files with brief note on each
- Test status (X/Y passing)
- Any running processes or servers
- Environment details that matter]

## In Progress
[Work currently underway — what was being done when compaction fired]

## Blocked
[Any blockers, errors, or issues not yet resolved. Include exact error messages.]

## Key Decisions
[Important technical decisions and WHY they were made]

## Resolved Questions
[Questions the user asked that were ALREADY answered — include the answer so the next assistant does not re-answer them]

## Pending User Asks
[Questions or requests from the user that have NOT yet been answered or fulfilled. If none, write "None."]

## Relevant Files
[Files read, modified, or created — with brief note on each]

## Remaining Work
[What remains to be done — framed as context, not instructions]

## Critical Context
[Any specific values, error messages, configuration details, or data that would be lost without explicit preservation. NEVER include API keys, tokens, passwords, or credentials — write [REDACTED] instead.]

Target ~u   tokens. Be CONCRETE — include file paths, command outputs, error messages, line numbers, and specific values. Avoid vague descriptions like "made some changes" — say exactly what changed.

Write only the summary body. Do not include any preamble or prefix.z

You are updating a context compaction summary. A previous compaction produced the summary below. New conversation turns have occurred since then and need to be incorporated.

PREVIOUS SUMMARY:
z

NEW TURNS TO INCORPORATE:
u  

Update the summary using this exact structure. PRESERVE all existing information that is still relevant. ADD new completed actions to the numbered list (continue numbering). Move items from "In Progress" to "Completed Actions" when done. Move answered questions to "Resolved Questions". Update "Active State" to reflect current state. Remove information only if it is clearly obsolete. CRITICAL: Update "## Active Task" to reflect the user's most recent unfulfilled request — this is the most important field for task continuity.

a  

Create a structured handoff summary for a different assistant that will continue this conversation after earlier turns are compacted. The next assistant should be able to understand what happened without re-reading the original turns.

TURNS TO SUMMARIZE:
z

Use this exact structure:

z

FOCUS TOPIC: "z"
The user has requested that this compaction PRIORITISE preserving all information related to the focus topic above. For content related to "u  ", include full detail — exact values, file paths, command outputs, error messages, and decisions. For content NOT related to the focus topic, summarise more aggressively (brief one-liners or omit if truly irrelevant). The focus topic sections should receive roughly 60-70% of the summary token budget. Even for the focus topic, NEVER preserve API keys, tokens, passwords, or credentials — use [REDACTED].compression)r   r   r   r   r   userr   r%   g?)taskmain_runtimer   
max_tokensr   r   r   r   Fz$no auxiliary LLM provider configuredztContext compression: no provider available for summary. Middle turns will be dropped without summary for %d seconds.status_coderesponse)i  i  model_not_foundzdoes not existzno available channel_summary_model_fallen_backTzWSummary model '%s' not available (%s). Falling back to main model '%s' for compression.      rY   r.  zMSummary model '%s' failed (%s). Retrying on main model '%s' before giving up.rx   zWFailed to generate context summary: %s. Further summary attempts paused for %d seconds.r*   )(time	monotonicr   r   debugr  r-  r   r   r   r   r   r   r   r   r   choicesmessager%   r   r   r   r   r9  r   _with_summary_prefixRuntimeError!_SUMMARY_FAILURE_COOLDOWN_SECONDSloggingr   	Exceptionr   lowerr   __name__r   rstripr   r   _generate_summary)r   r  r.  nowsummary_budgetcontent_to_summarize_summarizer_preamble_template_sectionspromptcall_kwargsr7  r%   r  e_status_err_str_is_model_not_found	_err_text_transient_cooldownerr_texts                       r"   rJ  z#ContextCompressor._generate_summary  s   $ n555LLL4s:   4556HII#::;MNN, 	 9Gn 
o9G 9G 9Gv ! 	.  
      FF / 	 	
 	 	 	 	F  	v vv v NYv v v vF
y	%!Z $ $#| $! ! '-@@A!.3"677 K ! :'+'9G$..+..H&q)19Ggs++ :*19#g,,,r ,GMMOO<<G%,D"36D0.3D+'+D$,,W555 	 	 	37>3C3CFg3gD0'MD$O . >? ? ? 44 R	 R	 R	
 a55sJX\A]A]_lnr9s9sG1vv||~~H:% 6$06#x/6 *X5	   $[&[ &$*44&BEJJ 5 37/G&4:    FFLLNNBak.B	y>>C'' )$3$ 6 6 8 85 @I5>2595G2%'"7:4--.@k-ZZZZZZZZ "[&$*44&BEJJ 5 37/D&4:    FFLLNNBak.B	y>>C'' )$3$ 6 6 8 85 @I5>2595G2%'"7:4--.@k-ZZZZZZZZ #%37>3C3CFY3YD01vv||~~=)=H8}}s""#DSD>0022U:'/D$OB#	   44444eR	s;   )C'F AS	
S	)E
S3S	9C&SS	%BSS	r  c                     | pd                                 }t          t          fD ]B}|                    |          r+|t	          |          d                                         } nC|rt           d| nt          S )z@Normalize summary text to the current compaction handoff format.r   Nr'   )r   LEGACY_SUMMARY_PREFIXSUMMARY_PREFIXr  r   lstrip)r  r   prefixs      r"   rB  z&ContextCompressor._with_summary_prefix  s     2$$&&,n= 	 	Fv&& CKKLL)0022 /3F.**D***Fr$   c                     t          | t                    r.|                     dd          p|                     dd          pdS t          | dd          pt          | dd          pdS )zEExtract the call ID from a tool_call entry (dict or SimpleNamespace).r  r   r   )r   r   r   r   )r  s    r"   _get_tool_call_idz#ContextCompressor._get_tool_call_id  sk     b$ 	C66)R((BBFF4,<,<BBr9b))HWRr-B-BHbHr$   c                   	 t                      }|D ]a}|                    d          dk    rF|                    d          pg D ].}|                     |          }|r|                    |           /bt                      }|D ]G}|                    d          dk    r,|                    d          }|r|                    |           H||z
  		r=	fd|D             }| j        s(t
                              dt          	                     ||z
  }|rg }|D ]|}|                    |           |                    d          dk    rL|                    d          pg D ]4}|                     |          }||v r|                    dd|d	           5}|}| j        s(t
                              d
t          |                     |S )a  Fix orphaned tool_call / tool_result pairs after compression.

        Two failure modes:
        1. A tool *result* references a call_id whose assistant tool_call was
           removed (summarized/truncated).  The API rejects this with
           "No tool call found for function call output with call_id ...".
        2. An assistant message has tool_calls whose results were dropped.
           The API rejects this because every tool_call must be followed by
           a tool result with the matching call_id.

        This method removes orphaned results and inserts stub results for
        orphaned calls so the message list is always well-formed.
        r   r   r   r   r   c                 t    g | ]4}|                     d           dk    r|                     d          v 2|5S )r   r   r   )r   )r+   r   orphaned_resultss     r"   rE   z:ContextCompressor._sanitize_tool_pairs.<locals>.<listcomp>  sO       f//AEE.4I4IM]4]4] 4]4]4]r$   z9Compression sanitizer: removed %d orphaned tool result(s)u@   [Result from earlier conversation — see context summary above])r   r%   r   z3Compression sanitizer: added %d stub tool result(s))	setr   r_  addr   r   r   r   r.   )
r   r   surviving_call_idsr  r  r  result_call_idsmissing_resultspatchedrb  s
            @r"   _sanitize_tool_pairsz&ContextCompressor._sanitize_tool_pairs  s9    #&%% 	4 	4Cwwv+--'',//52 4 4B0044C 4*..s333"uu 	- 	-Cwwv&((ggn-- -#'',,, +-?? 	p   #  H ? pWY\]mYnYnooo -> 	i,.G 
 
s###776??k11!ggl339r  "44R88/11#NN(.+m03, ,   
 H? iQSVWfSgSghhhr$   idxc                     |t          |          k     rV||                             d          dk    r7|dz  }|t          |          k     r||                             d          dk    7|S )zPush a compress-start boundary forward past any orphan tool results.

        If ``messages[idx]`` is a tool result, slide forward until we hit a
        non-tool message so we don't start the summarised region mid-group.
        r   r   rT   r   r   )r   r   rj  s      r"   _align_boundary_forwardz)ContextCompressor._align_boundary_forward"  sn     CMM!!hsm&7&7&?&?6&I&I1HC CMM!!hsm&7&7&?&?6&I&I
r$   c                 h   |dk    s|t          |          k    r|S |dz
  }|dk    rI||                             d          dk    r*|dz  }|dk    r||                             d          dk    *|dk    r<||                             d          dk    r||                             d          r|}|S )aV  Pull a compress-end boundary backward to avoid splitting a
        tool_call / result group.

        If the boundary falls in the middle of a tool-result group (i.e.
        there are consecutive tool messages before ``idx``), walk backward
        past all of them to find the parent assistant message.  If found,
        move the boundary before the assistant so the entire
        assistant + tool_results group is included in the summarised region
        rather than being split (which causes silent data loss when
        ``_sanitize_tool_pairs`` removes the orphaned tail results).
        r   rT   r   r   r   r   rl  )r   r   rj  checks       r"   _align_boundary_backwardz*ContextCompressor._align_boundary_backward,  s     !88sc(mm++JaqjjXe_0088FBBQJE qjjXe_0088FBB A::(5/--f55DDRWI\I\]iIjIjDC
r$   head_endc                     t          t          |          dz
  |dz
  d          D ]%}||                             d          dk    r|c S &dS )zMReturn the index of the last user-role message at or after *head_end*, or -1.rT   r   r   r1  )r   r   r   )r   r   rq  r  s       r"   _find_last_user_message_idxz-ContextCompressor._find_last_user_message_idxH  s\     s8}}q((Q,;; 	 	A{v&&&00 1rr$   cut_idxc                     |                      ||          }|dk     r|S ||k    r|S | j        st                              d||           t	          ||dz             S )u  Guarantee the most recent user message is in the protected tail.

        Context compressor bug (#10896): ``_align_boundary_backward`` can pull
        ``cut_idx`` past a user message when it tries to keep tool_call/result
        groups together.  If the last user message ends up in the *compressed*
        middle region the LLM summariser writes it into "Pending User Asks",
        but ``SUMMARY_PREFIX`` tells the next model to respond only to user
        messages *after* the summary — so the task effectively disappears from
        the active context, causing the agent to stall, repeat completed work,
        or silently drop the user's latest request.

        Fix: if the last user-role message is not already in the tail
        (``messages[cut_idx:]``), walk ``cut_idx`` back to include it.  We
        then re-align backward one more time to avoid splitting any
        tool_call/result group that immediately precedes the user message.
        r   zjAnchoring tail cut to last user message at index %d (was %d) to prevent active-task loss after compressionrT   )rs  r   r   r?  r   )r   r   rt  rq  last_user_idxs        r"   !_ensure_last_user_message_in_tailz3ContextCompressor._ensure_last_user_message_in_tailQ  s}    , 888LL1NG##N  	LLI	   =(Q,///r$   token_budgetc                 2   || j         }t          |          }||z
  dk    rt          d||z
  dz
            nd}t          |dz            }d}|}t	          |dz
  |dz
  d          D ]}	||	         }
|
                    d          pd}t          |          }|t          z  d	z   }|
                    d
          pg D ][}t          |t                    rD|                    di                               dd          }|t          |          t          z  z  }\||z   |k    r||	z
  |k    r n||z  }|	}||z
  }||k    r|}||k    rt          ||dz             }|                     ||          }|                     |||          }t          ||dz             S )a  Walk backward from the end of messages, accumulating tokens until
        the budget is reached. Returns the index where the tail starts.

        ``token_budget`` defaults to ``self.tail_token_budget`` which is
        derived from ``summary_target_ratio * context_length``, so it
        scales automatically with the model's context window.

        Token budget is the primary criterion.  A hard minimum of 3 messages
        is always protected, but the budget is allowed to exceed by up to
        1.5x to avoid cutting inside an oversized message (tool output, file
        read, etc.).  If even the minimum 3 messages exceed 1.5x the budget
        the cut is placed right after the head so compression still runs.

        Never cuts inside a tool_call/result group.  Always ensures the most
        recent user message is in the tail (see ``_ensure_last_user_message_in_tail``).
        NrT   r   r   g      ?r   r%   r   r   r   r   r   )r   r   r   r   r   r   r#   r   r   r   r   rp  rw  )r   r   rq  rx  nmin_tailsoft_ceilingr  rt  r  r  r   r   r  r  r:   fallback_cuts                    r"   _find_tail_cut_by_tokensz*ContextCompressor._find_tail_cut_by_tokens  s   ( 1LMM/08|a/?/?3q!h,*+++Q<#-..q1uhlB// 	 	A1+C''),,2K4[AAK$(882=Jggl++1r @ @b$'' @66*b1155k2FFD#d))/?"??JZ',66AEh;N;N:%KGG 8|\!!"G h,155G //'BB 887HUU7HqL)))r$   c                 p    |                      || j                  }|                     ||          }||k     S )zReturn True if there is a non-empty middle region to compact.

        Overrides the ABC default so the gateway ``/compress`` guard can
        skip the LLM call when the transcript is still entirely inside
        the protected head/tail.
        )rm  r   r~  )r   r   compress_startcompress_ends       r"   has_content_to_compressz)ContextCompressor.has_content_to_compress  s<     55h@TUU44X~NN,,r$   current_tokensc                    d| _         d| _        d| _        d| _        d| _        t          |          }| j        dz   dz   }||k    r%| j        st          	                    d||           |S |r|n| j
        pt          |          }|                     || j        | j                  \  }}|r"| j        st                              d|           | j        }|                     ||          }|                     ||          }	||	k    r|S |||	         }
| j        st                              d	|| j                   t                              d
| j        | j        dz  | j                   ||	z
  }t                              d|dz   |	t          |
          ||           |                     |
|          }g }t-          |          D ]}||                                         }|dk    rp|                    d          dk    rW|                    d          }d}|t3          |          vr/t5          |t7          |t8                    r|rd|z   n|          |d<   |                    |           |sA| j        st          	                    d           |	|z
  }|| _         d| _        t<           d| d}d}|dk    r||dz
                               dd          nd}|	|k     r||	                             dd          nd}|dv rd}nd}||k    r|dk    rdnd}||k    r|}nd}|s|                    ||d           t-          |	|          D ]h}||                                         }|r5||	k    r/|dz   }t5          |                    d          |d          |d<   d}|                    |           i| xj        dz  c_        |                      |          }t          |          }||z
  }|dk    r||z  dz  nd}|| _!        |dk     r| xj"        dz  c_"        nd| _"        | j        sKt                              d|t          |          ||           t                              d| j                   |S ) a~  Compress conversation messages by summarizing middle turns.

        Algorithm:
          1. Prune old tool results (cheap pre-pass, no LLM call)
          2. Protect head messages (system prompt + first exchange)
          3. Find tail boundary by token budget (~20K tokens of recent context)
          4. Summarize middle turns with structured LLM prompt
          5. On re-compression, iteratively update the previous summary

        After compression, orphaned tool_call / tool_result pairs are cleaned
        up so the API never receives mismatched IDs.

        Args:
            focus_topic: Optional focus string for guided compression.  When
                provided, the summariser will prioritise preserving information
                related to this topic and be more aggressive about compressing
                everything else.  Inspired by Claude Code's ``/compact``.
        r   FNr   rT   z-Cannot compress: only %d messages (need > %d))r   r   z-Pre-compression: pruned %d old tool result(s)z9Context compression triggered (%d tokens >= %d threshold)z,Model context limit: %d tokens (%.0f%% = %d)r   zISummarizing turns %d-%d (%d turns), protecting %d head + %d tail messagesr<  r   systemr%   z[Note: Some earlier conversation turns have been compacted into a handoff summary to preserve context space. The current session state may still reflect earlier work, so build on that summary and state rather than re-doing work.]r$  uF   Summary generation failed — inserting static fallback context markerTz%
Summary generation was unavailable. z message(s) were removed to free context space but could not be summarized. The removed messages contained earlier work in this session. Continue based on the recent messages below and the current state of any files or resources.r1  )r   r   r   r2  uZ   

--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---

r3   r   z8Compressed: %d -> %d messages (~%d tokens saved, %.0f%%)zCompression #%d complete)#r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   rm  r~  r   r   r   rJ  r   r   r   r2   r8   r   r   r.   r[  r   ri  r   r   )r   r   r  r.  
n_messages_min_for_compressdisplay_tokenspruned_countr  r  r  	tail_msgsr  
compressedr  r  existing_compression_note	n_dropped_merge_summary_into_taillast_head_rolefirst_tail_rolesummary_roleflippedmerged_prefixnew_estimatesaved_estimatesavings_pcts                               r"   compresszContextCompressor.compress  s   * ,-(+0(#' -1*-1*]]
 014q8***? C 1   O+9  Ct?V  @CZx  zB  [C  [C "&!=!=)< $ 6 "> "
 "
,  	W 	WKKGVVV -55hOO 44X~NN\))O%n\&AB 	KKK%  
 KK>#&,%	   #\1IKK["&''   (();(UU 
~&& 
	# 
	#A1+""$$CAvv#''&//X55779-- %L!$,Fx,P,PPP%< 6@36O6OsT\s!222bs& &C	N c""""  	? ighhh$~5I/8D,/3D,! Z Z7@Z Z Z  $) M[^_M_M_.1"4599&&IIIekHTWaHaHa(<044VVDDDgm 222!LL&L ?**%1V%;%;kkG.((& ,0(' 	J|HHIII|Z00 	# 	#A1+""$$C' 1A,=,=RR 
 "9GGI&&! " " "I
 ,1(c""""!#..z::
5jAA',6 BPRSASAS~6<<YZ-8*//14///23D/ 	LKKJJ   KK2D4JKKKr$   )r   N)r   r   r   r   )r   r   r   r   FNr   r   Nr   r   r)   )NN))rH  
__module____qualname____doc__propertyr   r   r   r   r   floatboolr   r   r   r   r   r   tupler  r  r%  r&  r'  r(  r)  r-  r   rJ  staticmethodrB  r_  ri  rm  rp  rs  rw  r~  r  r  __classcell__)r   s   @r"   r   r   ?  s         c    X0 0 0 0 0 0$ 
 

 
 	

 
 
 
 

 
 
 
> $(  &* &*,0RA RARA !RA 	RA
 RA $RA RA !$RA RA RA  #TzRA RA RA RA RA RAhH$sCx. H H H H
 S D    8 +/K KT#s(^,KBEK 4ZK 
tDcN#S(	)K K K Kb	N$tCH~:N 	NSV 	N 	N 	N 	N LMMNO5"Dc3h,@ 5"S 5" 5" 5" 5"nH HDc3h4H HWZ Hfnorfs H H H HT Gc Gc G G G \G I I I I \I:T$sCx.-A :d4PSUXPX>FZ : : : :xT#s(^0D 3 SV    d38n1E C TW    8T#s(^,8;	   -0tCH~&-0 -0 	-0
 
-0 -0 -0 -0b $(>* >*T#s(^,>*8;>*Dj>* 
>* >* >* >*H	-T#s(^0D 	- 	- 	- 	- 	-s sd38n!5 ss s`c sostxy|  B  zB  uC  pD s s s s s s s sr$   r   )r9   )+r  r   rH   rE  r   r=  typingr   r   r   r   agent.auxiliary_clientr   agent.context_enginer   agent.model_metadatar	   r
   r   agent.redactr   	getLoggerrH  r   r[  rZ  r  r  r   r  r   _IMAGE_TOKEN_ESTIMATEr   rD  r   r#   r   r2   r  r8   rO   r   r   r*   r$   r"   <module>r     sg   &    				  , , , , , , , , , , , , + + + + + + . . . . . .         
 / . . . . .		8	$	$	L  -      M      /1AA $' !C C    B     . IN ; ; ;S ; ; ;RU ; ; ; ;$+4 +4 +4 +4s +4 +4 +4 +4\wFc wFc wF wFQT wF wF wF wFtG G G G G G G G G Gr$   