+
    .pÐj2 ã                  óÌ  a € 0 t $ R t^ RIHt ^ RIt^ RIt^ RIt^ RIt^ RIt^ RI	t	^ RI
t
^ RIt^ RIHt ^ RIHtHtHtHtHt ^ RIHtHt ^ RIHt ^ RIHt ]P6                  ! ]4      tRsR]R	&   ]	P@                  ! 4       t!^ s"R
]R&   ]	P@                  ! 4       t#/ t$R]R&   ^t%^2t&R¤t'Rt(^t)R¥t*Rt+]	P@                  ! 4       t,Rt-Rt.]	P@                  ! 4       t/]0! 4       t1R]R&   / t2R]R&   Rt3Rt4Rt5Rt6]	P@                  ! 4       t7Rs8R]R&   ]	Pr                  ! 4       t:0 R¦mt;R§t<R¨t=R©t>Rªt?R t@R R ltAR R ltBR  tCR! R" ltDR# R$ ltER% R& ltFR' R( ltGR) R* ltHR+ R, ltIR- R. ltJR/ R0 ltKR1 R2 ltLR3 R4 ltMR5R/R6 R7 lltNR5R/R8 R9 lltOR: R; ltPR< R= ltQR> R? ltRR@ RA ltSRB RC ltTRD RE ltURF RG ltVRH RI ltWRJ RK ltXRL RM ltYRN RO ltZRP RQ lt[RR RS lt\RT RU lt]RV RW lt^]_! 0 R«m4      t`R¬taRX RY ltbR­R[^R5R/R\ R] llltcR^ R_ ltdR` Ra lteRb Rc ltfRd Re ltgR®Rf Rg llthRh Ri ltiRj Rk ltjRl Rm ltkRn Ro ltlRp Rq ltmRr Rs ltnRt Ru ltoRvRRwRRxR/Ry Rz lltpR{RR|RZR}RZR~RR]%R€R/R� R‚ lltqR{RR|RZR}RZR~RR]%RƒRR€RRvRRwRRxR/
R„ R… lltrR† R‡ ltsRˆ R‰ lttRŠ R‹ ltuRŒ R� ltvRŽ R� ltwR� R‘ ltxR’ R“ ltyR” R• ltzR– R— lt{R˜ R™ lt|Rš R› lt}Rœ R� lt~R¯Rž RŸ lltR°R  R¡ llt€R¢ R£ lt�R# )±a   Async (background) delegation registry behind ``delegate_task(background=true)``.

The parent dispatches a subagent on a module-level daemon executor and returns a handle
immediately. On completion a ``type="async_delegation"`` event (self-contained task-source
block) is pushed onto the SHARED ``process_registry.completion_queue`` the CLI/gateway drain
while idle, so results surface as a NEW turn (never mid-turn) and inherit its de-dup and
crash-recovery wiring. Only the async lifecycle lives here; the child run is an injected ``runner``.)ÚannotationsN)ÚThreadPoolExecutor)ÚAnyÚCallableÚDictÚListÚOptional)Úget_hermes_homeÚhermes_home_key)ÚDaemonThreadPoolExecutor)Úpropagate_context_to_threadzOptional[ThreadPoolExecutor]Ú	_executorÚintÚ_executor_max_workerszdict[str, dict[str, Any]]Ú_recordsiè  g     Àr@g      >@g      N@ÚsetÚ_offeredzdict[str, float]Ú_last_orphan_sweepg      |@g     À’@g      ^@zOptional[threading.Thread]Ú_monitor_threadc                 ó$   € \        4       R ,          # )zstate.db)r	   © ó    Ú%/opt/hermes/tools/async_delegation.pyÚ_db_pathr   a   s   € ÜÓ˜zÕ)Ð)r   c               ó   € V ^8„  d   QhRR/# )é   Úreturnúsqlite3.Connectionr   )Úformats   "r   Ú__annotate__r   e   s   € ÷ ñ Ð$ñ r   c            	     óª   € ^ RI Hp  ^ RIHp ^ RIHp \        4       pV! VP                  4       V! VRR7       V ! VRRRR	\        R
7      pV! V4       V# )é    )Úopen_db)Úmkdir_under_hermes_home)Ú_secure_state_db_filesT)Úcreate_mainzstate.db (async_delegation)i'  FN)Údb_labelÚbusy_timeout_msÚwalÚrow_factoryÚ
initialize)	Úhermes_cli.sqlite_utilr"   Úhermes_constantsr#   Úhermes_stater$   r   ÚparentÚ_initialize_schema)r"   r#   r$   ÚpathÚconns        r   Ú_connectr2   e   sR   € Ý.õ 9Ý3ä‹:€Dá˜DŸK™KÔ(Ù˜4¨TÕ2á�4Ð"?ÐQWØ¨$Ô;MôO€Dá˜4Ô Ø€Kr   c               ó    € V ^8„  d   QhRRRR/# )r   r1   r   r   ÚNoner   )r   s   "r   r   r   x   s   € ÷ !ñ !Ð/ð !°Dñ !r   c                ó>   € ^ RI Hp ^ RIHp V! V 4       V! V 4       R# )r!   )Úapply_durability_barriers)Úreconcile_state_schemaN)Úhermes_state_repairr6   Úhermes_state_schemar7   )r1   r6   r7   s   &  r   r/   r/   x   s   € Ý=Ý:ñ ˜dÔ#ñ ˜4Ö r   c                 ó.   € ^ RI Hp  V ! \        4       4      # )r!   ©Útransaction)r+   r<   r2   r;   s    r   Ú_transactionr=   ˆ   s   € Ý2á”x“zÓ"Ð"r   c               ó   € V ^8„  d   QhRR/# ©r   r   údict[str, Any]r   )r   s   "r   r   r   Ž   s   € ÷ ñ  ñ r   c                 ó²   €  ^ RI Hp  \         Uu/ uF(  q! RVP                  4        2R4      ;p'       g   K&  WbK*  	  up# u upi   \         d    / u # i ; i)zÄSnapshot scope_id/user_id/user_name on the PARENT thread (the daemon worker
has no contextvars) so a restart-replayed completion can rebuild a SessionSource.
Best-effort: empty values are omitted.©Úget_session_envÚHERMES_SESSION_Ú )Úgateway.session_contextrC   Ú_ROUTING_KEYSÚupperÚ	Exception)rC   ÚkÚvs      r   Ú_capture_routing_originrL   Ž   s^   € ðÝ;Ý+Ói™m˜°_ÀÐWX×W^ÑW^ÓW`ÐVaÐEbÐdfÓ5gÐ0g°Ó0g”�’™mÑiÐiùÒiøÜô ØŠ	ðús&   ‚A �#A¸A¾A ÁA ÁAÁAc               ó    € V ^8„  d   QhRRRR/# )r   Úrecordr@   r   r4   r   )r   s   "r   r   r   ™   s   € ÷ ñ ˜nð °ñ r   c                ó>  € \         P                   ! 4       p ^ RIHp V! \        P                  ! 4       4      p. RO\        O Uu/ uF  pW@9   g   K  W@P                  V4      bK  	  pp \        P                  ! 4       VR&   \        ;_uu_ 4        \        4       ;_uu_ 4       pVP                  RV R,          V P                  RR4      V P                  RR4      V P                  R	4      V R
,          V\        P                  ! 4       V\        P                  ! V4      V P                  RR4      3
4       RRR4       RRR4       \        4        R#   \
         d    Rp EL'i ; iu upi   \         d     Lôi ; i  + '       g   i     LN; i  + '       g   i     LY; i)r!   )Úget_process_start_timeNÚ	owner_cwda~  INSERT OR REPLACE INTO async_delegations
               (delegation_id, origin_session, origin_ui_session_id,
                parent_session_id, state, dispatched_at, updated_at,
                delivery_state, delivery_attempts, owner_pid,
                owner_started_at, task_json, origin_session_id)
               VALUES (?, ?, ?, ?, 'running', ?, ?, 'pending', 0, ?, ?, ?, ?)Údelegation_idÚsession_keyrE   Úorigin_ui_session_idÚparent_session_idÚdispatched_atÚorigin_session_id)	ÚgoalÚgoalsÚcontextÚtoolsetsÚroleÚmodelÚis_batchÚtask_indexesÚtask_transcripts)ÚtimeÚgateway.statusrP   ÚosÚgetpidrI   rG   ÚgetÚgetcwdÚOSErrorÚ_DB_LOCKr=   ÚexecuteÚjsonÚdumpsÚ_prune_durable_records)rN   ÚnowrP   Úowner_started_atÚkeyÚtask_payloadr1   s   &      r   Ú_persist_dispatchrq   ™   sU  € Ü
�)Š)‹+€Cð Ý9Ù1´"·)²)³+Ó>Ðò
 Mô  Lñ  Móñ MˆCØ‰=ô 	ˆ�Z‰Z˜‹_Òñ Mð ð ðÜ$&§I¢I£Kˆ�[Ñ!÷ 
Ž”<—>”> TØ�‰ð Qð �OÕ$ f§j¡j°ÀÓ&CÀVÇZÁZÐPfÐhjÓEkØ�Z‰ZÐ+Ó,¨f°_Õ.EÀsÌBÏIÊIËKÐYiÜ�ZŠZ˜Ó% v§z¡zÐ2EÀrÓ'JðLô	M÷ "�ô Öøô) ô  ØÓð üòøô ô Ùðúç!—>ú��úsT   —!E ÁE#ÁE#Á)E( ÂFÂ"BE9	Ä3FÅE ÅE Å(E6Å5E6Å9F	ÆFÆF	c               ó   € V ^8„  d   QhRR/# ©r   r   r4   r   )r   s   "r   r   r   µ   s   € ÷ Bñ B ñ Br   c            	     óZ  € \         P                   ! 4       \        ,
          p \        ;_uu_ 4        \        4       ;_uu_ 4       pVP	                  RV 34       VP	                  R4      P                  4       ^ ,          pV\        8”  d   VP	                  RV\        ,
          34       VP	                  R4      P                  4       ^ ,          pV\        8”  d   VP	                  RV\        ,
          34       RRR4       RRR4       R#   + '       g   i     L; i  + '       g   i     R# ; i)zBBound terminal history, preferring delivered records for deletion.zQDELETE FROM async_delegations WHERE delivery_state='delivered' AND updated_at < ?zRSELECT COUNT(*) FROM async_delegations WHERE state NOT IN ('running','finalizing')aX  DELETE FROM async_delegations WHERE delegation_id IN (
                     SELECT delegation_id FROM async_delegations
                     WHERE state NOT IN ('running','finalizing')
                     ORDER BY CASE delivery_state WHEN 'delivered' THEN 0 ELSE 1 END,
                              updated_at ASC LIMIT ?
                   )z~SELECT COUNT(*) FROM async_delegations
               WHERE state NOT IN ('running','finalizing') AND delivery_state='pending'a  DELETE FROM async_delegations WHERE delegation_id IN (
                     SELECT delegation_id FROM async_delegations
                     WHERE state NOT IN ('running','finalizing') AND delivery_state='pending'
                     ORDER BY updated_at ASC LIMIT ?
                   )N)ra   Ú_DURABLE_RETENTION_SECONDSrh   r=   ri   ÚfetchoneÚ_MAX_RETAINED_COMPLETEDÚ_MAX_DURABLE_PENDING)Úcutoffr1   Úterminal_countÚpending_counts       r   rl   rl   µ   sê   € ä�YŠY‹[Ô5Õ5€Fß	Ž”<—>”> TØ�‰Ø_ÐbhÐajô	làŸ™Ø`óbßbjÑbjÓblÐmnõpˆàÔ3Ô3Ø�L‰Lð ð
 )Ô+BÕBÐDôFð Ÿ™ð &[ó \ß\dÑ\dÓ\fÐghõjˆàÔ/Ô/Ø�L‰Lð ð (Ô*>Õ>Ð@ô	B÷ "�‰—>—>ú��ˆús$   ¯DÁB2D	Ã4DÄDÄDÄD*	c               ó$   € V ^8„  d   QhRRRRRR/# )r   Úeventr@   Úresultr   r4   r   )r   s   "r   r   r   Î   s&   € ÷ Mñ M˜~ð M°~ð MÈ$ñ Mr   c                ó°  € \         P                   ! 4       p\        ;_uu_ 4        \        4       ;_uu_ 4       pVP                  R V P	                  RR4      V P	                  RV4      V\
        P                  ! V 4      \
        P                  ! V4      V R,          34       RRR4       RRR4       R#   + '       g   i     L; i  + '       g   i     R# ; i)z­UPDATE async_delegations SET state=?, completed_at=?, updated_at=?,
               event_json=?, result_json=?, delivery_state='pending'
               WHERE delegation_id=?ÚstatusÚ	completedÚcompleted_atrR   N)ra   rh   r=   ri   re   rj   rk   )r}   r~   rm   r1   s   &&  r   Ú_persist_completionrƒ   Î   s„   € Ü
�)Š)‹+€Cß	Ž”<—>”> TØ�‰ð (ð �Y‰Y�x Ó-¨u¯y©y¸ÈÓ/MÈsÜ�ZŠZ˜Ó¤§
¢
¨6Ó 2°E¸/Õ4JðLô	M÷ "�‰—>—>ú��ˆús#   ¤C·A(B1	ÂCÂ1CÂ<CÃC	c               ó$   € V ^8„  d   QhRRRRRR/# )r   rR   ÚstrÚentryr@   r   r4   r   )r   s   "r   r   r   Ø   s&   € ÷ Iñ I Sð I°ð IÀDñ Ir   c                óJ  €  \         ;_uu_ 4        \        4       ;_uu_ 4       pVP                  RV 34      P                  4       pVf    RRR4       RRR4       R# \        P
                  ! V^ ,          ;'       g    R4      ;'       g    / pVP                  R4      ;'       g    .  Uu. uF+  qUP                  R4      VP                  R4      8w  g   K)  VNK-  	  ppVP                  V4       VP                  R\        P                  ! RVRR/4      \        P                  ! 4       V 34       RRR4       RRR4       R# u upi   + '       g   i     L; i  + '       g   i     R# ; i  \         d,    \        P                  R	YP                  R4      RR
7        R# i ; i)an  Durably record ONE finished child of a still-running multi-child unit on the unit's own row, so a crash before
the unit joins loses only the children that had not finished. Stored in ``result_json`` (overwritten by the real
result at finalize); ``recover_abandoned_delegations`` replays it. Best-effort: a failed write costs recovery
fidelity, never the live result.zSSELECT result_json FROM async_delegations WHERE delegation_id=? AND state='running'Nú{}ÚresultsÚ
task_indexzbUPDATE async_delegations SET result_json=?, updated_at=? WHERE delegation_id=? AND state='running'ÚpartialTz7Async delegation %s: could not record finished child %s©Úexc_info)rh   r=   ri   rv   rj   Úloadsre   Úappendrk   ra   rI   ÚloggerÚwarning)rR   r†   r1   Úrowr‹   Úrr‰   s   &&     r   Úrecord_unit_childr”   Ø   sG  € ð
IßŽX”|—~”~¨Ø—,‘,ÐtØ -Ð/ó1ß19±³ð àŠ{Ø÷	 &�X‰Xô
 —j’j  Q¥§ ¨4Ó0×6Ð6°BˆGØ")§+¡+¨iÓ"8×">Ð">¸BÐ">ÓqÑ">˜QÇ%Á%ÈÓBUÐY^×YbÑYbÐcoÓYpÑBp—q�qÑ">ˆGÐqØ�N‰N˜5Ô!Ø�L‰LÐ}ÜŸ*š* i°¸)ÀTÐ%JÓKÌTÏYÊYË[ÐZgÐhôj÷ &�X‰Xùò r÷ &—~ú�X�XˆXûô ô IÜ�‰ÐPÐR_×ajÑajÐkwÓaxð  DHˆ÷  	IðIús‚   ‚E, �E£'E	Á
EÁE, ÁE	Á<E	Â
E	Â%E	Â*&E ÃE ÃAE	Ä.EÄ6E, Å E	ÅEÅEÅE)	Å#E, Å)E, Å,2F"Æ!F"c               ó(   € V ^8„  d   QhRRRRRRRR/# )	r   Útaskr@   Úresult_jsonúOptional[str]Úerrorr…   r   zOptional[list[dict[str, Any]]]r   )r   s   "r   r   r   ì   s0   € ÷ yñ y˜^ð y¸-ð yÐPSð yÐXvñ yr   c                óˆ  € \         P                  ! T;'       g    R4      ;'       g    / pV P                  R4      '       d/   VP                  R4      '       d   VP                  R4      '       g   R# VR,           Uu/ uF4  p\        VP                  R4      \        4      '       g   K*  VR,          VbK6  	  ppV P                  R4      ;'       g7    \        \        \        V P                  R4      ;'       g    . 4      4      4      pV Uu. uF%  quP                  V4      ;'       g    RVR	R
RRRV/NK'  	  up# u upi u upi )zaPer-task results for an abandoned unit: recorded children as they finished, the rest ``unknown``.rˆ   r^   r‹   r‰   NrŠ   r_   rY   r€   ÚunknownÚsummaryr™   )rj   rŽ   re   Ú
isinstancer   ÚlistÚrangeÚlen)r–   r—   r™   r‹   r“   ÚrecordedÚindexesÚis   &&&     r   Ú_recovered_resultsr¤   ì   s  € ä�jŠj˜×,Ð,¨Ó-×3Ð3°€GØ�H‰H�Z× Ò  W§[¡[°×%;Ò%;ÀÇÁÈI×@VÒ@VÙØ,3°IÖ,>ÓgÑ,> qÄ*ÈQÏUÉUÐS_ÓM`Ôbe×BfÔ"��,• Ò"Ñ,>€HÐgØ�h‰h�~Ó&×SÐS¬$¬u´S¸¿¹À'Ó9J×9PÐ9PÈbÓ5QÓ/RÓ*S€GÙpwÓxÑpwÐkl�L‰L˜‹O×fÐf ¨a°¸9ÀiÐQUÐW^Ð`eÐfÒfÑpwÑxÐxùò hùâxs   Á='D:Â)D:ÄD?Ä(D?c               ó   € V ^8„  d   QhRR/# )r   r   z$Optional[Callable[[Any, Any], bool]]r   )r   s   "r   r   r   ö   s   € ÷ ñ Ð=ñ r   c                 ó\   aaa€  ^ RI HoHoHo R TTT3R llp T #   \         d     R# i ; i)z‘``alive(owner_pid, owner_started_at)`` over the shared drift-tolerant start-time comparator,
or None when the liveness probes cannot be imported.)Ú_pid_existsrP   Ústart_time_fingerprints_matchNc               ó   € V ^8„  d   QhRR/# )r   r   Úboolr   )r   s   "r   r   Ú%_owner_liveness.<locals>.__annotate__þ   s   € ÷ nñ n˜tñ nr   c                ó¸   <€ \        V 4      ;'       dH    S! \        V 4      4      ;'       d/    VR J ;'       g#    S! TS! \        V 4      4      ;'       g    ^ 4      # ©N)rª   r   )ÚpidÚstartedr§   rP   r¨   s   &&€€€r   ÚaliveÚ_owner_liveness.<locals>.aliveþ   s`   ø€ Ü�C‹y÷ nð n™[¬¨S«Ó2÷ nð nØ�tˆO×lÐlÑ<¸WÑF\Ô]`ÐadÓ]eÓFf×FkÐFkÐjkÓlð	nr   )rb   r§   rP   r¨   rI   )r°   r§   rP   r¨   s    @@@r   Ú_owner_livenessr²   ö   s5   ú€ ðßeÑe÷nò nð €Løô ô Úðús   …
 œ+ª+c               ó   € V ^8„  d   QhRR/# ©r   r   r   r   )r   s   "r   r   r     s   € ÷ /ñ / sñ /r   c                 óÜ  € \        4       p V f   ^ # \        P                  ! 4       ^ r!\        ;_uu_ 4        \        4       ;_uu_ 4       pVP	                  R4      P                  4       pV EFA  pVw  rgr‰r«rÍrïpV ! W¼4      '       d   K  \        P                  ! T;'       g    R4      pRp\        VVV4      pV'       d%   \        R V 4       4      pRV R\        V4       R2pR	TR
VP                  R
4      ;'       g    / /p^ RIHpHp V! VR
,          4      ;p'       d   VVR&   V! VP                  R4      4      ;p'       d   VVR&   / RRbRVbRVbRVbRT;'       g    RbRV	bRVP                  RR4      bRVP                  R4      bRVP                  R4      bRVP                  R4      bRVP                  R4      bRVP                  R4      bR\        VP                  R4      4      bRRbR RbR!VbVCV'       d   R"V/M/ CR#V
R$V/C\          Uu/ uF&  pVP                  V4      '       g   K  VVV,          bK(  	  upCpRRR RR!VR!,          /VCV'       d   R"V/M/ CpVP	                  R%W\        P"                  ! V4      \        P"                  ! V4      V34       V^,          pEKD  	  RRR4       RRR4       V# u upi   + '       g   i     L; i  + '       g   i     T# ; i)&z´Classify records whose owning process disappeared as outcome unknown; children a multi-child unit had already
recorded (``record_unit_child``) are replayed with their real results.Na%  SELECT delegation_id, origin_session, origin_ui_session_id,
                      parent_session_id, dispatched_at, owner_pid,
                      owner_started_at, task_json, origin_session_id, result_json, state
               FROM async_delegations WHERE state IN ('running','finalizing')rˆ   zLDelegation owner exited before recording a terminal result; outcome unknown.c              3  óT   "  € T F  qP                  R 4      R8w  g   K  ^x € K   	  R# 5i)r€   r›   N©re   ©Ú.0r“   s   & r   Ú	<genexpr>Ú0recover_abandoned_delegations.<locals>.<genexpr>  s!   é € ÐXÑ&7 ¿5¹5À»?ÈiÑ;WŸ1š1Ó&7ùs   ‚(ž
(z2Delegation owner exited before the unit finished; Ú/zJ child results were recorded and are included below, the rest are unknown.Úlast_known_statusr`   )Úgit_state_hintÚtranscript_tailsr¿   rQ   r¾   ÚtypeÚasync_delegationrR   rS   rT   rW   rE   rU   rX   rY   rZ   r[   r\   r]   r^   r€   r›   rœ   r™   r‰   rV   r‚   z½UPDATE async_delegations SET state='unknown', completed_at=?,
                   updated_at=?, event_json=?, result_json=?, delivery_state='pending'
                   WHERE delegation_id=?)r²   ra   rh   r=   ri   Úfetchallrj   rŽ   r¤   Úsumr    re   Ú%tools.async_delegation_recovery_hintsr¾   r¿   rª   rG   rk   )r°   rm   Ú	recoveredr1   Úrowsr’   rR   rS   Ú	origin_uiÚ	parent_idrV   r®   r¯   Ú	task_jsonÚ
origin_sidr—   Ú
last_stater–   r™   Úrecovered_resultsÚdoneÚdiagnosticsr¾   r¿   ÚtailsÚhintrJ   r}   r~   s                                r   Úrecover_abandoned_delegationsrÑ     s�  € ô Ó€EØ‚}ÙÜ—Y’Y“[ !ˆß	Ž”<—>”> TØ�|‰|ð Qó R÷ S[ÑRZÓR\ð 	ô ˆCð MPñ  JˆM¨	¸mÐRYÐfpð  @JÙ�S×"Ò"ÙÜ—:’:˜i×/Ð/¨4Ó0ˆDØbˆEÜ 2°4¸ÀeÓ LÐß ÜÑXÑ&7ÓXÓX�ØMÈdÈVÐSTÔUXÐYjÓUkÐTlð m_ð _�à.°
Ð<NÐPT×PXÑPXÐYkÓPl×PrÐPrÐprÐsˆK÷ _Ù(¨Ð5GÕ)HÓIÐIˆuÖIØ27�Ð.Ñ/Ù% d§h¡h¨{Ó&;Ó<Ð<ˆtÖ<Ø04�Ð,Ñ-ð	FØÐ*ð	FØ,;¸]ð	FØLYÐ[fð	Fà&¨	ð	Fà3FÈ
×HXÐHXÐVXð	Fð $ Yð	Fð 17¸¿¹ÀÈÓ8Lð	Fð OVÐW[×W_ÑW_Ð`gÓWhð	Fð ˜4Ÿ8™8 IÓ.ð		Fð 1;¸D¿H¹HÀZÓ<Pð		Fð SYÐZ^×ZbÑZbÐciÓZjð		Fð
 ˜Ÿ™ 'Ó*ð	Fð
 -7¼¸T¿X¹XÀjÓ=QÓ8Rð	Fð ˜)ð	Fð &/°ð	Fð 7>¸uð	Fð ITð	F÷ 6G�IÐ0Ñ1ÈBð	Fð   °Àñ	Fõ (5ÓD¡} !¸¿¹À¿”:�1�d˜1•g’:¡}ÑDð	FˆEð  	¨9°d¸GÀUÈ7Å^ð WÐWbð Wß;L˜)Ð%6Ñ7ÐRTðWˆFà�L‰Lð ,à.1¼¿
º
À5Ó8IÌ4Ï:Ê:ÐV\ÓK]Ð_lÐ-môoð ˜�N‹IñE ÷ "�ðP Ðùò E÷C "—>ú�ŽðP Ðúsc   µKÁAK	Â AK	Ã="K	Ä #K	ÅK	Å B5K	ÈKÈ3KÉK	ÉAK	Ê0KËK	ËKËKËK+	c               ó   € V ^8„  d   QhRR/# r´   r   )r   s   "r   r   r   6  s   € ÷ >ñ >°Sñ >r   c           
     ó¤  € \        4       P                  4       '       g   ^ # \        4        \        P                  ! 4       p\        ;_uu_ 4        \        4       ;_uu_ 4       pVP                  R4      P                  4       p\        W#W4      uuRRR4       uuRRR4       #   + '       g   i     M; iRRR4       R#   + '       g   i     R# ; i)u�  Enqueue durable pending completions as fresh turns after process start.
Restored events are stamped ``restored=True`` in memory only: they came from a PREVIOUS
process, so drains without an ownership filter must leave them for a consumer that can
prove ownership. Rows older than ``_MAX_COMPLETION_REPLAY_AGE_S`` are terminally dropped
instead of replaying a turn nobody is waiting on.

Every restored event is stamped ``restored=True`` (in-memory only â€” the stamp is added after the durable
payload is deserialized and is never persisted). Restored events originate from a *previous* process, so
no consumer in THIS process implicitly owns them: drain paths that run without an ownership filter (the
legacy single-session behavior) must leave them queued for a consumer that can positively prove
ownership, otherwise a brand-new session adopts a dead session's delegation results seconds after boot
(#64484).
z÷SELECT delegation_id, event_json, completed_at, dispatched_at
               FROM async_delegations
               WHERE state != 'running' AND delivery_state='pending' AND event_json IS NOT NULL
               ORDER BY completed_at, delegation_idN)	r   ÚexistsrÑ   ra   rh   r=   ri   rÂ   Ú_replay_pending)Útarget_queuerm   r1   rÆ   s   &   r   Úrestore_undelivered_completionsr×   6  s{   € ô ‹:×Ñ×ÒÙÜ!Ô#Ü
�)Š)‹+€Cß	Ž”<—>”> TØ�|‰|ð 7ó 8÷ 9A¹»
ð 	ô ˜t¨<Ó=÷ "‘>�Š—>—>ú���Šús$   ÁB>Á!+B!	Â
B>Â!B1Â,B>Â>C	c               ó    € V ^8„  d   QhRRRR/# )r   rm   Úfloatr   r   r   )r   s   "r   r   r   P  s   € ÷ ñ °5ð ¸Sñ r   c                ó0  € \        \        4       4      ^ rTV Fè  w  rgr‰T;'       g    T	p
V
'       dW   W:,
          \        8”  dF   V P                  RW634       \        P                  RWcV
,
          R,          \        R,          4       Kp  \        P                  ! V4      p\        V\        4      '       d   RVR&   VP                  V4       \        ;_uu_ 4        \        P                  WF34       RRR4       V^,          pKê  	  V#   + '       g   i     L; i)a)  Put each pending ``(delegation_id, event_json, completed_at, dispatched_at)`` row on ``target_queue``
stamped ``restored``, or terminally drop it past ``_MAX_COMPLETION_REPLAY_AGE_S``. Records the offer so
the orphan sweep skips the row until the copy is handed back (``return_completion_offer``).zìUPDATE async_delegations SET delivery_state='dropped',
                          delivery_claim=NULL, delivery_claimed_at=NULL,
                          updated_at=?
                   WHERE delegation_id=? AND delivery_state='pending'z|Async delegation %s: pending completion is %.1fh old (cap %.1fh); terminally dropping the replay (result remains queryable).g      ¬@TÚrestoredN)r
   r	   Ú_MAX_COMPLETION_REPLAY_AGE_Sri   r�   r‘   rj   rŽ   r�   ÚdictÚputÚ_orphan_lockr   Úadd)r1   rÆ   rÖ   rm   ÚhomerÛ   rR   Úpayloadr‚   rV   Ú	age_basisÚevts   &&&&        r   rÕ   rÕ   P  sí   € ô %¤_Ó%6Ó7¸ˆ(Û?CÑ;ˆ Ø ×1Ð1 Mˆ	ß˜#�/Ô-IÔIØ�L‰Lð Ið LOÐJ^ô`ô �N‰Nð eà(°­?¸fÕ*DÔFbÐekÕFkômñ Ü�jŠj˜Ó!ˆÜ�cœ4× Ò Ø"ˆC�
‰OØ×Ñ˜ÔßŽ\Ü�L‰L˜$Ð.Ô/÷ à�A�Šñ# @Dð$ €O÷ �\ús   ÃDÄDrm   c               ó    € V ^8„  d   QhRRRR/# ©r   rm   úOptional[float]r   r   r   )r   s   "r   r   r   j  s   € ÷ *Añ *A°_ð *AÐPSñ *Ar   c               óÆ  € \        4       pVe   \        4       P                  4       '       g   ^ # \        4        Vf   \        P                  ! 4       MTp\        \        4       4      p\        ;_uu_ 4        \         UUu0 uF  w  rEWC8X  g   K  VkK  	  pppRRR4       \        ;_uu_ 4        \        4       ;_uu_ 4       pVP                  RV\        ,
          V\        ,
          34      P                  4       p. p	V Fw  w  rZr¼rÞpVX9   g   V! WÞ4      '       d   K  T;'       g    ^ \        8¼  d1   VP                  RW34       \         P#                  RV\        4       Kd  V	P%                  WZW¼34       Ky  	  \'        WyW4      uuRRR4       uuRRR4       # u uppi   + '       g   i     EL; i  + '       g   i     M; iRRR4       R#   + '       g   i     R# ; i)aŒ  Offer this home's completions whose owner died after THIS process started (#97202).

Startup replay (``restore_undelivered_completions``) covers owners that died before the process
started; this covers the rest while it runs. Abandoned in-flight rows are first classified by
``recover_abandoned_delegations``. A terminal row qualifies when it is pending with an event, idle
past ``_ORPHAN_STALE_S``, not under a live delivery claim, and its owner fails the shared liveness
check. A row is offered once per live in-memory copy: a consumer that discards the copy with the row
still pending hands it back for the next sweep. The consumer's ``claim_completion_delivery`` stays
the atomic cross-process gate, so two processes offering one row never both deliver it. Rows past
the delivery budget or the replay age converge to ``dropped``. Reads the current profile's ledger:
callers bind the owning profile first.Na½  SELECT delegation_id, event_json, completed_at, dispatched_at,
                      owner_pid, owner_started_at, delivery_attempts
               FROM async_delegations
               WHERE state NOT IN ('running','finalizing') AND delivery_state='pending'
                 AND event_json IS NOT NULL AND updated_at < ?
                 AND (delivery_claim IS NULL OR delivery_claimed_at < ?)
               ORDER BY completed_at, delegation_idzÚUPDATE async_delegations SET delivery_state='dropped',
                              delivery_claim=NULL, delivery_claimed_at=NULL, updated_at=?
                       WHERE delegation_id=? AND delivery_state='pending'únAsync delegation %s exhausted its %d delivery attempts; marking terminally dropped (result remains queryable).)r²   r   rÔ   rÑ   ra   r
   r	   rß   r   rh   r=   ri   Ú_ORPHAN_STALE_SÚ_CLAIM_LEASE_SrÂ   Ú_MAX_DELIVERY_ATTEMPTSr�   r‘   r�   rÕ   )rÖ   rm   r°   rá   ro   rR   Úofferedr1   rÆ   Úorphansrâ   r‚   rV   r®   r¯   Úattemptss   &$              r   Úsweep_orphaned_completionsrð   j  sv  € ô Ó€EØ‚}œH›J×-Ñ-×/Ò/ÙÜ!Ô#ØšŒ$�)Š)Œ+¨#€CÜœ?Ó,Ó-€Dß	ŽÝ;CÔS¹8Ñ%7 SÀsÁ{—=�=¹8ˆÑS÷ 
ç	Ž”<—>”> TØ�|‰|ð 7ð :=¼Õ9NÐPSÔVdÕPdÐ8eóg÷ hpÑgoÓgqð 	ð ˆÛ[_ÑWˆM LÀÈxØ Ô'©5°×+>Ò+>ÙØ—�˜AÔ"8Ô8à—‘ð MàORÐNbôdô —‘ð  Xà,Ô.DôFñ Ø�N‰N˜M°LÐPÖQñ \`ô ˜t¨lÓ@÷- "‘>�Šùó T÷ 
�ˆúç!—>ú���ŠúsP   Á5
FÁ?
F
ÂF
ÂFÂ-GÃ A$F2	Ä%AF2	Æ
GÆFÆF/	Æ2GÆ=GÇG 	c               ó    € V ^8„  d   QhRRRR/# ræ   r   )r   s   "r   r   r   —  s   € ÷ ñ ¸?ð ÐVYñ r   c               ó˜  € \        \        4       4      pVf   \        P                  ! 4       MTp\        ;_uu_ 4        \
        P                  V4      pVe   W,
          \        8  d    RRR4       ^ # V\
        V&   RRR4        \        V 4      #   + '       g   i     L; i  \         d    \        P                  RRR7        ^ # i ; i)zµ``sweep_orphaned_completions`` at most once per ``ORPHAN_SWEEP_INTERVAL_S`` per home (``now`` is
monotonic), for delivery loops that tick far more often. Never raises into the loop.Nz&Orphaned async delegation sweep failedTrŒ   )r
   r	   ra   Ú	monotonicrß   r   re   ÚORPHAN_SWEEP_INTERVAL_Srð   rI   r�   Údebug)rÖ   rm   rá   Úlasts   &$  r   Ú maybe_sweep_orphaned_completionsr÷   —  s    € ô œ?Ó,Ó-€DØ!škŒ$�.Š.Ô
¨s€Cß	ŽÜ!×%Ñ% dÓ+ˆØÒ ¥
Ô-DÔ DØ÷ 
‰ð $'Ô˜4Ñ ÷	 
ð
Ü)¨,Ó7Ð7÷ 
�ûô ô Ü�‰Ð=ÈˆÔMÚðús#   ½,BÁ3	BÂ
B# ÂB 	Â#"C	ÃC	c               ó$   € V ^8„  d   QhRRRRRR/# )r   Úsqlr…   ÚparamsÚtupler   rª   r   )r   s   "r   r   r   ¨  s!   € ÷ 7ñ 7˜#ð 7 uð 7°ñ 7r   c           	     ó  € \         ;_uu_ 4        \        4       ;_uu_ 4       pVP                  W4      P                  ^8H  uuRRR4       uuRRR4       #   + '       g   i     M; iRRR4       R#   + '       g   i     R# ; i)z?Run one UPDATE on the ledger; True iff exactly one row changed.N)rh   r=   ri   Úrowcount)rù   rú   r1   s   && r   Ú_update_deliveryrþ   ¨  s?   € ç	Ž”<—>”> TØ�|‰|˜CÓ(×1Ñ1°QÑ6÷ "‘>�Š—>—>ú���Šús"   �A2¢A	Á 
A2ÁA%Á A2Á2B	c               ó    € V ^8„  d   QhRRRR/# ©r   rR   r…   r   rª   r   )r   s   "r   r   r   ®  s   € ÷ `ñ `¨Sð `°Tñ `r   c                óH   € \         P                   ! 4       p\        RWV 34      # )zDAtomically acknowledge successful injection of a durable completion.z–UPDATE async_delegations SET delivery_state='delivered', delivered_at=?, updated_at=?
           WHERE delegation_id=? AND delivery_state!='delivered'©ra   rþ   )rR   rm   s   & r   Úmark_completion_deliveredr  ®  s+   € ä
�)Š)‹+€CÜð	DØFIÐP]ÐE^ó`ð `r   c               ó$   € V ^8„  d   QhRRRRRR/# ©r   rR   r…   Úclaim_idr   rª   r   )r   s   "r   r   r   ¶  s!   € ÷ !ñ !¨Sð !¸Cð !ÀDñ !r   c                óÈ  € \         P                   ! 4       p\        ;_uu_ 4        \        4       ;_uu_ 4       pVP                  RV 34      P	                  4       pVf    RRR4       RRR4       R# VP                  RWW V\
        ,
          34      pVP                  ^8H  uuRRR4       uuRRR4       #   + '       g   i     M; iRRR4       R#   + '       g   i     R# ; i)zBClaim one pending completion across competing consumers/processes.zBSELECT delivery_state FROM async_delegations WHERE delegation_id=?NTa  UPDATE async_delegations SET delivery_claim=?, delivery_claimed_at=?,
                      delivery_attempts=delivery_attempts+1, updated_at=?
               WHERE delegation_id=? AND delivery_state='pending'
                 AND (delivery_claim IS NULL OR delivery_claimed_at < ?))ra   rh   r=   ri   rv   rë   rý   )rR   r  rm   r1   r’   Úcurs   &&    r   Úclaim_completion_deliveryr	  ¶  sž   € ä
�)Š)‹+€Cß	Ž”<—>”> TØ�l‰lØPÐS`ÐRbódßdlÑdlÓdnð 	àŠ;Ø÷	 "�‰ð
 �l‰lð Lð ˜C°´nÕ0DÐEó	Gˆð
 �|‰|˜qÑ ÷ "‘>�Š—>—>ú���Šús.   ¤C·'B3	ÁCÁ0.B3	Â
CÂ3CÂ>CÃC!	c               ó    € V ^8„  d   QhRRRR/# )r   rä   r@   r   rª   r   )r   s   "r   r   r   Æ  s   € ÷ Zñ Z ^ð Z¸ñ Zr   c                ón   € V P                  R4      R8H  ;'       d    \        V P                  R4      4      # )a  An early per-task notice for a batch that is still running. It shares the batch's
``delegation_id`` but is NOT the durable completion: it must never claim, acknowledge or
dedup against the final result's row (independent review reproduced exactly that loss).rÀ   rÁ   Útask_failure_notice)re   rª   )rä   s   &r   Úis_interim_delegation_eventr  Æ  s/   € ð �7‰7�6‹?Ð0Ñ0×YÐY´T¸#¿'¹'ÐBWÓ:XÓ5YÐYr   c               ó$   € V ^8„  d   QhRRRRRR/# )r   rä   r@   Úconsumerr…   r   r˜   r   )r   s   "r   r   r   Í  s&   € ÷ Tñ T˜nð T¸ð TÀñ Tr   c                óR  € \        V 4      '       d   R# V P                  R4      R8X  d%   \        V P                  R4      ;'       g    R4      MRpV'       g   R# V R\        P                  ! 4        R\
        P                  ! 4       P                   2p\        W#4      '       d   V# R# )zYClaim a durable delegation event; non-durable events (and interim notices) need no token.rE   rÀ   rÁ   rR   Ú:N)	r  re   r…   rc   rd   ÚuuidÚuuid4Úhexr	  )rä   r  rR   r  s   &&  r   Úclaim_event_deliveryr  Í  s‚   € ä" 3×'Ò'ÙØ;>¿7¹7À6»?ÐN`Ô;`”C˜Ÿ™ Ó0×6Ð6°BÔ7Ðfh€MßÙØ�˜1œRŸYšY›[˜M¨¬4¯:ª:«<×+;Ñ+;Ð*<Ð=€HÜ0°×IÒIˆ8ÐSÈtÐSr   c               ó$   € V ^8„  d   QhRRRRRR/# r  r   )r   s   "r   r   r   Ø  s!   € ÷ !ñ !¨sð !¸cð !Àdñ !r   c                óð  € \         P                   ! 4       p\        ;_uu_ 4        \        4       ;_uu_ 4       pVP                  RW V\        34      pVP
                  ^8X  d/   \        P                  RV \        4        RRR4       RRR4       R# VP                  RW V34      pVP
                  ^8H  uuRRR4       uuRRR4       #   + '       g   i     M; iRRR4       R#   + '       g   i     R# ; i)zÐRelease a failed delivery claim so another consumer may retry. Attempts are
counted at claim time; once the budget is exhausted the row converges to
terminal ``dropped`` (only pending rows replay on restart).a	  UPDATE async_delegations SET delivery_state='dropped',
                      delivery_claim=NULL, delivery_claimed_at=NULL, updated_at=?
               WHERE delegation_id=? AND delivery_state='pending'
                 AND delivery_claim=? AND delivery_attempts>=?ré   NTzÖUPDATE async_delegations SET delivery_claim=NULL,
                      delivery_claimed_at=NULL, updated_at=?
               WHERE delegation_id=? AND delivery_state='pending'
                 AND delivery_claim=?)ra   rh   r=   ri   rì   rý   r�   r‘   )rR   r  rm   r1   Úcappedr  s   &&    r   Úrelease_completion_deliveryr  Ø  sº   € ô �)Š)‹+€Cß	Ž”<—>”> TØ—‘ð Bð  Ô+AÐBó	Dˆð
 �?‰?˜aÔÜ�N‰Nð Tà(Ô*@ôBð ÷ "�‰ð �l‰lð )ð ,/¸xÐ*HóJˆð �|‰|˜qÑ ÷ "‘>�Š—>—>ú���Šús/   ¤C$·AC	Á>C$Â"C	Â2
C$ÃCÃC$Ã$C5	c               ó$   € V ^8„  d   QhRRRRRR/# r  r   )r   s   "r   r   r   ï  s!   € ÷ 0ñ 0¨Sð 0¸Cð 0ÀDñ 0r   c                óD   € \        R\        P                  ! 4       W34      # )zOReturn an unadmitted completion to pending without spending a delivery attempt.zþUPDATE async_delegations SET delivery_claim=NULL,
                  delivery_claimed_at=NULL, delivery_attempts=MAX(0, delivery_attempts-1),
                  updated_at=?
           WHERE delegation_id=? AND delivery_state='pending' AND delivery_claim=?©rþ   ra   ©rR   r  s   &&r   Údefer_completion_deliveryr  ï  s%   € äð Vô 
�Š‹�mÐ.ó	0ð 0r   c               ó$   € V ^8„  d   QhRRRRRR/# r  r   )r   s   "r   r   r   ø  s&   € ÷ 	Nñ 	N¨Cð 	N¸3ð 	NÀ4ñ 	Nr   c                óD   € \        R\        P                  ! 4       W34      # )u,  Terminally drop a claimed completion whose target is permanently gone (the
spawning session ended at an explicit user boundary such as /new or reset).
``dropped`` â€” not ``delivered`` â€” keeps the ack honest; not ``pending`` keeps
restart recovery from replaying it into a fail-closed drop forever.zöUPDATE async_delegations SET delivery_state='dropped',
                  updated_at=?, delivery_claim=NULL,
                  delivery_claimed_at=NULL
           WHERE delegation_id=? AND delivery_state='pending'
             AND delivery_claim=?r  r  s   &&r   Údrop_completion_deliveryr!  ø  s(   € ô
 ð %ô (,§y¢y£{°MÐ&Ló	Nð Nr   c               ó$   € V ^8„  d   QhRRRRRR/# r  r   )r   s   "r   r   r     s&   € ÷ Kñ K°ð K¸sð KÀtñ Kr   c                óH   € \         P                   ! 4       p\        RW"W34      # )z;Acknowledge acceptance for the consumer holding this claim.a  UPDATE async_delegations SET delivery_state='delivered',
                  delivered_at=?, updated_at=?, delivery_claim=NULL,
                  delivery_claimed_at=NULL
           WHERE delegation_id=? AND delivery_state='pending'
             AND delivery_claim=?r  )rR   r  rm   s   && r   Úcomplete_completion_deliveryr$    s+   € ä
�)Š)‹+€CÜð %ð (+°Ð&Ió	Kð Kr   c               ó    € V ^8„  d   QhRRRR/# r   r   )r   s   "r   r   r     s   € ÷ Cñ C¨sð CÀTñ Cr   c           
     óv  € \         P                   ! 4       p\        ;_uu_ 4        \        4       ;_uu_ 4       pVP                  RW \        34      pVP
                  ^8X  d/   \        P                  RV \        4        RRR4       RRR4       R# VP                  RW 34      pVP
                  ^8w  d    RRR4       RRR4       R# VP                  RV 34      P                  4       p\        W6W4      ^8H  uuRRR4       uuRRR4       #   + '       g   i     M; iRRR4       R#   + '       g   i     R# ; i)aX  Offer an acknowledged completion again when its receiving turn could not confirm the owner.

The row returns to pending and its event goes back on ``target_queue``, so the next delivery
re-runs the pre-flight. A row past the delivery budget converges to ``dropped`` instead, which
bounds the loop; a row without a stored event is left as it is.z UPDATE async_delegations SET delivery_state='dropped', updated_at=?
               WHERE delegation_id=? AND delivery_state='delivered' AND delivery_attempts>=?ré   NFzËUPDATE async_delegations SET delivery_state='pending',
                      delivered_at=NULL, updated_at=?
               WHERE delegation_id=? AND delivery_state='delivered' AND event_json IS NOT NULLzySELECT delegation_id, event_json, completed_at, dispatched_at
               FROM async_delegations WHERE delegation_id=?)
ra   rh   r=   ri   rì   rý   r�   r‘   rÂ   rÕ   )rR   rÖ   rm   r1   Ú	exhaustedÚreopenedrÆ   s   &&     r   Úrequeue_admitted_completionr)    sú   € ô �)Š)‹+€Cß	Ž”<—>”> TØ—L‘Lð "`àÔ!7Ð8ó:ˆ	ð ×Ñ Ô"Ü�N‰Nð Tà(Ô*@ôBð ÷ "�‰ð —<‘<ð !bð Ð ó"ˆð ×Ñ Ô!Ø÷ "�‰ð �|‰|ð ?ØANÐ@PóRßRZÑRZÓR\ð 	ä˜t¨<Ó=ÀÑB÷# "‘>�Š—>—>ú���Šús;   ¤D'·AD
	Á=D'Â%D
	Â4D'Ã/D
	Ã5
D'Ä
DÄD'Ä'D8	c               ó$   € V ^8„  d   QhRRRRRR/# ©r   rä   r@   r  r…   r   r4   r   )r   s   "r   r   r   )  s&   € ÷ Añ A ð A¸3ð AÀ4ñ Ar   c                ó&   € \        \        W4       R # r­   )Ú_event_deliveryr$  ©rä   r  s   &&r   Úcomplete_event_deliveryr/  )  s   € ÜÔ0°#Ö@r   c               ó$   € V ^8„  d   QhRRRRRR/# r+  r   )r   s   "r   r   r   -  s!   € ÷ !ñ ! ð !¸#ð !À$ñ !r   c                ó<   € \        \        W4       \        V 4       R# )z—Release a failed claim for a consumer that discards its copy (the TUI poller): the row is pending
again, so it must stay eligible for the orphan sweep.N)r-  r  Úreturn_completion_offerr.  s   &&r   Úrelease_event_deliveryr3  -  s   € ô Ô/°Ô?Ü˜CÖ r   c               ó    € V ^8„  d   QhRRRR/# )r   rä   r@   r   r4   r   )r   s   "r   r   r   4  s   € ÷ 	Yñ 	Y ð 	Y°Dñ 	Yr   c           	     ó„  € V P                  R4      R8X  d%   \        V P                  R4      ;'       g    R4      MRpV'       d   \        V 4      '       d   R# \        ;_uu_ 4        \        P                  \         Uu0 uF  q"^,          V8X  g   K  VkK  	  up4       RRR4       R# u upi   + '       g   i     R# ; i)ap  Hand an offered completion back to the orphan sweep after its in-memory copy was discarded while
the durable row stays pending, e.g. a TUI session that cannot prove it owns the event drops it (every
session poller drains one process-wide queue). The next sweep may offer the row again. Delegation ids
are unique across profiles, so this clears the offer in every home.rÀ   rÁ   rR   rE   N)re   r…   r  rß   r   Údifference_update)rä   rR   ro   s   &  r   r2  r2  4  s„   € ð
 <?¿7¹7À6»?ÐN`Ô;`”C˜Ÿ™ Ó0×6Ð6°BÔ7Ðfh€MßÔ7¸×<Ò<Ùß	ŽÜ×"Ñ"µ8Ó#W±8¨CÀ1½vÈÑ?V§C C±8Ñ#WÔX÷ 
‰ùÚ#W÷ 
�ˆús$   Á&B.Á>B)ÂB)ÂB.Â)B.Â.B?	c               ó$   € V ^8„  d   QhRRRRRR/# r+  r   )r   s   "r   r   r   @  s!   € ÷ :ñ :˜^ð :°sð :¸tñ :r   c                ó    € V'       dF   VP                  R 4      R8X  d.   T ! \        VP                  R4      ;'       g    R4      V4       R# R# R# )rÀ   rÁ   rR   rE   N)re   r…   )Úfnrä   r  s   &&&r   r-  r-  @  s<   € ß�C—G‘G˜F“OÐ'9Ô9Ù
Œ3ˆs�w‰w�Ó'×-Ð-¨2Ó.°Ö9ñ :�xr   c               ó    € V ^8„  d   QhRRRR/# )r   rR   r…   r   zOptional[dict[str, Any]]r   )r   s   "r   r   r   E  s   € ÷ 	Hñ 	H¨#ð 	HÐ2Jñ 	Hr   c                óö  € \         ;_uu_ 4        \        4       ;_uu_ 4       pVP                  R V 34      P                  4       pRRR4       RRR4       Xf   R# RT RV^ ,          RV^,          RV^,          RV^,          RV^,          '       d   \        P
                  ! V^,          4      MRRV^,          R	V^,          R
V^,          ;'       g    R/	#   + '       g   i     L™; i  + '       g   i     L¤; i)zäSELECT origin_session, state, dispatched_at, completed_at,
                      result_json, delivery_state, delivery_attempts,
                      origin_session_id
               FROM async_delegations WHERE delegation_id=?NrR   Úorigin_sessionÚstaterV   r‚   r~   Údelivery_stateÚdelivery_attemptsrW   rE   )rh   r=   ri   rv   rj   rŽ   )rR   r1   r’   s   &  r   Úget_durable_delegationr@  E  sÖ   € ß	Ž”<—>”> TØ�l‰lð ?ð BOÐ@PóR÷ S[ÑRZÓR\ð 	÷ "�ð
 ’;ˆ4ð HØ˜Ð(8¸#¸a½&À'È3ÈqÍ6ÐSbÐdgÐhiÕdjØ˜˜A� ÀÀAÇÄ¬$¯*ª*°S¸µVÔ*<ÈDÐRbÐdgÐhiÕdjØ˜S �VÐ%8¸#¸a½&¿,¸,ÀBð%Hð H÷ "—>ú��ús"   �C(¢"C	ÁC(ÃC%Ã C(Ã(C8	c               ó    € V ^8„  d   QhRRRR/# )r   Úrawr˜   r   r@   r   )r   s   "r   r   r   U  s   € ÷ 4ñ 4�mð 4¨ñ 4r   c                óž   €  V '       d   \         P                  ! V 4      M/ p\        T\        4      '       d   T# / #   \         d    / u # i ; ir­   )rj   rŽ   Ú
ValueErrorr�   rÝ   )rB  Úvalues   & r   Ú_json_objectrF  U  sG   € ðß#&”—
’
˜3”¨Bˆô ˜u¤d×+Ò+ˆ5Ð3°Ð3øô ô ØŠ	ðús   ‚< Š< ¼AÁArE   Úlimitc          
     ó,   € V ^8„  d   QhRRRRRRRRRR	/# )
r   rT   r…   rU   rG  r   rm   rç   r   úlist[dict[str, Any]]r   )r   s   "r   r   r   ]  s4   € ÷ (ñ (Øð(Ø7:ð(ØKNð(ØZið(àñ(r   c               óÖ  € RV 3RV33 UUu. uF  w  rEV'       g   K  WE3NK  	  pppV'       g   . # Ve   TM\         P                   ! 4       \        ,
          pRP                  R V 4       4      p\        ;_uu_ 4        \	        4       ;_uu_ 4       p	V	P                  RV R2. R V 4       OVNVN54      P                  4       p
RRR4       RRR4       . pX
 EF\  w  rÍrïpp\        V4      \        V4      pp\        VP                  R	4      \        4      '       d!   VR	,          '       d   VP                  R	4      MVP                  R
4      ;'       g    R.p\        \        VP                  R4      ;'       g    \        \        V4      4      V4      4      p\        VP                  R4      \        4      '       d
   VR,          MVP                  R4      '       d   . MV.pV'       g9   \        V4      P!                  4       \"        9   d   R^ RVP                  R4      /.pV EF  p\        VP                  R4      ;'       g    T;'       g    R4      P!                  4       pV\"        9  d   KM  \        VP                  R4      \$        4      '       d   VP                  R4      M^ pVP                  R4      ;'       g    VP                  R4      pTP'                  RTRTRTR
\        VP                  VV^ ,          4      ;'       g    R4      RV'       d   \        V4      MRRVRV/4       EK  	  EK_  	  VRV # u uppi   + '       g   i     EL‰; i  + '       g   i     EL•; i)a=  Recently failed async delegation tasks owned by a session, newest first.

The live roster forgets a child once it ends and does not survive a renderer reload, so a failed
delegation had nowhere to show (#97202). This reads the durable row instead: one entry per failed
task (a batch unit that "completed" can still carry failed tasks) with ``delegation_id``,
``task_index``, ``goal``, ``status``, ``error``, ``dispatched_at`` and ``completed_at``. Either selector claims a row:
the UI session id at dispatch, or the spawner's durable session id (survives a reload re-mint).rT   rU   Nz OR c              3  ó0   "  € T F  w  rV R 2x € K  	  R# 5i)z=?Nr   )r¹   ÚcolÚ_s   &  r   rº   Ú1failed_delegations_for_session.<locals>.<genexpr>l  s   é € Ð?±Y©6¨3˜s˜e 2�J³Yùs   ‚zSELECT delegation_id, state, dispatched_at, completed_at, task_json, result_json FROM async_delegations
                WHERE (zt) AND state NOT IN ('running','finalizing') AND completed_at >= ?
                ORDER BY completed_at DESC LIMIT ?c              3  ó*   "  € T F	  w  rVx € K  	  R # 5ir­   r   )r¹   rM  Úvals   &  r   rº   rN  r  s   é € Ð+¡‘v�q�s£ùs   ‚rY   rX   rE   r_   r‰   r^   rŠ   r™   r€   rR   rV   r‚   )ra   Ú_FAILURE_SURFACE_WINDOW_SÚjoinrh   r=   ri   rÂ   rF  r�   re   rž   rÝ   ÚziprŸ   r    r…   ÚlowerÚ_FAILED_TASK_STATESr   r�   )rT   rU   rG  rm   rL  rP  Ú	selectorsry   Ú	owner_sqlr1   rÆ   ÚfailedrR   r=  rV   r‚   rÉ   r—   r–   r~   rY   Úgoal_forÚtasksr†   r€   Úindexr™   s   &&$$                       r   Úfailed_delegations_for_sessionr\  ]  sé  € ð 
 Ð!5Ð6Ð9LÐN_Ð8`ñ-bô jñ -b¡ Üehô �#“ñ -b€Iñ jçØˆ	Ø’_‰c¬$¯)ª)«+Ô9RÕR€FØ—‘Ñ?±YÓ?Ó?€Iß	Ž”<—>”> TØ�|‰|ðØ!�{ð #3ð6ð <Ñ+¡Ó+Ð;¨VÐ;°UÑ;ó	=÷ >F¹X»Zð	 	÷ "�ð $&€FÜUYÑQˆ˜m¸9ÀkÜ# IÓ.´¸[Ó0IˆfˆÜ%/°·±¸Ó0AÄ4×%HÒ%HÈTÐRYÏ]Ì]�—‘˜Ô!Ðae×aiÑaiÐjpÓaq×awÐawÐuwÐ`xˆÜœ˜DŸH™H ^Ó4×IÐI¼¼cÀ%»jÓ8IÈ5ÓQÓRˆÜ%/°·
±
¸9Ó0EÄt×%LÒ%L��yÖ!ÐX\×X`ÑX`Ðak×XlÒXlÑRTÐsyÐrzˆßœ˜U›×)Ñ)Ó+Ô/BÔBØ" A w°·
±
¸7Ó0CÐDÐEˆEÜˆEÜ˜Ÿ™ 8Ó,×;Ð;°×;Ð;¸Ó<×BÑBÓDˆFØÔ0Ô0ÙÜ/9¸%¿)¹)ÀLÓ:QÔSV×/WÒ/W�E—I‘I˜lÔ+Ð]^ˆEØ—I‘I˜gÓ&×=Ð=¨&¯*©*°WÓ*=ˆEØ�M‰MØ °¸eÀXÈvØœ˜HŸL™L¨°°aµÓ9×?Ð?¸RÓ@À'×Y^Ì3ÈuÌ:ÐdhØ °ÀðN÷ Oô ñ VZð" �&�5ˆ>Ðùó=j÷ "—>�>ú��ˆús.   ŒL=�L=Á=MÂ3M	ÃMÍMÍ	MÍM(	c               ó    € V ^8„  d   QhRRRR/# )r   Úmax_workersr   r   r   r   )r   s   "r   r   r   ‰  s   € ÷ ñ ˜sð Ð'9ñ r   c                óÈ   € \         ;_uu_ 4        \        f   \        V RR7      sV sMV \        8”  d   V \        n        V s\        uuRRR4       #   + '       g   i     R# ; i)z¤Lazily create (or grow in place, never shrink) the shared daemon executor. Raising
``_max_workers`` is enough: the next ``submit`` spawns threads up to the new cap.Nzasync-delegate)r^  Úthread_name_prefix)Ú_executor_lockr   r   r   Ú_max_workers)r^  s   &r   Ú_get_executorrc  ‰  sH   € ÷ 
ŽÜÒÜ0¸[Ð]mÔnˆIØ$/Ñ!ØÔ0Ô0Ø%0ŒIÔ"Ø$/Ð!Ü÷ 
��‹ús   �6AÁA!	c               ó   € V ^8„  d   QhRR/# r´   r   )r   s   "r   r   r   —  s   € ÷ Tñ T�cñ Tr   c                 ó¤   € \         ;_uu_ 4        \        R \        P                  4        4       4      uuRRR4       #   + '       g   i     R# ; i)zfNumber of live async delegation UNITS (one per completion message: a task group or an ungrouped task).c              3  ó\   "  € T F"  qP                  R 4      \        9   g   K  ^x € K$  	  R# 5i©r€   N©re   Ú_LIVE_STATESr¸   s   & r   rº   Úactive_count.<locals>.<genexpr>š  s!   é € ÐSÑ/˜·5±5¸³?ÄlÑ3R—1’1Ó/ùó   ‚,¢
,N©Ú_records_lockrÃ   r   Úvaluesr   r   r   Úactive_countro  —  s(   € ç	ŽÜÑSœhŸo™oÔ/ÓSÓS÷ 
��‹úó	   �$>¾A	c               ó   € V ^8„  d   QhRR/# r´   r   )r   s   "r   r   r   �  s   € ÷ Xñ X˜3ñ Xr   c                 ó¤   € \         ;_uu_ 4        \        R \        P                  4        4       4      uuRRR4       #   + '       g   i     R# ; i)u—   Number of running child subagents (a batch of N contributes N; a batch with
no goal list counts 1) â€” the truthful observability figure, unlike slots.c              3  óL  "  € T Fš  qP                  R 4      R9   g   K  VP                  R4      '       df   \        VP                  R4      \        \        34      '       d;   VR,          '       d,   \	        VP                  R4      ;'       g
    VR,          4      M^x € Kœ  	  R# 5i)r€   r^   rY   r_   N>   ÚrunningÚ
finalizing)re   r�   rž   rû   r    r¸   s   & r   rº   Ú$active_task_count.<locals>.<genexpr>¡  s„   é € ð Xñ '�¯%©%°«/Ð=VÑ*VôeØ�u‰u�Z× Ò ¤Z°·±°g³ÄÄuÀ×%NÒ%NÐSTÐU\×S]ÔS]ô �—‘�nÓ%×3Ð3¨¨7­Ô4Øcdôeã&ùs   ‚B$žB$µ9B$Á/B$ÂB$Nrl  r   r   r   Úactive_task_countrw  �  s6   € ÷ 
ŽÜñ Xô —_‘_Ô&óXó X÷ 
��‹úrp  c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   rS   r…   rT   rU   r   rž   r   )r   s   "r   r   r   §  s0   € ÷ [ñ [¨Cð [Àsð [Ð_bð [Ðgkñ [r   c           	     óØ  a€ RV3RV3RV33 UUu. uF  w  rEV'       g   K  WE3NK  	  pppV'       g   . # \         ;_uu_ 4        \        P                  4        Uau. uF_  oSP                  R4      V 9   g   K  \        ;QJ d    V3R lV 4       F  '       g   K   RM	  RM! V3R lV 4       4      '       g   K]  SNKa  	  upuuRRR4       # u uppi u upi   + '       g   i     R# ; i)	u>  Records in ``statuses`` owned by a session: any non-empty selector claims the
record â€” ``origin_ui_session_id`` (TUI tab), ``session_key`` (routing key at
dispatch), or ``parent_session_id`` (spawner's durable id â€” the right one for
gateway chats, whose session_key survives ``/new`` while the session id rotates).rT   rS   rU   r€   c              3  óv   <"  € T F.  w  r\        SP                  V4      ;'       g    R 4      V8H  x € K0  	  R# 5i)rE   N)r…   re   )r¹   ÚfieldÚwantedr“   s   &  €r   rº   Ú#_session_records.<locals>.<genexpr>³  s-   øé € ÐYÉy¹m¸eœ˜AŸE™E %›L×.Ð.¨BÓ/°6Ö9Ëyùs   ƒ#9§9TFN)rm  r   rn  re   Úany)ÚstatusesrS   rT   rU   r{  r|  rV  r“   s   &&&&   `r   Ú_session_recordsr€  §  sÊ   ø€ ð 
 Ð!5Ð6¸ÈÐ8TØ	Ð/Ð0ñ72ô =ñ 72¡] Uä5;ô !�%“ñ 72€Iñ =÷ Øˆ	ß	ŽÜ#Ÿ?™?Ô,ô [Ñ,�a°·±°h³À8Ñ0K”ß“CÔYÉyÓY—C—C’CÔYÉyÓY×Y÷ �Ñ,ñ [÷ 
Šùó=ùò[÷ 
�ˆús@   �C¡CÁCÁCÁ8
CÂCÂCÂ:CÃ CÃCÃC)	c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   rS   r…   rT   rU   r   rª   r   )r   s   "r   r   r   ¶  s0   € ÷ fñ f cð fÀcð fÐcfð fÐptñ fr   c                ó6   € \        \        \        WV4      4      # )zOWhether a session still owns any live (running/stalling/finalizing) delegation.)rª   r€  ri  )rS   rT   rU   s   &&&r   Úhas_live_for_sessionrƒ  ¶  s   € äÔ ¤¨{ÐRcÓdÓeÐer   c               ó   € V ^8„  d   QhRR/# ©r   r   r…   r   )r   s   "r   r   r   »  s   € ÷ +ñ +˜Cñ +r   c                 óT   € R \         P                  ! 4       P                  R,           2# )Údeleg_:Né   N)r  r  r  r   r   r   Ú_new_delegation_idr‰  »  s!   € Ø”D—J’J“L×$Ñ$ RÕ(Ð)Ð*Ð*r   c               ó   € V ^8„  d   QhRR/# rs   r   )r   s   "r   r   r   ¿  s   € ÷  ñ   ñ  r   c                 óD  € \         P                  4        U Uu. uF$  w  rVP                  R4      \        9  g   K!  W3NK&  	  pp pVP	                  R R7       VR\        ^ \        V4      \        ,
          4        F  w  r\         P                  V R4       K  	  R# u upp i )zðDrop the oldest completed records beyond the cap. Caller holds ``_records_lock``.
``stalling``/``finalizing`` are still live: evicting one makes the late runner return hit
``_finalize``'s missing-record path and silently drop a real result.r€   c                ó†   € V ^,          P                  R4      ;'       g#    V ^,          P                  R4      ;'       g    ^ # )é   r‚   rV   r·   )Úkvs   &r   Ú<lambda>Ú)_prune_completed_locked.<locals>.<lambda>Ä  s2   €  " Q¥%§)¡)¨NÓ";×"^Ð"^¸rÀ!½u¿y¹yÈÓ?Y×"^Ð"^Ð]^Ð"^r   )ro   N)	r   Úitemsre   ri  ÚsortÚmaxr    rw   Úpop)Úridr“   r�   rM  s       r   Ú_prune_completed_lockedr–  ¿  s€   € ô )1¯©Ô(8Ô`Ñ(8™f˜c¸A¿E¹EÀ(»OÔS_Ñ<_”�#“Ñ(8€IÑ`Ø‡N�NÑ^€NÔ_ØÐNœc !¤S¨£^Ô6MÕ%MÓNÓO‰ˆÜ�‰�S˜$Öó Pùó as
   ˜B»Bc               ó   € V ^8„  d   QhRR/# r…  r   )r   s   "r   r   r   É  s   € ÷ ñ  Cñ r   c                 ó†   €  ^ RI Hp  V ! RR4      R8H  pV'       d   V ! RR4      ;'       g    R# R#   \         d     R# i ; i)a¶  Raw session id of the ORIGINATING api_server request, or ``""``. ``HERMES_SESSION_ID``
is unsafe here: building the child agent calls ``set_current_session_id(child.session_id)``
just before dispatch, so the wake would self-post into the subagent's own session. The
request-scoped ``HERMES_SESSION_CHAT_ID`` (raw X-Hermes-Session-Id on api_server) survives
child construction; on push platforms chat_id is a chat, not a session => ``""``.rB   ÚHERMES_SESSION_PLATFORMrE   Ú
api_serverÚHERMES_SESSION_CHAT_ID)rF   rC   rI   )rC   Úis_apis     r   Ú_current_origin_session_idr�  É  sL   € ðÝ;Ù Ð!:¸BÓ?À<ÑOˆßHN‘Ð 8¸"Ó=×CÐCÀÐVÐTVÐVøÜô Úðús   ‚1 œ1 ¬1 ¯1 ±A ¿A c               ó$   € V ^8„  d   QhRRRRRR/# ©r   r™   r…   ÚdurationrÙ   r   r@   r   )r   s   "r   r   r   Ø  s&   € ÷ nñ n˜ð n¨ð n°.ñ nr   c           
     ó   € R RRRRV R^ RV/# )r€   r™   rœ   NÚ	api_callsÚduration_secondsr   ©r™   r   s   &&r   Ú_single_crashr¥  Ø  s   € Ø�g˜y¨$°¸ÀÈQÐPbÐdlÐmÐmr   c               ó$   € V ^8„  d   QhRRRRRR/# rŸ  r   )r   s   "r   r   r   Ü  s&   € ÷ Oñ O˜ð O uð O°ñ Or   c                ó   € R . RV RV/# )r‰   r™   Útotal_duration_secondsr   r¤  s   &&r   Ú_batch_crashr©  Ü  s   € Ø�r˜7 EÐ+CÀXÐNÐNr   c               ó    € V ^8„  d   QhRRRR/# )r   Úcombinedr@   r   r…   r   )r   s   "r   r   r   à  s   € ÷ oñ o˜Nð o¨sñ or   c                óÖ   a€ V P                  R4      ;'       g    . pRoV'       dC   \        ;QJ d    V3R lV 4       F  '       d   K   RM	  RM! V3R lV 4       4      '       d   R# R# )zCBatch status: completed unless every child errored/was interrupted.r‰   r�   c              3  óJ   <"  € T F  qP                  R 4      S9  x € K  	  R# 5irg  r·   )r¹   r“   Úoks   & €r   rº   Ú _batch_status.<locals>.<genexpr>ä  s   øé € Ð+]É}È!¯E©E°(«OÀ2Ö,EË}ùs   ƒ #FTr™   )r�   Úsuccess)re   Úall)r«  Úchild_resultsr®  s   & @r   Ú_batch_statusr³  à  sL   ø€ à—L‘L Ó+×1Ð1¨r€MØ	!€Bß#¯«Ô+]É}Ó+]¯¯ªÔ+]É}Ó+]×(]Ò(]ˆ7ÐnÐcnÐnr   c               ó   € V ^8„  d   QhRR/# r?   r   )r   s   "r   r   r   ç  s   € ÷ ,ñ ,˜>ñ ,r   c                 óÂ   € ^ RI Hp VP                  4       ;_uu_ 4       pV'       g   RRRR/uuRRR4       # \        R/ V B uuRRR4       #   + '       g   i     R# ; i)r!   ©Ú
retirementr€   Úrejectedr™   z*backend is retiring; reconnect to continueNr   )Úhermes_cli.backend_retirementr·  ÚworkÚ_dispatch_admitted)Úkwargsr·  Úadmitteds   ,  r   Ú	_dispatchr¾  ç  sH   € Ý8à	�‰×	Ô	˜hßØ˜j¨'Ð3_Ð`÷ 
Ò	ô "Ñ+ FÑ+÷ 
×	×	Ó	ús   ŸA¸
AÁA	Úslot_keyr_   r`   c          (     óh   € V ^8„  d   QhRRRRRRRRRRR	RR
RRRRRRRRRRRRRRRRRRRRRRRRRRR/# )r   rR   r…   rX   rY   úOptional[list[str]]rZ   r˜   r[   r\   r]   rS   rU   ÚrunnerúCallable[[], dict[str, Any]]rT   rW   Úinterrupt_fnúOptional[Callable[[], None]]Úmax_async_childrenr   Úprogress_fnúOptional[Callable[[], tuple]]Úcapacity_errorr¿  r_   úOptional[list[int]]r`   úOptional[dict[str, str]]r   r@   r   )r   s   "r   r   r   ð  sú   € ÷ RDñ RDØðRDØ!$ðRDØ-@ðRDØKXðRDà!ðRDà),ðRDà5BðRDàQTðRDð %ðRDð /KðRDð cfðRDð ð	RDð +Gð	RDð ]`ð	RDð
 /ðRDð
 ADðRDð
 P]ðRDð &ðRDð /ðRDð ñRDr   c                óÀ  a a	aaaa a!€ VRJpV'       d   RMRo V'       d   \         MR oV'       d   \        M\        o\        P                  ! 4       oRS RV/V'       d   R\	        V4      /M/ CRTR	V'       d   \	        V4      MRR
VRVRVRV
RVRV/C\        4       CRRRSRRRV/CV'       d   RR/M/ CRTRT;'       g    S /CV'       d   R\        V4      /M/ CVe   R\	        V4      /M/ CR\        P                  ! 4       RRRSRR/Cp\        ;_uu_ 4        \        P                  4        Uu0 uFA  pVP                  R4      \        9   g   K  VP                  R4      ;'       g
    VR,          kKC  	  ppVR,          V9  d!   \        V4      V8¼  d   RRR V/uuRRR4       # V\        S &   \        R! \        P                  4        4       4      pRRR4       \!        V4       \#        \%        VX4      4      pR" VVV VV V	3R# llp^ R$IHo! S!P+                  4         VP-                  \/        V4      4      pVP1                  V!3R% l4       Te   \?        4        RR)RS /# u upi   + '       g   i     L�; i  \2         dÕ   pS!P5                  4        \        ;_uu_ 4        \        P7                  S R4       RRR4       M  + '       g   i     M; i\8        ;_uu_ 4        \;        4       ;_uu_ 4       pTP=                  R&S 34       RRR4       M  + '       g   i     M; iRRR4       M  + '       g   i     M; iRRR R'S  R(T 2/u Rp?# Rp?ii ; i)*a  Shared dispatch core for single (``goals is None``) and batch units. Capacity check +
record insert happen under ONE lock hold so concurrent dispatches can't both pass the check
and exceed the cap. At capacity the dispatch is REJECTED (never queued) so a runaway model
can't pile up unbounded background work. ``slot_key`` names the pool slot the unit occupies
(default: its own id); the units of one delegate_task call share the first unit's id so
splitting a call into per-group completions never consumes more capacity than the call did.Nú batchrE   c                ó8   € V P                  R 4      ;'       g    R# )r€   r�   r·   )r“   s   &r   r�  Ú$_dispatch_admitted.<locals>.<lambda>  s   € ¸¿¹¸x»×9WÐ9WÈKÐ9Wr   rR   rX   rY   rZ   r[   r\   r]   rS   rT   rW   rU   r€   rt  rV   r‚   rÄ  r^   TrÇ  r¿  r`   r_   Ú_contextÚ_progress_tokenÚ_progress_tsÚ_interrupted_atr¸  r™   c              3  ó\   "  € T F"  qP                  R 4      \        9   g   K  ^x € K$  	  R# 5irg  rh  r¸   s   & r   rº   Ú%_dispatch_admitted.<locals>.<genexpr>  s!   é € ÐYÑ$5˜q¿¹¸x»ÌLÑ9XŸšÓ$5ùrk  c               ó   € V ^8„  d   QhRR/# rs   r   )r   s   "r   r   Ú(_dispatch_admitted.<locals>.__annotate__   s   € ÷ 5ñ 5�Tñ 5r   c                 ó>  <€ / p R p\         ;_uu_ 4        \        P                  S4      pVe'   VP                  R\        P                  ! 4       R7       RRR4        S	! 4       ;'       g    / p S! V 4      p\        SW4       R#   + '       g   i     L8; i  \
         dj   p\        P                  RS R2S4       S! \        T4      P                   RT 2\        \        P                  ! 4       S,
          ^4      4      p  Rp?L�Rp?ii ; i  \        SY4       i ; i)r™   NT)Ú_startedrÒ  úAsync delegationz %s crashedú: )rm  r   re   Úupdatera   rI   r�   Ú	exceptionrÀ   Ú__name__ÚroundÚ	_finalize)
r~   r€   ÚrecÚexcÚclassifyÚcrash_resultrR   rV   ÚlabelrÂ  s
       €€€€€€r   Ú_workerÚ#_dispatch_admitted.<locals>._worker   sà   ø€ Ø!#ˆØˆßŽ]Ü—,‘,˜}Ó-ˆCØŠà—
‘
 D´t·y²y³{�
ÔC÷	 ð
	5Ù“X—^�^ ˆFÙ˜fÓ%ˆFô
 �m VÖ4÷ �]ûô ô 	iÜ×ÑÐ/°¨w°kÐBÀMÔRÙ!¤T¨#£Y×%7Ñ%7Ð$8¸¸3¸%Ð"@Ä%ÌÏ	Ê	ËÐVcÕHcÐefÓBgÓh�Fûð	iûô �m VÕ4ús7   ”A BÁB ÂB	ÂDÂ"ADÄD ÄDÄD ÄDr¶  c                ó$   <€ SP                  4       # r­   )Úrelease)rM  r·  s   &€r   r�  rÏ  8  s   ø€ ¨:×+=Ñ+=Ô+?r   z3DELETE FROM async_delegations WHERE delegation_id=?z#Failed to schedule async delegationrÛ  Ú
dispatched) r³  r©  r¥  ra   rž   rL   rÝ   ÚcontextvarsÚcopy_contextrm  r   rn  re   Ú_ACTIVE_STATESr    rÃ   rq   rc  r“  r¹  r·  ÚacquireÚsubmitr   Úadd_done_callbackrI   ré  r”  rh   r=   ri   Ú_ensure_stale_monitor)"rR   rX   rY   rZ   r[   r\   r]   rS   rU   rÂ  rT   rW   rÄ  rÆ  rÇ  rÉ  r¿  r_   r`   r^   rN   r“   Úactive_slotsÚ
live_unitsÚexecutorræ  Úfuturerâ  r1   rã  rä  rV   rå  r·  s"   d$$$$$$$$d$$$$$$$$$          @@@@@r   r»  r»  ð  s(  þ€ ð ˜DÐ €Hß ‰H b€Eß (�}Ñ/W€Hß#+•<´€LÜ—I’I“K€Mà˜¨°ðYßS[¸'Ä4ÈÃ;Ñ9OÐacðYà�7˜J¿(¬¨X¬ÈÈfÐVZÐ\cÐejØ�{Ð$:Ð<PØÐ.Ð0CÐEVñ	Yô
 "Ó
#ðYð 	�)˜_¨m¸^ÈTØ˜ñY÷ @H¨*°dÑ);ÈRðYð S`ÐalØ�H×-Ð- ñY÷ <LÐ¤Ð%5Ó 6Ñ7ÐQSðYð 4@Ò3KˆNœD Ó.Ñ/ÐQSðYð 	”K×,Ò,Ó.à˜4 °Ð@QÐSWñ!Y€F÷" 
ŽÜIQÏÉÔIZó  AÑIZÀAÐ^_×^cÑ^cÐdlÓ^mÔqÑ^Ô?˜Ÿ™˜jÓ)×?Ð?¨Q¨Õ-?Ò?ÑIZˆð  AØ�*Õ \Ô1´c¸,Ó6GÐK]Ô6]Ø˜j¨'°>ÐB÷ 
Šð #)Œ�ÑÜÑY¤H§O¡OÔ$5ÓYÓYˆ
÷ 
ô �fÔô œSÐ!3°ZÓ@ÓA€H÷5õ 5õ" 9ð ×ÑÔð	eØ—‘Ô!<¸WÓ!EÓFˆØ× Ñ Ô!?Ô@ð ÒÜÔØ�l O°]ÐCÐCùòY A÷ 
�ûôH ô eØ×ÑÔßŽ]Ü�L‰L˜¨Ô-÷ �]�]ˆ]úçŽX”|—~”~¨Ø�L‰LÐNÐQ^ÐP`Ôa÷ &—~—~�~ú�X�X�XˆXúà˜* gÐ1TÐUZÐT[Ð[]Ð^aÐ]bÐ/cÐdÕdûðeús–   ÄI+Ä2I&ÅI&Å+I&Å9%I+Æ)-I+È#/I> É&I+É+I;	É>MÊ	MÊ'KÊ>	MËKËMË(L4Ë;LÌ	L4ÌL(Ì#L4Ì+	MÌ4MÌ?MÍMÍMrU   rT   rW   rÄ  rÆ  rÇ  c               óP   € V ^8„  d   QhRRRRRRRRRRR	RR
RRRRRRRRRRRRRRR/# )r   rX   r…   rZ   r˜   r[   rÁ  r\   r]   rS   rU   rÂ  rÃ  rT   rW   rÄ  rÅ  rÆ  r   rÇ  rÈ  r   r@   r   )r   s   "r   r   r   E  sŒ   € ÷ ñ ØðØ(ðØ4GðØORðØ[hðàðà)6ðàGcðð ðð 8;ðð Plðð ð	ð Ifð	ð
 ñr   c                ó  € \        4       p\        R/ RVbRV bRRbRVbRVbRVbRVbR	VbR
VbRVbRVbRV	bRV
bRVbRVbRRV R2b pVR,          R8X  d3   \        P                  RYÕ;'       g    RT ;'       g    RR,          4       V# )a   Spawn ``runner`` on the daemon executor and return a handle immediately.
``session_key``/``parent_session_id`` are captured on the parent thread (the worker carries
no contextvars) and route the completion back to the spawning session.
``progress_fn() -> (token, in_tool)`` enables stale monitoring; omitted = unmonitored.
Returns ``{"status": "dispatched", "delegation_id"}`` or ``{"status": "rejected", "error"}``.rR   rX   rY   NrZ   r[   r\   r]   rS   rU   rÂ  rT   rW   rÄ  rÆ  rÇ  rÉ  ú#Async delegation capacity reached (zà running). Wait for one to finish (its result will re-enter the chat), or run this task synchronously (background=false). Raise delegation.max_concurrent_children in config.yaml to allow more concurrent background subagents.r€   rê  z3Dispatched async delegation %s (session_key=%s): %sú<cli>rE   :NéP   Nr   )r‰  r¾  r�   Úinfo)rX   rZ   r[   r\   r]   rS   rU   rÂ  rT   rW   rÄ  rÆ  rÇ  rR   Úhandles   $$$$$$$$$$$$$  r   Údispatch_async_delegationrý  E  s  € ô 'Ó(€MÜò 	wÙ#ð	wÙ*.ð	wÙ6:ð	wÙDKð	wáð	wá $ð	wá,1ð	wá?Jð	wñ ,ð	wñ 5;ð	wñ 2ð		wñ FWð		wñ
 "ð	wñ
 7Ið	wñ
 Wbð	wð 2Ð2DÐ1Eð Fuñ uð	w€Fð ˆhÕ˜<Ô'Ü�‰ÐIØ!×#9Ð#9°'¸D¿J¸JÀBÈÕ;Lô	Nà€Mr   rR   c          $     ó`   € V ^8„  d   QhRRRRRRRRR	RR
RRRRRRRRRRRRRRRRRRRRRRRRR/# )r   rY   z	list[str]rZ   r˜   r[   rÁ  r\   r…   r]   rS   rU   rÂ  rÃ  rT   rW   rÄ  rÅ  rÆ  r   rR   rÇ  rÈ  r¿  r_   rÊ  r`   rË  r   r@   r   )r   s   "r   r   r   a  s¶   € ÷ !ñ !Øð!Ø"/ð!Ø;Nð!ØVYð!Øboð!àð!à)6ð!àGcð!ð ð!ð 8;ð!ð Plð!ð ð	!ð KXð	!ð
 /ð!ð
 BOð!ð &ð!ð /ð!ð ñ!r   c                óî  € T;'       g    \        4       pVe   V Uu. uF  pV V,          NK  	  upM
\        V 4      p\        V4      pV^8X  d
   V^ ,          M!V R2RP                  R V 4       4      ,           p\	        R/ RVbRVbRV bRVbRVbR	VbR
VbRVbRVbRVbRVbRV	bRV
bRVbRVbRVbRVbRVbRRV R2b pVR,          R8X  d#   \
        P                  RTTT;'       g    R4       V# u upi )u™  Dispatch a fan-out unit (a whole batch, or one ``group`` of a delegate_task call) as ONE
background unit: ``runner`` runs its tasks and returns the combined ``{"results": [...],
"total_duration_seconds": N}`` dict. The unit occupies ONE async slot â€” or joins the slot named
by ``slot_key`` (in-unit parallelism is bounded separately) â€” and produces a SINGLE completion
event carrying per-task ``results``.z parallel subagents: z; c              3  ó2   "  € T F  qR ,          x € K  	  R# 5i):Né(   NNr   )r¹   Úgs   & r   rº   Ú2dispatch_async_delegation_batch.<locals>.<genexpr>s  s   é € ÐXtÑisÐdeÐ[^×Y_ÒY_Óisùs   ‚rR   rX   rY   rZ   r[   r\   r]   rS   rU   rÂ  rT   rW   rÄ  rÆ  rÇ  r¿  r_   r`   rÉ  rø  z¬ running). Wait for one to finish (its result will re-enter the chat), or raise delegation.max_concurrent_children in config.yaml to allow more concurrent background units.r€   rê  zADispatched async delegation batch %s (%d task(s), session_key=%s)rù  r   )r‰  rž   r    rR  r¾  r�   rû  )rY   rZ   r[   r\   r]   rS   rU   rÂ  rT   rW   rÄ  rÆ  rR   rÇ  r¿  r_   r`   r£   Ú
unit_goalsÚnÚcombined_goalrü  s   $$$$$$$$$$$$$$$$$     r   Údispatch_async_delegation_batchr  a  s’  € ð "×9Ð9Ô%7Ó%9€Mà5AÒ5M¡LÓ1¡L˜q�%˜—(�(¡LÒ1ÔSWÐX]ÓS^€JÜˆJ‹€AØ%&¨!¤V�J˜q–M°A°3Ð6KÐ1LÈtÏyÉyÑXtÑisÓXtÓOtÕ1t€MÜò 
GÙ#ð
GÙ*7ð
GÙ?Dð
GÙNUð
Gáð
Gá $ð
Gá,1ð
Gá?Jð
Gñ ,ð
Gñ 5;ð
Gñ 2ð	
Gñ FWð	
Gñ
 "ð
Gñ
 7Ið
Gñ
 Wbð
Gñ
 muð
Gñ "ð
Gñ 5Eð
Gð 2Ð2DÐ1Eð FEñ Eð
G€Fð ˆhÕ˜<Ô'Ü�‰ÐWØ! 1 k×&<Ð&<°Wô	>à€Mùò# 2s   �C2c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   rR   r…   r~   r   r€   r   r4   r   )r   s   "r   r   r   †  s(   € ÷ "ñ "˜Sð "¨#ð "°sð "¸tñ "r   c                ó&  € \         ;_uu_ 4        \        P                  V 4      pVe   VP                  R4      \        9  d    RRR4       R# RVR&   \        P                  ! 4       VR&   RVR&   RVR&   \        V4      pRRR4       \        X\        V4      '       d	   V! V4      MTV4       \         ;_uu_ 4        V \        9   d   V\        V ,          R&   \        4        RRR4       R#   + '       g   i     Lt; i  + '       g   i     R# ; i)a»  Atomically claim terminal delivery, push the completion event, then mark ``status``.
``result`` is a dict or a callable receiving the record snapshot (stall path). The record
stays active ("finalizing") until durable persistence and queue publication finish; otherwise
process shutdown can kill this daemon worker after status flips but before SQLite commits.
A second call for the same id (late runner return after a forced stall) is a no-op.Nr€   ru  r‚   rÄ  rÇ  )	rm  r   re   rí  ra   rÝ   Ú_push_completion_eventÚcallabler–  )rR   r~   r€   rN   Úsnapshots   &&&  r   rà  rà  †  sÏ   € ÷ 
ŽÜ—‘˜mÓ,ˆØŠ>˜VŸZ™Z¨Ó1¼ÔGØ÷ 
‰ð (ˆˆxÑÜ!%§¢£ˆˆ~ÑØ!%ˆˆ~ÑØ $ˆˆ}ÑÜ˜“<ˆ÷ 
ô ˜8¼À&×9IÒ9I¡V¨HÔ%5ÈvÐW]Ô^ß	ŽØœHÔ$Ø06ŒH�]Õ# HÑ-ÜÔ!÷ 
‰÷ 
�ú÷ 
�ˆús   �5C,Á2C,Â<&C?Ã,C<	Ã?D	c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   rN   r@   r~   r€   r…   r   r4   r   )r   s   "r   r   r   œ  s0   € ÷ 0Jñ 0J >ð 0J¸>ð 0JÐSVð 0JÐ[_ñ 0Jr   c                óº  € \        V P                  R4      4      pV'       d   RMRp ^ RIHp T P                  R	4      ;'       g    \        P                  ! 4       pT P                  R
4      ;'       g    \        P                  ! 4       pT'       dt   RRRTP                  R4      ;'       g    . RTP                  R4      RTP                  R4      RTP                  R4      /TP                  R4      e   RTR,          /M/ Cp	MXRTP                  R4      RTP                  R4      RTP                  R^ 4      RTP                  R\        Y‡,
          ^4      4      /p	RRRT P                  R4      RT P                  RR4      RT P                  RR4      RT P                  RR4      RT P                  R4      RT P                  RR4      /T'       d   RT P                  R4      /M/ CRT P                  R4      RT P                  R4      RT P                  R4      RT'       d   T P                  R4      M)TP                  R4      ;'       g    T P                  R4      R T/CT	CR	TR
T/CT'       d   / MR!TP                  R!4      /C\         U
u/ uF$  q P                  T
4      '       g   K  Y T
,          bK&  	  up
C\         U
u/ uF  qªT9   g   K  Y¡T
,          bK  	  up
Cp \        Y±4        TP                  P                  T4       R#   \         d6   p\
        P                  RT R2T P                  R4      T4        Rp?R# Rp?ii ; iu up
i u up
i   \         d5   p\
        P                  RT R"2T P                  R4      T4        Rp?L¥Rp?ii ; i  \         d6   p\
        P                  RT R#2T P                  R4      T4        Rp?R# Rp?ii ; i)$a[  Push a type='async_delegation' event onto the shared completion queue. Batch records
(``is_batch``) carry the per-task ``results`` list (plus live transcript paths, the
full-fidelity record of each child's run) instead of a single summary. Best-effort: failure
must not crash the worker, but it WOULD mean a silently-lost result, so we log loudly.r^   rÍ  rE   ©Úprocess_registryrÚ  z@ %s finished but process_registry import failed; result lost: %srR   NrV   r‚   Tr‰   Úlive_transcriptsr™   r¨  Úgrouprœ   r¢  r£  rÀ   rÁ   rS   rT   rW   rU   rX   rY   rZ   r[   r\   r]   r€   Úexit_reasonzo %s: durable completion write failed; delivering in-memory only (a restart may report this unit as unknown): %sz8 %s: failed to enqueue completion event; result lost: %s)rª   re   Útools.process_registryr  rI   r�   r™   ra   rß  rG   Ú_STALL_META_KEYSrƒ   Úcompletion_queuerÞ   )rN   r~   r€   r^   rå  r  râ  rV   r‚   râ   rJ   rä   s   &&&         r   r
  r
  œ  s®  € ô
 �F—J‘J˜zÓ*Ó+€Hß ‰H b€EðÝ;ð
 —J‘J˜Ó/×>Ð>´4·9²9³;€MØ—:‘:˜nÓ-×<Ð<´·²³€Lßà˜˜i¨¯©°IÓ)>×)DÐ)DÀ"Ø §
¡
Ð+=Ó >ÀÈÏÉÐT[ÓI\Ø$ f§j¡jÐ1IÓ&JðWð .4¯Z©Z¸Ó-@Ò-L�˜ �Ñ)ÐRTð	W‰ð �v—z‘z )Ó,¨g°v·z±zÀ'Ó7JÈKÐY_×YcÑYcÐdoÐqrÓYsØ §
¡
Ð+=¼uÀ\ÕEaÐcdÓ?eÓ fðhˆð 	Ð" O°V·Z±ZÀÓ5Pà�v—z‘z -°Ó4Ø §
¡
Ð+AÀ2Ó FØ˜VŸZ™ZÐ(;¸RÓ@Ø˜VŸZ™ZÐ(;Ó<Ø�—
‘
˜6 2Ó&ðC÷ NV¨G°V·Z±ZÀÓ5HÑ+IÐ[]ðCð 	�6—:‘:˜iÓ(¨*°f·j±jÀÓ6LÈfÐV\×V`ÑV`ÐagÓVhØ¯�—‘˜GÔ$°v·z±zÀ'Ó7J×7aÐ7aÈfÏjÉjÐY`ÓNaØ�&ñCð $ðCð &5°mÀ^ÐUañC÷ ‰2 ¨v¯z©z¸-Ó/HÐIðCõ "/Ó
@¡˜A·*±*¸Q·-Œ<ˆ1�Q�iŠ<¡Ñ
@ðCõ "2Ó
AÑ!1˜A¸&±[Œ<ˆ1�Q�iŠ<Ñ!1Ñ
AðC€CðoÜ˜CÔ(ðJØ×)Ñ)×-Ñ-¨cÖ2øôI ô Ü�‰Ð'¨ wð /'ð 'Ø(.¯
©
°?Ó(CÀSô	Jåûðüò8 AùÚ
Aøô ô oÜ�‰Ð'¨ wð /Lð LØMSÏZÉZÐXgÓMhÐjm÷	oñ 	oûðoûô
 ô JÜ�‰Ð'¨ wð /'ð 'Ø(.¯
©
°?Ó(CÀS÷	Jò 	JûðJús_   ¨L ÊMÊ+MËMËMË"M Ë.N ÌMÌ*MÍMÍNÍ#*NÎNÎOÎ%*OÏOc               ó(   € V ^8„  d   QhRRRRRRRR/# )	r   rR   r…   r†   r@   Ún_tasksr   r   r4   r   )r   s   "r   r   r   Ï  s0   € ÷  qñ  q¨Cð  q¸ð  qÐTWð  qÐ\`ñ  qr   c               óŽ  € \         ;_uu_ 4        \        P                  V 4      pVe   VP                  R4      \        9  d    RRR4       R# \	        V4      pRRR4        ^ RIHp / RRbRRbR	RbR
TbRT bRT.bRXP                  RR4      bRTP                  RR4      bRTP                  RR4      bRTP                  R4      bRTP                  RR4      bRTP                  R4      bRTP                  R4      bRTP                  R4      bRTP                  R4      bRTP                  R4      bRRbRTP                  R4      ;'       g    \        P                  ! 4       R\        P                  ! 4       /C\         Uu/ uF$  qtP                  T4      '       g   K  YtT,          bK&  	  upCp TP                  P                  T4       R#   + '       g   i     EL€; i  \         d"   p\        P                  RY4        Rp?R# Rp?ii ; iu upi   \         d"   p\        P                  RY4        Rp?R# Rp?ii ; i)a~  Surface ONE failed child of a still-running detached batch to the parent now, instead of
when the slowest sibling finishes. In a 1,393-agent run every wave-1 child died in a 401 storm
at 08:29 and the parent learned of it at 09:36, when the batch's "unknown outcome" block finally
arrived: 66 minutes of a dead wave with nothing running. The notice rides the same
``type="async_delegation"`` event shape as the batch result (so every drain/route/format path
treats it identically) with ``task_failure_notice=True`` and a single-entry ``results`` list; the
batch record is NOT finalized and its consolidated result still arrives as before.Nr€   r  zTAsync delegation batch %s: task failure notice dropped (process_registry import): %srÀ   rÁ   r  Tr^   r  rR   r‰   rS   rE   rT   rW   rU   rX   rY   rZ   r[   r\   r]   rt  rV   r‚   zDAsync delegation batch %s: failed to enqueue task failure notice: %s)rm  r   re   rí  rÝ   r  r  rI   r�   r™   ra   rG   r  rÞ   )	rR   r†   r  rN   r  r  râ  rJ   rä   s	   &&$      r   Úpush_task_failure_noticer  Ï  sp  € ÷ 
ŽÜ—‘˜mÓ,ˆØŠ>˜VŸZ™Z¨Ó1¼ÔGØ÷ 
‰ô ˜“<ˆ÷	 
ð
Ý;ð
FØÐ"ð
FØ$9¸4ð
FØAKÈTð
FØS\Ð^eð
Fà˜ð
Fà(1°E°7ð
Fð 	�x—|‘| M°2Ó6ð
Fð 	 §¡Ð-CÀRÓ Hð	
Fð
 	˜XŸ\™\Ð*=¸rÓBð
Fð 	˜XŸ\™\Ð*=Ó>ð
Fð 	�—‘˜V RÓ(ð
Fð +2°8·<±<ÀÓ3Hð
Fð KTÐU]×UaÑUaÐbkÓUlð
Fð 	�H—L‘L Ó,ð
Fð /5°h·l±lÀ6Ó6Jð
Fð MTÐU]×UaÑUaÐbiÓUjð
Fð 	�)ð
Fð -¨h¯l©l¸?Ó.K×.ZÐ.ZÌtÏyÊyË{Ð\jÔlp×luÒluÓlwñ
Fõ $1Ó
D¡=˜a·L±LÀ·OŒ>ˆ1�q�kŠ>¡=Ñ
Dð
F€CðqØ×)Ñ)×-Ñ-¨cÖ2÷- 
�ˆûô ô Ü�‰ÐkÐmzô  	AÝûðüò Eøô ô qÜ�‰Ð[Ð]j×pÒpûðqúsM   �5GÁGÁ"G$ ÆHÆ!HÆ3H ÇG!	Ç$HÇ/HÈHÈIÈ#H?È?Ic               ó   € V ^8„  d   QhRR/# rs   r   )r   s   "r   r   r   ó  s   € ÷  ñ  ˜tñ  r   c                 ó@  € \         ;_uu_ 4        \        e&   \        P                  4       '       d    RRR4       R# \        P	                  4        \
        P                  ! \        RRR7      s\        P                  4        RRR4       R#   + '       g   i     R# ; i)zÄStart (once) the stale-delegation monitor thread. One daemon thread serves
every dispatch; it exits when no monitorable records remain and is restarted
by the next dispatch with a ``progress_fn``.Nzasync-delegate-stale-monitorT)ÚtargetÚnameÚdaemon)	Ú_monitor_lockr   Úis_aliveÚ_monitor_stopÚclearÚ	threadingÚThreadÚ_stale_monitor_loopÚstartr   r   r   rñ  rñ  ó  sg   € ÷
 
ŽÜÒ&¬?×+CÑ+C×+EÒ+EØ÷ 
‰ô 	×ÑÔÜ#×*Ò*Ü&Ð-KÐTXôZˆä×ÑÔ÷ 
��Šús   �"B²B½ABÂB	c               ó   € V ^8„  d   QhRR/# )r   rm   rÙ   r   )r   s   "r   r   r     s   € ÷ #-ñ #-˜Uñ #-r   c           
     ó*  € . . Rr2p\         P                  4        EFO  pVP                  R4      pVR8X  dG   RpYP                  R4      ;'       g    T ,
          \        8¼  d   VP	                  VR,          4       Kb  VP                  R4      pVR8w  g   Vf   K€  RpVP                  R	4      '       g   K›   V! 4       w  rxWtP                  R
4      8w  d   VP                  WpR7       KÎ  YP                  R4      ;'       g    T ,
          p	V'       d   \        M\        p
Wš8¼  g   EK  VP                  RV \        V	^4      V
\        V4      R7       VP	                  VR,          W˜34       EKR  	  WV3#   \
         d    TP                  R
4      Rr‡ LÒi ; i)a   One monitor pass over ``_records``; caller holds ``_records_lock``. Returns
``(stalled, expired, any_monitorable)``: newly-stalling ``(delegation_id, quiet_for, in_tool)``
tuples, stalling ids past the grace window, and whether anything is left to monitor.Fr€   ÚstallingTrÓ  rR   rÇ  rt  rÙ  rÑ  )rÑ  rÒ  rÒ  )r€   rÓ  Ú_stall_quiet_secondsÚ_stall_threshold_secondsÚ_stall_in_tool)r   rn  re   Ú_STALL_GRACE_SECONDSr�   rI   rÜ  Ú_STALE_IN_TOOL_SECONDSÚ_STALE_IDLE_SECONDSrß  rª   )rm   ÚstalledÚexpiredÚany_monitorablerN   r€   rÇ  ÚtokenÚin_toolÚ	quiet_forrG  s   &          r   Ú_sweep_stale_lockedr7    st  € ð )+¨B°�o€GÜ—/‘/×#ˆØ—‘˜HÓ%ˆØ�ZÔØ"ˆOØ—j‘jÐ!2Ó3×:Ð:°sÕ;Ô?SÔSØ—‘˜v oÕ6Ô7ÙØ—j‘j Ó/ˆØ�YÔ +Ò"5ÙØˆØ�z‰z˜*×%Ò%Ùð	BÙ(›]‰NˆEð
 —J‘JÐ0Ó1Ô1Ø�M‰M¨%ˆMÔBÙØŸ:™: nÓ5×<Ð<¸Õ=ˆ	ß*1Õ&Ô7JˆØ×à�M‰MØ!°3ÌUÐS\Ð^_ÓM`Ø).¼tÀG»}ð ô Nð �N‰N˜F ?Õ3°YÐH×Iñ; $ð< ˜_Ð,Ð,øô ô 	Bð $ŸZ™ZÐ(9Ó:¸E’7ð	Bús   Â6	E2Å2FÆFc               ó    € V ^8„  d   QhRRRR/# )r   Úmsgr…   r   rª   r   )r   s   "r   r   r   '  s   € ÷ 	ñ 	˜Sð 	¨Dñ 	r   c                ó¢   € \        V 4      '       g   R#  V ! 4        R#   \         d&   p\        P                  ! T.TOTN5!    Rp?R# Rp?ii ; i)zLInvoke an ``interrupt_fn``; True on success, else debug-log ``msg`` (+ exc).FTN)r  rI   r�   rõ   )r9  r9  Úargsrâ  s   &&* r   Ú_call_interruptr<  '  sD   € ä�B�<Š<ÙðÙ
ŒÙøÜô Ü�Š�SÐ%˜4Ð% Ô%Ýûðús   • žA©A	Á	Ac               ó   € V ^8„  d   QhRR/# rs   r   )r   s   "r   r   r   3  s   € ÷ ñ ˜Tñ r   c                 óH  € \         P                  \        4      '       EgH   \        P                  ! 4       p \        ;_uu_ 4        \        V 4      w  rpRRR4       X Ft  w  rEp\        P                  RWEV\        4       \        ;_uu_ 4        \        P                  V4      ;'       g    / P                  R4      pRRR4       \        XRV4       Kv  	  X F€  p\        ;_uu_ 4        \        P                  V4      ;'       g    / P                  R4      ;'       g    \        P                  ! 4       pRRR4       XP                  \        WD3R lR4       K‚  	  X'       d   EKe  R# R#   + '       g   i     EL ; i  + '       g   i     LÊ; i  + '       g   i     Le; i)aG  Sweep running delegations for stalled progress. A changed progress token refreshes the
record's timestamp; a frozen token past the idle/in-tool threshold marks the record
``stalling`` and calls ``interrupt_fn``; a ``stalling`` record still unreturned after the
grace window is force-finalized with a terminal ``stalled`` event.Nu`   Async delegation %s made no progress for %.0fs (in_tool=%s) â€” interrupting; grace window %.0fsrÄ  z.Async delegation %s stall interrupt failed: %srÐ  c                ó   € \        W4      # r­   )Ú_stalled_result)rá  Úds   &&r   r�  Ú%_stale_monitor_loop.<locals>.<lambda>F  s
   € Ì?Ð[\ÔKbr   r1  )r"  ÚwaitÚ_STALE_CHECK_INTERVALra   rm  r7  r�   r‘   r.  r   re   r<  rë  rì  Úrunrà  )	rm   r1  r2  r3  rR   r6  r5  r9  Úctxs	            r   r&  r&  3  s"  € ô
 × Ñ Ô!6×7Ó7Ü�iŠi‹kˆßŽ]Ü0CÀCÓ0HÑ-ˆG˜o÷ ã18Ñ-ˆM gÜ�N‰Nð Oà(°WÔ>RôT÷ –Ü—l‘l =Ó1×7Ð7°R×<Ñ<¸^ÓL�÷ ä˜BÐ PÐR_Ö`ñ 29ó %ˆMß–Ü—|‘| MÓ2×8Ð8°b×=Ñ=¸jÓI×gÐgÌ[×MeÒMeÓMg�÷ à�G‰G”I˜}Ó.bÐdmÖnñ %÷ ŠÙñ! 8ç�]ˆ]ú÷ —ú÷ —ús*   ÁE*Â/E>Ã(5FÄFÅ*E;	Å>FÆF!c               ó    € V ^8„  d   QhRRRR/# )r   Úevent_recordr@   r   r…   r   )r   s   "r   r   r   K  s   € ÷ 	<ñ 	< nð 	<¸ñ 	<r   c                óH  € RP                  \        V P                  R4      ;'       g    R4      P                  4       4      pV'       d   RVR,           R2MRp\	        V P                  R4      ;'       g    ^ 4      pV^<8¼  d   R	\        V^<,          4       R
2MRpV RV R2# )u  Human wording for a force-finalized stall. This string reaches the user (CLI timeline, Desktop
async-result card), so it names the task, how long it was silent, and what to do â€” no issue
numbers or worker internals (those stay in the log line and the stall_* metadata).Ú rX   rE   zBackground task ":Néx   NÚ"zThe background taskr+  z after z min of no progressz stopped respondingz[ and was cancelled. Nothing else was affected; ask me to run it again if you still need it.)rR  r…   re   ÚsplitrÙ   rß  )rH  rX   rå  ÚquietÚsilences   &    r   Ú_stalled_error_textrP  K  s¦   € ð �8‰8”C˜×(Ñ(¨Ó0×6Ð6°BÓ7×=Ñ=Ó?Ó@€Dß15Ð  T¥
˜|¨1Ñ-Ð;P€EÜ�,×"Ñ"Ð#9Ó:×?Ð?¸aÓ@€EØBGÈ2Ä+�œ˜e b�jÓ)Ð*Ð*=Ñ>ÐSU€GØˆgÐ(¨¨	ð 2;ð ;ð <r   c               ó$   € V ^8„  d   QhRRRRRR/# )r   rR   r…   rH  r@   r   r   )r   s   "r   r   r   W  s&   € ÷ kñ k 3ð k°nð kÈñ kr   c                ó  € VP                  R4      ;'       g    \        P                  ! 4       p\        Y!P                  R4      ;'       g    T,
          ^4      p\        V4      p\        P                  RW4       VP                  R4      pRVP                  R4      RVP                  R4      R	V'       d   R
MVe   RMRR\        /pVP                  R4      '       d   / \        WC4      CVC# / \        WC4      CRRRR/CVC# )zPSynthetic terminal result for a stalling delegation whose runner never returned.r‚   rV   z:Async delegation %s force-finalized as stalled after %.0fsr-  Ústalled_after_quiet_secondsr+  Ústall_threshold_secondsr,  Ústall_phaser5  NÚidleÚstall_grace_secondsr^   r€   r1  r  )	re   ra   rß  rP  r�   r™   r.  r©  r¥  )rR   rH  r‚   r   r™   Ústall_in_toolÚ
stall_metas   &&     r   r@  r@  W  sù   € à×#Ñ# NÓ3×BÐB´t·y²y³{€LÜ�\×%5Ñ%5°oÓ%F×%VÐ%VÈ,ÕWÐYZÓ[€HÜ Ó-€EÜ
‡L�LÐMÈ}Ôgð !×$Ñ$Ð%5Ó6€Mà% |×'7Ñ'7Ð8NÓ'OØ! <×#3Ñ#3Ð4NÓ#OØ§M‘yÀÒAZ±vÐ`dØÔ3ð	5€Jð
 ×Ñ˜
×#Ò#Ø>”,˜uÓ/Ð>°:Ð>Ð>ØjŒm˜EÓ,Ðj¨h¸	À=ÐR[ÑjÐ_iÐjÐjr   c               ó$   € V ^8„  d   QhRRRRRR/# )r   r4  r   rm   rÙ   r   zOptional[list]r   )r   s   "r   r   r   k  s!   € ÷ ñ ¨ð °5ð ¸^ñ r   c                óæ  €  \        V 4      p. pT FÊ  p\        T\         \        34      '       d   \	        T4      ^8¼  g   TP                  R4       KB  RT^ ,          RT^,          /p\	        T4      ^8¼  dT   \        T^,          \        \        34      '       d1   \        \        RT\        T^,          4      ,
          4      ^4      TR&   TP                  T4       KÌ  	  T#   \         d     R# i ; i)zÓParse a progress token into per-child activity dicts (best-effort): delegate_tool
emits one ``(api_call_count, current_tool, last_activity_ts)`` tuple per child;
foreign token shapes degrade to ``None`` entries.Nr¢  Úcurrent_toolg        Úseconds_since_activity)
rž   Ú	TypeErrorr�   rû   r    r�   r   rÙ   rß  r“  )r4  rm   ÚpartsÚoutÚpartr†   s   &&    r   Ú_children_activity_from_tokenrb  k  sÎ   € ðÜ�U“ˆð +-€CÛˆÜ˜4¤$¬ ×/Ò/´C¸³IÀ´NØ�J‰J�tÔÙØ!,¨d°1­g°~ÀtÈAÅwÐ OˆÜˆt‹9˜Œ>œj¨¨a­´3¼°,×?Ò?Ü.3´C¸¸SÄ5ÈÈaÍÃ>Õ=QÓ4RÐTUÓ.VˆEÐ*Ñ+Ø�
‰
�5Öñ ð €Jøô ô Úðús   ‚C! Ã!C0Ã/C0c               ó   € V ^8„  d   QhRR/# )r   r   rI  r   )r   s   "r   r   r     s   € ÷ &ñ &Ð 4ñ &r   c            
     óÔ  € \         P                   ! 4       p / p\        ;_uu_ 4        . p\        P                  4        EF  pVP	                  4        UUu/ uF)  w  rEVR
9  g   K  VP                  R4      '       d   K'  WEbK+  	  pppVP                  R4      pV\        9   df   VP                  R4      '       d   \        WR,          ,
          ^4      VR&   \        VP                  R4      4      '       d   VR,          WR,          &   VR9   d8   \         F-  w  r‰VP                  V4      f   K  VP                  V4      Wi&   K/  	  VP                  V4       EK  	  RRR4       X FT  pVP                  VP                  R4      4      p
V
f   K)   V
! 4       w  r¼\        Y°4      pTe   YÖR&   \        T4      TR	&   KV  	  V# u uppi   + '       g   i     Lr; i  \         d     K�  i ; i)a9  Snapshot of async delegations (running + recently completed) without callables or private
monitor bookkeeping; adds computed live fields for UIs (``seconds_since_progress``,
``children_activity``/``in_tool`` sampled from ``progress_fn``) and stall context once tripped.

Safe to call from any thread. See #51690.
rÇ  rM  r€   rÒ  Úseconds_since_progressrR   NÚchildren_activityr5  >   rÇ  rÄ  )r*  r1  )ra   rm  r   rn  r‘  Ú
startswithre   rí  rß  r  Ú_STALL_FIELD_MAPr�   rI   rb  rª   )rm   Úsamplersr‘  r“   rJ   rK   Úitemr€   ÚsrcÚdstr9  r4  r5  Úactivitys                 r   Úlist_async_delegationsrn    s›  € ô �)Š)‹+€CØ$&€Hß	ŽØˆÜ—‘×"ˆAØ%&§W¡W¤YÔu¡Y™T˜Q°!Ð;ZÑ2Z”DÐcd×coÑcoÐps×ct”D�A’D¡YˆDÑuØ—U‘U˜8“_ˆFØœÔ'Ø—5‘5˜×(Ò(Ü5:¸3À>ÕARÕ;RÐTUÓ5V�DÐ1Ñ2Ü˜AŸE™E -Ó0×1Ò1Ø34°]Õ3C�H˜Õ/Ñ0ØÐ0Ô0ß 0‘H�CØ—u‘u˜S“zÔ-Ø$%§E¡E¨#£J˜›	ñ !1ð �L‰L˜×ñ #÷ 
ó" ˆØ�\‰\˜$Ÿ(™( ?Ó3Ó4ˆØŠ:Ùð	Ù›T‰NˆEô 1°Ó<ˆØÒØ(0Ð$Ñ%Ü˜w›-ˆˆY‹ñ ð €Lùó5 v÷ 
�ûô. ô 	Úð	úsH   ¦.GÁF?Á$F?Á=F?Â5GÂ9A0GÄ.-GÆ	GÆ?GÇG	ÇG'Ç&G'c          
     ó,   € V ^8„  d   QhRRRRRRRRRR/# )	r   ÚtargetsrI  Úcallerr…   Úreasonr9  r   r   r   )r   s   "r   r   r   ¨  s2   € ÷ ñ Ð 4ð ¸cð È3ð ÐUXð Ð]`ñ r   c                ón   a€ \        V3R lV  4       4      pV'       d   \        P                  W4V4       V# )zSCall ``interrupt_fn`` on each record; log ``msg`` once; returns how many succeeded.c           	   3  ó|   <"  € T F1  p\        VP                  R 4      RSVP                  R4      4      x € K3  	  R# 5i)rÄ  z%s: %s interrupt failed: %srR   N)r<  re   )r¹   r“   rq  s   & €r   rº   Ú%_interrupt_records.<locals>.<genexpr>ª  s=   øé € ð áˆAô 	˜Ÿ™˜nÓ-Ð/LÈfÐVW×V[ÑV[Ð\kÓVl×mÐmÛùs   ƒ9<)rÃ   r�   rû  )rp  rq  rr  r9  Úcounts   &f&& r   Ú_interrupt_recordsrw  ¨  s2   ø€ äô áóó €E÷ Ü�‰�C Ô'Ø€Lr   c               ó    € V ^8„  d   QhRRRR/# )r   rr  r…   r   r   r   )r   s   "r   r   r   ²  s   € ÷ kñ k˜#ð k¨sñ kr   c                óø   € \         ;_uu_ 4        \        P                  4        Uu. uF   qP                  R4      \        9   g   K  VNK"  	  ppRRR4       \        XRV R4      # u upi   + '       g   i     L#; i)z´Signal every running async delegation to stop (``/stop``, shutdown). Returns how
many. The child still emits a completion event (status='interrupted') via the
normal finalize path.r€   NÚinterrupt_allz'Interrupted %d async delegation(s) (%s))rm  r   rn  re   rí  rw  )rr  r“   rp  s   &  r   rz  rz  ²  sZ   € ÷ 
ŽÜ&Ÿo™oÔ/ÓUÑ/˜·5±5¸³?ÄnÑ3T—1�1Ñ/ˆÐU÷ 
ä˜g ¸Ð@iÓjÐjùò V÷ 
�ús"   �A)¦A$ÁA$ÁA)Á$A)Á)A9	c          
     ó,   € V ^8„  d   QhRRRRRRRRRR/# )r   rS   r…   rT   rU   rr  r   r   r   )r   s   "r   r   r   »  s;   € ÷ pñ pØðpØ14ðpØNQðpØ`cðpàñpr   c                ó@   € \        \        WV4      p\        VRVR4      # )zˆSignal running async delegations owned by ONE ending session to stop (any
selector matches, see ``_session_records``). Returns how many.Úinterrupt_for_sessionz:Interrupted %d async delegation(s) for ending session (%s))r€  rí  rw  )rS   rT   rU   rr  rp  s   &&&& r   r}  r}  »  s-   € ô
 œ~¨{ÐRcÓd€GÜØÐ(¨&Ð2nópð pr   c               ó   € V ^8„  d   QhRR/# rs   r   )r   s   "r   r   r   Å  s   € ÷ #ñ #˜$ñ #r   c                 ó¦  € \         ;_uu_ 4        \        e   \        P                  RR7       Rs^ sRRR4       \        P                  4        \        ;_uu_ 4        \        Rup sRRR4       X e)   V P                  4       '       d   V P                  ^R7       \        ;_uu_ 4        \        P                  4        RRR4       \        ;_uu_ 4        \        P                  4        \        P                  4        RRR4       R#   + '       g   i     LÜ; i  + '       g   i     L»; i  + '       g   i     Lw; i  + '       g   i     R# ; i)z@Test-only: clear all state and tear down the executor + monitor.NF)rC  )Útimeout)ra  r   Úshutdownr   r"  r   r   r   r!  rR  rm  r   r#  rß   r   r   )Úthreads    r   Ú_reset_for_testsrƒ  Å  sÊ   € ÷ 
ŽÜÒ Ü×Ñ EÐÔ*Øˆ	Ø !Ð÷	 
ô
 ×ÑÔß	ŽÜ"1°4Ðˆ�÷ 
àÒ˜fŸo™o×/Ò/Ø�‰˜AˆÔß	ŽÜ�‰Ô÷ 
ç	ŽÜ�‰ÔÜ× Ñ Ô"÷ 
‰÷ 
�ú÷ 
�ú÷ 
�úç	�ˆús/   �#DÁ
DÂ(D,Ã)D?ÄD	ÄD)	Ä,D<	Ä?E	i€:	 g     A>   rt  r*  ru  )rt  r*  )Úscope_idÚuser_idÚ	user_name)rS  rT  rU  rW  ))r+  rS  )r,  rT  )r-  rX  >   r™   rX  Úfailurer1  r€  r›   Úinterruptedg     õ@)rE   rE   )rE   rE   rE   )r�  )rE   rE   rE   Úsession_end)‚Ú__conditional_annotations__Ú__doc__Ú
__future__r   rë  rj   Úloggingrc   Úsqlite3r$  ra   r  Úconcurrent.futuresr   Útypingr   r   r   r   r   r,   r	   r
   Útools.daemon_poolr   Útools.thread_contextr   Ú	getLoggerrÞ  r�   r   Ú__annotations__ÚLockra  r   rm  r   Ú_DEFAULT_MAX_ASYNC_CHILDRENrw   ru   rx   rì   rÜ   rë   rh   rô   rê   rß   r   r   r   rD  r0  r/  r.  r   r   ÚEventr"  ri  rí  rG   r  rh  r   r2   r/   r=   rL   rq   rl   rƒ   r”   r¤   r²   rÑ   r×   rÕ   rð   r÷   rþ   r  r	  r  r  r  r  r!  r$  r)  r/  r3  r2  r-  r@  Ú	frozensetrU  rQ  rF  r\  rc  ro  rw  r€  rƒ  r‰  r–  r�  r¥  r©  r³  r¾  r»  rý  r  rà  r
  r  rñ  r7  r<  r&  rP  r@  rb  rn  rw  rz  r}  rƒ  )rŠ  s   @r   Ú<module>r™     s³  øðôhõ #ã Û Û Û 	Û Û Û Û Ý 1ß 6Õ 6ç =Ý 6Ý <à	×	Ò	˜8Ó	$€ð
 +/€	Ð'Ó .Ø—’Ó!€ØÐ �sÓ à—’Ó €à&(€Ð
#Ó (àÐ àÐ Ø-Ð ØÐ àÐ ð  +Ð à€Ø�>Š>Ó€ð Ð à€Ø�~Š~Ó€ñ “€ˆ#Ó Ø')Ð Ð$Ó )ð Ð ØÐ ØÐ ØÐ à—’Ó €Ø.2€Ð+Ó 2Ø—’Ó!€â4€Ø(€ð 5€àsÐ ðrÐ ò
*õõ&!ò #õõõ8Bõ2MõIõ(yõõ/õd>õ4ð4*AÀt÷ *AðZÈT÷ õ"7õ`õ!õ ZõTõ!õ.0õ	NõKõCõ6Aõ!õ	Yõ:õ
	Hñ  Ò nÓoÐ Ø'Ð õ4ñ(ØQSð(Ølp÷(ð (õXõTõXõ[÷fõ
+õ õõnõOõoõ,ðRDð
 `dðRDð )-ðRDð 26÷RDðjà9=ðð !#ðð >@ðð osðð :ð	ð im÷	ð8!à9=ð!ð !#ð!ð >@ð!ð osð!ð :ð	!ð [_ð	!ð
 26ð!ð
 RVð!ð )-ð!ð 26÷!õJ"õ,0Jõf qõH õ#-õL	õõ0	<õkõ(õ(&õR÷k÷p÷#r   