
    iT%                        d Z ddlmZ ddlZddlmZmZmZ  eh d          Z	 eh d          Z
 eh d          ZdddZddZddZddZddZdS )u  Helpers for translating OpenAI-style tool schemas to Moonshot's schema subset.

Moonshot (Kimi) accepts a stricter subset of JSON Schema than standard OpenAI
tool calling.  Requests that violate it fail with HTTP 400:

    tools.function.parameters is not a valid moonshot flavored json schema,
    details: <...>

Known rejection modes documented at
https://forum.moonshot.ai/t/tool-calling-specification-violation-on-moonshot-api/102
and MoonshotAI/kimi-cli#1595:

1. Every property schema must carry a ``type``.  Standard JSON Schema allows
   type to be omitted (the value is then unconstrained); Moonshot refuses.
2. When ``anyOf`` is used, ``type`` must be on the ``anyOf`` children, not
   the parent.  Presence of both causes "type should be defined in anyOf
   items instead of the parent schema".

The ``#/definitions/...`` → ``#/$defs/...`` rewrite for draft-07 refs is
handled separately in ``tools/mcp_tool._normalize_mcp_input_schema`` so it
applies at MCP registration time for all providers.
    )annotationsN)AnyDictList>   $defs
propertiesdefinitionspatternProperties>   allOfanyOfoneOfprefixItems>   notitemscontainspropertyNamesadditionalPropertiesTnoder   	is_schemaboolreturnc                   t          | t                    rd | D             S t          | t                    s| S i }|                                 D ]\  }}|t          v r7t          |t                    r"d |                                D             ||<   E|t
          v r%t          |t                    rd |D             ||<   s|t          v r0t          |t                    rt          |d          ||<   |||<   |||<   |s|S d|v rt          |d         t                    r|                    dd           d	 |d         D             }|r|t          |          t          |d                   k     rVt          |          d
k    r<d |                                D             }|
                    |d                    |}n	||d<   |S |S |                    dd           d|vrt          |          }d|v rct          |d         t                    rH|                    d          }|dv r/d |d         D             }|r||d<   n|                    d           |S )a5  Recursively apply Moonshot repairs to a schema node.

    ``is_schema=True`` means this dict is a JSON Schema node and gets the
    missing-type + anyOf-parent repairs applied.  ``is_schema=False`` means
    it's a container map (e.g. the value of ``properties``) and we only
    recurse into its values.
    c                0    g | ]}t          |d           S Tr   _repair_schema).0items     :/home/ubuntu/.hermes/hermes-agent/agent/moonshot_schema.py
<listcomp>z"_repair_schema.<locals>.<listcomp>4   s%    FFFtt444FFF    c                8    i | ]\  }}|t          |d           S r   r   )r   sub_keysub_vals      r    
<dictcomp>z"_repair_schema.<locals>.<dictcomp>?   s;       $GW 4@@@  r"   c                0    g | ]}t          |d           S r   r   r   vs     r    r!   z"_repair_schema.<locals>.<listcomp>D   s%    NNN1^A>>>NNNr"   Tr   r   typeNc                n    g | ]2}t          |t                    r|                    d           dk    0|3S )r*   null)
isinstancedictget)r   bs     r    r!   z"_repair_schema.<locals>.<listcomp>Y   sL     H H H!!!T**H/0uuV}}/F/F /F/F/Fr"      c                &    i | ]\  }}|d k    ||S )r    )r   kr)   s      r    r&   z"_repair_schema.<locals>.<dictcomp>a   s#    KKK$!Qa7llAlllr"   r   nullablez$refenum)stringintegernumberbooleanc                "    g | ]}||dk    
|S N r3   r(   s     r    r!   z"_repair_schema.<locals>.<listcomp>~   s,     5 5 5Q-AGG ,3GGr"   )r-   listr.   r   _SCHEMA_MAP_KEYS_SCHEMA_LIST_KEYS_SCHEMA_NODE_KEYSr   poplenupdate_fill_missing_typer/   )	r   r   repairedkeyvaluenon_nullmerge	node_typecleaneds	            r    r   r   )   s    $ G GFFFFFdD!!   "Hjjll " "
U"""z%'>'>" (-  HSMM %%%*UD*A*A%NNNNNHSMM%%% %&& & .u E E E % "HSMM  (z(7*;TBBVT"""H Hx0 H H H 	HHW,=(>(>>>
 8}}!!KK(..*:*:KKKXa[))) $,! O LLT"""
 X%h// j&)94@@LL((	BBB5 5(6"2 5 5 5G %#*  V$$$Or"   Dict[str, Any]c                j   d| v r| d         dvr| S d| v sd| v sd| v rd}nd| v sd| v rd	}nd
| v r|t          | d
         t                    ra| d
         rY| d
         d         }t          |t                    rd}n5t          |t                    rd}nt          |t                    rd}nd}nd}i | d|iS )z9Infer a reasonable ``type`` if this schema node has none.r*   r<   r   requiredr   objectr   r   arrayr6   r   r:   r8   r9   r7   )r-   r>   r   intfloat)r   inferredsamples      r    rE   rE      s    ~~$v,j88 tzT115Kt5S5S	DMT11	4JtF|T::tF|fafd## 	  HH$$ 	  HH&& 	 HHHH%d%FH%%%r"   
parametersc                   t          | t                    sdi dS t          t          j        |           d          }t          |t                    sdi dS |                    d          dk    rd|d<   d|vri |d<   |S )zNormalize tool parameters to a Moonshot-compatible object schema.

    Returns a deep-copied schema with the two flavored-JSON-Schema repairs
    applied.  Input is not mutated.
    rP   )r*   r   Tr   r*   r   )r-   r.   r   copydeepcopyr/   )rV   rF   s     r    !sanitize_moonshot_tool_parametersrZ      s     j$'' 4 333dmJ774HHHHh%% 4 333 ||Fx''#8##!#Or"   toolsList[Dict[str, Any]]c                   | s| S g }d}| D ]}t          |t                    s|                    |           -|                    d          }t          |t                    s|                    |           m|                    d          }t	          |          }||ur&d}i |d|i}|                    i |d|i           |                    |           |r|n| S )zGApply ``sanitize_moonshot_tool_parameters`` to every tool's parameters.FfunctionrV   T)r-   r.   appendr/   rZ   )r[   	sanitized
any_changetoolfnparamsrF   new_fns           r    sanitize_moonshot_toolsrf      s    &(IJ # #$%% 	T"""XXj!!"d## 	T"""%%4V<<6!!J33L(33F99j&99::::T"""""-99-r"   model
str | Nonec                
   | sdS |                                                                  }|                    dd          d         }|                    d          s|dk    rdS d|v sd	|v s|                    d          rdS dS )
a  True for any Kimi / Moonshot model slug, regardless of aggregator prefix.

    Matches bare names (``kimi-k2.6``, ``moonshotai/Kimi-K2.6``) and aggregator-
    prefixed slugs (``nous/moonshotai/kimi-k2.6``, ``openrouter/moonshotai/...``).
    Detection by model name covers Nous / OpenRouter / other aggregators that
    route to Moonshot's inference, where the base URL is the aggregator's, not
    ``api.moonshot.ai``.
    F/r1   zkimi-kimiTmoonshotz/kimi)striplowerrsplit
startswith)rg   baretails      r    is_moonshot_modelrt      s      u;;==  D;;sAr"Dw 46>>tTW__0G0G_t5r"   )T)r   r   r   r   r   r   )r   rM   r   rM   )rV   r   r   rM   )r[   r\   r   r\   )rg   rh   r   r   )__doc__
__future__r   rX   typingr   r   r   	frozensetr?   r@   rA   r   rE   rZ   rf   rt   r3   r"   r    <module>ry      s   . # " " " " "  " " " " " " " " " "
 9XXXYY  IHHHII  Icccdd \ \ \ \ \~& & & &6   ,. . . .6     r"   