ó
    °"³j=È  ã                  óŠ  • % S SK Jr  S SKrS SKrS SKrS SKrS SKJrJ	r	J
r
JrJrJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJrJrJrJr  S S	KJrJr  S S
KJrJr  S SK J!r!  SSK"J#r#J$r%  SSK&J'r'J(r(J)r)  SSK*J+r+  SSK,J-r-  \S\.\S4   \/\0\4   /\
\   4   r1 \(       a@  SSK2J3r3  SSK4J5r5  SSK6J7r7  SSK8J9r9  SSK:J;r;  SSK<J=r=J>r>  SSK?J@r@  SSKAJBrB  SSKCJDrD  SSKEJFrFJGrG  \" S\HSS9rI \" S \HSS!9rJ \" S"\%R–                  S#9rL\" S$\%Rš                  S#9rN " S% S&\O\%R                      5      rQS8S' jrR      S9S( jrS\R¨                  " SS)9 " S* S+5      5       rU\R¨                  " S,SS-9 " S. S/\\J   5      5       rV\VR®                  rX\" \X5      SS0.       S:S1 jj5       rY\Y\VlW        \" S2SS39rZS4\[S5'    S;S6 jr\\S<S7 j5       r]g)=é    )ÚannotationsN)ÚAsyncIterableÚAsyncIteratorÚ	AwaitableÚCallableÚ	GeneratorÚSequence)Úcontextmanager)Ú
ContextVar)Úfield)Úwraps)ÚTYPE_CHECKINGÚAnyÚGenericÚoverload)Ú
NoOpTracerÚTracer)ÚTypeVarÚ
deprecated)ÚDEFAULT_INSTRUMENTATION_VERSIONé   )Ú_utilsÚmessages)ÚEnqueueContentÚPendingMessageÚPendingMessagePriority)ÚPydanticAIDeprecationWarning)Ú	UserErrorúRunContext[Any].)ÚRunCancellation)ÚAgent)ÚAbstractCapability)ÚRunHeldToolset)ÚAbstractModel)ÚRealtimeModelSettingsÚRealtimeSession)ÚModelSettings)ÚToolManager)ÚToolDefinition)ÚRunUsageÚUsageLimitsÚ
AgentDepsTT)ÚdefaultÚcontravariantÚRunContextAgentDepsT)r-   Ú	covariantÚCustomEventT)ÚboundÚCapabilityEventTc                  óH   ^ • \ rS rSrSrSrSSU 4S jjjrSU 4S jjrSrU =r	$ )	ÚEventStreamBufferé4   a  The run's event buffer, notifying waiting stream mergers as soon as an event lands.

Extends `list` so graph-state persistence serializes it transparently; a buffer revived as a
plain list degrades to draining at stream position instead of waking a blocked stream merger.
)Úwaitersc                ó2   >• [         TU ]  U5        / U l        g ©N)ÚsuperÚ__init__r7   )ÚselfÚiterableÚ	__class__s     €ÚU/home/mande/repo/quber/.venv/lib/python3.13/site-packages/pydantic_ai/_run_context.pyr;   ÚEventStreamBuffer.__init__=   s   ø€ Ü‰Ñ˜Ô"Ø,.ˆ�ó    c                ój   >• [         TU ]  U5        U R                   H  nUR                  5         M     g r9   )r:   Úappendr7   Úset)r<   ÚeventÚwaiterr>   s      €r?   rC   ÚEventStreamBuffer.appendA   s&   ø€ Ü‰‰�uÔØ—l”lˆFØ�J‰JŽLò #rA   )© )r=   z$Sequence[_messages.AgentStreamEvent]©rE   ú_messages.AgentStreamEventÚreturnÚNone)
Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__Ú	__slots__r;   rC   Ú__static_attributes__Ú__classcell__)r>   s   @r?   r5   r5   4   s#   ø† ñð €I÷/ñ /÷õ rA   r5   c              ƒ  óÆ  #   • [        U[        R                  5      (       a  UR                  S:w  a  g[        R
                  " 5       nU R                  R                  [        U5      / 5      R                  U5         U R                  nUb-  UR                  U5      (       a  UR                  XS9I Sh  v•N   UR                  5         g N! UR                  5         f = f7f)zYDispatch an immediately dispatched capability event and mark it for stream deduplication.Ú	immediateN©rE   )Ú
isinstanceÚ	_messagesÚCapabilityEventÚevent_dispatchÚasyncioÚEventÚ_pending_immediate_dispatchesÚ
setdefaultÚidrC   Úroot_capabilityÚ
listens_toÚon_eventrD   )ÚctxrE   ÚsettledÚ
capabilitys       r?   Údispatch_event_immediaterg   G   s´   é € ä�eœY×6Ñ6×7Ñ7¸5×;OÑ;OÐS^Ó;^Øô �mŠm‹o€GØ×%Ñ%×0Ñ0´°E³¸BÓ?×FÑFÀwÔOðØ×(Ñ(ˆ
ØÑ! j×&;Ñ&;¸E×&BÑ&BØ×%Ñ% cÐ%Ð7×7Ð7ð 	�‰�ñ	 8øð 	�‰�üs0   ‚A:C!Á=7C Â4C
Â5C Â9C!Ã
C ÃCÃC!c               ó¾  #   • U R                   nU  Sh  v•N n[        U5      nU R                  R                  U5      =n(       a>  UR	                  S5      nU(       d  U R                  U	 UR                  5       I Sh  v•N   O0Ub-  UR                  U5      (       a  UR                  XS9I Sh  v•N   U R                  R	                  XC5      7v •  MÄ   N¿ NW N(
 g7f)zXDispatch events at their stream positions and deduplicate immediately dispatched events.Nr   rW   )	ra   r`   r^   ÚgetÚpopÚwaitrb   rc   Ú_event_stream_replacements)rd   Ústreamrf   rE   Úevent_idÚpendingre   s          r?   Údispatch_event_streamrp   ]   sÆ   é € ð ×$Ñ$€JÙ÷ 	BˆeÜ�e“9ˆØ×7Ñ7×;Ñ;¸HÓEÐEˆ7ÕEØ—k‘k !“nˆGÞØ×5Ñ5°hÐ?Ø—,‘,“.× Ñ ØÑ#¨
×(=Ñ(=¸e×(DÑ(DØ×%Ñ% cÐ%Ð7×7Ð7Ø×,Ñ,×0Ñ0°ÓAÕAñ	Bñ !á7ñ ùsJ   ‚C‘C•C–C™A&CÁ?CÂ 0CÂ0CÂ1$CÃCÃCÃCÃC)Úfrozenc                  óL   • \ rS rSr% Sr\" 5       rS\S'    \" 5       rS\S'   Sr	g)ÚAnchoredEvidenceén   u!  Reveal and load evidence the provider that served a response could still see.

`RunContext.discovered_tool_names` and `loaded_capability_ids` are cut at any `CompactionPart`,
because the consumer that matters for them is the *next* request, whose provider isn't knowable
when history is parsed. A call the model already made is a different question with a different
answer: the response records which provider served it, so a boundary that provider would have
skipped on the wire â€” another provider's, or one whose payload it doesn't render â€” hid nothing
from it. This holds what those parts of history still evidence.

Additive, never a replacement: the sets it widens are shared mutable run state that tool
execution writes in-step reveals into, so the widened view has to be a separate object.
zfrozenset[str]Údiscovered_tool_namesÚloaded_capability_idsrH   N)
rM   rN   rO   rP   rQ   Ú	frozensetru   Ú__annotations__rv   rS   rH   rA   r?   rs   rs   n   s)   ‡ ññ -6«KÐ˜>Ó7Ø`á,5«KÐ˜>Ó7Ú\rA   rs   F)ÚreprÚkw_onlyc                  ó¾  • \ rS rSr% SrS\S'    S\S'    S\S'    \" S	S
S9rS\S'    S	rS\S'    \" S	S
S9r	S\S'    S	r
S\S'    \" \\R                     S9rS\S'    S	rS\S'    \" \S9rS\S'    S
rS\S'    \rS\S'    \" \\\4   S9rS\S '    S	rS\S!'    S	rS\S"'    S#rS\S$'    S#rS\S%'    S#rS\S&'    S
rS\S''    S	rS\S('    S
r S\S)'    S	r!S\S*'    S	r"S\S+'    S	r#S,\S-'    S	r$S.\S/'    \" S	S
S9r%S0\S1'    \" S	S
S9r&S2\S3'    \" S	S
S9r'S4\S5'    \" \\\\(RR                     4   S
S69r*S7\S8'    \" \\\RV                  4   S
S69r,S9\S:'    \" S	S
S9r-S;\S<'    \" S	S
S9r.S=\S>'    \" S	S
S9r/S?\S@'    \" SA S
S69r0SB\SC'    S	r1SD\SE'    \" S	S
S9r2SF\SG'    S	r3SH\SI'    \" SJ S9r4SK\SL'    \" \5\   S9r6SM\SN'    S	r7SO\SP'    \" \5\   S9r8SM\SQ'    \" SR S
S69r9SS\ST'    \" S	S
S9r:SH\SU'    \;SoSV j5       r<\;\=" SW\>SX9SpSY j5       5       r?\?R€                  \=" SW\>SX9SqSZ j5       5       r?\;SrS[ j5       rA\;SrS\ j5       rB\;SsS] j5       rCStS^ jrD\;SuS_ j5       rE\;SuS` j5       rF\;\=" Sa\>SX9SuSb j5       5       rG\;SuSc j5       rH\;SuSd j5       rISvSe jrJ\;SwSf j5       rK\LSxSg j5       rM\LSySh j5       rM    SzSi jrMSjSk.     S{Sl jjrNS|Sm jrO\PR¢                  rRSnrSg	)}Ú
RunContexté„   z#Information about the current call.r/   Údepsr$   Úmodelr*   ÚusageNF)r-   ry   ú
str | NoneÚ	_model_idzUsageLimits | NoneÚusage_limitsz'Agent[RunContextAgentDepsT, Any] | NoneÚagentz,str | Sequence[_messages.UserContent] | NoneÚprompt)Údefault_factoryzlist[_messages.ModelMessage]r   r   Úvalidation_contextr   ÚtracerÚboolÚtrace_include_contentÚintÚinstrumentation_versionzdict[str, int]ÚretriesÚtool_call_idÚ	tool_namer   ÚretryÚmax_retriesÚrun_stepÚtool_call_approvedÚtool_call_metadataÚpartial_outputÚrun_idÚconversation_idzdict[str, Any] | NoneÚmetadataz,ModelSettings | RealtimeModelSettings | NoneÚmodel_settingszlist[PendingMessage] | NoneÚpending_messageszRunCancellation | NoneÚ_cancellationz'list[_messages.AgentStreamEvent] | NoneÚ_event_stream_buffer)r†   ry   zdict[int, list[asyncio.Event]]r^   z%dict[int, _messages.AgentStreamEvent]rl   z7dict[tuple[str, str], _DurableOperationDispatch] | NoneÚ_durable_operationsz)dict[str, AbstractCapability[Any]] | NoneÚ_run_capabilities_by_idz%dict[str, RunHeldToolset[Any]] | NoneÚ_run_held_toolsetsc                 ó   • 0 $ r9   rH   rH   rA   r?   Ú<lambda>ÚRunContext.<lambda>  s   € Ñ_arA   z$dict[str, dict[str, ToolDefinition]]Ú_mcp_tool_defs_cachez(ToolManager[RunContextAgentDepsT] | NoneÚtool_managerzRealtimeSession | NoneÚrealtime_sessionz/AbstractCapability[RunContextAgentDepsT] | Nonera   c                 ó   • 0 $ r9   rH   rH   rA   r?   r¡   r¢   N  s   € ÑfhrA   z3dict[str, AbstractCapability[RunContextAgentDepsT]]Úcapabilitiesúset[str]rv   úbool | NoneÚcapability_activeru   c                 ó   • [        5       $ r9   )rs   rH   rA   r?   r¡   r¢     s   € ÔIYÔI[rA   rs   Ú_anchored_evidenceÚ_capabilityc                ó   • U R                   $ )z÷The identifier from which the run's active `model` was resolved.

This is `None` when the model was passed as an instance instead of being resolved from an
identifier. The property is read-only; Pydantic AI manages the selection token internally.
)r‚   ©r<   s    r?   Úmodel_idÚRunContext.model_id‹  s   € ð �~‰~ÐrA   úŠ`capability_loaded` is deprecated, use `capability_active` instead: the value is `True` for an always-on capability that was never loaded.)Úcategoryc                ó   • U R                   $ )u  Whether the capability whose hook or callback is currently running is active right now.

Deprecated: use [`capability_active`][pydantic_ai.tools.RunContext.capability_active]. This
never meant "loaded" â€” it is `True` for an always-on capability nothing ever loaded.
©rª   r¯   s    r?   Úcapability_loadedÚRunContext.capability_loaded”  s   € ð ×%Ñ%Ð%rA   c                ó   • Xl         g r9   rµ   )r<   Úvalues     r?   r¶   r·   ¢  s
   € ð "'ÕrA   c                ó–   • [         R                  R                  S5      nUSL=(       a     [        U R                  UR
                  5      $ )uú  Whether this run is a realtime session, i.e. `model` is the connected `RealtimeModel`.

Reliable from `before_run` through session close, including instruction resolution â€” unlike
[`realtime_session`][pydantic_ai.tools.RunContext.realtime_session], which is only set once
the session is connected. The class is looked up through `sys.modules` rather than imported:
if the realtime package was never imported, no realtime model can exist, and a classic run
should not pay for (or cycle into) that import.
zpydantic_ai.realtimeN)ÚsysÚmodulesri   rX   r   ÚRealtimeModel)r<   Úrealtimes     r?   r¾   ÚRunContext.realtime­  s8   € ô —;‘;—?‘?Ð#9Ó:ˆØ˜tÐ#×V¬
°4·:±:¸x×?UÑ?UÓ(VÐVrA   c                ó4   • U R                   U R                  :H  $ )zPWhether this is the last attempt at running this tool before an error is raised.)r�   r‘   r¯   s    r?   Úlast_attemptÚRunContext.last_attemptº  s   € ð �z‰z˜T×-Ñ-Ñ-Ð-rA   c                ó0  •  U R                   U R                  p!UR                  nUb  US::  a  g[	        U5       HI  n[        U[        R                  5      (       d  M$  UR                  R                  nU(       a  XS-  s  $ Ss  $    g! [         a     gf = f)uå  Fraction of the model's context window occupied as of the most recent model response.

Computed as the latest response's reported
[`total_tokens`][pydantic_ai.usage.RequestUsage.total_tokens] (input, including cached tokens,
plus output) over the active model's
[`context_window`][pydantic_ai.models.AbstractModel.context_window]. This estimates how full
the next request may be; history processing and newly added content can change its actual
size, and the value can exceed `1.0` when the last response came from a model with a larger
window. Useful to trigger history compaction, e.g. in a
[history processor](https://pydantic.dev/docs/ai/message-history#processing-message-history).

Returns `None` â€” never a misleading `0.0` â€” when the ratio cannot be calculated: when the
context window, usage, or message history is unavailable, or before the first model response.
A [`FallbackModel`][pydantic_ai.models.fallback.FallbackModel] measures against the smallest
of its candidates' windows.
Nr   )
r   r   r   Úcontext_windowÚreversedrX   rY   ÚModelResponser€   Útotal_tokens)r<   r   r   rÄ   ÚmessageÚtokenss         r?   Úcontext_window_usedÚRunContext.context_window_used¿  s�   € ð$	Ø"Ÿj™j¨$¯-©-�8ð ×-Ñ-ˆØÑ! ^°qÓ%8ØÜ Ö)ˆGÜ˜'¤9×#:Ñ#:×;Ó;Ø Ÿ™×3Ñ3�Þ28�vÑ.ÒB¸dÒBñ *ð øô ó 	áð	ús   ‚B Â
BÂBc                ób   • U R                   c   S5       eU R                   R                  U5        g)uì   Append an event to the run's event buffer for the agent graph to drain into the event stream.

Private framework plumbing â€” not public API. Only valid during an agent run, where the buffer
is set (`_event_stream_buffer is not None`).
Nz?events are only emitted during an agent run, which has a buffer)rœ   rC   ©r<   rE   s     r?   Ú_emit_eventÚRunContext._emit_eventß  s0   € ð ×(Ñ(Ñ4ÐwÐ6wÓwÐ4Ø×!Ñ!×(Ñ(¨Õ/rA   c                ó¨   • U R                   R                  5        VVs1 s H  u  pUR                  SLd  M  UiM     snnU R                  -  $ s  snnf )uP  IDs of the capabilities whose contributions are live to the model right now.

*Active*, deliberately not *available*: a capability is not something the model calls, so
"available" would read as "offered in the catalog, there for the loading" â€” which is the
opposite set, the deferred ones that are **not** yet contributing. Active means the
capability's instructions, tools, settings and hooks are in force on this step:
non-deferred capabilities (`defer_loading` not `True`) plus the deferred ones the model has
loaded, so `active_capability_ids - loaded_capability_ids` is the auto/always-on subset.

Tools keep the word *available* because for them there is only one question â€” may the model
call this now? â€” and no catalog sense to collide with. So `is_tool_available` reads "revealed,
and its owning capability is active".

Two axes, deliberately not mixed. *Configuration* is set once by the author: a capability is
either **deferred** (`defer_loading=True`) or **always-on**. *Runtime* is derived per step:
**loaded** records what the model asked for, **active** what is in force. So "always-on" is
the antonym of "deferred", never of "active" â€” an always-on capability is always active, and
a deferred one becomes active once loaded.

Distinct from `capabilities`, the full registry (including deferred ones not yet
loaded). See `loaded_capability_ids` for the subset the model explicitly loaded.

Reliable from `before_run` onwards: the `capabilities` registry is seeded once at
run start, and `loaded_capability_ids` is refreshed from history before each model
request, so the loaded subset grows across steps as the model loads capabilities.
Because it grows step by step, where you read it in the
[hook order](../hooks.md#hook-ordering) determines what you see â€” e.g. a capability
loaded during one step is not reflected until the next step's hooks.
T)r§   ÚitemsÚdefer_loadingrv   ©r<   r`   Úcaps      r?   Úactive_capability_idsÚ RunContext.active_capability_idsè  sT   € ð@ #×/Ñ/×5Ñ5Ô7ô
Ú7‘7�2¸3×;LÑ;LÐTXÐ;X�BÑ7ò
à×&Ñ&ñ'ð 	'ùó 
s
   žA·Ac                ób   • U R                   U R                  R                  U R                  -  -  $ )u  `active_capability_ids`, widened by the anchored evidence for the response being dispatched.

The single answer to "may this capability act on the call being dispatched right now?", and
it has to be single: `is_tool_available` authorizes the call from it, and the `prepare_tools`
dispatch gate decides from it whether the owning capability's filter runs over that tool. If
only the first consulted the evidence, a tool authorized through a load the conservative
window dropped would execute with its owner's `prepare_tools` never having run â€” the
capability is not active, so nothing dispatched to it.

The evidence is narrowed to the run's configured deferred ids â€” the shape every load record
has, since only a deferred capability can be loaded. Inert for both predicates above, which
look up an id that came from a registered capability either way; it is there so that a
history naming a capability this run no longer configures doesn't leave a permanent
difference in `ToolManager.resolved_capability_ids` and rebuild the tools every dispatch.
`_deferred_capability_ids` rather than `capabilities` deliberately: it crosses the Temporal
activity boundary, where reading the live registry raises.

Outside tool-call dispatch `_anchored_evidence` is empty, so this is exactly
`active_capability_ids`.
)rÕ   r¬   rv   Ú_deferred_capability_idsr¯   s    r?   Ú_dispatch_active_capability_idsÚ*RunContext._dispatch_active_capability_ids  s1   € ð, ×)Ñ)Ø×#Ñ#×9Ñ9¸D×<YÑ<YÑYñ
ð 	
rA   z©`available_capability_ids` is deprecated, use `active_capability_ids` instead: for a capability, "available" reads as "there for the loading", which is the opposite set.c                ó   • U R                   $ )z­IDs of the capabilities whose contributions are live to the model right now.

Deprecated: use [`active_capability_ids`][pydantic_ai.tools.RunContext.active_capability_ids].
)rÕ   r¯   s    r?   Úavailable_capability_idsÚ#RunContext.available_capability_ids%  s   € ð ×)Ñ)Ð)rA   c                óŽ   • U R                   R                  5        VVs1 s H  u  pUR                  SL d  M  UiM     snn$ s  snnf )aõ  IDs of the capabilities configured to load on demand.

Private, and read only by `is_tool_available` and `_dispatch_active_capability_ids`, which
need the *configured* shape rather than the runtime one: `loaded_capability_ids` records what history says was loaded, which
can name a capability that has since been reconfigured as always-on. Overridden in
`TemporalRunContext` with the snapshot serialized at activity dispatch, since the
`capabilities` registry this reads does not cross that boundary.
T)r§   rÑ   rÒ   rÓ   s      r?   rØ   Ú#RunContext._deferred_capability_ids2  s=   € ð #'×"3Ñ"3×"9Ñ"9Ô";ÔYÒ";‘w�r¸s×?PÑ?PÐTXÐ?X—Ñ";ÒYÐYùÓYs
   žA·Ac                ó"  • U R                   b  U R                   R                  c  [        [           " 5       U R                  -  $ U R                  R                  5        VVs1 s H  u  pU R                  U5      (       d  M  UiM!     snn$ s  snnf )a¯  Names of function tools the model can call on the current turn.

The visible subset of [`tools`][pydantic_ai.tools.RunContext.tools]: always-visible
tools, tools revealed via [tool search](../tools-advanced.md#tool-search), and tools
owned by loaded deferred capabilities.

Only fully populated once the turn's tools have been resolved during model-request
preparation, so it is reliable in model-request hooks (`before_model_request`,
`wrap_model_request`, `after_model_request`) and tool hooks. In earlier hooks like
`before_run` it falls back to `discovered_tool_names` (reconstructed from history).
See [hook ordering](../hooks.md#hook-ordering) for how timing affects what you see.
)r¤   ÚtoolsrD   Ústrru   rÑ   Úis_tool_available)r<   ÚnameÚtool_defs      r?   Úavailable_tool_namesÚRunContext.available_tool_names>  so   € ð ×ÑÑ$¨×(9Ñ(9×(?Ñ(?Ñ(GÜ”s’8“: × :Ñ :Ñ:Ð:Ø+/¯:©:×+;Ñ+;Ô+=ÔbÒ+=™˜À×AWÑAWÐX`×Aa—Ñ+=ÒbÐbùÓbs   Á!BÂBc                ób  • [        U[        5      (       aR  U R                  b  U R                  R                  c  XR                  ;   $ U R                  R                  U5      nUc  gOUnSSKJn  UR                  UR                  :w  a  UR                  (       d  gUR                  nU R                  nUb9  X@R                  ;   a*  X@R                  UR                  -  ;   a  X@R                  ;   $ UR                   U R"                  UR"                  -  ;  a  gUSL =(       d    X@R                  ;   $ )aý  Whether a function tool is currently available to the model.

Pass a [`ToolDefinition`][pydantic_ai.tools.ToolDefinition] when checking a definition
held by a toolset, especially inside `get_tools`. This form evaluates the definition's
own fields against the reveal state recorded in history, so it remains
reliable when a wrapping toolset has removed the definition from the resolved tool set.

Pass a tool name where [`tools`][pydantic_ai.tools.RunContext.tools] is reliable, such as
model-request hooks or ordinary tool execution. The name form looks up the current definition
in `tools`; when live tool state is unavailable (including inside a Temporal activity), it
falls back to `available_tool_names`. An unknown name returns `False`. See
[`available_tool_names`][pydantic_ai.tools.RunContext.available_tool_names] for the timing
caveat, and [`ModelRequestParameters.revealed_tool_names`][pydantic_ai.models.ModelRequestParameters.revealed_tool_names]
for the reveal state sent through the model-request pipeline.
NFr   )ÚToolSearchToolT)rX   râ   r¤   rá   ræ   ri   Únative_tools._tool_searchré   Úwith_nativeÚkindrÒ   Úcapability_idr¬   rØ   rv   rÙ   rä   ru   )r<   Útoolrå   ré   rí   Úevidences         r?   rã   ÚRunContext.is_tool_availableP  s  € ô  �dœC× Ñ Ø× Ñ Ñ(¨D×,=Ñ,=×,CÑ,CÑ,Kð ×8Ñ8Ñ8Ð8Ø—z‘z—~‘~ dÓ+ˆHØÑØð  ð ˆHõ 	>ð ×Ñ >×#6Ñ#6Ó6¸x×?U×?UØØ ×.Ñ.ˆð ×*Ñ*ˆàÑ%Ø×!>Ñ!>Ó>Ø×!;Ñ!;¸h×>\Ñ>\Ñ!\Ó\à ×$HÑ$HÑHÐHØ�=‰= × :Ñ :¸X×=[Ñ=[Ñ [Ó[Øð  Ð$×]¨×9]Ñ9]Ñ(]Ð]rA   c                óà   • U R                   b  U R                   R                  c  0 $ U R                   R                  R                  5        VVs0 s H  u  pXR                  _M     snn$ s  snnf )z•All tool definitions present this turn, keyed by name (includes still-deferred ones). Index `available_tool_names` into this for the callable subset.)r¤   rá   rÑ   rå   )r<   rä   rî   s      r?   rá   ÚRunContext.toolsŽ  s^   € ð ×ÑÑ$¨×(9Ñ(9×(?Ñ(?Ñ(GØˆIØ6:×6GÑ6G×6MÑ6M×6SÑ6SÔ6UÔVÒ6U©
¨�—m‘mÒ#Ñ6UÒVÐVùÓVs   ÁA*c             ƒ  ó   #   • g 7fr9   rH   rÍ   s     r?   ÚemitÚRunContext.emit•  s   é € ØBEùó   ‚c             ƒ  ó   #   • g 7fr9   rH   rÍ   s     r?   rô   rõ   ˜  s   é € ØJMùrö   c             ƒ  óÄ  ^#   • U R                   c  [        S5      eSnU R                  mTb9  [        U4S jU R                  R                  5        5       TR                  5      nOŒU R                  b  U R                  br  U R                  R                  b[  U R                  R                  R                  U R                  5      =nb)  UR                  R                  nX@R                  ;   a  UOSn[        U[        R                  5      (       a"  Uc  [        S5      eUR                  c  X!l        OITb  TO#U R                  R                  U=(       d    S5      =n b  UR                   (       d  [        S5      eUR"                  c/  U R"                  b"  U R"                  Ul        U R                  Ul        U R%                  U5        ['        X5      I Sh  v•N   U$  N7f)u×  Emit a custom or capability event into the current run's event stream.

Application code emits an instance of an application-defined
[`CustomEvent` subclass](../agent.md#custom-events) with typed payload fields.
Capability hooks and capability-contributed tools instead emit a typed
[`CapabilityEvent`][pydantic_ai.messages.CapabilityEvent].

This method must be awaited, so it's available from async tools, capability hooks, history
processors, and async output validators. Sync tools cannot emit events; write async tools instead.
It's async rather than sync like [`enqueue`][pydantic_ai.tools.RunContext.enqueue] because
immediate dispatch (below) awaits listeners before returning, and because widening a sync
signature to async later would break every caller.
The event reaches the run's `event_stream_handler`,
[`Agent.run_stream_events`][pydantic_ai.agent.AbstractAgent.run_stream_events],
[`Agent.iter`][pydantic_ai.agent.AbstractAgent.iter] streaming, and the UI adapters.

When emitted from within a tool call and the event doesn't already set a
[`tool_call_id`][pydantic_ai.messages.CustomEvent.tool_call_id], the current
[`tool_call_id`][pydantic_ai.tools.RunContext.tool_call_id] and
[`tool_name`][pydantic_ai.tools.RunContext.tool_name] are stamped on the event in place so
consumers can attribute it to the originating tool call.

By default, capability and application listeners run when the event's stream position is
consumed, and this method returns without awaiting them. For tool-execution emissions this
happens before the next model request. An event emitted during `before_model_request` may
reach listeners only after that request begins, with the same as-soon-as-possible timing as
[`RunContext.enqueue`][pydantic_ai.tools.RunContext.enqueue]. That is a statement about *when*
listeners run, not about order: every consumer sees events in emission order either way.

A [`CapabilityEvent`][pydantic_ai.messages.CapabilityEvent] class declared with
`dispatch='immediate'` changes one thing â€” listeners are awaited before this method returns,
so the emitter can read decision fields they set (this is what makes a cancelable event
possible). Everything else is the same: the event still takes the stream position it would
have taken, the same listeners run in the same order, and it is delivered exactly once. What
stream consumers gain is that they never observe such an event mid-decision â€” the stream waits
for its listeners to settle before yielding it, so the values they read are final.

Args:
    event: The [`CustomEvent`][pydantic_ai.messages.CustomEvent] or
        [`CapabilityEvent`][pydantic_ai.messages.CapabilityEvent] to emit.

Returns:
    The same event instance, with any attribution fields stamped. For an immediately dispatched
    decision event, both the return value and the passed reference reflect listener decisions.

Raises:
    UserError: If this `RunContext` isn't backed by a running agent's event stream, or the event
        family doesn't belong to the current emitter.
Nz”`emit` is only available during an agent run (from tools, capability hooks, or `AgentRun.emit`). This `RunContext` has no event stream to emit into.c              3  ó:   >#   • U  H  u  pUTL d  M  Uv •  M     g 7fr9   rH   )Ú.0r–   rÔ   rf   s      €r?   Ú	<genexpr>Ú"RunContext.emit.<locals>.<genexpr>Ø  s   øé € ÐZÒ+D™K˜FÈÈzÐHY—‘Ò+Dùs   ƒ’	zØCapability events belong to capabilities and can only be emitted from a capability hook or capability-contributed tool. Application code should emit a `CustomEvent`; it can re-emit a received capability event as one.Ú zgCapabilities should define and emit `CapabilityEvent` subclasses instead of application `CustomEvent`s.)rœ   r   r­   Únextr§   rÑ   r`   r�   r¤   rá   ri   rå   rí   rX   rY   rZ   Ú_emits_app_eventsrŽ   rÎ   rg   )r<   rE   rí   rî   Útool_capability_idÚownerrf   s         @r?   rô   rõ   ›  sÆ  øé € ðh ×$Ñ$Ñ,ÜðXóð ð %)ˆØ×%Ñ%ˆ
ØÑ!Ü ÜZ¨4×+<Ñ+<×+BÑ+BÔ+DÓZÐ\f×\iÑ\ió‰Mð �^‰^Ñ'¨D×,=Ñ,=Ñ,IÈd×N_ÑN_×NeÑNeÑNqØ×)Ñ)×/Ñ/×3Ñ3°D·N±NÓCÐC�ÑPð &*§]¡]×%@Ñ%@Ð"Ø6H×L]ÑL]Ó6]Ñ 2Ðcg�ä�eœY×6Ñ6×7Ñ7ØÑ$Üð8óð ð
 ×"Ñ"Ñ*Ø&3Ô#øð $.Ñ#9‘Z¸t×?PÑ?P×?TÑ?TÐUb×UhÐfhÓ?iÐiˆEØñà#×5×5Üð"óð ð ×ÑÑ%¨$×*;Ñ*;Ñ*GØ!%×!2Ñ!2ˆEÔØ"Ÿn™nˆEŒOð 	×Ñ˜Ôô
 ' tÓ3×3Ð3Øˆñ 	4ùs   ƒGG ÇGÇG Úasap)Úpriorityc               ó´   • U R                   c  [        S5      e[        R                  " USU06nUc  gU R                   R	                  U5        UR
                  $ )uu  Enqueue content to be injected into the conversation.

Safe to call directly from async tools, sync tools running in another
thread, and capability hooks.

Args:
    *content: One or more [`EnqueueContent`][pydantic_ai.run.EnqueueContent] items.
        Adjacent [`UserContent`][pydantic_ai.messages.UserContent] (a `str` or multi-modal
        content like an [`ImageUrl`][pydantic_ai.messages.ImageUrl]) is gathered into one
        [`UserPromptPart`][pydantic_ai.messages.UserPromptPart], and each
        [`ModelRequestPart`][pydantic_ai.messages.ModelRequestPart] (e.g. a
        [`SystemPromptPart`][pydantic_ai.messages.SystemPromptPart]) is coalesced with adjacent
        part-style items into one [`ModelRequest`][pydantic_ai.messages.ModelRequest]; a complete
        [`ModelRequest`][pydantic_ai.messages.ModelRequest] or
        [`ModelResponse`][pydantic_ai.messages.ModelResponse] is kept as its own message. The
        assembled sequence must end in a request. Calling with no positional args is a no-op.
    priority: When to deliver:
        `'asap'` (default) â€” at the earliest opportunity (next model request,
            or a redirect if the agent would otherwise end). In a realtime session, an active
            assistant response is allowed to finish before the content is sent; otherwise it
            is sent immediately.
        `'when_idle'` â€” only when the agent would otherwise end, after `'asap'` messages.
            In a realtime session, this means after the next response completes. Either way
            the model gets a turn on the delivered content, a `SystemPromptPart` included: it
            marks provenance, not silence.

Returns:
    The `enqueue_id` of the queued message, echoed on the
    [`EnqueuedMessagesEvent`][pydantic_ai.messages.EnqueuedMessagesEvent] emitted when it's
    delivered, or `None` when there was nothing to enqueue (an empty call).

Raises:
    UserError: If the run or realtime session has ended, or this `RunContext` isn't backed
        by a running agent's queue (e.g. the synthetic context from
        `Agent.system_prompt_parts`), since there'd be nowhere to deliver the message.
NzŸ`enqueue` is only available during an agent run (from tools, capability hooks, or `AgentRun.enqueue`). This `RunContext` has no pending-message queue to drain.r  )rš   r   r   Úfrom_contentrC   Ú
enqueue_id)r<   r  Úcontentro   s       r?   ÚenqueueÚRunContext.enqueue  sc   € ðR × Ñ Ñ(Üð`óð ô !×-Ò-¨wÐJÀÑJˆØ‰?ØØ×Ñ×$Ñ$ WÔ-Ø×!Ñ!Ð!rA   c                óv   • U R                   R                  S5      nUc  [        S5      eUR                  5         g)u  Cancel the agent run this context belongs to.

Safe to call from anywhere a `RunContext` is available â€” tools, `event_stream_handler`s,
and capability hooks. This *requests* cancellation: it returns normally, and the calling
code keeps running until its next `await`, where the cancellation is delivered â€” so the
caller can still do cleanup, but its return value (e.g. a tool's result) is discarded. The
run then stops what it is doing (the in-flight model request is torn down, sibling tool
tasks are cancelled and drained, a suspended server-side job is best-effort cancelled) and
ends with [`RunCancelled`][pydantic_ai.exceptions.RunCancelled], preserving everything that
completed before the cancellation took effect in message history. Idempotent; a no-op once
the run has finished. Cancellation is terminal: capability hooks may observe it and clean
up, but cannot recover the run to success. Cancellation cannot forcibly stop synchronous
code running in a worker thread; it may continue and perform side effects, although its
result is discarded.

Raises:
    UserError: If this `RunContext` isn't backed by a running agent (e.g. the synthetic
        context from `Agent.system_prompt_parts`, or across a durable-execution
        serialization boundary such as a Temporal activity).
r›   Nz¶`cancel` is only available during an agent run (from tools, event stream handlers, or capability hooks) in the same process as the run itself. This `RunContext` has no run to cancel.)Ú__dict__ri   r   Úcancel)r<   Úcancellations     r?   r  ÚRunContext.cancel5  s>   € ð0 04¯}©}×/@Ñ/@ÀÓ/QˆØÑÜð:óð ð
 	×ÑÕrA   rµ   )rK   r�   )rK   r©   )r¹   r©   rK   rL   )rK   r‰   )rK   zfloat | NonerI   )rK   r¨   )rî   zstr | ToolDefinitionrK   r‰   )rK   zdict[str, ToolDefinition])rE   r1   rK   r1   )rE   r3   rK   r3   )rE   ú1_messages.CustomEvent | _messages.CapabilityEventrK   r  )r  r   r  r   rK   r�   )rK   rL   )TrM   rN   rO   rP   rQ   rx   r   r‚   rƒ   r„   r…   ÚlistrY   ÚModelMessager   r‡   r   rˆ   rŠ   r   rŒ   Údictrâ   r‹   r�   rŽ   r�   r�   r‘   r’   r“   r”   r•   r–   r—   r˜   r™   rš   r›   rœ   r\   r]   r^   ÚAgentStreamEventrl   r�   rž   rŸ   r£   r¤   r¥   ra   r§   rD   rv   rª   ru   r¬   r­   Úpropertyr°   r   r   r¶   Úsetterr¾   rÁ   rÊ   rÎ   rÕ   rÙ   rÜ   rØ   ræ   rã   rá   r   rô   r  r  r   Údataclasses_no_defaults_reprÚ__repr__rS   rH   rA   r?   r|   r|   „   sG  ‡ á-à
ÓØ%ØÓØQØƒOØ,Ù!¨$°UÑ;€IˆzÓ;Ø\Ø'+€LÐ$Ó+ðñ 6;À4ÈeÑ5T€EÐ2ÓTØ?à;?€FÐ8Ó?Ø5Ù-2À4È	×H^ÑH^ÑC_Ñ-`€HÐ*Ó`Ø8Ø"Ð˜Ó"ð QÙ¨:Ñ6€FˆFÓ6Ø0Ø"'Ð˜4Ó'ØFØ#BÐ˜SÓBØJÙ#°D¸¸c¸±NÑC€Gˆ^ÓCØ1Ø#€L�*Ó#Ø"Ø €IˆzÓ Ø(Ø€Eˆ3ƒNðð
 €K�Óðð
 €HˆcÓØ&Ø$Ð˜Ó$ØKØ"Ð˜Ó"ØoØ €N�DÓ ØFØ€FˆJÓØ/Ø"&€O�ZÓ&ðð '+€HÐ#Ó*ØAØCG€NÐ@ÓGðñ 5:À$ÈUÑ4SÐÐ1ÓSðñ -2¸$ÀUÑ,K€MÐ)ÓKðñ EJÐRVÐ]bÑDcÐÐAÓcðñ EJØ˜S $ w§}¡}Ñ"5Ð5Ñ6¸UñEÐ!Ð#Aó ð`ñ INØ˜S )×"<Ñ"<Ð<Ñ=ÀEñIÐÐ Eó ð GáSXÐaeÐlqÑSrÐÐPÓrðñ JOÐW[ÐbgÑIhÐÐFÓhØXá@EÈdÐY^Ñ@_ÐÐ=Ó_ðñ BGÑWaÐhmÑAnÐÐ>Ónðð >B€LÐ:ÓAðñ 05¸TÈÑ/NÐÐ,ÓNð	ð HL€OÐDÓKð
ñ INÑ^hÑHi€LÐEÓiðñ ',¸CÀ¹HÑ&EÐ˜8ÓEðð &*Ð�{Ó)ðñ ',¸CÀ¹HÑ&EÐ˜8ÓEð	ñ ,1ÑA[ÐbgÑ+hÐÐ(Óhðñ DIÐQUÐ\aÑCb€KÐ@ÓbØJàóó ðð Ùð	6à-ñó
&óó ð&ð ×ÑÙð	6à-ñó
'óó ð'ð
 ó
Wó ð
Wð ó.ó ð.ð óó ðô>0ð ó 'ó ð 'ðD ó
ó ð
ð2 Ùð	_à-ñó
*óó ð*ð ó	Zó ð	Zð ócó ðcô"<^ð| óWó ðWð ÛEó ØEàÛMó ØMðdØFðdà	:ôdðR ,2ñ2"à ð2"ð )ð2"ð 
õ	2"ôhðB ×2Ñ2ƒHrA   r|   )r¶   c               óz   • Ub,  [         R                  " S[        SS9  UR                  SU5        [	        U 40 UD6  g )Nr²   é   )Ú
stacklevelrª   )ÚwarningsÚwarnr   r_   Ú_run_context_init)r<   r¶   Úkwargss      r?   Ú(_run_context_init_with_capability_loadedr  \  sB   € ð Ñ$Ü�Šð:ä(Øò		
ð 	×ÑÐ-Ð/@ÔAÜ�dÑ%˜fÓ%rA   zpydantic_ai.current_run_context)r-   z"ContextVar[RunContext[Any] | None]Ú_CURRENT_RUN_CONTEXTc                 ó*   • [         R                  5       $ )z–Get the current run context, if one is set.

Returns:
    The current [`RunContext`][pydantic_ai.tools.RunContext], or `None` if not in an agent run.
)r   ri   rH   rA   r?   Úget_current_run_contextr"  z  s   € ô  ×#Ñ#Ó%Ð%rA   c              #  óž   #   • [         R                  U 5      n Sv •  [         R                  U5        g! [         R                  U5        f = f7f)z}Context manager to set the current run context.

Args:
    run_context: The run context to set as current.

Yields:
    None
N)r   rD   Úreset)Úrun_contextÚtokens     r?   Úset_current_run_contextr'  ƒ  s<   é € ô !×$Ñ$ [Ó1€Eð*Ûä×"Ñ" 5Õ)øÔ×"Ñ" 5Õ)üs   ‚A™3 �A³A
Á
A)rd   r   rE   rJ   rK   rL   )rd   r   rm   z)AsyncIterable[_messages.AgentStreamEvent]rK   z)AsyncIterator[_messages.AgentStreamEvent])r<   r   r¶   r©   r  r   rK   rL   )rK   zRunContext[Any] | None)r%  r   rK   zGenerator[None])^Ú
__future__r   Ú_annotationsr\   Údataclassesr»   r  Úcollections.abcr   r   r   r   r   r	   Ú
contextlibr
   Úcontextvarsr   r   Ú	functoolsr   Útypingr   r   r   r   Úopentelemetry.tracer   r   Útyping_extensionsr   r   Úpydantic_ai._instrumentationr   rý   r   r   rY   Ú_enqueuer   r   r   Ú	_warningsr   Ú
exceptionsr   Útupler  râ   Ú_DurableOperationDispatchÚ_cancelr    r„   r!   Úcapabilities.abstractr"   Údurable_exec._toolsetr#   Úmodelsr$   r¾   r%   r&   Úsettingsr'   r¤   r(   rá   r)   r€   r*   r+   Úobjectr,   r/   ÚCustomEventr1   rZ   r3   r  r  r5   rg   rp   Ú	dataclassrs   r|   r;   r  r  r   rx   r"  r'  rH   rA   r?   Ú<module>r@     s  ðÞ 2ã Û Û 
Û ß b× bÝ %Ý "Ý Ý ß 8Ó 8ç 2ß 1å Hç +ß LÑ LÝ 3Ý !à$Ø˜˜c 3˜h™¨¨c°3¨h©Ð8Øˆc�NðñÐ ð YæÝ(ÝÝ9Ý5Ý%ß@Ý'Ý)Ý%ß,á�\¨6ÀÑF€
Ø +áÐ5¸vÐQUÑVÐ Ø ?á�~¨Y×-BÑ-BÑC€ÙÐ-°Y×5NÑ5NÑOÐ ô˜˜Y×7Ñ7Ñ8ô ô&ð,BØ	ðBØ"KðBà.ôBð" ×Ò˜dÑ#÷]ð ]ó $ð]ð* ×Ò˜E¨4Ñ0ôQ3�Ð-Ñ.ó Q3ó 1ðQ3ðh ×'Ñ'Ð ñ ÐÓà?Cñ&Ø
ð&Ø1<ð&ØORð&à	ô&ó ð&ð& ?€
Ô ñ <FØ%Øñ<Ð Ð8ó ð Yô&ð ó*ó ñ*rA   