
    `gj&	                      d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	 ddl
mZmZmZmZ ddlmZ  ej"                  e      Zddddd	 	 	 	 	 	 	 	 	 d'd	Zda ej,                  d
ej.                        Zddd(dZddd)dZd*d+dZd,dZ	 d-	 	 	 	 	 d.dZd-d/dZh dZh dZ dZ!ddd0dZ"ddddd	 	 	 	 	 	 	 	 	 	 	 d1dZ#dd	 	 	 	 	 d2dZ$ddd 	 	 	 	 	 	 	 d3d!Z%d4d"Z&d4d#Z'd5d$Z(dd%	 	 	 	 	 d6d&Z)y)7u  Codex Responses API adapter.

Pure format-conversion and normalization logic for the OpenAI Responses API
(used by OpenAI Codex, xAI, GitHub Models, and other Responses-compatible endpoints).

Extracted from run_agent.py to isolate Responses API-specific logic from the
core agent loop. All functions are stateless — they operate on the data passed
in and return transformed results.
    )annotationsN)SimpleNamespace)AnyDictListOptional)DEFAULT_AGENT_IDENTITYFis_xai_responsesis_github_responsesis_codex_backendbase_urlc                $    | ry|ry|ry|rd| S y)a  Stable identifier for the Responses endpoint that mints encrypted_content.

    ``reasoning.encrypted_content`` is sealed to the endpoint that issued it:
    replaying a Codex-minted blob against xAI (or vice versa) deterministically
    returns HTTP 400 ``invalid_encrypted_content``. Stamping the issuer on
    persisted reasoning items and filtering at replay time lets a single
    conversation switch models without poisoning history with un-decryptable
    reasoning blocks.
    xai_responsesgithub_responsescodex_backendzother:other r
   s       P/root/.hermes/venv/lib/python3.12/site-packages/agent/codex_responses_adapter.py_classify_responses_issuerr      s)      !z""    z)(?:^|[\s>|])to=functions\.[A-Za-z_][\w.]*userrolec               "   |dk(  rdnd}t        | t              sg S g }| D ]k  }t        |t              r|r|j                  ||d       +t        |t              s<t        |j                  d      xs d      j                         j                         }|dv r8|j                  d      }t        |t              r|r|j                  ||d       |d	v s|j                  d
      }|j                  d      }t        |t              r$|j                  d      }	|j                  d|      }n|}	t        |	t              r|	s#d|	d}
t        |t              r#|j                         r|j                         |
d<   |j                  |
       n |S )u  Convert chat-style multimodal content to Responses API input parts.

    Input:  ``[{"type":"text"|"image_url", ...}]`` (native OpenAI Chat format)
    Output: ``[{"type":"input_text"|"output_text"|"input_image", ...}]`` (Responses format)

    The ``role`` parameter controls the text content type:
    - ``"user"`` (default) → ``"input_text"``
    - ``"assistant"`` → ``"output_text"``

    The Responses API rejects ``input_text`` inside assistant messages and
    ``output_text`` inside user messages, so callers MUST pass the correct
    role for the message being converted.

    Returns an empty list when ``content`` is not a list or contains no
    recognized parts — callers fall back to the string path.
    	assistantoutput_text
input_texttypetextr     >   r!   r   r   r!   >   	image_urlinput_imager#   detailurlr$   r    r#   )
isinstanceliststrappenddictgetstriplower)contentr   	text_type	convertedpartptyper!   	image_refr%   r&   
image_parts              r    _chat_content_to_responses_partsr7   O   sk   " "&!4,Igt$	&(I )dC   )T!BC$%DHHV$*+11399;9988F#D$$  )T!BC00-IXXh'F)T*mmE*"x8c3's2?c)RJ&#&6<<>'-||~
8$Z(5)6 r    )sepc               |   | yt        | t              r| S t        | t              rg }d}| D ]  }t        |t              r|r|j                  |       't        |t              s8t        |j                  d      xs d      j                         j                         }|dv r7|j                  d      }t        |t              s|s|j                  |       |dv s|dz  } |j                  |      j                         }|rd| d	|dk7  rd
nd d}|r| d| n|}|S 	 t        |       S # t        $ r Y yw xY w)u  Flatten message content to a plain-text summary.

    Multimodal messages arrive as a list of ``{type:"text"|"image_url", ...}``
    parts from the API server.  Several consumers want a plain string:

    - Logging, spinner previews, and trajectory files (the default ``sep=" "``).
    - External memory providers, which feed the text to regexes
      (``sanitize_context``) and text APIs — a raw list crashes the sync with
      ``expected string or bytes-like object, got 'list'`` (use ``sep="\n"``).

    Text parts are joined with ``sep``; images become a ``[N image(s)]`` marker
    so the turn isn't recorded as if the attachment never existed.  Returns an
    empty string for empty lists and ``str(content)`` for unexpected scalar
    types.
    r"   r   r    >   r!   r   r   r!   >   r#   r$      [z images]r8   )
r(   r*   r)   r+   r,   r-   r.   r/   join	Exception)	r0   r9   	text_bitsimage_countr3   r4   r!   summarynotes	            r   _summarize_user_message_for_logrE      sK     '3'4 !	 	!D$$$$T*dD)(.B/557==?E==xx'dC(T$$T*66q 	! ((9%++-{m61A#r)J!LD-4ay)$G7| s   $
D/ /	D;:D;c                    |  d| d| }t        j                  |j                  dd            j                         dd }d| S )u  Generate a deterministic call_id from tool call content.

    Used as a fallback when the API doesn't provide a call_id.
    Deterministic IDs prevent cache invalidation — random UUIDs would
    make every API call's prefix unique, breaking OpenAI's prompt cache.
    :utf-8replace)errorsN   call_)hashlibsha256encode	hexdigest)fn_name	argumentsindexseeddigests        r   _deterministic_call_idrV      sT     Ya	{!E7+D^^DKK	KBCMMOPSQSTF6(r   c                   t        | t              sy| j                         }|syd|v rA|j                  dd      \  }}|j                         xs d}|j                         xs d}||fS |j	                  d      rd|fS |dfS )z8Split a stored tool id into (call_id, response_item_id).)NN|r;   Nfc_)r(   r*   r.   split
startswith)raw_idvaluecall_idresponse_item_ids       r   _split_responses_tool_idr`      s    fc"LLNE
e|$)KKQ$7!!--/)T+113;t(((U{$;r   c                   t        |t              r#|j                         }|j                  d      r|S | xs dj                         }|j                  d      r|S |j                  d      r(t	        |      t	        d      kD  rd|t	        d      d  S t        j                  dd|      }|j                  d      r|S |j                  d      r(t	        |      t	        d      kD  rd|t	        d      d  S |rd|dd  S |xs/ t        |xs d      xs t        j                         j                  }t        j                  |j                  d            j                         dd }d| S )	zCBuild a valid Responses `function_call.id` (must start with `fc_`).rY   r"   rL   Nz[^A-Za-z0-9_-]0   rH      )r(   r*   r.   r[   lenresubuuiduuid4hexrM   sha1rO   rP   )r^   r_   	candidatesource	sanitizedrT   rU   s          r   "_derive_responses_function_call_idrn      sY   
 "C($**,	&m""$F!c&kCL&@VCLM*+,,("f5IE"G$Y#g,)FYs7|}-.//Ys^$%%DS)/R0DDJJL4D4DD\\$++g./99;CR@F>r   c                F   | syg }| D ]  }t        |t              r|j                  di       ni }|j                  d      }t        |t              r|j	                         sY|j                  d||j                  dd      d|j                  ddi d	      d
        |xs dS )zIConvert chat-completions tool schemas to Responses function-tool schemas.Nfunctionnamedescriptionr"   F
parametersobject)r    
propertiesr    rq   rr   strictrs   )r(   r,   r-   r*   r.   r+   )toolsr2   itemfnrq   s        r   _responses_toolsr{      s    &(I )3D$)?TXXj"%Rvvf~$$DJJL66-4&&PR/ST
 	 r   >   
web_searchfile_searchlocal_shellcode_interpreterimage_generationweb_search_previewcomputer_use_preview>   	completed
incompletein_progress@   r   )defaultc                   t        | t              rH| j                         j                         j	                  dd      j	                  dd      }|t
        v r|S |S )a%  Normalize a Responses assistant message status for replay.

    The API accepts completed/incomplete/in_progress on replayed assistant
    output messages.  Preserve those exactly (modulo case/hyphen spelling) so
    incomplete Codex continuation turns don't get falsely marked completed.
    -_r8   )r(   r*   r.   r/   rI   _RESPONSE_MESSAGE_STATUSES)r]   r   statuss      r   #_normalize_responses_message_statusr   +  sO     %$$&..sC8@@cJ//MNr   T)r   r   replay_encrypted_reasoningcurrent_issuer_kindc          	       , g }t               }| D ]  }t        |t              s|j                  d      }|dk(  r,|dv r|j                  dd      }	t        |	t              r1t        |	|      }
|dk(  rdnd	,dj                  ,fd
|
D              }ng }
|	t        |	      nd}|dk(  r3|r|j                  d      nd}d}t        |t              r|D ]  }t        |t              s|j                  d      s&|j                  d      }|r||v r>|j                  d      }|'|%||k7  r t        st        j                  d||       dax|j                         D ci c]  \  }}|dvr|| }}}|j                  |       |r|j                  |       d} |j                  d      }d}t        |t              r|D ]  }t        |t              s|j                  d      dk7  s|j                  d      dk7  r>|j                  d      }t        |t              s`g }|D ]  }t        |t              st        |j                  d      xs d      j                         }|dvrE|j                  dd      }|d}t        |t              st        |      }|j                  d|d        |sddt        |j                  d            |d}|j                  d      }|sGt        |t              r7|j                         r'|j                         }t!        |      t"        k  r||d<   |j                  d      }t        |t              r#|j                         r|j                         |d<   |j                  |       |dz  } |dkD  rnR|
r|j                  d|
d       n;|j                         r|j                  d|d       n|r|j                  ddd       |j                  d       }t        |t              r|D ]  }t        |t              s|j                  d!i       } | j                  d"      }!t        |!t              r|!j                         sYt%        |j                  d            \  }"}#|j                  d#      }$t        |$t              r|$j                         s|"}$t        |$t              r|$j                         s{t        |#t              r:|#j'                  d$      r)t!        |#      t!        d$      kD  rd%|#t!        d$      d  }$n1t        | j                  d&d'            }%t)        |!|%t!        |            }$|$j                         }$| j                  d&d'      }&t        |&t              rt+        j,                  |&d(      }&nt        |&t              st        |&      }&|&j                         xs d'}&|j                  d)|$|!|&d*        |
r|j                  ||
d       n|j                  ||d       |d+k(  s|j                  d,      }'t%        |'      \  }$}(t        |$t              r|$j                         s0t        |'t              r |'j                         r|'j                         }$t        |$t              r|$j                         s|j                  d      })t        |)t              rt        |)d-      }*|*r|*}+nd}+nt        |)xs d      }+|j                  d.|$|+d/        |S c c}}w )0ux
  Convert internal chat-style messages to Responses input items.

    ``is_xai_responses`` is kept for transport signature compatibility but
    no longer suppresses encrypted reasoning replay.  Earlier (PR #26644,
    May 2026) we believed xAI's OAuth/SuperGrok ``/v1/responses`` surface
    rejected replayed ``encrypted_content`` reasoning items minted by
    prior turns, and we stripped them.  That decision was wrong — xAI
    explicitly relies on Hermes threading encrypted reasoning back across
    turns for cross-turn coherence (the whole point of their partnership
    integration).  We now replay encrypted reasoning on every Responses
    transport (xAI, native Codex, custom relays) and let xAI tell us
    explicitly if a specific surface ever rejects a payload.

    ``replay_encrypted_reasoning`` is the per-session kill switch.  Some
    OpenAI-compatible relays accept the request but later reject the
    replayed encrypted blob with HTTP 400 ``invalid_encrypted_content``;
    when that happens the retry loop calls
    ``AIAgent._disable_codex_reasoning_replay`` which both strips cached
    items from the conversation history and threads ``replay_enabled=False``
    through this converter so subsequent turns send no reasoning items.

    ``is_github_responses`` drops the ``id`` field from replayed
    ``codex_message_items`` regardless of length. The Copilot backend
    (api.githubcopilot.com/responses) binds these ids to a specific
    backend "connection" — credential-pool rotation, a gateway restart,
    or routine load-balancer churn between turns all invalidate it — and
    rejects a stale id with HTTP 401 "input item ID does not belong to
    this connection" even for short ids (see #32716). ``phase``/
    ``status``/``content`` are still replayed; only ``id`` is unsafe to
    reuse across a Copilot connection.

    ``current_issuer_kind`` enables a per-item cross-issuer guard. The
    Responses API's ``encrypted_content`` blob is decryptable only by the
    endpoint that minted it — replaying a Codex-issued blob against xAI
    (or vice versa) always yields HTTP 400 ``invalid_encrypted_content``
    and breaks every subsequent turn in the same session.  When this
    argument is provided and a reasoning item carries an ``_issuer_kind``
    stamp from a different endpoint, the item is dropped from the replayed
    input.  Legacy items without a stamp are still replayed
    (backwards-compatible).  The two guards compose:
    ``replay_encrypted_reasoning=False`` is the session-wide kill switch
    (drops ALL replay); ``current_issuer_kind`` is the per-item filter
    that runs only when replay is still enabled.
    r   system>   r   r   r0   r"   r   r   r   r   c              3  l   K   | ]+  }|j                  d       k(  s|j                  dd       - yw)r    r!   r"   N)r-   ).0pr1   s     r   	<genexpr>z4_chat_messages_to_responses_input.<locals>.<genexpr>|  s1      '*+fQZ@ZAEE&"%'s   44Ncodex_reasoning_itemsFencrypted_contentid_issuer_kindu   Dropping reasoning item minted by %s while calling %s — encrypted_content is sealed to its issuer. This happens when a session switches model providers mid-conversation.T)r   r   codex_message_itemsr   r    message>   r!   r   r!   r   r   r    r   r   r0   phaser;   r   r0   
tool_callsrp   rq   r^   rY   rL   rR   {}ensure_asciifunction_callr    r^   rq   rR   tooltool_call_idr   function_call_outputr    r^   output)setr(   r,   r-   r)   r7   r?   r*   _CROSS_ISSUER_WARN_EMITTEDloggerwarningitemsr+   addr.   r   rd   _MAX_RESPONSES_ITEM_ID_LENGTHr`   r[   rV   jsondumps)-messagesr   r   r   r   r   seen_item_idsmsgr   r0   content_partscontent_textcodex_reasoninghas_codex_reasoningriitem_iditem_issuerkvreplay_itemr   replayed_message_itemsraw_itemraw_content_partsnormalized_content_partsr3   	part_typer!   stripped_idr   r   tcrz   rQ   embedded_call_idembedded_response_item_idr^   	_raw_argsrR   raw_tool_call_idr   tool_contentr2   output_valuer1   s-                                               @r   !_chat_messages_to_responses_inputr   9  s   h #%EM b#t$wwv8((ggi,G'4( @t T-1[-@Ml	!ww '/<'   !#/6/Bs7|{" 2 GG34  
 ',#ot4- *7%b$/BFF;N4O&(ffTlG&7m+C ( +-&&*@K 3 ?$/$;$/3F$F (B$*NN)U )45H%& BF$> ( 24+)-A#$,B#B !"1+K + "LL5& - 1 1' :26/U*7` '*gg.C&D#)*&148$7 -4)(D9$#<</9<V@TXc@c$,4LL,C))*;TB$350$5 cD#-dD#9 ((+DHHV,<,B(C(I(I(KI(0GG (#'88FB#7D#|')#-dC#8'*4y4;;]\`<abc  8$ %.$/&I(,,W_J`&a'?	' #+,,t"4 3 *7C 8 '*1--/K";/3PP4?D 1 (W 5%eS1ekkm38;;=K0[1.!3.[-4^ *A-"LL+-!PQ!'')LL+,!OP( LL+"!EF WW\2
j$/( &)"d3$VVJ3"$&&.)'37w}}$F^FF4LGC(*C #%&&"3)'37w}}&6G)'37w}} *+Dc J$=$H$H$O$'(A$BSZ$O,12KCPUJK2X1Y*Z,/{D0I,J	*@)UXY^U_*`")--/$&FF;$=	%i6(,

95(QI!+Is!;(+II$-OO$5$=	$3'.$+)2	& C&N  d}EFd|DE6>"ww~612BCJGQgs+7==?.49I9O9O9Q.446Ggs+7==? 779-L,-< v	 #,L#%L"<#526LL."& }bH LC+s   \
r   c                  t        | t              st        d      g }t               }t	        |       D ]  \  }}t        |t
              st        d| d      |j                  d      }|dk(  r|j                  d      }|j                  d      }t        |t              r|j                         st        d| d      t        |t              r|j                         st        d| d	      |j                  d
d      }	t        |	t
              rt        j                  |	d      }	nt        |	t              st        |	      }	|	j                         xs d}	|j                  d|j                         |j                         |	d       Z|dk(  r|j                  d      }t        |t              r|j                         st        d| d      |j                  dd      }
|
d}
t        |
t              rg }|
D ]  }t        |t
              s|j                  d      }|dk(  r:|j                  d      }t        |t              sL|sO|j                  d|d       d|dk(  sj|j                  d      }t        |t              s|sd|d}|j                  d      }t        |t              r#|j                         r|j                         |d<   |j                  |        |j                  d|j                         |r|ndd       t        |
t              st        |
      }
|j                  d|j                         |
d       |dk(  r|j                  d      }t        |t              r~|r||j                  d      }t        |t              r|r||v rp|j                  |       d|d}|j                  d      }t        |t              r||d<   ng |d<   |j                  |       |d k(  r|j                  d!      }|d"k7  rt        d| d#      |j                  d$      }t        |t              st        d| d%      g }t	        |      D ]  \  }}t        |t
              st        d| d&| d      |j                  d      }|d'vrt        d| d&| d(|d)      |j                  dd      }|d}t        |t              st        |      }|j                  d*|d        |st        d| d+      d d"t        |j                  d,            |d-}|j                  d      }|sGt        |t              r7|j                         r'|j                         }t        |      t        k  r||d<   |j                  d.      }t        |t              r#|j                         r|j                         |d.<   |j                  |       |j                  d!      }|d/v rE|j                  d$d      }|d}t        |t              r|d"k(  rd*nd}g }t	        |      D ]  \  }}t        |t              r|r|j                  ||d       .t        |t
              st        d| d0| d1      t        |j                  d      xs d      j                         j!                         }|d2v rF|j                  dd      }t        |t              st        |xs d      }|j                  ||d       |d3v r|j                  dd      } |j                  d      }t        | t
              r%| j                  d4d      }| j                  d|      }n| }t        |t              st        |xs d      }d|d}!t        |t              r#|j                         r|j                         |!d<   |j                  |!       t        d| d0| d(|j                  d      d)       |j                  ||d5       t        |t              st        |      }|j                  ||d5       t        d| d6|d7|d8       |S )9Nz4Codex Responses input must be a list of input items.zCodex Responses input[] must be an object.r    r   r^   rq   z#] function_call is missing call_id.z ] function_call is missing name.rR   r   Fr   r   r   z*] function_call_output is missing call_id.r   r"   r   r!   r   r$   r#   r'   r%   r   	reasoningr   r   r    r   rC   r   r   r   z+] message items must have role='assistant'.r0   z&] message item must have content list.z] message content[>   r!   r   ] has unsupported type .r   z3] message item must contain at least one text part.r   r   r   >   r   r   z
].content[z] must be an object or string.>   r!   r   r   >   r#   r$   r&   r   z#] has unsupported item shape (type=z, role=z).)r(   r)   
ValueErrorr   	enumerater,   r-   r*   r.   r   r   r+   r   r   rd   r   r/   )"	raw_itemsr   
normalizedseen_idsidxry   	item_typer^   rq   rR   r   cleanedr3   r4   r!   r&   entryr%   	encryptedr   reasoning_itemrC   r   r0   normalized_contentpart_idxr   normalized_itemr   r   r1   	validatedr5   r6   s"                                     r   _preflight_codex_input_itemsr   [  s   
 i&OPP')JEHy) M
	T$%5cU:NOPPHHV$	'hhy)G88F#Dgs+7==? #9#>a!bccdC(

 #9#>^!_``d3I)T* JJyuE		3/	N	!)1TI+&}} JJL!*	 ..hhy)Ggs+7==? #9#>h!ijjXXh+F~
 &$' 13" 2D%dD1  HHV,E,#xx/%dC0T#NNL$+OP-/"hh{3%c3/C=JY\4]E%)XXh%7F)&#66<<>28,,.h#NN512  !! 6#*==?-4'" fc*V2&}}$ #!45I)S)i((4.gs+(* LL)*5I!V
 ((9-gt,07N9-02N9-!!.1	!88F#D{" #9#>i!jkkhhy)Ggt, #9#>d!eff!#"+G"4 Q$!$-$05GzQef  !HHV,	$;;$05GzQhirhuuvw  xx+<D!$,t9D"))=$*OPQ  & #9#>q!rss!#=dhhx>PQ-	/O hhtnG'w,MMO%mmo{#'DD,7OD)HHW%E%%%++-+0;;=(o.xx((hhy"-G'4( .2[-@Ml	24	&/&8  NHd!$,%,,i-NO %dD1(4SEH:Mkl    0 6B7==?EEGE EE#xx3)$4#&tzr?D!(()T)JK">>$(HH["$=	!%(!3%i6"+--r":C%.]]8V%DF"+C)#s3"%ciR.C>KZ]5^
%fc2v||~39<<>Jx0!((4(4SEH:Mdeiememnteudxxyz = B !!4I"FGgs+g,t@A$SE)LYMY`ae`hhjk
 	
WM
^ r   )allow_streamr   c          	       & t        | t              st        d      h d}|D cg c]	  }|| vs| }}|r't        ddj                  t	        |             d      | j                  d      }t        |t              r|j                         st        d      |j                         }| j                  d      }|d	}t        |t              st        |      }|j                         xs t        }t        | j                  d
      |      }| j                  d      }	d }
|	t        |	t              st        d      g }
t        |	      D ]r  \  }}t        |t              st        d| d      |j                  d      }|t        v r|
j                  t        |             Z|dk7  r!t        d| d|j                  d      d      |j                  d      }|j                  d      }t        |t              r|j                         st        d| d      t        |t              st        d| d      |j                  dd	      }|d	}t        |t              st        |      }|j                  dd      }t        |t              st        |      }|
j                  d|j                         |||d       u | j                  dd      }|durt        d      h d&|||dd}|
|
|d<   | j                  d      }t        |t              r||d<   | j                  d       }t        |t              r||d <   | j                  d!      }t        |t              r#|j                         r|j                         |d!<   | j                  d"      }t        |t        t         f      r|d#kD  rt        |      |d"<   | j                  d$      }t        |t        t         f      r>t        |t              s.d#t!        |      cxk  rt!        d%      k  rn nt!        |      |d$<   | j                  d&      }t        |t        t         f      rt!        |      |d&<   d'D ]  }| j                  |      }||||<    | j                  d(      }|t        |t              st        d)      i }|j#                         D ]O  \  }}t        |t              r|j                         st        d*      |4t        |      ||j                         <   Q |r||d(<   | j                  d+      }|+t        |t              st        d,      |rt        |      |d+<   |r=| j                  d-      } | | d.urt        d/      | d.u rd.|d-<   &j%                  d-       nd-| v rt        d0      t        | j                  d      xs d	      j'                         }!|!j)                  d1      }"|"r)|j                  d      r	 d#d2lm}#  |#|d         \  |d<   }$t	        &fd3| D              }%|%rt        d4dj                  |%       d      |S c c}w # t.        $ r Y Fw xY w)5Nz'Codex Responses request must be a dict.>   inputmodelinstructionsz3Codex Responses request missing required field(s): z, r   r   z;Codex Responses request 'model' must be a non-empty string.r   r"   r   r   rx   z=Codex Responses request 'tools' must be a list when provided.zCodex Responses tools[r   r    rp   r   rq   rs   z] is missing a valid name.z] is missing valid parameters.rr   rw   Frv   storez6Codex Responses contract requires 'store' to be false.>   r   r   r   rx   includetimeoutr   
extra_bodytemperaturetool_choicer   service_tierextra_headersprompt_cache_keymax_output_tokensparallel_tool_calls)r   r   r   r   r   r   r   r   r   r   infr   )r   r   r   r   z:Codex Responses request 'extra_headers' must be an object.zGCodex Responses request 'extra_headers' keys must be non-empty strings.r   z7Codex Responses request 'extra_body' must be an object.streamTz/Codex Responses 'stream' must be true when set.zKCodex Responses stream flag is only allowed in fallback streaming requests.)zgrok-z
x-ai/grok-)strip_slash_enumc              3  ,   K   | ]  }|vs|  y wNr   )r   keyallowed_keyss     r   r   z._preflight_codex_api_kwargs.<locals>.<genexpr>  s     MS5LMs   	z2Codex Responses request has unsupported field(s): )r(   r,   r   r?   sortedr-   r*   r.   r	   r   r)   r   _RESPONSES_BUILTIN_TOOL_TYPESr+   boolintfloatr   r   r/   r[   tools.schema_sanitizerr   r@   )'
api_kwargsr   r   requiredr   missingr   r   normalized_inputrx   normalized_toolsr   r   	tool_typerq   rs   rr   rw   r   r   r   r   r   r   r   r   passthrough_keyvalr   normalized_headersr]   r   r   model_name_for_provider_checkis_xai_modelr   r   
unexpectedr   s'                                         @r   _preflight_codex_api_kwargsr  7  sH    j$'BCC1H&@s#Z*?s@G@NtyyY_`gYhOiNjjklmmNN7#EeS!VWWKKME>>.1LlC(<(%%'A+AL3w/
 NN7#E%&\]]"5) .	ICdD) #9#>R!STT(I 99 ''T
3J& #9#>UVZV^V^_eVfUiij!kll88F#D,/JdC(

 #9#>X!YZZj$/ #9#>\!]^^((="5K" k3/!+.XXh.Ffd+f##& JJL#.$",M.	` NN7E*EEQRRL $!	"J #.
7 {+I)T""+
;nnY'G'4  '
9>>.1L,$););)=%1%7%7%9
>" #':;#c5\27H17L*-.?*@
&'nnY'G7S%L)7D)g-u- %g
9../K+U|,$)+$6
=! V .nn_-?*-J'.
 NN?3M -.YZZ-/'--/ 	9JCc3'syy{ !jkk}.1%jsyy{+	9 *<J'-J*d+VWW '+J'7J|$)&"4NOOT>#'Jx "	Z	fgg %(
w(?(E2$F$L$L$N!0;;<STL
w/	?%5j6I%J"Jw MzMMJ@:AV@WWXY
 	
 { Ah  		s   	X<X</Y 	YYc                   t        | dd      }t        |t              syg }|D ]F  }t        |dd      }|dvrt        |dd      }t        |t              s3|s6|j	                  |       H dj                  |      j                         S )z<Extract assistant text from a Responses message output item.r0   Nr"   r    >   r!   r   r!   getattrr(   r)   r*   r+   r?   r.   )ry   r0   chunksr3   r4   r!   s         r   _extract_responses_message_textr    s    dIt,Ggt$F  fd+//tVT*dC TMM$  776?  ""r   c                T   t        | dd      }t        |t              r\g }|D ]4  }t        |dd      }t        |t              s!|s$|j	                  |       6 |rdj                  |      j                         S t        | dd      }t        |t              r|r|j                         S y)zAExtract a compact reasoning text from a Responses reasoning item.rC   Nr!   
r"   r  )ry   rC   r  r3   r!   s        r   !_extract_responses_reasoning_textr    s    dIt,G'4  	$D4.D$$d#	$ 99V$**,,4&D$zz|r   c                   d}d}t        | t              r#| j                  d      }| j                  d      }n| t        | dd      }t        | dd      }t        |t              rt	        |      j                         n|rt	        |      j                         nd}t        |t              rt	        |      j                         n|rt	        |      j                         nd}|r	|r| d| S |r|S |r|S | rt	        |       S d| dS )ac  Build a human-readable error string from a Responses ``response.error`` payload.

    The OpenAI Responses API carries failure details under ``response.error``
    on terminal ``response.failed`` events, in the shape
    ``{"code": "rate_limit_exceeded", "message": "Slow down", "param": ...}``.
    Earlier code only surfaced ``message``, which left users staring at bare
    strings like ``"Slow down"`` while the failure mode (rate limit vs
    context-length vs internal_error vs model-overloaded) was hidden in
    ``code``. We now prefix ``code`` when both are present so consumers can
    distinguish failure modes without parsing the bare message.

    Falls back to ``code`` alone when ``message`` is empty, and to a stable
    default referencing the response status when no error payload is
    available at all. Adapted from anomalyco/opencode#28757.
    Ncoder   r"   z: zResponses API returned status '')r(   r,   r-   r  r*   r.   )	error_objresponse_statusr  r   code_strmessage_strs         r   _format_responses_errorr  '  s    " DG)T"}}V$--	*		y&$/)Y5$.tS$9s4y UYD	@Q_aH*4Wc*B#g,$$&ahWI[I[I]npKK2k]++ 9~,_,=Q??r   )issuer_kindc                  t        | dd      }t        |t              r|j                         j	                         }nd}t        | dd      }d}t        |t
              r;t        |j                  d      xs d      j                         j	                         }n8|6t        t        |dd      xs d      j                         j	                         }|dk(  xr |dk(  }t        | dd      }t        |t              r|st        | d	d      }t        |t              ro|j                         r_t        j                  d
t        |j                                      t        dddt        d	|j                               g      g}|| _        n%|rt        dddg       g}|| _        nt        d      |dv r$t        | dd      }t        ||      }	t        |	      g }
g }g }g }g }|dv }|dv }d}d}d}h d}|D ]  }t        |dd      }t        |dd      }t        |t              r|j                         j	                         }nd}|dv r||vrd}d}|dk(  rt        |dd      }d}d}t        |t              r-|j                         j	                         }|dv rd}d}n|dv rd}t        |      }|s|r|j!                  |       n|
j!                  |       ddt#        |      d	|dgd}t        |dd      }t        |t              r|r||d<   |r||d<   |j!                  |       3|dk(  rd}t%        |      }|r|j!                  |       t        |dd      }t        |t              sx|s|d|d} |r|| d <   t        |dd      }t        |t              r)|j'                  d!      rt        j                  d"|       t        |t              r|r|| d<   t        |d#d      }!t        |!t              r@g }"|!D ]4  }#t        |#d$d      }$t        |$t              s!|"j!                  d%|$d       6 |"| d#<   |j!                  |        U|d&k(  r)|dv rat        |d'd      xs d}%t        |d(d)      }&t        |&t              st)        j*                  |&d*      }&t        |d+d      }'t        |dd      }(t-        |(      \  })}*t        |'t              r|'j                         r|'n|)}+t        |+t              r|+j                         st/        |%|&t        |            }+|+j                         }+t        |(t              r|(nd},t1        |+|,      },|j!                  t        |+|+|,d,t        |%|&-      .             |d/k(  st        |d'd      xs d}%t        |d0d)      }&t        |&t              st)        j*                  |&d*      }&t        |d+d      }'t        |dd      }(t-        |(      \  })}*t        |'t              r|'j                         r|'n|)}+t        |+t              r|+j                         st/        |%|&t        |            }+|+j                         }+t        |(t              r|(nd},t1        |+|,      },|j!                  t        |+|+|,d,t        |%|&-      .              d1j3                  |
D -cg c]  }-|-s|-	 c}-      j                         }.|.s=t5        | d	      r1|r|r-t        | d	d      }t        |t              r|j                         }.d}/|.r4|s2t6        j9                  |.      rd}/t        j;                  d2|.dd3        d}.|d4k(  r|.s|s|rd5j3                  |      }0|0j=                  d6      }1|1d7k7  ry|0|1t        d6      z   d }2|2j?                  d8      }3|3d7k7  r|2d|3 }2|2j                         }2|2r;t        j;                  d9t        |2             |2}.|0d|1 j                         }4|4r|4gng }t        |.||rd5j3                  |      j                         nddd|xs d|xs d:      }5|rd;}6|5|6fS |rd}6|5|6fS |/rd}6|5|6fS |rd}6|5|6fS |s|r|sd}6|5|6fS |s|s|r|.s|dk(  r
|d<vrd=}6|5|6fS d}6|5|6fS d=}6|5|6fS c c}-w )>ar  Normalize a Responses API object to an assistant_message-like object.

    ``issuer_kind`` (when provided) is stamped onto each reasoning item the
    response yields, so future replays can detect when the active endpoint
    differs from the one that minted the encrypted_content blob and drop
    the item instead of triggering HTTP 400 invalid_encrypted_content.
    r   Nincomplete_detailsr"   reasonr   content_filterr   r   z`Codex response has empty output but output_text is present (%d chars); synthesizing output item.r   r   r   r   r   z&Responses API returned no output items>   failed	cancellederror>   queuedr   r   >   r'  r   F>   mcp_callcomputer_callweb_search_callfile_search_calllocal_shell_callcode_interpreter_callimage_generation_callr    Tr   >   analysis
commentary>   finalfinal_answerr   r   r   r   r   rs_tmp_z@Skipping transient Codex reasoning item during normalization: %srC   r!   summary_textr   rq   rR   r   r   r^   rp   )rq   rR   )r   r^   r_   r    rp   custom_tool_callr   r  zCodex response contains leaked tool-call text in assistant content (no structured function_call items). Treating as incomplete so the continuation path can re-elicit a proper tool call. Leaked snippet: %ri,  r   z

z
<response>z</response>zxAI response delivered its final answer inside the reasoning channel (<response> delimiter); promoting %d chars to assistant content.)r0   r   r   reasoning_contentreasoning_detailsr   r   r   )r   r   r   stop) r  r(   r*   r.   r/   r,   r-   r)   r   debugrd   r   r   RuntimeErrorr  r  r+   r   r  r[   r   r   r`   rV   rn   r?   hasattr_TOOL_CALL_LEAK_PATTERNsearchr   rfindfind)7responser  r  r!  incomplete_reason"response_incomplete_content_filterr   out_textr  	error_msgr   reasoning_partsreasoning_items_rawmessage_items_rawr   has_incomplete_items saw_streaming_or_item_incompletesaw_commentary_phasesaw_final_answer_phasesaw_reasoning_item_SERVER_SIDE_TOOL_CALL_TYPESry   r   item_status
item_phasenormalized_phaseis_commentary_phasemessage_textraw_message_itemr   reasoning_textr   r   rC   raw_summaryr3   r!   rQ   rR   raw_call_idraw_item_idr   r   r^   r_   r   
final_textleaked_tool_call_textjoined_reasoningmarkersalvagedclosingreasoning_prefixassistant_messagefinish_reasons7                                                          r   _normalize_codex_responserb  U  sJ	    h$7O/3')//1779 +?F$d+ 2 6 6x @ FBGMMOUUW		'(:Hb I ORPVVX^^`<'Q,=AQ,Q ' Xx.Ffd#6 8]D9h$)9LL,-01A-B &[(m(..BRST F %HO/
 &[b F %HOGHH11Hgt4	+IG	9%%!M!#O02.0J*.UU'6:S'S$ "&$   CD&$/	dHd3k3'%++-335KK BB!==#' /3,	! w5J#"'*c*#-#3#3#5#;#;#= #'AA+/(*.'%)BB-1*:4@L '#**<8!((6%'A+N)6 MN	4  "$d3gs+-4$T*#0@$W-!(()9:+%!%>tDN&&~6  &94@I)S)i$/iP
 /:H^,!$d3gs+0B0B90MLLZ gs+%,HTN!$	48gt,"$K ' W&tVT:%dC0'..PT/UVW +6HY'#**84/)EEdFB/52Gk48Ii- JJyuE	!$	48K!$d3K":;"Ga%/S%AkFWFWFYk_oGgs+7==?0)S_UmmoG.8c.J{PTA'K[\o!1(gK  ,,dFB/52Ggt4Ii- JJyuE	!$	48K!$d3K":;"Ga%/S%AkFWFWFYk_oGgs+7==?0)S_UmmoG.8c.J{PTA'K[\o!1(gK {CJ }:!A:;AACJHm,%.D8]B7h$!)J& "*)@)G)G
)S $U t		
 
" 	&!;;7!''5R<'\1B(B(CDHmmM2G"}#HW-~~'H5 M	 &
#3GV#<#B#B#D 8H#3"4b':I&++o.446t19T-5 $F m++E 
,(B m++A 
$> m++= 
*$: m++9 "6@V$6 m++5 4FPZ  k)k B
 /

 #M
 m++ )M m++ m++} ;s   1a>9a>)
r   r   r   r   r   r   r   Optional[str]returnr*   )r0   r   r   r*   rd  List[Dict[str, Any]])r0   r   r9   r*   rd  r*   )r   )rQ   r*   rR   r*   rS   r   rd  r*   )r\   r   rd  z#tuple[Optional[str], Optional[str]]r   )r^   r*   r_   rc  rd  r*   )rx   Optional[List[Dict[str, Any]]]rd  rf  )r]   r   r   r*   rd  r*   )r   re  r   r   r   r   r   r   r   rc  rd  re  )r   r   r   r   rd  re  )r  r   r   r   r   r   rd  zDict[str, Any])ry   r   rd  r*   )r  r   r  r*   rd  r*   )rA  r   r  rc  rd  ztuple[Any, str])*__doc__
__future__r   rM   r   loggingre   rg   typesr   typingr   r   r   r   agent.prompt_builderr	   	getLogger__name__r   r   r   compile
IGNORECASEr=  r7   rE   rV   r`   rn   r{   r   r   r   r   r   r   r  r  r  r  rb  r   r   r   <module>rq     s   #    	  ! , , 7			8	$
 # %""  	
  	: #  %"**0MM  CI 0f AD -h	& '+# 	B<!  H  !#  GR " # %'+)-["[ [ 	[
 !%[ '[ [J	 !&YY Y 	Y~  %	GG G 	G
 G\#""'@b "&f,f, f, 	f,r   