
    xjI                    B   d Z ddlmZ ddlmZmZ ddlZddlmZ ddl	m
Z
mZmZmZmZ dZdZd	Zd
ZeeehZ ed           G d d                      Z ed           G d d                      Z ed           G d d                      Z ed           G d d                      Z eddd           G d d                      Z G d de          Zd7d8dZd7d9d!Zd7d9d"Zdddd#d:d)Zd;d-Zd<d0Zd=d2Z  G d3 d4          Z! G d5 d6          Z"dS )>a  RuntimeAdapter seam for WebUI-owned run execution.

This is the #1925 RuntimeAdapter seam.  The default WebUI chat path remains the
legacy direct route; enabling ``HERMES_WEBUI_RUNTIME_ADAPTER=legacy-journal``
routes through this protocol-translator facade over the same legacy execution
path plus the Slice 1 run journal.  Slice 4 adds a default-off runner-local
selection point for tests and future runner backends, but live chat routes still
stay on the legacy path until a separate route-wiring slice is reviewed.  This
module intentionally does not own AIAgent instances, cancellation flags,
approval callbacks, clarify callbacks, or new long-lived queues.
    )annotations)	dataclassfieldN)Path)AnyCallableIterableLiteralProtocolHERMES_WEBUI_RUNTIME_ADAPTERzlegacy-directzlegacy-journalzrunner-localT)frozenc                      e Zd ZU ded<   ded<    ee          Zded<   dZded	<   dZded
<   dZ	ded<   dZ
ded<    ee          Zded<   dZded<    ee          Zded<   dS )StartRunRequeststr
session_idmessagedefault_factorylist[dict[str, Any]]attachmentsN
str | None	workspaceprofileprovidermodel	list[str]toolsetswebuisourcedict[str, Any]metadata)__name__
__module____qualname____annotations__r   listr   r   r   r   r   r   r   dictr!        6/Users/bertmahoney/hermes-webui/api/runtime_adapter.pyr   r      s         OOOLLL(-d(C(C(CKCCCC I    GHE%555H5555F$uT:::H::::::r)   r   c                      e Zd ZU ded<   ded<   ded<   dZded<   dZded	<   dZd
ed<    ee          Z	ded<    ee
          Zded<   dS )RunStartResultr   run_idr   	stream_idstartedstatusNzfloat | None
started_atr   cursorr   r   active_controlsr    payload)r"   r#   r$   r%   r0   r1   r2   r   r&   r3   r'   r4   r(   r)   r*   r,   r,   ,   s         KKKOOONNNF#J####F!&t!<!<!<O<<<<#eD999G999999r)   r,   c                  X    e Zd ZU ded<    ee          Zded<   dZded<   dZded	<   dS )
RunEventStreamr   r-   r   r   eventsNr   r2   last_event_id)	r"   r#   r$   r%   r   r&   r7   r2   r8   r(   r)   r*   r6   r6   8   s[         KKK#(5#>#>#>F>>>>F $M$$$$$$r)   r6   c                      e Zd ZU ded<   dZded<   dZded<   dZded<   dZded	<    ee	
          Z
ded<   dZded<   dZded<   dS )	RunStatusr   r-   Nr   r   unknownr0   r8   terminal_stater   r   r3   pending_approval_idpending_clarify_id)r"   r#   r$   r%   r   r0   r8   r<   r   r&   r3   r=   r>   r(   r)   r*   r:   r:   @   s         KKK!J!!!!F $M$$$$!%N%%%%!&t!<!<!<O<<<<&*****%)))))))r)   r:   F)r   equnsafe_hashc                  f    e Zd ZU ded<   dZded<   dZded<   dZded<    ee	          Z	d
ed<   dS )ControlResultboolacceptedr   r0   Nr   event_idsafe_messager   r    r4   )
r"   r#   r$   r%   r0   rE   rF   r   r'   r4   r(   r)   r*   rB   rB   L   sn          NNNFH#L#####eD999G999999r)   rB   c                  ^    e Zd Zd#dZddd$dZd%dZd&dZd'dZd(dZddd)dZ		 d*d+d"Z
dS ),RuntimeAdapterrequestr   returnr,   c                    d S Nr(   )selfrI   s     r*   	start_runzRuntimeAdapter.start_runZ         r)   Nr2   r-   r   r2   r   r6   c                   d S rL   r(   )rM   r-   r2   s      r*   observe_runzRuntimeAdapter.observe_run[   rO   r)   r:   c                    d S rL   r(   rM   r-   s     r*   get_runzRuntimeAdapter.get_run\   rO   r)   rB   c                    d S rL   r(   rT   s     r*   
cancel_runzRuntimeAdapter.cancel_run]   rO   r)   approval_idchoicec                    d S rL   r(   rM   r-   rX   rY   s       r*   respond_approvalzRuntimeAdapter.respond_approval^   rO   r)   
clarify_idresponsec                    d S rL   r(   rM   r-   r]   r^   s       r*   respond_clarifyzRuntimeAdapter.respond_clarify_   rO   r)   queuemoder   rd   c                   d S rL   r(   rM   r-   r   rd   s       r*   queue_messagezRuntimeAdapter.queue_message`   rO   r)    r   action<Literal['set', 'pause', 'resume', 'clear', 'status', 'edit']textc                    d S rL   r(   rM   r   ri   rk   s       r*   update_goalzRuntimeAdapter.update_goala   s	    
 r)   rI   r   rJ   r,   r-   r   r2   r   rJ   r6   r-   r   rJ   r:   r-   r   rJ   rB   r-   r   rX   r   rY   r   rJ   rB   r-   r   r]   r   r^   r   rJ   rB   r-   r   r   r   rd   r   rJ   rB   rh   r   r   ri   rj   rk   r   rJ   rB   )r"   r#   r$   rN   rR   rU   rW   r\   ra   rg   rn   r(   r)   r*   rH   rH   Y   s        HHHH?C[[[[[[4444;;;;````````FMdddddd
 	      r)   rH   environdict[str, str] | NonerJ   r   c                    | t           j        n| }t          |                    t          t
                    pd                                                                          }|t          v r|nt
          S )zGReturn the configured adapter mode, defaulting safely to legacy-direct.Nrh   )	osrx   r   get_RUNTIME_ADAPTER_ENV_RUNTIME_ADAPTER_DIRECTstriplower_VALID_RUNTIME_ADAPTER_MODES)rx   r   raws      r*   runtime_adapter_moder   i   sa    "?RZZF
fjj-/FGGM2
N
N
T
T
V
V
\
\
^
^C55533;RRr)   rC   c                2    t          |           t          k    S rL   )r   _RUNTIME_ADAPTER_JOURNALrx   s    r*   runtime_adapter_enabledr   p   s    ((,DDDr)   c                2    t          |           t          k    S rL   )r   _RUNTIME_ADAPTER_RUNNER_LOCALr   s    r*   runtime_adapter_runner_enabledr   t   s    ((,IIIr)   )rx   legacy_adapter_factoryrunner_client_factoryr   #Callable[[], RuntimeAdapter] | Noner   Callable[[], Any] | NoneRuntimeAdapter | Nonec                    t          |           }|t          k    rdS |t          k    r|t          d           |            S |t          d          t	           |                      S )a  Build the configured RuntimeAdapter without changing route behavior.

    ``None`` means the safe default ``legacy-direct`` path should keep using the
    existing direct route.  ``legacy-journal`` is opt-in and delegates to the
    supplied legacy factory.  ``runner-local`` is also opt-in and only constructs
    a ``RunnerRuntimeAdapter`` around an injected client; this function does not
    create process-global runner state or wire live chat to the runner backend.
    Nz5legacy-journal mode requires a legacy adapter factoryz2runner-local mode requires a runner client factory)client)r   r~   r   NotImplementedErrorRunnerRuntimeAdapter)rx   r   r   rd   s       r*   build_runtime_adapterr   x   s      ((D&&&t'''!)%&]^^^%%'''$!"VWWW'<'<'>'>????r)   r2   r   
int | Nonec                    | dv rd S 	 t          |           }d|v r|                    dd          d         }t          dt          |                    S # t          t
          f$ r Y dS w xY w)N)Nrh   :   r   )r   rsplitmaxint	TypeError
ValueError)r2   rk   s     r*   _cursor_to_after_seqr      s    t6{{$;;;;sA&&r*D1c$ii   z"   qqs   AA A)(A)valuer   c                   t          | t                    r| S t          | t                    rt          |                     dd                    }t          |t          |                     d          p|                     d          p|rdnd          |s|                     d          ndt          |           	          S t          |           }t          ||rdnd|rdnd
          S )a~  Normalize legacy delegate responses without changing their payloads.

    ``status`` is an adapter-level summary used by current control tests and
    future runtime backends.  For legacy goal payloads it may mirror the goal
    action (``set`` / ``pause`` / ``status``), while public route behavior keeps
    using the payload itself to preserve existing HTTP response shapes.
    okTr0   ri   rD   z
not-activer   N)rD   r0   rF   r4   z*Legacy control did not accept the request.)rD   r0   rF   )
isinstancerB   r'   rC   r|   r   )r   rD   s     r*   _active_control_resultr      s     %'' % 
		$--..uyy**oeii.A.AoT\Fnjjbnpp5=G9---4KK	
 
 
 	
 E{{H%7zz<%WTT+W   r)   namec                ,    t          dd|  d          S )NFunsupportedz) is not supported by this runner backend.r0   rF   )rB   )r   s    r*   _runner_unsupported_controlr      s+    GGG   r)   c                  j    e Zd ZdZd'dZd(d	Zd
dd)dZd*dZd+dZd,dZ	d-dZ
ddd.d Z	 d/d0d&Zd
S )1r   ax  Protocol-translator facade for a future runner/sidecar backend.

    Slice 4 moves runtime ownership behind a runner boundary, but the WebUI
    adapter must remain a translator.  This class deliberately delegates to an
    injected client instead of owning process-local streams, cancellation flags,
    approval queues, clarify queues, or cached agent instances itself.
    r   r   c                   || _         d S rL   )_client)rM   r   s     r*   __init__zRunnerRuntimeAdapter.__init__   s    r)   rI   r   rJ   r,   c           
        t          | j        dd           }|t          d           ||          }t          |t                    r|S t          |pi           }t          |                    d          p|                    d          pd          }t          |                    d          p|          }t          |                    d          p|j                  }|                    d          }t          |t                    sg }t	          |||t          |                    d          pd	          |                    d
          |                    d          ||          S )NrN   z7RunnerRuntimeAdapter.start_run requires a runner clientr-   r.   rh   r   r3   r0   r/   r1   r2   r-   r   r.   r0   r1   r2   r3   r4   )
getattrr   r   r   r,   r'   r   r|   r   r&   )rM   rI   rN   r4   r-   r.   r   r3   s           r*   rN   zRunnerRuntimeAdapter.start_run   sX   DL+t<<	%&_```)G$$g~.. 	Nw}"%%W[[**Lgkk+.F.FL"MMK00:F;;	\22Hg6HII
!++&788/400 	! O!w{{8,,9	::{{<00;;x((+	
 	
 	
 		
r)   NrP   r-   r   r2   r   r6   c                  t          | j        dd           }|t          |g |d           S  |||          }t          |t                    r|S t	          |pi           }t          |                    d          pg           }|                    d          p|r|d                             d          nd }|                    d          }|,|r*t          |d                             d	          pd
          }t          t          |                    d          p|          ||t          |          n||          S )NrR   r-   r7   r2   r8   rP   r7   r8   r   rE   r2   seqrh   r-   )r   r   r6   r   r'   r&   r|   r   )	rM   r-   r2   rR   resultr4   r7   r8   next_cursors	            r*   rR   z RunnerRuntimeAdapter.observe_run   sK   dlM4@@!6Y]^^^^VF333fn-- 	Mv|$$gkk(++1r22O44hW]9g
9S9S9Scgkk(++6fRjnnU339r::Kw{{8,,677'2'>3{###F'	
 
 
 	
r)   r:   c                   t          | j        dd           }|t          |          S  ||          }t          |t                    r|S t	          |pi           }|                    d          }t          |t                    sg }t          t          |                    d          p|          t          |                    d          pd          pd t          |                    d          pd          |                    d	          |                    d
          ||                    d          |                    d                    S )NrU   r-   r3   r-   r   rh   r0   r;   r8   r<   r=   r>   )r-   r   r0   r8   r<   r3   r=   r>   )r   r   r:   r   r'   r|   r&   r   )rM   r-   rU   r   r4   r3   s         r*   rU   zRunnerRuntimeAdapter.get_run   s;   $,	488?F++++fi(( 	Mv|$$!++&788/400 	! Ow{{8,,6777;;|44:;;Ctw{{8,,9	::!++o66";;'788+ ',A B B&{{+?@@	
 	
 	
 		
r)   rB   c                    t          | j        dd           }|t          d          S t           ||                    S )NrW   Cancelr   r   r   r   )rM   r-   rW   s      r*   rW   zRunnerRuntimeAdapter.cancel_run  sA    T\<>>
.x888%jj&8&8999r)   rX   rY   c                    t          | j        dd           }|t          d          S t           ||||                    S )Nr\   Approvalr   )rM   r-   rX   rY   r\   s        r*   r\   z%RunnerRuntimeAdapter.respond_approval  sI    "4<1CTJJ#.z:::%&6&6v{F&S&STTTr)   r]   r^   c                    t          | j        dd           }|t          d          S t           ||||                    S )Nra   Clarifyr   )rM   r-   r]   r^   ra   s        r*   ra   z$RunnerRuntimeAdapter.respond_clarify  sF    !$,0A4HH".y999%oofj(&S&STTTr)   rb   rc   r   rd   c                   t          | j        dd           }|t          d          S t           ||||                    S )Nrg   Queuerc   r   )rM   r-   r   rd   rg   s        r*   rg   z"RunnerRuntimeAdapter.queue_message!  sH    otDD .w777%mmFG$&O&O&OPPPr)   rh   r   ri   rj   rk   c                    t          | j        dd           }|t          d          S t           ||||                    S )Nrn   Goalr   )rM   r   ri   rk   rn   s        r*   rn   z RunnerRuntimeAdapter.update_goal'  sG     dlM4@@.v666%kk*fd&K&KLLLr)   )r   r   ro   rp   rq   rr   rs   rt   ru   rv   rw   r"   r#   r$   __doc__r   rN   rR   rU   rW   r\   ra   rg   rn   r(   r)   r*   r   r      s           
 
 
 
2 @D 
 
 
 
 
 
(
 
 
 
,: : : :U U U UU U U U GN Q Q Q Q Q Q 		M 	M 	M 	M 	M 	M 	Mr)   r   c            	      ~    e Zd ZdZdddddddddd3dZd4dZddd5dZd6dZd7d!Zd8d$Z	d9d'Z
d(d)d:d,Z	 d;d<d2ZdS )=LegacyJournalRuntimeAdapterzProtocol-translator facade over the current legacy streaming path.

    Delegates keep Slice 2 honest: this adapter has no worker thread, AIAgent
    cache, cancellation registry, approval queue, or clarify queue of its own.
    N)start_run_delegatecancel_delegateapproval_delegateclarify_delegatequeue_delegategoal_delegatelive_stream_lookupsession_dirr   2Callable[[StartRunRequest], dict[str, Any]] | Noner   Callable[[str], Any] | Noner   %Callable[[str, str, str], Any] | Noner   r   r   r   Callable[[str], bool] | Noner   Path | Nonec                   || _         || _        || _        || _        || _        || _        |pd | _        |t          |          nd | _        d S )Nc                    dS )NFr(   )_run_ids    r*   <lambda>z6LegacyJournalRuntimeAdapter.__init__.<locals>.<lambda>L  s    % r)   )	_start_run_delegate_cancel_delegate_approval_delegate_clarify_delegate_queue_delegate_goal_delegate_live_stream_lookupr   _session_dir)	rM   r   r   r   r   r   r   r   r   s	            r*   r   z$LegacyJournalRuntimeAdapter.__init__:  se     $6  /"3!1-+#5#P:O:O 1<1HD---dr)   rI   r   rJ   r,   c           
        | j         t          d          t          |                      |          pi           }t          |                    d          p|                    d          pd          }t          |                    d          p|          }t          |                    d          p|j                  }|                    d          }t          |t                    s|rdgng }t          |||t          |                    d          pd	          |                    d
          |                    d          ||          S )Nz@LegacyJournalRuntimeAdapter.start_run requires a legacy delegater.   r-   rh   r   r3   cancelr0   r/   r1   r2   r   )	r   r   r'   r   r|   r   r   r&   r,   )rM   rI   r4   r.   r-   r   r3   s          r*   rN   z%LegacyJournalRuntimeAdapter.start_runO  s<   #+%&hiiit//88>B??K00OGKK4I4IORPP	W[[**7i88\22Hg6HII
!++&788/400 	>,5=xjj2O!w{{8,,9	::{{<00;;x((+	
 	
 	
 		
r)   rP   r-   r   r2   r   r6   c          	        ddl m}m}  ||| j                  }|st	          |g |d           S  |t          |                    d          pd          |t          |          | j                  }t          |                    d          pg           }|r|d	                             d
          n|                    d          }t	          |||r(t          |d	                             d                    n||          S )Nr   )find_run_summaryread_run_eventsr   r   r   rh   )	after_seqr   r7   r   rE   r8   r   )	api.run_journalr   r   r   r6   r   r|   r   r&   )	rM   r-   r2   r   r   summaryjournalr7   r8   s	            r*   rR   z'LegacyJournalRuntimeAdapter.observe_rund  s)   EEEEEEEE""6t7HIII 	_!6Y]^^^^!/L))/R00*622)	
 
 
 gkk(++1r226<^r
z222'++oB^B^17C3vbz~~e,,---V'	
 
 
 	
r)   r:   c                    ddl m} t          |                     |                    } ||| j                  }|rQt          |t          |pi                     d          pd          pd d|pi                     d          d dg	          S |rp|                    d
          }t          |t          |                    d          pd          pd t          |pd          |                    d          |g 	          S t          |          S )Nr   )r   r   r   rh   runningr8   r   )r-   r   r0   r8   r<   r3   r<   r;   r   )r   r   rC   r   r   r:   r   r|   )rM   r-   r   liver   r<   s         r*   rU   z#LegacyJournalRuntimeAdapter.get_runy  s?   444444D,,V4455""6t7HIII 	222<@@FBGGO4 &}"11/BB#!)
     		$[[)9::Nw{{<88>B??G4>6Y77%kk/::- "    ''''r)   rB   c                x    | j         t          ddd          S t          |                      |                    S )NFr   z%Cancel is not wired for this adapter.r   )r   rB   r   rT   s     r*   rW   z&LegacyJournalRuntimeAdapter.cancel_run  s=     ( }Krssss%d&;&;F&C&CDDDr)   rX   rY   c                |    | j         t          ddd          S t          |                      |||                    S )NFr   z)Approval is delegated to the legacy path.r   )r   rB   r   r[   s       r*   r\   z,LegacyJournalRuntimeAdapter.respond_approval  sB    "* }Kvwwww%d&=&=fkSY&Z&Z[[[r)   r]   r^   c                |    | j         t          ddd          S t          |                      |||                    S )NFr   z(Clarify is delegated to the legacy path.r   )r   rB   r   r`   s       r*   ra   z+LegacyJournalRuntimeAdapter.respond_clarify  sB    !) }Kuvvvv%d&<&<VZQY&Z&Z[[[r)   rb   rc   r   rd   c               |    | j         t          ddd          S t          |                      |||                    S )NFr   z&Queue is delegated to the legacy path.r   )r   rB   r   rf   s       r*   rg   z)LegacyJournalRuntimeAdapter.queue_message  sA    ' }Kstttt%d&:&:67D&Q&QRRRr)   rh   r   ri   rj   rk   c                |    | j         t          ddd          S t          |                      |||                    S )NFr   z%Goal is delegated to the legacy path.r   )r   rB   r   rm   s       r*   rn   z'LegacyJournalRuntimeAdapter.update_goal  sC     & }Krssss%d&9&9*fd&S&STTTr)   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ro   rp   rq   rr   rs   rt   ru   rv   rw   r   r(   r)   r*   r   r   3  sC         RV7;CGBF@D?C;?#'S S S S S S*
 
 
 
* @D 
 
 
 
 
 
*( ( ( (4E E E E
\ \ \ \
\ \ \ \
 GN S S S S S S 	U U U U U U Ur)   r   rL   )rx   ry   rJ   r   )rx   ry   rJ   rC   )rx   ry   r   r   r   r   rJ   r   )r2   r   rJ   r   )r   r   rJ   rB   )r   r   rJ   rB   )#r   
__future__r   dataclassesr   r   r{   pathlibr   typingr   r   r	   r
   r   r}   r~   r   r   r   r   r,   r6   r:   rB   rH   r   r   r   r   r   r   r   r   r   r(   r)   r*   <module>r      se  
 
 # " " " " " ( ( ( ( ( ( ( ( 				       = = = = = = = = = = = = = =5 ) +  . !   $
; 
; 
; 
; 
; 
; 
; 
; $: : : : : : : : $% % % % % % % % $* * * * * * * * $4U333	: 	: 	: 	: 	: 	: 	: 43	:    X    S S S S SE E E E EJ J J J J &*BF6:	@ @ @ @ @ @4	 	 	 	   4   pM pM pM pM pM pM pM pMf|U |U |U |U |U |U |U |U |U |Ur)   