@@ -145,6 +145,42 @@ def _map_batch_results(
145145 formatter = format_data_structure ,
146146 )
147147
148+ def _maybe_compress_context (self ) -> bool :
149+ """Compress the conversation when it nears the context limit.
150+
151+ ``ContextCompressor`` measures and compacts
152+ ``agent.short_memory``, but the request body actually sent to
153+ the model is ``self._transcript`` — so after a compaction the
154+ transcript is rebuilt around the summary. Compressing only the
155+ mirror would leave the payload growing unbounded, which is the
156+ failure the compressor exists to prevent.
157+
158+ Returns:
159+ bool: True when a compression ran and the transcript was
160+ re-seeded. The caller must then restore whatever immediate
161+ instruction the model needs (e.g. the prompt for the
162+ subtask in flight).
163+ """
164+ compressor = getattr (self .agent , "_context_compressor" , None )
165+ if compressor is None :
166+ return False
167+ summary = compressor .maybe_compress (self .agent )
168+ if summary is None :
169+ return False
170+
171+ # compact() already re-seeded short_memory with the summary,
172+ # so the transcript copy must not be mirrored back a second
173+ # time.
174+ self ._transcript = Transcript ()
175+ self ._say_user (
176+ "[Compressed Memory Summary]\n "
177+ "Earlier turns were compressed to stay within the "
178+ "context window. Progress so far:\n \n "
179+ f"{ summary } " ,
180+ mirror = False ,
181+ )
182+ return True
183+
148184 def _run_autonomous_loop (
149185 self ,
150186 task : Optional [Union [str , Any ]] = None ,
@@ -674,6 +710,16 @@ def _run_autonomous_loop(
674710 ):
675711 subtask_iterations += 1
676712
713+ # Between iterations every recorded tool call has
714+ # been answered, so this is the one point the
715+ # transcript can be replaced without orphaning a
716+ # tool_call id.
717+ if self ._maybe_compress_context ():
718+ # The rebuilt transcript holds only the
719+ # summary; restore the instruction for the
720+ # subtask in flight.
721+ self ._say_user (execution_prompt )
722+
677723 try :
678724 response = self .agent .call_llm (
679725 task = None ,
0 commit comments