
    Yjib                         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     KC:\Users\server\AppData\Local\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de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}  ||                    d          du |                    d          du |                    d          du |                    d                    S )	z>Classify the current Responses endpoint from transport params.r   )_classify_responses_issueris_xai_responsesTis_github_responsesis_codex_backendbase_url)rA   rB   rC   rD   )agent.codex_responses_adapterr@   r   )r<   r>   r@   s      r   _resolve_issuer_kindz*ResponsesApiTransport._resolve_issuer_kindB   s|    LLLLLL))#ZZ(:;;tC &

+@ A AT I#ZZ(:;;tCZZ
++	
 
 
 	
r   messagesc                     ddl m} |                     |          }|| _         |||                    d          du |                    d          du t          |                    dd                    |          S )z:Convert OpenAI chat messages to Responses API input items.r   )!_chat_messages_to_responses_inputrA   TrB   replay_encrypted_reasoningrA   rB   rJ   current_issuer_kind)rE   rI   rF   r8   r   bool)r<   rG   kwargsrI   issuers        r   convert_messagesz&ResponsesApiTransport.convert_messagesL   s    SSSSSS**622!'00#ZZ(:;;tC &

+@ A AT I'+

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_tools[   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u }
|                    d          du }|                    d          du }t          |                    dd                    }| 	                    |          }|| _
        d}d}|                    d          }|rLt          |t                    r7|                    d          du rd}n|                    d          r|d         }ddi}d|pd                                v rd|d<   |                    dd          r|                    dddd           |                    ||          } ||          }|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
           |                    d0|                    d0                    }t          |t*          t,          f          rRt          |t                    s=dt-          |          cxk     rt-          d1          k     rn nt-          |          |d0<   n|                    d0d
           |rt          |pd                                          }|rl|                    d2          }i }t          |t                    r1|                    d3 |                                D                        ||d&<   ||d4<   ||d2<   |                    d5          } | |s| |d6<   |r|r|                    d2          }i }t          |t                    r1|                    d7 |                                D                        ||d8<   ||d2<   |                    d9          }!i }"t          |!t                    r|"                    |!           |"                    d'|           |"|d9<   |S ):u  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   )rI   rR   )DEFAULT_AGENT_IDENTITYr
   r   rolesystemr3      NrB   TrC   rA   rJ   mediumreasoning_configenabledFeffortminimallowzgpt-5.6maxultrahigh)xhighr`   ra   c              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   re   rf   r   s     r   
<listcomp>z6ResponsesApiTransport.build_kwargs.<locals>.<listcomp>   sI       &q$//45EE&MM\4Q4Q 4Q4Q4Qr   r   re   rK   )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>Z  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   r{   r|   s      r   r~   z6ResponsesApiTransport.build_kwargs.<locals>.<dictcomp>m  sD       &C $)#4 C#e**#4#4#4r   zx-grok-conv-id
extra_body)rE   rI   rR   	run_agentrV   r   r   striprM   rF   r8   r   r   lowerupdateanyappendr5   agent.model_metadatarp   popintfloatitems
setdefault)#r<   rT   rG   r   r>   rI   rR   rV   r
   payload_messagesrB   rC   rA   rJ   issuer_kindreasoning_effortreasoning_enabledr[   _effort_clampresponse_toolshas_client_web_searchfilteredrN   rn   	cache_keyrp   github_reasoningru   rw   cache_scope_idexisting_extra_headersmerged_extra_headersr   existing_extra_bodymerged_extra_bodys#                                      r   build_kwargsz"ResponsesApiTransport.build_kwargs`   sG   :	
 	
 	
 	
 	
 	
 	
 	

 	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)>??4G!::&899TA!::&899TA%)JJ3T::&
 &
" //77!, $ !::&899 	>
+;T B B 	>##I..%77$)!!!%%h// >#3H#= "E*"++----%*M'"::(%00 	T  6&6!R!RSSS(,,-=?OPP))%00^  	* 	*$' ( ('( ( ( % %! % * -    6777!) (66 !1$7+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stoprr   )r3   
tool_callsfinish_reasonrr   usager   )rE   r   r   r8   r   hasattrr   r   r   r	   r   r   r   getattrr   r   r   r   r   r3   rr   )
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                 f   |dS t          |dd          }t          |t                    r|st          t          |dd          pd                                                                          }t          |dd          }t          |t                    rIt          |                    d          pd                                                                          }nDt          t          |dd          pd                                                                          }|dk    o|d	k    S d
S )u  Check Codex Responses API response has valid output structure.

        Returns True only if response.output is a non-empty list. Also treats
        terminal content-filter incomplete responses as valid: the Responses API
        may return status=incomplete with incomplete_details.reason='content_filter'
        and no output items. That is a provider refusal signal, not a malformed
        response, and must reach normalization so the agent loop can use the
        content-policy / fallback path instead of invalid-response retries.

        Does NOT check output_text fallback — the caller handles that with
        diagnostic logging for stream backfill recovery.
        NFoutputstatusr   incomplete_detailsreason
incompletecontent_filterT)r   r   listr   r   r   r   r   )r<   r   r   r   r   r   s         r   validate_responsez'ResponsesApiTransport.validate_response  s%    58T22&$'' 	Iv 	I8R88>B??EEGGMMOOF!(3G!N!N,d33 ^/33H==CDDJJLLRRTTW%72FFL"MMSSUU[[]]\)Hf8H.HHtr   Fallow_streamrB   
api_kwargsr   rB   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   rB   r   s        r   preflight_kwargsz&ResponsesApiTransport.preflight_kwargs  s:     	NMMMMM**% 3
 
 
 	
r   
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)	completedr   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   rF   r   rP   rS   r   r   r   rM   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	a aa tCH~&a T#s(^,-	a 
c3ha a a aF	.
3 .
=O .
 .
 .
 .
`# $    < #$)
 
 

 	

 "
 

 
 
 
$,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|, |, |, |, |,- |, |, |,@ 0 / / / / /  $&; < < < < <r   