
    ީ^j+                        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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".
3. Every object schema must carry a ``required`` array, even an empty one.
   Standard JSON Schema allows omitting it; Moonshot 400s with
   "required must be an array".

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           |                    d          dk    rt          |          }|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     7/home/ice/.hermes/hermes-agent/agent/moonshot_schema.py
<listcomp>z"_repair_schema.<locals>.<listcomp>7   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>B   s;       $GW 4@@@  r"   c                0    g | ]}t          |d           S r   r   r   vs     r    r!   z"_repair_schema.<locals>.<listcomp>G   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>\   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>d   s#    KKK$!Qa7llAlllr"   r   nullablez$refenum>   numberstringbooleanintegerc                "    g | ]}||dk    
|S )N r3   r(   s     r    r!   z"_repair_schema.<locals>.<listcomp>   s,     5 5 5Q-AGG ,3GGr"   object)r-   listr.   r   _SCHEMA_MAP_KEYS_SCHEMA_LIST_KEYS_SCHEMA_NODE_KEYSr   poplenupdate_fill_missing_typer/   _ensure_required_array)	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$$$ ||Fx'')(33Or"   Dict[str, Any]c                    |                      d          |                      d          }t          |t                    r't          t                    rfd|D             | d<   ng | d<   | S )u  Guarantee an object schema carries a ``required`` array (Moonshot rule).

    Standard JSON Schema lets you omit ``required`` when nothing is required;
    Moonshot 400s on that ("required must be an array").  Ensure the key is a
    list.  When ``properties`` is known, prune ``required`` entries that don't
    name a real property — defensive against dangling names, which Moonshot
    also rejects.  Mutates and returns ``node``.
    r   requiredc                    g | ]}|v |	S r3   r3   )r   rpropss     r    r!   z*_ensure_required_array.<locals>.<listcomp>   s    ===a!u*****r"   )r/   r-   r>   r.   )r   reqrS   s     @r    rF   rF      sy     HH\""E
((:

C#t eT"" 	>====3===DZKr"   c                   |                      d          }t          |t                    r"t          d |D             d          }i | d|iS d| v r|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*   c              3  L   K   | ]}t          |t                    |d v|V   dS )>   r<   r,   N)r-   str)r   ts     r    	<genexpr>z%_fill_missing_type.<locals>.<genexpr>   s;      RR1Z3%7%7RA\<Q<QQ<Q<Q<Q<QRRr"   r8   >   Nr<   r   rP   r   r=   r   r   arrayr6   r   r9   r:   r7   )r/   r-   r>   nextr   intfloat)r   rL   concreteinferredsamples        r    rE   rE      sV     I)T"" *RR	RRR
 
 *$))))~~):55 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 g dS t          t          j        |           d          }t          |t                    sdi g dS |                    d          dk    rd|d<   d|vri |d<   t          |           |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.
    r=   )r*   r   rP   Tr   r*   r   )r-   r.   r   copydeepcopyr/   rF   )ra   rG   s     r    !sanitize_moonshot_tool_parametersre      s     j$'' D CCCdmJ774HHHHh%% D CCC ||Fx''#8##!#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functionra   T)r-   r.   appendr/   re   )rf   	sanitized
any_changetoolfnparamsrG   new_fns           r    sanitize_moonshot_toolsrq      s    &(IJ # #$%% 	T"""XXj!!"d## 	T"""%%4V<<6!!J33L(33F99j&99::::T"""""-99-r"   model
str | Nonec                D   | sdS |                                                                  }|                    dd          d         }|                    d          s|dk    rdS |dk    s|                    d	          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k3)zk3.zk3-moonshotz/kimi)striplowerrsplit
startswith)rr   baretails      r    is_moonshot_modelr      s      u;;==  D;;sAr"Dw 46>>t t||t~66|tTW__0G0G_t5r"   )T)r   r   r   r   r   r   )r   rN   r   rN   )ra   r   r   rN   )rf   rg   r   rg   )rr   rs   r   r   )__doc__
__future__r   rc   typingr   r   r   	frozensetr?   r@   rA   r   rF   rE   re   rq   r   r3   r"   r    <module>r      s#   4 # " " " " "  " " " " " " " " " "
 9XXXYY  IHHHII  Icccdd ` ` ` ` `F   && & & &D   .. . . .6     r"   