
    `gj+                        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y)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additionalPropertiesc           
     H   t        | t              r| D cg c]  }t        |d       c}S t        | t              s| S i }| j	                         D ]  \  }}|t
        v rCt        |t              r3|j	                         D ci c]  \  }}|t        |d       c}}||<   Q|t        v r/t        |t              r|D cg c]  }t        |d       c}||<   |t        v r't        |t              rt        |d      ||<   |||<   |||<    |s|S d|v rt        |d   t              r|j                  dd       |d   D 	cg c](  }	t        |	t              r|	j                  d      dk7  r|	* }
}	|
rot        |
      t        |d         k  rUt        |
      dk(  r@|j	                         D ci c]  \  }}|dk7  s|| }}}|j                  |
d          |}n	|
|d<   |S |S |j                  d	d       d
|vrt        |      }d|v rZt        |d   t              rG|j                  d      }|dv r2|d   D cg c]  }||dk7  r| }}|r||d<   n|j                  d       |j                  d      dk(  rt        |      }|S c c}w c c}}w c c}w c c}	w c c}}w c c}w )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.
    T	is_schemar   typeNnull   r   nullablez$refenum>   numberstringbooleaninteger object)
isinstancelist_repair_schemadictr   _SCHEMA_MAP_KEYS_SCHEMA_LIST_KEYS_SCHEMA_NODE_KEYSpopgetlenupdate_fill_missing_type_ensure_required_array)noder   itemrepairedkeyvaluesub_keysub_valvbnon_nullkmerge	node_typecleaneds                  H/root/.hermes/venv/lib/python3.12/site-packages/agent/moonshot_schema.pyr$   r$   ,   s    $ BFFtt4FFdD!  "Hjjl "
U""z%'>
 ).$GW 4@@HSM %%*UD*AHMN1^A>NHSM%% %& .u E % "HSM'"*  (z(7*;TBVT"'0 H!!!T*quuV}/F  H HHHW,=(>>
 8}!*2..*:K$!Qa7lAKKXa[) $,! O LLT"
 X%h/ j&)94@LL(	BB"*6"2 5Q-AG  5G 5#* V$ ||Fx')(3Ok G
 O*H L:5s)   JJ	=J-J.J<J8Jc                    | j                  d      }| j                  d      }t        |t              r*t        |t              r|D cg c]	  }||v s| c}| d<   | S g | d<   | S c c}w )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   required)r*   r"   r#   r%   )r/   propsreqrs       r=   r.   r.      sl     HH\"E
((:
C#teT"+.=a!u*=D K ZK  >s   	A$A$c                   | j                  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}nmd	| v sd
| v rd}nbd| v r\t        | d   t              rI| d   rD| d   d   }t        |t              rd}n+t        |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              s|d vs|  yw)>   r    r   N)r"   str).0ts     r=   	<genexpr>z%_fill_missing_type.<locals>.<genexpr>   s      R1Z3%7A\<QQRs   $$$r   >   Nr    r   r?   r   r!   r   r   arrayr   r   r   r   r   )r*   r"   r#   nextboolintfloat)r/   r;   concreteinferredsamples        r=   r-   r-      s     I)T"R	R
 *$)))~):5 tzT15Kt5S	DMT1	4JtF|T:tF|fafd# H$ H&HH%d%FH%%    c                    t        | t              sdi g dS t        t        j                  |       d      }t        |t              sdi g dS |j                  d      dk7  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   r?   Tr   r   r   )r"   r%   r$   copydeepcopyr*   r.   )
parametersr1   s     r=   !sanitize_moonshot_tool_parametersrV      s     j$' CCdmmJ74HHh% CC ||Fx'#8#!#8$OrQ   c                |   | s| S g }d}| D ]  }t        |t              s|j                  |       %|j                  d      }t        |t              s|j                  |       X|j                  d      }t	        |      }||ur"d}i |d|i}|j                  i |d|i       |j                  |        |r|S | S )zGApply ``sanitize_moonshot_tool_parameters`` to every tool's parameters.FfunctionrU   T)r"   r%   appendr*   rV   )tools	sanitized
any_changetoolfnparamsr1   new_fns           r=   sanitize_moonshot_toolsra      s    &(IJ #$%T"XXj!"d#T"%4V<6!J33L(3F99j&9:T"#" #9--rQ   c                    | sy| j                         j                         }|j                  dd      d   }|j                  d      s|dk(  ry|dk(  s|j                  d	      ryd
|v sd|v s|j                  d      ryy)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/r   zkimi-kimiTk3)zk3.zk3-moonshotz/kimi)striplowerrsplit
startswith)modelbaretails      r=   is_moonshot_modelro      s~     ;;= D;;sAr"Dw46> t|t~6TW_0GrQ   )T)r/   r   r   rK   returnr   )r/   Dict[str, Any]rp   rq   )rU   r   rp   rq   )rZ   List[Dict[str, Any]]rp   rr   )rl   z
str | Nonerp   rK   )__doc__
__future__r   rS   typingr   r   r   	frozensetr&   r'   r(   r$   r.   r-   rV   ra   ro    rQ   r=   <module>rx      sc   4 #  " "
 XY  HI  cd `F&&D..6rQ   