
    YjY                      d Z ddlmZ ddlZddlZddlmZ ddlZddl	Z	ddl
Z
ddlZddlZddlmZmZ ddlmZmZmZmZmZmZmZ ddlmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z% dd	l&m'Z' dd
l(m)Z) ddl*m+Z+m,Z, ddl-m.Z.m/Z/m0Z0  ej1        e2          Z3dIdZ4dZ5dZ6dJdZ7dKdZ8dLdZ9d Z:dMd"Z;dddddd#dNd2Z<dOdPd5Z=d3d6dd7dQd:Z>dRd<Z?dSd>Z@dTd@ZAdUdAdBdVdEZBdUdAdBdVdFZCdWdXdGZDg dHZEdS )Yu  Tool-call execution — sequential and concurrent dispatch.

Both AIAgent methods (``_execute_tool_calls_sequential`` and
``_execute_tool_calls_concurrent``) live here as module-level
functions that take the parent ``AIAgent`` as their first argument.

``run_agent`` keeps thin wrappers so existing call sites work; tests
that patch ``run_agent._set_interrupt`` are honored because the
extracted functions reach back through the ``run_agent`` module via
``_ra()`` for that symbol.
    )annotationsN)Path)AnyOptional)KawaiiSpinnerbuild_tool_previewbuild_tool_labelget_cute_tool_messageget_tool_emojiredact_tool_args_for_display_detect_tool_failure)ToolGuardrailDecision)_is_destructive_command_is_multimodal_tool_result_multimodal_text_summary!_append_subdir_hint_to_multimodal_plan_tool_batch_segmentsmake_tool_result_message)get_active_env)propagate_context_to_thread)maybe_persist_tool_resultenforce_turn_budget)BudgetConfigDEFAULT_BUDGETbudget_for_context_windowreturnr   c                    	 t          t          | dd          dd          }|rt          t          |                    nt          S # t          $ r
 t          cY S w xY w)a  Resolve a tool-result BudgetConfig scaled to the agent's context window.

    Large-context models keep the historical 100K/200K char defaults; small
    models (e.g. a 65K-token local model switched into mid-session) get a budget
    proportional to their window so a single large tool result can't push the
    request past the model's limit (#23767). Falls back to the default budget
    when the context length isn't resolvable.
    context_compressorNcontext_length)getattrr   intr   	Exception)agentctxs     HC:\Users\server\AppData\Local\hermes\hermes-agent\agent\tool_executor.py_budget_for_agentr&   8   sm    ge%94@@BRTXYY69M(S222~M   s   AA AA   g     @z@raw_argumentsr   tuple[dict, Optional[str]]c                    	 t          j        |           }n# t           j        t          f$ r d}Y nw xY wt	          |t
                    r|dfS i t          j        dddd          fS )zAParse model-emitted arguments without repairing or coercing them.NzInvalid tool argumentszBTool arguments must be a valid JSON object; tool was not executed.)errormessageFensure_ascii)jsonloadsJSONDecodeError	TypeError
isinstancedictdumps)r(   	argumentss     r%   _parse_tool_argumentsr7   O   s    J}--		 ),   			)T"" $tz-T	
 	
     s    22float | Nonec                    t          j        dd                                          } | st          S 	 t	          |           }n8# t
          $ r+ t                              d| t                     t          cY S w xY w|dk    rd S |S )N HERMES_CONCURRENT_TOOL_TIMEOUT_S z8invalid HERMES_CONCURRENT_TOOL_TIMEOUT_S=%r; using %.0fsr   )osgetenvstrip"_DEFAULT_CONCURRENT_TOOL_TIMEOUT_Sfloat
ValueErrorloggerwarning)rawvalues     r%    _resolve_concurrent_tool_timeoutrF   b   s    
)6
;
;
A
A
C
CC 2112c

 2 2 2F.	
 	
 	

 21112 zztLs   A 2A76A7messagesliststagestrNonec                   	 |                      |           dS # t          $ r'}t                              d||           Y d}~dS d}~ww xY w)a`  Best-effort incremental SessionDB flush for tool-call progress.

    Tool execution can perform side effects that terminate or restart the
    current Hermes process before the normal turn-end persistence path runs.
    Flush the already-appended assistant/tool messages immediately so the
    transcript survives destructive-but-valid tool calls.
    z5Incremental tool-call persistence failed after %s: %sN)_flush_messages_to_session_dbr"   rB   rC   )r#   rG   rI   excs       r%   %_flush_session_db_after_tool_progressrO   t   sp    \++H55555 \ \ \NPUWZ[[[[[[[[[\s    
A
AA
c                     ddl } | S )zRLazy reference to ``run_agent`` so patches like ``run_agent._set_interrupt`` work.r   N	run_agentrQ   s    r%   _rarS      s        rN   RuntimeErrorboolc                $    dt          |           v S )Nz6cannot schedule new futures after interpreter shutdown)rJ   )rN   s    r%   %_is_interpreter_shutdown_submit_errorrX      s    Cs3xxOOrT   )duration_msstatus
error_typeerror_messagemiddleware_tracefunction_namefunction_argsr4   resulteffective_task_idtool_call_idrY   r!   rZ   
str | Noner[   r\   r]   Optional[list[dict[str, Any]]]c       
            	 ddl m}  |||||pdt          | dd          pd|pdt          | dd          pdt          | dd          pd||||	t          |
pg                      d S # t          $ r Y d S w xY w)Nr   )_emit_post_tool_call_hookr;   
session_id_current_turn_id_current_api_request_id)r^   r_   r`   task_idrg   rb   turn_idapi_request_idrY   rZ   r[   r\   r]   )model_toolsrf   r    rH   r"   )r#   r^   r_   r`   ra   rb   rY   rZ   r[   r\   r]   rf   s               r%   _emit_terminal_post_tool_callrn      s    999999!!''%+ulB77=2%+E#5r::@b"5*CRHHNB#!'!"2"8b99	
 	
 	
 	
 	
 	
    s   A$A( (
A65A6user interruptreasonc                :    t          j        d|  ddd          S )NTool execution cancelled by 	cancelled)r+   rZ   Fr-   )r/   r5   )rp   s    r%   _cancelled_tool_resultrt      s8    :<F<<!	
 	
    rT   keyboard_interrupt)rp   r[   r]   
start_timer@   c                   t          |          }	t          | |||	||t          t          j                    |z
  dz            d|d| t	          |pg                      |	S )N  rs   rr   )
r^   r_   r`   ra   rb   rY   rZ   r[   r\   r]   )rt   rn   r!   timerH   )
r#   r^   r_   ra   rb   rv   rp   r[   r]   r`   s
             r%   '_emit_cancelled_terminal_post_tool_callrz      s~     $F++F!##+!z1T9::=V==.4"55    MrT   	frozensetc                :   	 ddl }ddlm} ddlm} n# t
          $ r t                      cY S w xY wt          | dd          }t          | dd          }t          |dd          |t          |          nd|t          |          ndf}t          | dd          }||d         |k    r|d	         S 	 |                    ||d
d
          pg }|	                    |          }	n# t
          $ r t                      }	Y nw xY w	 ||	f| _
        n# t
          $ r Y nw xY w|	S )a  Return the deferrable tool names the session may invoke via tool_call.

    The Tool Search unwrap dispatches the underlying tool directly, bypassing
    the bridge branch (and its scope check) in
    ``model_tools.handle_function_call``. To keep a restricted-toolset session
    (subagent, kanban worker, curated gateway session) from reaching tools it
    was never granted, the unwrap validates the underlying name against this
    set: the deferrable subset of the session's own enabled/disabled toolset
    scope.

    Result is cached on the agent and refreshed when the tool registry's
    generation changes (e.g. an MCP server reconnects), so the common case is
    a dict lookup, not a full tool-defs rebuild on every tool call.
    r   Ntool_search)registryenabled_toolsetsdisabled_toolsets_generation_tool_search_scope_cache   T)r   r   
quiet_modeskip_tool_search_assembly)rm   toolsr~   tools.registryr   r"   r{   r    get_tool_definitionsscoped_deferrable_namesr   )
r#   rm   _ts	_registryenableddisabled	cache_keycachedscoped_defsnamess
             r%   _tool_search_scoped_namesr      s   ,,,,,,8888888   {{ e/66Gu1488H	=!,,%1	't'3	(I
 U6==FfQi944ay	!66$&&*	 7 
 
 
  	 ++K88   *3U);&&   Ls0    ..10C" "C=<C=	D 
DD!tuple[dict, list[dict[str, Any]]]c                  	 ddl m}  ||||pdt          | dd          pd|pdt          | dd          pdt          | dd          pd          }t          |j        t
                    r|j        n|}|t          |j                  fS # t          $ r)}t          
                    d|           |g fcY d }~S d }~ww xY w)	Nr   )apply_tool_request_middlewarer;   rg   rh   ri   )rj   rg   rb   rk   rl   z!tool_request middleware error: %s)hermes_cli.middlewarer   r    r3   payloadr4   rH   tracer"   rB   debug)	r#   r^   r_   ra   rb   r   r`   r   rN   s	            r%   (_apply_tool_request_middleware_for_agentr     s   !GGGGGG..%+ulB77=2%+E#5r::@b"5*CRHHNB
 
 
 %/v~t$D$DW&..-V\**** ! ! !8#>>>b       !s   BB
 

B=B82B=8B=tuple[Any, dict]c                  	 	d	fd}ddl m}  ||||pdt          | d	d          pd|pdt          | d
d          pdt          | dd          pd	  	        }|	fS )N	next_argsr4   r   r   c                L    t          | t                    r| n           S N)r3   r4   )r   executer_   observed_argss    r%   _executez6_run_agent_tool_execution_middleware.<locals>._execute2  s+    %/	4%@%@S		mw}%%%rT   r   )run_tool_execution_middlewarer;   rg   rh   ri   )original_argsrj   rg   rb   rk   rl   r   r4   r   r   )r   r   r    )
r#   r^   r_   ra   rb   r   r   r   r`   r   s
     `  `   @r%   $_run_agent_tool_execution_middlewarer   '  s     "M& & & & & & & &
 DCCCCC**#!'R5,339r!'R1266<"u&?DDJ
 
 
F =  rT   Tfinalizeapi_call_countr   c               b%   YZ[ |j         }t          |          }t                     } j        rt	           j         d| d           |D ]d}	                    t          |	j        j	        d|	j        j	         d|	j
        d                     t           d|	j        j	                    ed	S g Z|D ]}
|
j        j	        }t          |
j        j                  \  }}|Z                    |
||g |d
f           I|dk    rd _        n|dk    rd _        d	}	 ddlm} ||j        k    rO|                    |          \  }}}|s4|r2|t)                     v r|}|}nt+          j        dd| did
          }n# t.          $ r Y nw xY wt1           ||t3          |
dd          pd          \  }}d	}d
}|;|}t5           |||t3          |
dd          pddd|t7          |          
  
         nS	 ddlm}  |||pdt3           dd          pdt3          |
dd          pdt3           dd          pdt3           dd          pdt7          |                    }n# t.          $ r d	}Y nw xY w|Pt+          j        d|id
          }t5           |||t3          |
dd          pddd|t7          |          
  
         n j                            ||          }|j         s_ !                    |          }d}t5           |||t3          |
dd          pddd t3          |d!d	          pd"t7          |          
  
         ||d#v rn j"        j#        rb	 |$                    d$d          }|r8 j"        %                    |          } j"        &                    |d%|            n# t.          $ r Y nw xY w|d&k    r j"        j#        r	 |$                    d'd          }tO          |          ra|$                    d(          p%tQ          j)        d)tQ          j*                              } j"        &                    |d*|d	d+                     n# t.          $ r Y nw xY wZ                    |
|||||f           d,+                    d- ZD                       } j,        sPt3           d.d/          d0k    r:t	          d1| d2|            t[          Zd3          D ]\  }\  }	}} }}}t]          ||           p| }!t+          j        |!d
          }" j/        rqt	          d4| d5| d6t7          |!0                                           d7           t	           1                    d8t+          j        |!d9d
:                               t          |"           j2        k    r|"d	 j2                 d;z   n|"}#t	          d4| d5| d6t7          | 0                                           d<|#            ZD ]}\  }	}} }}}| j3        rj	 t]          ||           p| }!ti          ||!          }$ 3                    d=||$|!           O# t.          $ r!}%tk          j6        d>|%            Y d	}%~%ud	}%~%ww xY w~ZD ]q\  }	}} }}}| j7        r^	 t]          ||           p| }! 7                    |	j
        ||!           C# t.          $ r!}%tk          j6        d?|%            Y d	}%~%id	}%~%ww xY wrd	g|z  [t[          Z          D ]\  }\  }	}} }}}||| |d@dd|f[|<   | _8         9                    dA| dB|             [fdC}&d	}' :                                rj ;                                rVty          j=        t}          j?                              }(t}          |( dD| dEdF j@        G          }'|'A                                 	 dH t[          Z          D             })g }*i Yt                      }+t                      },|,t          jE                    |,z   nd	}-|)rt          t          |)          t                    }.ddIlHmI}/  |/|.J          }0d
}1	 t[          |)          D ]\  }2\  }}	}} 	 |0J                    t          |&          ||	|| Z|         dK                   }3n# t          $ r}4t          |4          s |)|2d	         }5t          O                    dLt          |5                     |5D ]/\  }6}7}8}9[|6          Z|6         dK         }dM|8 dN}:|8|9|:d@dd
|f[|6<   0Y d	}4~4 n#d	}4~4ww xY w|*                    |3           |Y|3<   t          jD                    };d
}<	 dO}=|-l|-t          jE                    z
  }>|>dk    rt                      dP |*D             }@}?nYt          |=|>          }=t          jQ        R                    |*|=Q          \  }?}@n$t          jQ        R                    |*|=Q          \  }?}@|@sn|- t          jE                    |-k    rd}1YfdR|@D             }+ZfdS|+D             }At          O                    dT|,t          |+          d,+                    |Ad	dU                              |@D ]}3|3S                                  jT        5  t7           jU                  }Bd	d	d	           n# 1 swxY w Y   |BD ]5}C	 t                      W                    d|C           &# t.          $ r Y 2w xY wn j        rpd}1|<s1d}< X                     j         dVt          |@           dWdX           |@D ]}3|3S                                 t          jQ        R                    |@dYQ           nt          t          jD                    |;z
            }D|Ddk    r_|DdZz  d[k     rVYZfd\|@D             }A 9                    d]|D d^t          |@           d_d,+                    |Ad	dK                    d7           |0Z                    |1 |1`           n# |0Z                    |1 |1`           w xY w|'rRt          da [D                       }Et          db [D                       }F|'\                    dc|E dd| de|Fdfdg           nZ# |'rSt          da [D                       }Et          db [D                       }F|'\                    dc|E dd| de|Fdfdg           w w xY wt[          Z          D ]R\  }\  }	}} }}}[|         }Gd
}Hd	}I||+v r`|G^|,|,dfdhndi}JdM| dj|J }Kdk}It5           || |Kt3          |	dd          pddldm|Kt7          |          
  
         t          |,pd@          }Ln|G j        r>d| d}Kt5           || |Kt3          |	dd          pddndodpt7          |          
  
         n=dM| dq}Kt5           || |Kt3          |	dd          pdddr|Kt7          |          
  
         d@}Ln]|G\  }}}K}L}M}H}|Hrd}I|Hs ^                    |||K|Ms          }K|MrKt          |K          }Nt          |N          dtk    r
|Nd	dt         n|N}Ot          O                    du||L|O           |HsF	  `                    |||K|M           n,# t.          $ r}Ptk          j6        dv|P           Y d	}P~Pnd	}P~Pww xY w|HsS j3        rL	  3                    dw|d	d	|L|M|Kx           n.# t.          $ r!}%tk          j6        d>|%            Y d	}%~%nd	}%~%ww xY w j/        rCtk          j6        dy| dz|Ld{dh           tk          j6        d|t          |K           d}|K             :                                r,t          || |L|K~          }Q b                    d|Q            n j,        st3           d.d/          d0k    rt          |K          }R j/        r>t	          d|d3z    dz|Ld{dh           t	           1                    d|R                     nHt          |R           j2        k    r|Rd	 j2                 d;z   n|R}St	          d|d3z    dz|Ld{d|S            d	 _8         9                    d| d|Ldfd           |Hsf jc        r_	 t]          ||           p| }! c                    |	j
        ||!|K           n.# t.          $ r!}%tk          j6        d|%            Y d	}%~%nd	}%~%ww xY wt          |K          s&t          |K||	j
        t                    |          n|K}K jg        h                    ||           }T|Tr%t          |K          rt          |K|T           n|K|Tz  }K j                    ||K          }Ut          ||U|	j
        |I          }V                    |V           |V$                    d          }W|Wn|W$                    d          dk    rU j3        rN	  3                    d|d	d	|	j
        |W           n,# t.          $ r}%tk          j6        d|%           Y d	}%~%nd	}%~%ww xY wt           d|             k                    d3           Tt          Z          }|r0|dk    r*| d	         }Xt          |Xt                    |           |r|dk    r k                    |           d	S d	S d	S )u  Execute multiple tool calls concurrently using a thread pool.

    Results are collected in the original tool-call order and appended to
    messages so the API sees them in the expected sequence.

    ``finalize=False`` skips the end-of-batch aggregate budget enforcement
    and /steer injection — used when this call is one segment of a larger
    mixed batch and the segmented dispatcher owns the turn-end work.
       ⚡ Interrupt: skipping  tool call(s)   [Tool execution cancelled — # was skipped due to user interrupt]noneeffect_dispositioncancelled tool result rI   NFmemoryr   skill_manager}   r+   'O' is not available in this session. Use tool_search to find tools you can call.r-   idr;   r^   r_   ra   rb   blockedtool_scope_block	r^   r_   r`   ra   rb   rZ   r[   r\   r]   resolve_pre_tool_blockrg   rh   ri   rj   rg   rb   rk   rl   r]   plugin_blockTguardrail_blockr,    Tool blocked by guardrail policy>   patch
write_filepathbefore terminalcommandworkdirTERMINAL_CWDbefore terminal: <   z, c              3  (   K   | ]\  }}}}}}|V  d S r    ).0_names      r%   	<genexpr>z0execute_tool_calls_concurrent.<locals>.<genexpr>  s/      LL(;4Aq!tLLLLLLrT   tool_progress_modealloffu     ⚡ Concurrent: u    tool calls — r        📞 Tool : ()Args:    indentr.   ...) - tool.startedTool progress callback error: Tool start callback error:         z
executing z tools concurrently: c                f   t          j                    j        }j        5  j                            |           ddd           n# 1 swxY w Y   j        r4	 t                                          d|           n# t          $ r Y nw xY w	 ddl
m}  |j                   n# t          $ r Y nw xY wt          j                    }	 	                     |||j        ddt!          |                    }nP# t"          $ r
 	                     d           n# t          $ r Y nw xY wt'          ||t)          |dd          pd|t!          |          	          }t          j                    |z
  }	t*                              d
||	           ||||	dd|f| <   Y j        5  j                            |           ddd           n# 1 swxY w Y   	 t                                          d|           dS # t          $ r Y dS w xY wt          $ r0}
d| d|
 }t*                              d||
d           Y d}
~
nd}
~
ww xY wt          j                    |z
  }	t3          ||          \  }}|r&t*                              d||	|dd                    n*t*                              d||	t5          |                     ||||	|d|f| <   j        5  j                            |           ddd           n# 1 swxY w Y   	 t                                          d|           dS # t          $ r Y dS w xY w# j        5  j                            |           ddd           n# 1 swxY w Y   	 t                                          d|           w # t          $ r Y w w xY wxY w)z%Worker function executed in a thread.NTr   set_activity_callback)rG   pre_tool_block_checkedskip_tool_request_middlewaretool_request_middleware_tracekeyboard interruptr   r;   r^   r_   ra   rb   rv   r]   ztool %s cancelled (%.2fs)FError executing tool '': z_invoke_tool raised for %s: %sexc_infoztool %s failed (%.2fs): %s   #tool %s completed (%.2fs, %d chars))	threadingcurrent_threadident_tool_worker_threads_lock_tool_worker_threadsadd_interrupt_requestedrS   _set_interruptr"   tools.environments.baser   _touch_activityry   _invoke_toolr   rH   KeyboardInterrupt	interruptrz   r    rB   infodiscardr+   r   len)index	tool_callr^   r_   r]   _worker_tidr   startr`   duration
tool_erroris_errorr   r#   ra   rG   resultss                r%   	_run_toolz0execute_tool_calls_concurrent.<locals>._run_tool=  s   
  .006, 	8 	8&**;777	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 % 	$$T;7777   	EEEEEE!!%"78888 	 	 	D	
 	4	i++!!%L%+/15267G2H2H , 	 	 %   OO$89999    D@"/"/&7!(D"!=!=!C$%)*:%;%;    9;;.7QQQ"/RVX]_o!p$ 0 @ @*22;???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$$UK88888   +  i i iP-PPJPP=}jcghhhhhhhhi y{{U*H.}fEEKHa i8-SYZ^[^Z^S_````A=RZ\_`f\g\ghhh+]FHhX]_opGEN 0 @ @*22;???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$$UK88888   	 0 @ @*22;???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$$UK8888   s'  AAA"A> >
B
BB& &
B32B3/C< :M <I	DI	
D+(I	*D++A5I	 M (GGG"G? ?
HH	I	&I?M I		B
M LLL"L1 1
L?>L?N0
M1%N01M55N08M59N0="N N0 
N-*N0,N--N0u    ⚡ running z tools concurrentlydotsspinner_typeprint_fnc                2    g | ]\  }\  }}}}}}|||||fS r   r   )r   itcr   argsr]   block_resultblocked_by_guardrails           r%   
<listcomp>z1execute_tool_calls_concurrent.<locals>.<listcomp>  sD     
 
 
YYBd$4lDX# D$###rT   )DaemonThreadPoolExecutor)max_workers   zWinterpreter shutdown while scheduling concurrent tools; skipping %d unsubmitted tool(s)r   z<': Python interpreter is shutting down; tool was not startedg      @c                :    h | ]}|                                 |S r   )done)r   fs     r%   	<setcomp>z0execute_tool_calls_concurrent.<locals>.<setcomp>  s5     5 5 5&'!&&((5 !5 5 5rT   )timeoutc                (    h | ]}|v |         S r   r   )r   r  future_to_indexs     r%   r  z0execute_tool_calls_concurrent.<locals>.<setcomp>  s3     - - - ! O33 ,A.333rT   c                ,    g | ]}|         d          S r   r   )r   r  parsed_callss     r%   r  z1execute_tool_calls_concurrent.<locals>.<listcomp>  s2     * * * ! )OA.* * *rT   zIconcurrent tool batch timed out after %.1fs; %d tool(s) still running: %s   u   ⚡ Interrupt: cancelling z pending concurrent tool(s)forceg      @      c                @    g | ]}|v |                  d          S r"  r   )r   r  r   r#  s     r%   r  z1execute_tool_calls_concurrent.<locals>.<listcomp>#  s=     * * * ! O33 ));<Q?333rT   zconcurrent tools running (zs, z remaining: )waitcancel_futuresc              3     K   | ]}|dV  	d S )Nr   r   r   rs     r%   r   z0execute_tool_calls_concurrent.<locals>.<genexpr>9  s"      @@!!-A----@@rT   c              3  *   K   | ]}||d         V  d S )Nr  r   r-  s     r%   r   z0execute_tool_calls_concurrent.<locals>.<genexpr>:  s&      CCQQ]AaD]]]]CCrT   u   ⚡ /z tools completed in .1fzs totalszthe configured timeoutz': timed out after unknownr  tool_timeoutrs   ru   z*Tool execution cancelled by user interruptz!': thread did not return a resultthread_missing_resultfailedr   "Tool %s returned error (%.2fs): %s(file-mutation verifier record failed: %stool.completedr  r	  r`   Tool  completed in .2fTool result (	 chars): r`          ✅ Tool Result: s - tool completed:  (s)Tool complete callback error: content	tool_nametool_use_idenvconfig_tool_output_riskrisklowtool.output_riskrb   risk_metadata#Tool output risk callback error: %stool result rN  rO  )m
tool_callsr  r&   r   print
log_prefixappendr   functionr   r   rO   r7   r6   _turns_since_memory_iters_since_skillr   r~   TOOL_CALL_NAMEresolve_underlying_callr   r/   r5   r"   r   r    rn   rH   hermes_cli.pluginsr   _tool_guardrailsbefore_callallows_execution_guardrail_block_result_checkpoint_mgrr   getget_working_dir_for_pathensure_checkpointr   r<   r=   getcwdjoinr   	enumerate_redact_tool_args_for_displayverbose_loggingkeys_wrap_verboselog_prefix_charstool_progress_callback_build_tool_previewloggingr   tool_start_callback_current_toolr    _should_emit_quiet_tool_messages_should_start_quiet_spinnerrandomchoicer   get_waiting_faces	_print_fnr  setrF   ry   	monotonicmin_MAX_TOOL_WORKERStools.daemon_poolr  submitr   rU   rX   rB   rC   
concurrentfuturesr*  cancelr   r   rS   r   _vprintr!   shutdownsumstopr@   _append_guardrail_observationr   _record_file_mutation_result_get_cute_tool_message_impl_safe_printtool_complete_callbackr   r   r   _subdirectory_hintscheck_tool_callr   %_tool_result_content_for_active_model$_apply_pending_steer_to_tool_resultsr   )\r#   assistant_messagerG   ra   r   r   rY  	num_tools_tool_budgetr  r  r^   r_   malformed_args_result_ts_scope_blockr   _underlying_underlying_args_errr]   r  r  r   block_messageguardrail_decision	file_pathwork_dircmdcwdtool_names_strr  r   r  display_argsargs_strargs_previewpreviewcb_errr  spinnerfacerunnable_callsr  timed_out_indices	timeout_sdeadliner  r  executorabandon_executorsubmit_indexr  submit_errorskipped_calls	skipped_i_tcskipped_nameskipped_argsr`   _conc_start_interrupt_loggedwait_timeout	remainingr  not_done_still_runningworker_tidstid_conc_elapsed	completed	total_durr.  r   r   suffixfunction_resulttool_durationr	  	_err_textresult_preview_ver_errcute_msg_preview_strresponse_previewsubdir_hints_tool_contenttool_messagerU  turn_tool_msgsr   r#  r
  s\   ` ``                                                                                     @@@r%   execute_tool_calls_concurrentr  G  s	    #-JJI %U++L ! !SS9SSSTTT 	 	BOO4 f1Afff#)	      2Ar{/?AA    
 	 L a} a}	!*//D(0
 0
,, !,!!)	 	 	  H$$()E%%n,,'(E$$ 	000000 222696Q6QR_6`6`3-t 
/ 
/"&?&F&FFF(3(8*.*#!NK !N !N !N6
 ).+/ +/ +/  	 	 	D	 +S''/ D"55;+
 +
 +
'' $&*L)++#"3$Yb99?R --!%&6!7!7    %EEEEEE 6 6!!-3&ulB??E2!(D"!=!=!C#E+=rBBHb#*52KR#P#P#VTV%)*:%;%;	! 	! 	!  % % % $% (#z7M*BQVWWW-"/"/'&7!(D"!=!=!C$-"/%)*:%;%;     &+%;%G%GWd%e%e"): #(#@#@AS#T#TL+/(1&3&3+*;%,Yb%A%A%GR(#4&-.@)T&R&R&xVx)-.>)?)?     777E<Q<Y7 - 1 1&" = =I  e#(#8#Q#QR[#\#\-??JcTaJcJcddd    D 
**u/D/L*'++Ir::C.s33 +//	::dbiXZXaXcXc>d>d-??!?S"X!?!?   !   D 	Y}FVXdfz{|||| YYLL|LLLLLN 
X/CU K Ku T TN9NNnNNOOOYbcoqrYsYs 	X 	XUAUD$ 0,@T8tDDLLz,UCCCH$ XMQMM$MMl6G6G6I6I1J1JMMMNNNe))(DJ|TUdi4j4j4jkkllllLOPXMM\a\rLrLrx(?)?(?@5HH  yAVQVV$VVdiikk1B1BVVVVWWWWP\ 	I 	ILD$(,8L#' 	II<T4HHPD-dLAA,,^T7LYYYY I I IGvGGHHHHHHHHI	I Q] F FLD$(,8L#$ 	FF<T4HHPD))"%|DDDD F F FDFDDEEEEEEEEF		F fy GU^_kUlUl W WQQBd,l<P#lCtEUVGAJ )E	WyWW~WWXXXR R R R R R R Rj G--// E4U4U4W4W }]<>>??4 T Ti T T Tcity  uD  E  E  Ecc
 
]fgs]t]t
 
 

 &)ee466	3<3H4>##i//d R	c.113DEEK CBBBBB//KHHHH$H9B>9R9R #+ #+5L"51b$$OO7	BBAr4QUWcdeWfghWi  (   D\RR "!(6|}}(E>..  
 KX " "FIsL,&y193?	3J13M 0%`\ %` %` %` !'
 %1$0$*$'$($)$46"	 2 34 NN1%%%)*OA&& #ikk$)!Q#&L+$,t~/?/?$?	$>>-0UU 5 5+25 5 5(DD ,/|Y+G+GL-7-?-D-D ' .E . .ND(( *4);)@)@#\ *A * *h $ +0@0@H0L0L+/(- - - -%-- - -)
* * * *%6* * * ;% 122 IInRaR&899   "* ' 'AHHJJJJ"< K K*.u/I*J*JKK K K K K K K K K K K K K K K#. % %C% # 4 4T3 ? ? ? ?#, % % % $% 1 +/(0 04-!MM#(#3 !N !N#&x==!N !N !N&* *   
 "* ' 'AHHJJJJ #*//#/FFF$'	k(A$B$BM$q((]R-?!-C-C* * * * *%-* * *
 --[ [ ["8}}[ [:>))NSUTUSUDV:W:W[ [ [  ]Qp !!--#3 "    !!--#3 "    
  	c@@w@@@@@ICC'CCCCCILLa	aaIaa9aaaabbb	  	c@@w@@@@@ICC'CCCCCILLa	aaIaa9aaaabbbb		c V__kUlUl u@ u@QQBd,l<PAJ
 "!!!ai,5,A	(((((G_FXtXXPVXXO!*)""&"3$Rr228b )-!%&6!7!7    ")"2s33MMY) "l4"l"l"l-"&"&*&7!(T2!6!6!<"&3"N%)*:%;%;     #c4"b"b"b-"&"&*&7!(T2!6!6!<""6"1%)*:%;%;     MMpqmM=/=(T[]m ,%+" "'"E"E!!##	 #F # #  s4_EE	47	NNS4H4H4C4iC]Tacqrrr
  XX66%}ox    ! X X XM"LhWWWWWWWWX  Mu; MM00(-t!.. 1    
 ! M M MM"K6"K"KLLLLLLLLM $ `WmWW=WWWWXXX^c/.B.B^^_^^___ 1133 
	b24}UdeeeHo8oo....! 	bge5I5&Q&QUZ&Z&Z3ODDL$ bKAaCKK}KKKKLLLe))*lCCDDDDTWXdTeTehmh~T~T~<0G1G0G#H5#P#P  EQ `AaC``}```N^``aaa"NNNNNNNOOO 	I57 	II<T4HHPD,,RUD,XXXX I I IGvGGHHHHHHHHI ,O<<R3#011
 
 
 
 CR 	 0@@tLL 	0)/:: 0 2/<PPPP</ CCD/ZZ/E1	
 
 
 	%%%$(()<==%!!&))U22, 3
M,,&!#"/ -      M M MCVLLLLLLLLM-'''	
 	
 	
 	
 	228Q???? L!!I hIMM!9*++.N?P0Q0QZfgggg  HIMM228YGGGGGH HMMs  !A F
FF<A,I))I87I8"AN33
O ?O BQ
Q*)Q*:Y
Y=Y88Y=.[
[1[,,[1Br p 73b+*p +
d45A4d/)p /d44E)p j>2p >kp kp "k10p 1
k>;p =k>>Dp r p77r As&6z
z8z33z8{""
|,||B /AB0B0
ACB:ACCACG AG3G3
AHG=AHHAHc               5   CD t                     }t          |j        d          D ]7\  }D j        r|j        |dz
  d         }|r/                      j         dt          |           dd           |D ]R}	|	j        j        }
	                    t          |
d|
 d|	j        d	
                     t           d|
            S nDj        j        Ct          Dj        j                  \  }}|V	                    t          C|Dj                             t           dC                                 d           (d}	 ddlm} C|j        k    r9|                    |          \  }}}|s|r|t)                     v r|C|}nd| d}n# t*          $ r Y nw xY wt-           C|t/          Ddd          pd          \  }}d}d}||}d}n~	 ddlm}  |C|pdt/           dd          pdt/          Ddd          pdt/           dd          pdt/           dd          pdt5          |                    }n# t*          $ r Y nw xY wd}|$ j                            C|          }|j        s|}|dup|du}|rnCdk    rd _        nCdk    rd _         j         st/           dd          d k    rtC          C|          p|}tE          j#        |d!"          } j$        rqtK          d#| d$C d%t5          |&                                           d&           tK           '                    d'tE          j#        |d(d!)                               nft          |           j(        k    r|d j(                 d*z   n|}tK          d#| d$C d%t5          |&                                           d+|            |sC _)         *                    d,C            |s(	 dd-l+m,}  | j*                   n# t*          $ r Y nw xY w|sq j-        rj	 tC          C|          p|}t]          C|          } -                    d.C||           n.# t*          $ r!}t_          j0        d/|            Y d}~nd}~ww xY w|se j1        r^	 tC          C|          p|} 1                    Dj        C|           n.# t*          $ r!}t_          j0        d0|            Y d}~nd}~ww xY w|srCd1v rn j2        j3        rb	 |4                    d2d          }|r8 j2        5                    |          }  j2        6                    | d3C            n# t*          $ r Y nw xY w|sCd4k    r j2        j3        r	 |4                    d5d          }!to          |!          ra|4                    d6          p%tq          j9        d7tq          j:                              }" j2        6                    |"d8|!dd9                     n# t*          $ r Y nw xY wtw          j;                    }#|StE          j#        d:|id!"          }$d;}%ty           C||$t/          Ddd          pdd<||t5          |          =
  
         n|a =                    |          }$d;}%ty           C||$t/          Ddd          pdd<d>t/          |d?d          pd@t5          |          =
  
         nwCdAk    rd fdF}&t}           C|t/          Ddd          pd|&G          \  }$}tw          j;                    |#z
  }% ?                                r)                     dHt          dA||%|$I                      nCdJk    rd fdK}&t}           C|t/          Ddd          pd|&G          \  }$}tw          j;                    |#z
  }% ?                                r)                     dHt          dJ||%|$I                      ncCdk    rd DfdL}&t}           C|t/          Ddd          pd|&G          \  }$}tw          j;                    |#z
  }% ?                                r)                     dHt          d||%|$I                      n׉CdMk    rd fdN}&t}           C|t/          Ddd          pd|&G          \  }$}tw          j;                    |#z
  }% ?                                r)                     dHt          dM||%|$I                      nMCdOk    rd fdP}&t}           C|t/          Ddd          pd|&G          \  }$}tw          j;                    |#z
  }% ?                                r)                     dHt          dO||%|$I                      
nÉCdQk    r|4                    dR          }'|'r)t          |'t4                    rdSt          |'           dT}(n)|4                    dU          pdddV         })|)rdW|) dXndY}(d}* ?                                ri B                                rUt          jD        t          jF                              }+t          |+ dZ|( d[ jG        \          }*|*H                                 |* _I        d},	 d fd]}&t}           C|t/          Ddd          pd|&G          \  }$}|$},d _I        tw          j;                    |#z
  }%t          dQ||%|,I          }-|*r|*J                    |-           	nP ?                                r                     dH|-            	n"# d _I        tw          j;                    |#z
  }%t          dQ||%|,I          }-|*r|*J                    |-           w  ?                                r                     dH|-            w w xY w jK        rC jK        v rd}* ?                                rt          jD        t          jF                              }+t          C          }.tC          C|          p|}t          C|          pC}t          |+ dZ|. dZ| d[ jG        \          }*|*H                                 d}/	 d Cfd^}&t}           C|t/          Ddd          pd|&G          \  }$}|$}/nQ# t*          $ rD}0tE          j#        d:d_C d`|0 i          }$t          O                    daC|0db           Y d}0~0nd}0~0ww xY wtw          j;                    |#z
  }%t          C||%|/I          }-|*r|*J                    |-           n+ ?                                r                     dH|-            n# tw          j;                    |#z
  }%t          C||%|/I          }-|*r|*J                    |-           w  ?                                r                     dH|-            w w xY w jP        r: jP        Q                    C          rd}* ?                                r B                                rt          jD        t          jF                              }+t          C          }.tC          C|          p|}t          C|          pC}t          |+ dZ|. dZ| d[ jG        \          }*|*H                                 d}1	 d Cfdc}&t}           C|t/          Ddd          pd|&G          \  }$}|$}1nQ# t*          $ rD}0tE          j#        d:ddC d`|0 i          }$t          O                    deC|0db           Y d}0~0nd}0~0ww xY wtw          j;                    |#z
  }%t          C||%|1I          }-|*r|*J                    |-           n ?                                r                     dH|-            n# tw          j;                    |#z
  }%t          C||%|1I          }-|*r|*J                    |-           w  ?                                r                     dH|-            w w xY w j         rd}* ?                                r B                                rt          jD        t          jF                              }+t          C          }.tC          C|          p|}t          C|          pC}t          |+ dZ|. dZ| d[ jG        \          }*|*H                                 d}2	 t                      S                    C|Dj         jT        pdt/           dd          pdt/           dd          pd jU        rt5           jU                  ndddt/           dfd          t/           dgd          t5          |          h          }$|$}2n# t          $ r_ t           C|t/          Ddd          pd|#t5          |          i          }$|$}2	  X                    dj           n# t*          $ r Y nw xY w t*          $ r0}0dkC dl|0 }$t          O                    dmC|0db           Y d}0~0nd}0~0ww xY wtw          j;                    |#z
  }%t          C||%|2I          }-|*r|*J                    |-           n ?                                r                     dH|-            n# tw          j;                    |#z
  }%t          C||%|2I          }-|*r|*J                    |-           w  ?                                r                     dH|-            w w xY w	 t                      S                    C|Dj         jT        pdt/           dd          pdt/           dd          pd jU        rt5           jU                  ndddt/           dfd          t/           dgd          t5          |          h          }$n# t          $ r] t           C|t/          Ddd          pd|#t5          |          i           	  X                    dj           n# t*          $ r Y nw xY w t*          $ r0}0dkC dl|0 }$t          O                    dmC|0db           Y d}0~0nd}0~0ww xY wtw          j;                    |#z
  }%t          |$t                    r8 j$        r|$nt          |$          dnk    r
|$ddn         n|$}3t          |$          }4n|$}3t          t          |$                    }4t          C|$          \  }5}6ddol[m\}7 | o |7 C          }8|8rEty           C||$t/          Ddd          pdt          |%dpz            t5          |          q           |sA ^                    C||$|5r          }$ j$        r|$nt          |$          dnk    r
|$ddn         n|$}3|5rt          _                    dsC|%|3           nt          `                    dtC|%|4           |sF	  a                    C||$|5           n,# t*          $ r}9t_          j0        du|9           Y d}9~9nd}9~9ww xY w|sS j-        rL	  -                    dvCdd|%|5|$w           n.# t*          $ r!}t_          j0        d/|            Y d}~nd}~ww xY wd _)         *                    dxC dy|%dzd{            j$        rRt_          j0        d|C d}|%d~d           t          |$          }:t_          j0        dt          |:           d|:            |sf jc        r_	 tC          C|          p|} c                    Dj        C||$           n.# t*          $ r!}t_          j0        d|            Y d}~nd}~ww xY wt          |$          s&t          |$CDj        t                    |          n|$}$ jg        h                    C|          };|;r%t          |$          rt          |$|;           n|$|;z  }$ j                    C|$          }<t          C|<Dj                  }=	                    |=           |=4                    d          }>|>n|>4                    d          dk    rU j-        rN	  -                    dCddDj        |>           n,# t*          $ r}t_          j0        d|           Y d}~nd}~ww xY wt           dC                                 d            j         st/           dd          d k    r j$        r;tK          d| d}|%d~d           tK           '                    d|$                     nkt          |$t                    r|$nt          |$          }?t          |?           j(        k    r|?d j(                 d*z   n|?}@tK          d| d}|%d~d|@             j        r|t          |j                  k     rt          |j                  |z
  }A                      j         d|A dd           |j        |d         D ]R}	|	j        j        }
	                    t          |
d|
 d|	j        d	
                     t           d|
            S n> jk        dk    r1|t          |j                  k     rtw          jl         jk                   9t          |j                  }B|r.|Bdk    r(t          |B d         t                    |           |r|Bdk    r                     |B           dS dS dS )uB  Execute tool calls sequentially (original behavior). Used for single calls or interactive tools.

    ``finalize=False`` skips the end-of-batch aggregate budget enforcement
    and /steer injection — used when this call is one segment of a larger
    mixed batch and the segmented dispatcher owns the turn-end work.
    r   Nr   r   Tr%  r   r   r   r   r   r   zinvalid tool arguments r   r}   r   r   r   r;   r   r   r   r   rg   rh   ri   r   r   r   r   r   r   Fr-   r   r   r   r   r   r   r   r   r   zexecuting tool: r   r   r   r   >   r   r   r   r   r   r   r   r   r   r   r+   r   r   r   r   r,   r   todor   r4   r   r   c                    ddl m}  ||                     d          |                     dd          j                  S )Nr   )	todo_tooltodosmergeF)r  r  store)tools.todo_toolr  rh  _todo_store)r   
_todo_toolr#   s     r%   r   z/execute_tool_calls_sequential.<locals>._execute  sT    CCCCCC!z#--00#--77+   rT   )r^   r_   ra   rb   r   rB  rA  session_searchc                                                    }|s%ddlm} t          j        d |            d          S ddlm}  ||                     dd          |                     d          |                     d	d
          |                     d          |                     d          |                     dd          |                     d          |j        	  	        S )Nr   )format_session_db_unavailableF)successr+   )r  queryr;   role_filterlimitr  rg   around_message_idwindowr$  sort)	r  r  r  rg   r  r  r  dbcurrent_session_id)	_get_session_db_for_recallhermes_stater  r/   r5   tools.session_search_toolr  rh  rg   )r   
session_dbr  _session_searchr#   s       r%   r   z/execute_tool_calls_sequential.<locals>._execute  s    "==??
! dJJJJJJ:%B_B_BaBa&b&bcccWWWWWW&#--44 )m < <#--33(}}\::&/mm4G&H&H$==155"v..!','7
 
 
 
rT   c                Z   |                      dd          }|                      d          }ddlm}  ||                      d          ||                      d          |                      d          |j        	          }j        r"j                            || fd
           |S )Ntargetr   
operationsr   )memory_toolactionrK  old_text)r  r  rK  r  r  r  c                 P                          t          dd                     S )Nr   )rj   rb   )_build_memory_write_metadatar    )r#   ra   r  s   r%   <lambda>zAexecute_tool_calls_sequential.<locals>._execute.<locals>.<lambda>#  s/    u/Q/Q$5)0D$)G)G 0R 0 0 rT   )build_metadata)rh  tools.memory_toolr  _memory_store_memory_managernotify_memory_tool_write)r   r  r  _memory_toolr`   r#   ra   r  s        r%   r   z/execute_tool_calls_sequential.<locals>._execute  s    "x::&]]<88
IIIIII%$==22!%MM)44&]]:66)-   ( )BB!( ( ( ( ( ( C    rT   clarifyc                    ddl m}  ||                     dd          |                     d          j                  S )Nr   )clarify_toolquestionr;   choices)r  r  callback)tools.clarify_toolr  rh  clarify_callback)r   _clarify_toolr#   s     r%   r   z/execute_tool_calls_sequential.<locals>._execute5  sT    LLLLLL$}&]]:r::%MM)44"3   rT   read_terminalc           	         ddl m}  ||                     d          |                     d          t          dd                     S )Nr   )read_terminal_tool
start_linecountread_terminal_callback)r  r  r  )tools.read_terminal_toolr  rh  r    )r   _read_terminal_toolr#   s     r%   r   z/execute_tool_calls_sequential.<locals>._executeH  s]    ^^^^^^**(}}\::#--00$U,DdKK   rT   delegate_tasktasksu   🔀 delegating u    tasks · (/agents to monitor)goalr'  u   🔀 u    · (/agents to monitor)u'   🔀 delegating · (/agents to monitor) r  r  c                .                         |           S r   )_dispatch_delegate_task)r   r#   s    r%   r   z/execute_tool_calls_sequential.<locals>._executem  s     88CCCrT   c                >    j                             |           S )N)rG   )r   handle_tool_call)r   r#   r^   rG   s    r%   r   z/execute_tool_calls_sequential.<locals>._execute  s#     3DD]T]hpDqqqrT   zContext engine tool 'z
' failed: z1context_engine.handle_tool_call raised for %s: %sr   c                :    j                             |           S r   )r  r  )r   r#   r^   s    r%   r   z/execute_tool_calls_sequential.<locals>._execute  s     0AA-QZ[[[rT   zMemory tool 'z1memory_manager.handle_tool_call raised for %s: %sr   r   )
rb   rg   rk   rl   enabled_toolsskip_pre_tool_call_hookr   r   r   r   r   r   r   r   z&handle_function_call raised for %s: %sr   )!agent_runtime_owns_post_tool_hookrx   )r^   r_   r`   ra   rb   rY   r]   r6  r8  r   r9  r:  r;  rF  rG  r1  rH  r<  r=  r>  r2  r?  r@  rI  rJ  rP  rQ  rR  rS  rT  rV  rW  rC  rD  rE  z remaining tool call(s)u   [Tool execution skipped — z* was not started. User sent a new message]zskipped tool result rX  r   )nr&   rm  rY  r   r  r[  r  r]  r   r\  r   r   rO   r7   r6   r  r   r~   r`  ra  r   r"   r   r    rb  r   rH   rc  rd  re  r^  r_  r   rn  r/   r5   ro  rZ  rp  rq  rr  rw  r   r   r   rs  rt  ru  r   rv  rg  r   rh  ri  rj  r   r<   r=   rk  ry   rn   rf  r   rx  r  r3   ry  rz  r{  r   r|  r}  r  _delegate_spinnerr  _context_engine_tool_names_get_tool_emoji_build_tool_labelrB   r+   r  has_toolrS   handle_function_callrg   valid_tool_namesr   rz   r   rJ   r   agent.agent_runtime_helpersr  r!   r  rC   r   r  r   r  r   r   r   r  r  r   r  
tool_delaysleepr   )Er#   r  rG   ra   r   r   r  r  remaining_calls
skipped_tcr  r_   r  r  r   r  r  r  r]   
_block_msg_block_error_typer   _guardrail_block_decisionr  _execution_blockedr  r  r  r   r  r  r  r  r  r  tool_start_timer  r  r   	tasks_argspinner_labelgoal_previewr  r  _delegate_resultr  emoji
_ce_resultr  _mem_result_spinner_resultr  _result_len_is_error_resultr   r  _executor_must_emit_post_hookr  _log_resultr  r  r  rU  _fr_strr  r  num_tools_seqr^   r  sE   ` ``                                                               @@r%   execute_tool_calls_sequentialr6    s#    %U++L!"3">BB q
) q
)9 % 	/:1Q344@O |!1nn3K_K_nnnvz{{{-  
)27 8 f\fffM'-	! ! !    6A<AA    
 E!*//D(0
 0
,, !,OO(!)L    2???   
 66xCCC
 *.	000000 222696Q6QR_6`6`3-t  "&?&F&FFF(3(8J J J J (  	 	 	D	 +S''/ D"55;+
 +
 +
'' %)
*&(J 2EEEEEE33!!-3&ulB??E2!(D"!=!=!C#E+=rBBHb#*52KR#P#P#VTV%)*:%;%;	 	 	

     CG!!&!7!C!CMS`!a!a%6 ?,>)'t3\7PX\7\ 	) h&&()E%%n,,'(E$ 	jGE3G$O$OSX$X$X8VVgZgLz,UCCCH$ jVQVV-VV$|?P?P?R?R:S:SVVVWWWe))(DJ|TUdi4j4j4jkkllllLOPXMM\a\rLrLrx(?)?(?@5HH  yAhQhh-hh$}?Q?Q?S?S:T:ThhZfhhiii! 	F"/E!!"D]"D"DEEE
 " 	IIIIII%%e&;<<<<    " 	Ie&B 	II<]MZZk^k-m\JJ,,^]GUabbbb I I IGvGGHHHHHHHHI " 	Fe&? 	FF<]MZZk^k))),|TTTT F F FDFDDEEEEEEEEF " 		m7N&N&NSXShSp&N)--fb99	 $4MMiXXH);; ";M";";       " 		mz&A&AeF[Fc&A#''	266*3// '++I66`")NTVT]T_T_:`:`C);;;SbS;;       )++!"j':)>USSSOM)++&"3$Yb99?R ,(!%&6!7!7     '2 $;;<UVVOM)++&"3$Yb99?R ,%&?DQQwUw!%&6!7!7     f$$      .R++"3$Yb99?R . . .*O] !IKK/9M5577 @~#>v}Vcl{#|#|#|~~...     " .R++"3$Yb99?R . . .*O] !IKK/9M5577 J  I#>?OQ^`m  wF  $G  $G  $G  I  I  J  J  Jh&&       2 .R++"3$Yb99?R . . .*O] !IKK/9M5577 B  A#>xXen}#~#~#~  A  A  B  B  Bi''      .R++"3$Yb99?R . . .*O] !IKK/9M5577 C  B#>y-Yfo~###  B  B  C  C  Co--      .R++"3$Yb99?R . . .*O] !IKK/9M5577 I  H#>P]_l  vE  $F  $F  $F  H  H  I  I  Io--%))'22I Z	488  a3y>> a a a - 1 1& 9 9 ?R"E $CBLBBBBB 
 G5577  E<]<]<_<_  }]%D%F%FGG'4(A(A-(A(APVafapqqq&-E##3D D D D D D1U"/"/&7!(D"!=!=!C$2 2 2. $3 *.' $	o =6Wdm}~~~ 3LL****;;== 3MM/x//222 +/' $	o =6Wdm}~~~ 3LL****;;== 3MM/x//22223- W	:-5Cc2c2cG5577  }]%D%F%FGG'66<]MZZk^k+M<HHYM'4(C(C%(C(C'(C(CRXchcrsssJ3r r r r r r r r1U"/"/&7!(D"!=!=!C$2 2 2. -

 | | |"&*g7t}7t7thr7t7t-u"v"vPR_akvz{{{{{{{{| !%	o =6}mUbkuvvv 3LL****;;== 3MM/x//222 !%	o =6}mUbkuvvv 3LL****;;== 3MM/x//22223" v	:u'<'E'Em'T'T v	: G5577  E<]<]<_<_  }]%D%F%FGG'66<]MZZk^k+M<HHYM'4(C(C%(C(C'(C(CRXchcrsssK3\ \ \ \ \ \ \1U"/"/&7!(D"!=!=!C$2 2 2. . | | |"&*g7l}7l7l`j7l7l-m"n"nPR_akvz{{{{{{{{| !%	o =6}mUbkvwww 3LL****;;== 3MM/x//222 !%	o =6}mUbkvwww 3LL****;;== 3MM/x//22223 T	:G5577  E<]<]<_<_  }]%D%F%FGG'66<]MZZk^k+M<HHYM'4(C(C%(C(C'(C(CRXchcrsss"O(3"%%%"<"<!=2C!*$/52#E+=rBBHb#*52KR#P#P#VTVBGBX"b$u'=">">">^b,015%,U4F%M%M&-e5H$&O&O267G2H2H #= # # #2$   "I"/"/&7!(D"!=!=!C.%)*:%;%;# # # #2OO$89999    D q q q"Y="Y"YZ"Y"YE}V`koppppppppq !%	o =6}mUbkz{{{ 3LL****;;== 3MM/x//222 !%	o =6}mUbkz{{{ 3LL****;;== 3MM/x//22223q"%%%"<"<!=2C!*$/52#E+=rBBHb#*52KR#P#P#VTVBGBX"b$u'=">">">^b,015%,U4F%M%M&-e5H$&O&O267G2H2H #= # # %   7"/"/&7!(D"!=!=!C.%)*:%;%;   OO$89999    D q q q"Y="Y"YZ"Y"YE}V`koppppppppq !IKK/9Mos++ 	4050E __),_)=)=)C)C%%  o..KK -Nc/2233K 3=/RR! 	RQQQQQ"" H11%GG 	& ) 
	)++&"3$Yb99?R 455!%&6!7!7	 	 	 	 " 		#AA'	 B  O 160E __),_)=)=)C)C%%   	jNN?P]_mnnnnKK=}m]hiii " 	TT22!=/CS     T T TH(SSSSSSSST " 	Ie&B 	II,,$mT4*5E* -    
  I I IGvGGHHHHHHHHI #WWW-WWWWXXX  	TMS-SS}SSSSTTT2?CCKMR#k*:*:RR[RRSSS! 	Ie&B 	II<]MZZk^k,,Y\=,Xghhhh I I IGvGGHHHHHHHHI ,O<<R3##!011
 
 
 
 CR 	 0@@P]^^ 	0)/:: 01/<PPPP</ CCMSbcc/}il[[%%%$(()<==%!!&))U22, 3
M,,&!!*"/ -      M M MCVLLLLLLLLM-000	
 	
 	
 	
 	228Q??? 	`GE3G$O$OSX$X$X$ `IAII]IIIIJJJe))*oFFGGGG-7-M-Mg//SVWfSgSgORSZ||^c^tOtOt7+BE,B+B#Ce#K#K  {B ^A^^]^^^L\^^___% 	!c2C2N.O.O*O*O-899A=IMMU-iiyiiiquMvvv/:122>  
)27 8 k<kkkM'-	! ! !    6???    
 EaA,=,H(I(I$I$IJu'((( )455M sMA%%Hm^__5>J[;\;\eqrrrr
  LMA%%228]KKKKKL L%%sB  A
F  
F-,F-$A,I
II7P
PP(:Q##
R-R		R.S


S5S00S5AU
U)(U)BX
XX1l88A7n/(3ru
s*&:s% u%s**uA0w+2{~
|,(:|'"~'|,,~A0A@CB$AE7E6AJE7A AHF8AGGAHG
AGGAHGAGGAHG(&AHHAJHAHHAJJA0AK;K?B"AN"N">AQO!AO7O6AQO7
APPAQPAPPAQP&AP<P<AQV7AWW
AW9WAW4W4AW9XAX#X#
AYX-AY	Y	AY[/A\\
A\3\A\.\.A\3`( Aa	a	
Aa2aAa-a-Aa2c           	        ddl m} |Dt          |          }||j        rt	          |j                  nd}t          |j        |          }|D ]O\  }	}
 |t          |
                    }|	dk    rt          | ||||d           :t          | ||||d           Pt          |j                  }|dk    rOt          |           }t          || d         t          |          |	           |                     ||           dS dS )
u  Execute a mixed tool-call batch as ordered parallel/sequential segments.

    ``segments`` is the ``(kind, calls)`` plan from
    ``_plan_tool_batch_segments``: maximal contiguous runs of parallel-safe
    calls execute on the concurrent path, barrier calls on the sequential
    path, strictly in the model's original call order. Because segments are
    contiguous, every tool result is still appended one-per-call in emission
    order and no call ever starts before an earlier barrier finishes —
    identical ordering and side-effect boundaries to fully-sequential
    execution, with I/O parallelism recovered inside the safe runs.

    Turn-end work (aggregate budget enforcement + /steer injection) is done
    once here for the WHOLE batch; the per-segment executor calls run with
    ``finalize=False`` so a multi-segment turn cannot multiply the budget or
    truncate a steer marker.

    Interrupt semantics: each segment executor already checks
    ``agent._interrupt_requested`` up front and appends a cancelled/skipped
    result per call, so an interrupt during segment *k* drains segments
    *k+1..n* without executing them while preserving one result per
    tool_call_id.
    r   )SimpleNamespaceN)execution_cwd)rY  parallelFr   rX  )typesr8  r   r  r   r   rY  rH   r  r6  r  r&   r   r  )r#   r  rG   ra   r   segmentsr8  _active_env	_exec_cwdkindcallssegment_messagetotal_toolsr  s                 r%   execute_tool_calls_segmentedrC    sr   . &%%%%%$%677-8-D-DD)))^b	,->-IYbccc  e)/T%[[AAA:)2C^    
 *2C^     '233KQ(//k\]]#011	
 	
 	
 	

 	228[IIIII rT   )r  r6  rC  )r   r   )r(   r   r   r)   )r   r8   )rG   rH   rI   rJ   r   rK   )rN   rU   r   rV   )r^   rJ   r_   r4   r`   r   ra   rJ   rb   rJ   rY   r!   rZ   rc   r[   rc   r\   rc   r]   rd   r   rK   )ro   )rp   rJ   r   rJ   )r^   rJ   r_   r4   ra   rJ   rb   rJ   rv   r@   rp   rJ   r[   rJ   r]   rd   r   rJ   )r   r{   )
r^   rJ   r_   r4   ra   rJ   rb   rJ   r   r   )
r^   rJ   r_   r4   ra   rJ   rb   rJ   r   r   )r   )
rG   rH   ra   rJ   r   r!   r   rV   r   rK   )r   N)rG   rH   ra   rJ   r   r!   r   rK   )F__doc__
__future__r   concurrent.futuresr  r/   pathlibr   ru  r<   rz  r   ry   typingr   r   agent.displayr   r   rt  r	   r  r
   r  r   r  r   rn  r   agent.tool_guardrailsr   agent.tool_dispatch_helpersr   r   r   r   r   r   tools.terminal_toolr   tools.thread_contextr   tools.tool_result_storager   r   tools.budget_configr   r   r   	getLogger__name__rB   r&   r  r?   r7   rF   rO   rS   rX   rn   rt   rz   r   r   r   r  r6  rC  __all__r   rT   r%   <module>rS     s  
 
 # " " " " "             				                                        8 7 7 7 7 7                     = < < < < <        X W W W W W W W W W		8	$	$   "   &+ "   &   $\ \ \ \&  P P P P ! $7;           F    $ #*7;     :. . . .b! ! ! !6! ! ! !@y
H  RV y
H y
H y
H y
H y
H y
HzEL  RV EL EL EL EL EL ELT4J 4J 4J 4J 4Jn  rT   