
    i#                         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  ej        e          ZdZdZd	Zd
ZdZdZdZ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_roughuR  [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]   iX  	tool_name	tool_argstool_contentreturnc           	      
   	 |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   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_filecontentz[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=   (   =)jsonloadsJSONDecodeError	TypeErrorlenstripcountgetresearchgroup
isinstancelistr(   itemsstr)"r   r   r   argsr!   content_len
line_countcmd
exit_match	exit_coder   r   written_linesr#   r%   match_countrV   r'   r/   r0   detailr5   r7   url_descr9   code_previewrA   rC   rF   sid	first_argkvsvs"                                     @/home/agentuser/.hermes/hermes-agent/agent/context_compressor.py_summarize_tool_resultrp   B   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@deeeef                  d:ed+edeeeef                  fd;Z& xZ'S )A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
compressor )selfs    ro   rA   zContextCompressor.name   s    |    Nc                     t                                                       d| _        d| _        d| _        d| _        d| _        dS )z/Reset all per-session state for /new or /reset.FN      Y@r   )superon_session_reset_context_probed_context_probe_persistable_previous_summary_last_compression_savings_pct_ineffective_compression_count)rv   	__class__s    ro   r{   z"ContextCompressor.on_session_reset   sG      """$*/'!%-2*./+++rw   r   modelcontext_lengthbase_urlapi_keyproviderapi_modec                     || _         || _        || _        || _        || _        || _        t          t          || j        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)rv   r   r   r   r   r   r   s          ro   update_modelzContextCompressor.update_model   s]     
   , #!7788"!
 !
rw         ?      r   Fr   protect_first_nprotect_last_nsummary_target_ratio
quiet_modesummary_model_overrideconfig_context_lengthc                    || _         || _        |	| _        || _        || _        || _        || _        || _        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 S )Ng?g?)r   r   r   r   r   g?zContext compressor initialized: model=%s context_length=%d threshold=%d (%.0f%%) target_ratio=%.0f%% tail_budget=%d provider=%s base_url=%sd   noneFr   ry           )r   r   r   r   r   r   r   r   r   minr   r   r
   r   r   r	   r   compression_counttail_token_budget_SUMMARY_TOKENS_CEILINGmax_summary_tokensloggerinfor|   last_prompt_tokenslast_completion_tokenssummary_modelr~   r   r   _summary_failure_cooldown_until)rv   r   r   r   r   r   r   r   r   r   r   r   r   target_tokenss                 ro   __init__zContextCompressor.__init__   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,,,rw   usagec                 r    |                     dd          | _        |                     dd          | _        dS )z-Update tracked token usage from API response.prompt_tokensr   completion_tokensN)rW   r   r   )rv   r   s     ro   update_from_responsez&ContextCompressor.update_from_response1  s5    "'))OQ"?"?&+ii0CQ&G&G###rw   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.
        NFrM   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)rv   r   tokenss      ro   should_compressz!ContextCompressor.should_compress6  so     #0";AXD)))5.!33? / 7	   5trw   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||	<   Ɍ||dk    r~d}t	          |          }t          |t	          |          dz
            }t          t	          |          dz
  dd          D ]	}||         }|                     d          pd}t          |t                    rt          d |D                       n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                    r^|                     di                                dd          }t	          |          dk    r!i |di |d         d|dd         dz   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 ru   )copy).0ms     ro   
<listcomp>z=ContextCompressor._prune_old_tool_results.<locals>.<listcomp>j  s     ---q!&&((---rw   role	assistant
tool_callsidr   functionrA   unknown	argumentsNr   r!   c              3   \   K   | ]'}t          |                    d d                    V  (dS )textr   NrT   rW   )r   ps     ro   	<genexpr>z<ContextCompressor._prune_old_tool_results.<locals>.<genexpr>  s8      !N!NQ#aeeFB&7&7"8"8!N!N!N!N!N!Nrw   
   tool   zutf-8r(   )errors   u>   [Duplicate tool output — same content as a more recent call]tool_call_idr   z[Duplicate tool output)r   r   Fi  z...[truncated]T)rW   r[   dictgetattrrT   r   ranger\   sum_CHARS_PER_TOKENr   hashlibmd5encode	hexdigest_PRUNED_TOOL_PLACEHOLDER
startswithrp   append)rv   r   r   r   resultprunedcall_id_to_toolmsgtccidfnrA   args_straccumulatedboundarymin_protectiraw_contentr`   
msg_tokensr_   prune_boundarycontent_hashesr!   hcall_idr   r   summarynew_tcsmodifieds                                  ro   _prune_old_tool_resultsz)ContextCompressor._prune_old_tool_resultsP  sT   .  	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++/BBK3v;;?B33  Qi!ggi006BR\]hjnRoRo  Fc!N!N+!N!N!NNNNux  zE  vF  vF(,<<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ooJ0n2j>0n;PTUYVYUYPZ]mPm0n0noo#'r"""" ;:s:L'::q	v~rw   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   )rv   r   content_tokensbudgets       ro   _compute_summary_budgetz)ContextCompressor._compute_summary_budget  sB     88JKK^n455&FD4K(L(LMMMrw   ip  i  i  i  turnsc           	      <   g }|D ]}|                     dd          }|                     d          pd}|dk    rm|                     dd          }t          |          | j        k    r#|d| j                 dz   || j         d         z   }|                    d	| d
|            |dk    rpt          |          | j        k    r#|d| j                 dz   || j         d         z   }|                     dg           }|rg }|D ]}	t          |	t                    r|	                     di           }
|
                     dd          }|
                     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|            t          |          | 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.
        r   r   r!   r   r   r   Nz
...[truncated]...
z[TOOL RESULT z]: r   r   r   rA   r   r   r   z  ()z(...)z
[Tool calls:
r   z
]z[ASSISTANT]: r2   

)rW   rT   _CONTENT_MAX_CONTENT_HEAD_CONTENT_TAILr   r[   r   _TOOL_ARGS_MAX_TOOL_ARGS_HEADr   joinupper)rv   r   partsr   r   r!   tool_idr   tc_partsr   r   rA   r_   s                ro   _serialize_for_summaryz(ContextCompressor._serialize_for_summary  s     '	9 '	9C7769--Dggi((.BG 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#%66+r#:#:D"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!!!rw   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}|                                }|| _        d| _        d| _        |                     |          S # t0          $ r> t          j                    t2          z   | _        t5          j        dt2                     Y dS t8          $ 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        rw| j        | j        k    rgt;          | d d          sVd!| _        t5          j        d"| j        || j                   d| _        d| _        |                     t@          |          cY d}~S d#}t          j                    |z   | _        t5          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)NuD  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.uQ  ## 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]

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 "u0  ", 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.compression)r   r   r   r   r   userr   r!   g?)taskmain_runtimer   
max_tokensr   r   r   r   FztContext 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.r:   zWFailed to generate context summary: %s. Further summary attempts paused for %d seconds.ru   )!time	monotonicr   r   debugr   r  r~   r   r   r   r   r   r   r   r   choicesmessager!   r[   r^   rU   r  _with_summary_prefixRuntimeError!_SUMMARY_FAILURE_COOLDOWN_SECONDSloggingr   	Exceptionr   lower_generate_summaryr   )rv   r   r  nowsummary_budgetcontent_to_summarize_summarizer_preamble_template_sectionspromptcall_kwargsr  r!   r   e_status_err_str_is_model_not_found_transient_cooldowns                     ro   r  z#ContextCompressor._generate_summary!  s6   $ 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  	M MM M NYM M M MF
I	%!Z $ $#| $! ! '-@@A!.3"677 K ! :'+'9G$..+..H&q)19Ggs++ :*19#g,,,rmmooG%,D"36D0.3D+,,W555 	 	 	37>3C3CFg3gD0O . >? ? ? 44 &	 &	 &	
 a55sJX\A]A]_lnr9s9sG1vv||~~H:% 6$06#x/6 *X5	   $H&H &$*44&BEJJ 5 37/G&4:  
 &("7:4--hGGGGGGGG #%37>3C3CFY3YD0OB#	   44444M&	s-   )CE= =AK.
K.CK)*K.03K))K.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   )rU   LEGACY_SUMMARY_PREFIXSUMMARY_PREFIXr   rT   lstrip)r   r   prefixs      ro   r  z&ContextCompressor._with_summary_prefix  s     2$$&&,n= 	 	Fv&& CKKLL)0022 /3F.**D***Frw   c                 ~    t          | t                    r|                     dd          S t          | dd          pdS )zEExtract the call ID from a tool_call entry (dict or SimpleNamespace).r   r   )r[   r   rW   r   )r   s    ro   _get_tool_call_idz#ContextCompressor._get_tool_call_id  sA     b$ 	$66$###r4$$**rw   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   )rW   )r   r   orphaned_resultss     ro   r   z:ContextCompressor._sanitize_tool_pairs.<locals>.<listcomp>*  sO       f//AEE.4I4IM]4]4] 4]4]4]rw   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))	setrW   r0  addr   r   r   rT   r   )
rv   r   surviving_call_idsr   r   r   result_call_idsmissing_resultspatchedr3  s
            @ro   _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rw   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   r   r   )rv   r   r;  s      ro   _align_boundary_forwardz)ContextCompressor._align_boundary_forwardF  sn     CMM!!hsm&7&7&?&?6&I&I1HC CMM!!hsm&7&7&?&?6&I&I
rw   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   r   r   r   r   r   r   )rv   r   r;  checks       ro   _align_boundary_backwardz*ContextCompressor._align_boundary_backwardP  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
rw   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.r   r   r   r	  )r   rT   rW   )rv   r   rA  r   s       ro   _find_last_user_message_idxz-ContextCompressor._find_last_user_message_idxl  s\     s8}}q((Q,;; 	 	A{v&&&00 1rrw   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 compressionr   )rC  r   r   r  r   )rv   r   rD  rA  last_user_idxs        ro   !_ensure_last_user_message_in_tailz3ContextCompressor._ensure_last_user_message_in_tailu  s}    , 888LL1NG##N  	LLI	   =(Q,///rw   token_budgetc                 .   || 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``).
        Nr   r   r   g      ?r   r!   r   r   r   r   r   )r   rT   r   r   r   rW   r   r[   r   r   r@  rG  )rv   r   rA  rH  nmin_tailsoft_ceilingr   rD  r   r   r!   r   r   r_   fallback_cuts                   ro   _find_tail_cut_by_tokensz*ContextCompressor._find_tail_cut_by_tokens  s   ( 1LMM/08|a/?/?3q!h,*+++Q<#-..q1uhlB// 	 	A1+Cggi((.BGW)99B>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)))rw   current_tokensc                    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 ]x}||                                         }|dk    rA|                    d          dk    r(|                    d          pd}d}||vr|dz   |z   |d<   |                    |           y|s3| j        st                              d           |	|z
  }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 ]]}||                                         }|r*||	k    r$|                    d          pd}|dz   |z   |d<   d}|                    |           ^| 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   r   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 messages)r  r   r   systemr!   r   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 markerz%
Summary generation was unavailable. z conversation turns were removed to free context space but could not be summarized. The removed turns contained earlier work in this session. Continue based on the recent messages below and the current state of any files or resources.Fr	  )r   r   r   Tr
  uZ   

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

r   z8Compressed: %d -> %d messages (~%d tokens saved, %.0f%%)zCompression #%d complete)rT   r   r   r   r   r   r   r   r   r   r   r=  rN  r   r   r   r  r   r   rW   r   r,  r   r:  r   r   )rv   r   rO  r  
n_messages_min_for_compressdisplay_tokenspruned_countcompress_startcompress_endr   	tail_msgsr   
compressedr   r   existing_compression_note	n_dropped_merge_summary_into_taillast_head_rolefirst_tail_rolesummary_roleflippedoriginalnew_estimatesaved_estimatesavings_pcts                               ro   compresszContextCompressor.compress  sX   & ]]
 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--3 %L!$H44%-%69J%JC	Nc""""  
	? ighhh$~5I! 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,=,=779--3RR  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rw   )r   N)r   r   r   r   )r   r   r   r   FNr   r   Nr   r   )N)NN)(__name__
__module____qualname____doc__propertyr^   rA   r{   r   r   floatboolr   r   r   r   r   r   tupler   r   r   r   r   r   r   r  r   r  staticmethodr  r0  r:  r=  r@  rC  rG  rN  rf  __classcell__)r   s   @ro   rr   rr      s~         c    X0 0 0 0 0 0 
 

 
 	

 
 
 
 

 
 
 
0 $(  &* &*,0F: F:F: !F: 	F:
 F: $F: F: !$F: F: F:  #TzF: F: F: F: F: F:PH$sCx. H H H H
 S D    8 +/D DT#s(^,DBED 4ZD 
tDcN#S(	)D D D DT	N$tCH~:N 	NSV 	N 	N 	N 	N LMMNO1"Dc3h,@ 1"S 1" 1" 1" 1"fR RDc3h4H RWZ Rfnorfs R R R Rh Gc Gc G G G \G + + + + \+: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=* 
=* =* =* =*Fd dd38n!5 ds d`c dostxy|  B  zB  uC  pD d d d d d d d drw   rr   )!rj  r   rP   r  rX   r  typingr   r   r   r   agent.auxiliary_clientr   agent.context_enginer   agent.model_metadatar	   r
   r   	getLoggerrg  r   r,  r+  r   r   r   r   r   r  r^   rp   rr   ru   rw   ro   <module>rv     s   &    				  , , , , , , , , , , , , + + + + + + . . . . . .          
	8	$	$	L  -      M   $' !wFc wFc wF wFQT wF wF wF wFtO O O O O O O O O Orw   