
    @=jQZ                         d Z ddlZddlZddlmZmZmZmZ ddlm	Z	 ddl
mZmZ dedeeeeef                           dee         fd	Z G d
 de	          ZddlmZ  ede           dS )u   OpenAI Responses API (Codex) transport.

Delegates to the existing adapter functions in agent/codex_responses_adapter.py.
This transport owns format conversion and normalization — NOT client lifecycle,
streaming, or the _run_codex_stream() call path.
    N)AnyDictListOptional)ProviderTransport)NormalizedResponseToolCallinstructionstoolsreturnc                     | s|sdS d}|r4t          d |D             d           }t          j        |ddd	          }| pd d
| }t          j        |                    dd                                                    dd         }d| S )u  Content-address the prompt cache key from the static request prefix.

    Returns ``pck_<sha256[:24]>`` of (instructions + sorted tool schemas), or
    None when there is nothing static to key on. The cache key is a routing
    hint only — never a correctness boundary — so two requests sharing a system
    prompt and tool set intentionally resolve to the same warm prefix bucket.

    The fix this exists for: recurring cron jobs build session_id as
    ``cron_<id>_<timestamp>``, so using session_id as the cache key made every
    fire cache-cold. The static prefix (identity + tools) is identical across
    fires, so hashing it gives a stable key that stays warm within the
    provider's cache TTL. Sorting tools by name keeps the hash insertion-order
    independent.
    N c              3   D   K   | ]}t          |t                    |V  d S N)
isinstancedict.0ts     </home/rurouni/.hermes/hermes-agent/agent/transports/codex.py	<genexpr>z%_content_cache_key.<locals>.<genexpr>$   s1      551At!4!45Q555555    c                 t    t          |                     d          p|                     d          pd          S )Nnametyper   )strget)r   s    r   <lambda>z$_content_cache_key.<locals>.<lambda>%   s,    #aeeFmmBquuV}}BCC r   )keyTF),:)	sort_keysensure_ascii
separators zutf-8replace)errors   pck_)sortedjsondumpshashlibsha256encode	hexdigest)r
   r   
tools_partsorted_toolscontentdigests         r   _content_cache_keyr5      s       tJ 
55555CC
 
 
 ZDu
 
 


 #5555G^GNN79NEEFFPPRRSVTVSVWF&??r   c                   |   e Zd ZU dZdZee         ed<   edefd            Z	de
eef         defdZdee
eef                  defd	Zd
ee
eef                  defdZ	 ddedee
eef                  d
eee
eef                           de
eef         fdZdedefdZdedefdZdddededefdZdedefdZdS )ResponsesApiTransportzyTransport for api_mode='codex_responses'.

    Wraps the functions extracted into codex_responses_adapter.py (PR 1).
    N_last_issuer_kindr   c                     dS )Ncodex_responses )selfs    r   api_modezResponsesApiTransport.api_mode>   s      r   paramsc           	         ddl m}  |t          |                    d                    t          |                    d                    t          |                    d                    |                    d                    S )z>Classify the current Responses endpoint from transport params.r   )_classify_responses_issueris_xai_responsesis_github_responsesis_codex_backendbase_url)rA   rB   rC   rD   )agent.codex_responses_adapterr@   boolr   )r<   r>   r@   s      r   _resolve_issuer_kindz*ResponsesApiTransport._resolve_issuer_kindB   s    LLLLLL))!&**-?"@"@AA $VZZ0E%F%F G G!&**-?"@"@AAZZ
++	
 
 
 	
r   messagesc           
          ddl m} |                     |          }|| _         ||t	          |                    d                    t	          |                    dd                    |          S )z:Convert OpenAI chat messages to Responses API input items.r   )!_chat_messages_to_responses_inputrA   replay_encrypted_reasoningTrA   rK   current_issuer_kind)rE   rJ   rG   r8   rF   r   )r<   rH   kwargsrJ   issuers        r   convert_messagesz&ResponsesApiTransport.convert_messagesL   s    SSSSSS**622!'00!&**-?"@"@AA'+

7>>( ( !'
 
 
 	
r   r   c                 $    ddl m}  ||          S )zBConvert OpenAI tool schemas to Responses API function definitions.r   )_responses_tools)rE   rR   )r<   r   rR   s      r   convert_toolsz#ResponsesApiTransport.convert_toolsZ   s%    BBBBBB&&&r   modelc                 
   ddl m}m} ddlm} |                    dd          }|}	|sg|re|d                             d          dk    rFt          |d                             d          pd                                          }|d	d
         }	|s|}|                    dd          }
|                    dd          }|                    dd          }t          |                    dd                    }| 	                    |          }|| _
        d}d}|                    d          }|rLt          |t                    r7|                    d          du rd}n|                    d          r|d         }ddi}|                    ||          } ||          }|rB|r@t          d |D                       }|r%d |D             }|                    ddi           |}|| ||	|||          dd}|r||d<   d|d<   d|d <   |                    d!          }t          ||          p|}|
s	|s|r||d"<   |r%|r#dd#lm} |rd$gng |d%<    ||          rd|i|d&<   n=|r2|
r|                    d'          }|||d&<   n|dd(|d&<   |rd$gng |d%<   n	|
s|sg |d%<   |                    d)          }|r|                    |           |r|                    d*d
           |                    d+|                    d+                    }t          |t(          t*          f          rRt          |t                    s=dt+          |          cxk     rt+          d,          k     rn nt+          |          |d+<   n|                    d+d
           |rt          |pd                                          }|rl|                    d-          }i }t          |t                    r1|                    d. |                                D                        ||d!<   ||d/<   ||d-<   |                    d0          } | |s| |d1<   |r|r|                    d-          }i }t          |t                    r1|                    d2 |                                D                        ||d3<   ||d-<   |                    d4          }!i }"t          |!t                    r|"                    |!           |"                    d"|           |"|d4<   |S )5u  Build Responses API kwargs.

        Calls convert_messages and convert_tools internally.

        params:
            instructions: str — system prompt (extracted from messages[0] if not given)
            reasoning_config: dict | None — {effort, enabled}
            session_id: str | None — transcript/session id; drives the xAI
                x-grok-conv-id header and the Codex cache-scope headers, and is
                the fallback prompt_cache_key when there is no static prefix to
                content-address
            max_tokens: int | None — max_output_tokens
            timeout: float | None — per-request timeout forwarded to the SDK
            request_overrides: dict | None — extra kwargs merged in
            provider: str | None — provider name for backend-specific logic
            base_url: str | None — endpoint URL
            base_url_hostname: str | None — hostname for backend detection
            is_github_responses: bool — Copilot/GitHub models backend
            is_codex_backend: bool — chatgpt.com/backend-api/codex
            is_xai_responses: bool — xAI/Grok backend
            github_reasoning_extra: dict | None — Copilot reasoning params
        r   )rJ   rR   )DEFAULT_AGENT_IDENTITYr
   r   rolesystemr3      NrB   FrC   rA   rK   Tmediumreasoning_configenabledeffortminimallowc              3   r   K   | ]2}t          |t                    o|                    d           dk    V  3dS )r   
web_searchNr   r   r   r   s     r   r   z5ResponsesApiTransport.build_kwargs.<locals>.<genexpr>   sT       ( ( 1d##Ef(E( ( ( ( ( (r   c                 n    g | ]2}t          |t                    r|                    d           dk    0|3S )r   ra   rb   r   s     r   
<listcomp>z6ResponsesApiTransport.build_kwargs.<locals>.<listcomp>   sI       &q$//45EE&MM\4Q4Q 4Q4Q4Qr   r   ra   rL   )rT   r
   inputstorer   autotool_choiceparallel_tool_calls
session_idprompt_cache_key)grok_supports_reasoning_effortzreasoning.encrypted_contentinclude	reasoninggithub_reasoning_extra)r]   summaryrequest_overridesservice_tiertimeoutinfextra_headersc                 V    i | ]&\  }}|r|	t          |          t          |          'S r   r   r   r   values      r   
<dictcomp>z6ResponsesApiTransport.build_kwargs.<locals>.<dictcomp>R  sD        *U" (-'8  HHc%jj'8'8'8r   zx-client-request-id
max_tokensmax_output_tokensc                 V    i | ]&\  }}|r|	t          |          t          |          'S r   rw   rx   s      r   rz   z6ResponsesApiTransport.build_kwargs.<locals>.<dictcomp>e  sD       &C $)#4 C#e**#4#4#4r   zx-grok-conv-id
extra_body)rE   rJ   rR   	run_agentrV   r   r   striprF   rG   r8   r   r   anyappendr5   agent.model_metadatarl   updatepopintfloatitems
setdefault)#r<   rT   rH   r   r>   rJ   rR   rV   r
   payload_messagesrB   rC   rA   rK   issuer_kindreasoning_effortreasoning_enabledr[   _effort_clampresponse_toolshas_client_web_searchfilteredrN   rj   	cache_keyrl   github_reasoningrq   rs   cache_scope_idexisting_extra_headersmerged_extra_headersr{   existing_extra_bodymerged_extra_bodys#                                      r   build_kwargsz"ResponsesApiTransport.build_kwargs_   s   :	
 	
 	
 	
 	
 	
 	
 	

 	544444zz."55# 	0 0HQKOOF33x??"8A;??9#=#=#CDDJJLL#+ABB<  	21L$jj)>FF!::&8%@@!::&8%@@%)JJ3T::&
 &
" //77!, $ !::&899 	>
+;T B B 	>##I..%77$)!!!%%h// >#3H#= "E*(,,-=?OPP))%00^  	* 	*$' ( ('( ( ( % %! % * -    6777!) (66 !1+E$/	   

 

  	1,F7O$*F=!,0F()ZZ--
 '|^DDR
	 # 	3+; 	3	 	3)2F%& 	#!1 	#KKKKKK 4NU.//SU 9 .-e44 C'/1A&B{# 	#" #)::.F#G#G #/*:F;'1Af&U&U{#7QY233WY y!! % 	#-= 	# "F9"JJ':;; 	-MM+,,,  	-JJ~t,,, **Y

9(=(=>>we--	(w--	( E'NN1111U5\\11111 %gF9JJy$''' 	? !!1r2288::N ?)/O)D)D&79$4d;; (// .D.J.J.L.L     6D$\2>L$%:;*>'ZZ--
!*:!*4F&' 	5
 	5%+ZZ%@%@"35 0$77 $++ *@*F*F*H*H     6@ !12&:F?# #)**\":":02-t44 >!(()<===(();YGGG#4F< r   responsec                    ddl m} |                    d          p| j        } |||          \  }}d}|r	|j        rg }|j        D ]}i }	t          |d          r|j        r
|j        |	d<   t          |d          r|j        r
|j        |	d<   |                    t          t          |d          r|j
        nt          |d	          r|j        j        ndt          |d	          r|j        j        nt          |d
d          t          |d	          r|j        j        nt          |dd          |	pd                     i }	|r!t          |d          r|j        r
|j        |	d<   |r!t          |d          r|j        r
|j        |	d<   |r!t          |d          r|j        r
|j        |	d<   t%          |r|j        nd||pd|rt          |d          r|j        ndd|	pd          S )z=Normalize Codex Responses API response to NormalizedResponse.r   )_normalize_codex_responser   )r   Ncall_idresponse_item_ididfunctionr   r   	argumentsz{})r   r   r   provider_datacodex_reasoning_itemscodex_message_itemsreasoning_detailsstoprn   )r3   
tool_callsfinish_reasonrn   usager   )rE   r   r   r8   r   hasattrr   r   r   r	   r   r   r   getattrr   r   r   r   r   r3   rn   )
r<   r   rN   r   r   msgr   r   tcr   s
             r   normalize_responsez(ResponsesApiTransport.normalize_response{  s   	
 	
 	
 	
 	
 	
 jj//I43I66x[YYY]
 	3> 	Jn   "2y)) :bj :/1zM),2122 Lr7J L8:8KM"45!!( 'D 1 1nruuGTVXbLcLc8m8H8Him-4R-D-Da))'RTV\^`JaJa7>r:7N7Nrbk33T[\^`kmqTrTr"/"74	# # #      	O73 788 	OS=V 	O585NM12 	K73 566 	K3;R 	K363JM/0 	G73 344 	G9N 	G141FM-.!#&0CKKD!'16'*RwsK/H/HRcmmd'/4
 
 
 	
r   c                 b    |dS t          |dd          }t          |t                    r|sdS dS )u  Check Codex Responses API response has valid output structure.

        Returns True only if response.output is a non-empty list.
        Does NOT check output_text fallback — the caller handles that
        with diagnostic logging for stream backfill recovery.
        NFoutputT)r   r   list)r<   r   r   s      r   validate_responsez'ResponsesApiTransport.validate_response  sC     58T22&$'' 	v 	5tr   Fallow_stream
api_kwargsr   c                (    ddl m}  |||          S )zValidate and sanitize Codex API kwargs before the call.

        Normalizes input items, strips unsupported fields, validates structure.
        r   )_preflight_codex_api_kwargsr   )rE   r   )r<   r   r   r   s       r   preflight_kwargsz&ResponsesApiTransport.preflight_kwargs  s-    
 	NMMMMM**:LQQQQr   
raw_reasonc                 <    ddddd}|                     |d          S )aK  Map Codex response.status to OpenAI finish_reason.

        Codex uses response.status ('completed', 'incomplete') +
        response.incomplete_details.reason for granular mapping.
        This method handles the simple status string; the caller
        should check incomplete_details separately for 'max_output_tokens'.
        r   length)	completed
incompletefailed	cancelled)r   )r<   r   _MAPs      r   map_finish_reasonz'ResponsesApiTransport.map_finish_reason  s2      "	
 
 xx
F+++r   r   )__name__
__module____qualname____doc__r8   r   r   __annotations__propertyr=   r   r   rG   r   rP   rS   r   r   r   rF   r   r   r   r   r;   r   r   r7   r7   1   s          (,x}+++!# ! ! ! X!
4S> 
c 
 
 
 

d38n)= 
C 
 
 
 
'4S#X#7 'C ' ' ' ' 15	Z ZZ tCH~&Z T#s(^,-	Z 
c3hZ Z Z Zx.
3 .
=O .
 .
 .
 .
`# $     IN R R R3 R RRV R R R R,C ,C , , , , , ,r   r7   )register_transportr:   )r   r-   r+   typingr   r   r   r   agent.transports.baser   agent.transports.typesr   r	   r   r5   r7   agent.transportsr   r;   r   r   <module>r      s      , , , , , , , , , , , , 3 3 3 3 3 3 ? ? ? ? ? ? ? ?S $tCH~:N1O T\]`Ta    B^, ^, ^, ^, ^,- ^, ^, ^,D 0 / / / / /  $&; < < < < <r   