6060 SessionItem as SessionItem ,
6161 WebSearchCallItem ,
6262)
63- from ._function_tools import FunctionTool as FunctionTool , Tool as Tool , ToolContext as ToolContext
63+ from ._function_tools import (
64+ FunctionTool as FunctionTool ,
65+ Tool as Tool ,
66+ ToolContext as ToolContext ,
67+ ToolTimeoutError as ToolTimeoutError ,
68+ )
6469from ._history import project_history as project_history
6570from ._lifecycle import (
6671 _close_after_error as _close_after_error ,
@@ -8456,6 +8461,7 @@ async def _invoke_tool_body(
84568461 args = (context ,)
84578462 if not self ._admit_tool (state , request ):
84588463 return
8464+ timeout_output : ToolOutput | None = None
84598465 duration = entry .callback_timeout
84608466 if duration is None :
84618467 value = await _call_callback (
@@ -8464,12 +8470,84 @@ async def _invoke_tool_body(
84648470 * args ,
84658471 ** kwargs ,
84668472 )
8473+ elif entry .timeout_behavior == "error_as_result" :
8474+ loop = asyncio .get_running_loop ()
8475+ cutoff = loop .time () + duration
8476+ expired = False
8477+ timeout_error = ToolTimeoutError (entry .name , duration )
8478+
8479+ def admit_body () -> bool :
8480+ return not expired and self ._admit_tool (state , request )
8481+
8482+ def expire_body (cancel_body : bool = True ) -> None :
8483+ nonlocal expired
8484+ if self ._closing or state .stopping or state .failure .done ():
8485+ return
8486+ expired = True
8487+ if cancel_body :
8488+ cancel_once (body )
8489+
8490+ timer = loop .call_at (cutoff , expire_body )
8491+
8492+ async def invoke_body () -> Any :
8493+ try :
8494+ if admit_body ():
8495+ return await _call_callback (entry .callback , admit_body , * args , ** kwargs )
8496+ return None
8497+ finally :
8498+ timer .cancel ()
8499+ # Settle at body exit, before unrelated ready work can
8500+ # delay the parent. Busy callbacks may outlast the timer.
8501+ if loop .time () >= cutoff :
8502+ expire_body (cancel_body = False )
8503+
8504+ try :
8505+ body = asyncio .create_task (invoke_body ())
8506+ try :
8507+ # Do not let parent cancellation cancel an already
8508+ # unwinding body a second time and cut cleanup short.
8509+ await asyncio .wait ((body ,))
8510+ except BaseException as error :
8511+ cancel_once (body )
8512+
8513+ async def join_body () -> None :
8514+ await _join (body )
8515+
8516+ await _close_after_error (error , join_body )
8517+ raise
8518+ finally :
8519+ timer .cancel ()
8520+ body_error = None if body .cancelled () else body .exception ()
8521+ if not self ._admit_tool (state , request ):
8522+ return
8523+ if expired :
8524+ if body_error is not None :
8525+ timeout_error .__cause__ = body_error
8526+ # No late value is validated or serialized. Format only
8527+ # under the still-live parent's native admission.
8528+ text = str (timeout_error )
8529+ if entry .timeout_error_function is not None :
8530+ text = await _call_callback (
8531+ entry .timeout_error_function ,
8532+ lambda : self ._admit_tool (state , request ),
8533+ context ,
8534+ timeout_error ,
8535+ )
8536+ if not self ._admit_tool (state , request ):
8537+ return
8538+ if not isinstance (text , str ):
8539+ raise TypeError ("Function timeout_error_function must return str" )
8540+ timeout_output = ToolOutput .error (text )
8541+ timeout_output ._validate ()
8542+ value = None
8543+ else :
8544+ value = body .result ()
84678545 else :
84688546 loop = asyncio .get_running_loop ()
84698547 cutoff = loop .time () + duration
84708548 callback_task = asyncio .current_task ()
84718549 assert callback_task is not None
8472- timeout_error = TimeoutError ( f"Tool { entry .name !r } exceeded its callback timeout" )
8550+ timeout_error = ToolTimeoutError ( entry .name , duration )
84738551
84748552 def expire_callback (cancel_body : bool = True ) -> None :
84758553 if self ._closing or state .stopping or state .failure .done ():
@@ -8494,26 +8572,27 @@ def expire_callback(cancel_body: bool = True) -> None:
84948572 expire_callback (cancel_body = False )
84958573 if not self ._admit_tool (state , request ):
84968574 return
8497- output : ToolOutput | None = None
8498- try :
8499- value = entry .output_adapter .validate_python (value )
8500- if isinstance (value , ToolOutput ):
8501- output = value
8502- else :
8503- wire = entry .output_adapter .dump_json (value , warnings = "error" ).decode ()
8504- # Declared strings retain raw text; other results keep JSON wire semantics.
8505- text = json .loads (wire ) if isinstance (value , str ) else wire
8506- output = ToolOutput .text (text if isinstance (text , str ) else wire )
8507- del wire , text
8508- output ._validate ()
8509- except Exception :
8510- output = None
8511- if output is None :
8512- # End ownership of the original admission request and every
8513- # invocation data reference without altering caller-owned objects.
8514- del request , message , raw_arguments , parsed , kwargs , context , args , value
8515- raise ValueError ("Tool result failed validation" )
8516- if entry .after is not None :
8575+ output : ToolOutput | None = timeout_output
8576+ if timeout_output is None :
8577+ try :
8578+ value = entry .output_adapter .validate_python (value )
8579+ if isinstance (value , ToolOutput ):
8580+ output = value
8581+ else :
8582+ wire = entry .output_adapter .dump_json (value , warnings = "error" ).decode ()
8583+ # Declared strings retain raw text; other results keep JSON wire semantics.
8584+ text = json .loads (wire ) if isinstance (value , str ) else wire
8585+ output = ToolOutput .text (text if isinstance (text , str ) else wire )
8586+ del wire , text
8587+ output ._validate ()
8588+ except Exception :
8589+ output = None
8590+ if output is None :
8591+ # End ownership of the original admission request and every
8592+ # invocation data reference without altering caller-owned objects.
8593+ del request , message , raw_arguments , parsed , kwargs , context , args , value
8594+ raise ValueError ("Tool result failed validation" )
8595+ if entry .after is not None and timeout_output is None :
85178596 output = await _call_callback (
85188597 entry .after , lambda : self ._admit_tool (state , request ), context , output
85198598 )
@@ -8529,6 +8608,7 @@ def expire_callback(cancel_body: bool = True) -> None:
85298608 # The hook may have mutated the original callback result.
85308609 del request , message , raw_arguments , parsed , kwargs , context , args , value
85318610 raise ValueError ("Tool result failed validation" )
8611+ assert output is not None
85328612 reply = json .dumps ({"request" : message , "response" : output .to_native ()})
85338613 if not self ._admit_tool (state , request ):
85348614 return
0 commit comments