trae 0.2.24: a Kimi model's tool schemas get the types Moonshot requires (code 4027) (#462)
Trae passed a request's tools to the model as they were. Moonshot (Kimi) refuses the whole request when a schema node has no type: Trae answers code 4027, "tools.function.parameters is not a valid moonshot flavored json schema … type is not defined". Claude Code's enum-only properties trigger it. For a model whose config, model_name or request model matches /kimi|moonshot/i, nativeTools now deep-clones each tool's parameters and rewrites them with kimi-work's moonshotSchema (ported). An enum or const with no type gets the type its values have, and a $ref beside a type and a type beside an anyOf are written the way Kimi takes them. Other models' tools, and schemas Kimi already accepts, go byte for byte. README note, new moonshot.test.mjs, and 0.2.23 -> 0.2.24. By edifierx666 (#462). Reviewed at 4c8dc7401f74fb44615bcb70ee0178337a017951. The only change since is 31c88fe84 (maintainer): the README's Kimi bullet moved after the native-tools bullet's continuation paragraph. The text is unchanged. Run at 31c88fe84 (macOS, via mote-run, sandbox HOME): bun test packages/trae, 221 pass, 0 fail; bun scripts/check.mjs trae passes. Run at 4c8dc7401 as well: the same 221/0, plus check. Broken by hand at 4c8dc7401, running moonshot.test.mjs: - moonshotModel always false: 4 of 6 red. - Always true: the non-Kimi test red. - structuredClone dropped: red. Edge cases run through chatBody, 18 schemas: null, mixed, object and empty enums; nullable; anyOf/oneOf; nested objects; arrays without items; untyped and self $refs; boolean schemas; properties named enum or const. glm-5's parameters are byte-identical in every case. For Kimi, enums and consts only gain a type. Not tried: a live Trae CN or Trae Global request (the author ran Trae CN live, per the PR).
This commit is contained in:
@@ -134,6 +134,13 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`:
|
||||
error (plugins#38). Trae takes no two messages of one role in a row,
|
||||
so an assistant turn's text is folded into the calls turn after it
|
||||
and consecutive calls turns join one `tool_calls` list.
|
||||
- For a Kimi (Moonshot) model the tools' schemas are first rewritten for
|
||||
Moonshot's "moonshot flavored json schema", which Trae's 4027 "tool call
|
||||
failed" quotes when it refuses them: an `enum` or `const` with no `type`
|
||||
gets the one its values have, a `$ref` beside a `type` and a `type` beside
|
||||
an `anyOf` are written as Kimi holds them (the same rules as kimi-work's).
|
||||
The request's own tools are not changed, and a schema Kimi takes as it is
|
||||
goes byte for byte. Other models' tools go as they are.
|
||||
- A call with no name is dropped, and the `tool` result answering it
|
||||
with it: Trae requires the name, and an empty `tool_calls` list with a
|
||||
result naming no call is not a turn it takes.
|
||||
|
||||
+151
-5
@@ -1126,11 +1126,157 @@ function traeMessages(req, sees = false) {
|
||||
})
|
||||
}
|
||||
|
||||
// nativeTools are the tools as Trae names them: parameters a JSON string
|
||||
const nativeTools = (tools) =>
|
||||
// Moonshot (Kimi) validates tools against its own "moonshot flavored json
|
||||
// schema" and refuses the whole request (Trae answers code 4027, "tool call
|
||||
// failed: Invalid request: tools.function.parameters is not a valid moonshot
|
||||
// flavored json schema, details: <At path 'properties.ops.items.properties.op':
|
||||
// type is not defined>") for shapes a JSON Schema allows and agents send: an
|
||||
// enum or const with no type (Claude Code's tools carry them), a $ref beside a
|
||||
// type, a type beside an anyOf. Trae passes the tools to Kimi as they are, so
|
||||
// they are rewritten here for the rules Kimi has been seen to hold, for a
|
||||
// Kimi/Moonshot model only (moonshotModel). This is kimi-work's moonshotSchema,
|
||||
// which carries the reasons for each rule, ported. The tools sent are
|
||||
// a copy: the request's own stay as they were, and a schema Kimi takes as it is
|
||||
// goes byte for byte.
|
||||
const jsIsObj=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
||||
const msMAP_KEYS=['properties','$defs','definitions','dependentSchemas','patternProperties'];
|
||||
const msSUB_KEYS=['items','additionalProperties','contains','propertyNames','not','if','then','else','allOf','anyOf','oneOf','prefixItems','unevaluatedProperties','unevaluatedItems','contentSchema'];
|
||||
const msALL_TYPES=['string','number','integer','boolean','object','array','null'];
|
||||
|
||||
function msEachSchema(node,f) {
|
||||
if(Array.isArray(node)) {for(const v of node)msEachSchema(v,f);return;}
|
||||
if(!jsIsObj(node))return;
|
||||
f(node);
|
||||
for(const k of msMAP_KEYS) if(jsIsObj(node[k])) for(const v of Object.values(node[k])) msEachSchema(v,f);
|
||||
for(const k of msSUB_KEYS) if(k in node) msEachSchema(node[k],f);
|
||||
}
|
||||
|
||||
function msRefTarget(root,ref) {
|
||||
if(typeof ref!=='string'||(ref!=='#'&&!ref.startsWith('#/')))return undefined;
|
||||
let cur=root;
|
||||
for(let tok of ref.split('/').slice(1)) {
|
||||
tok=tok.replace(/~1/g,'/').replace(/~0/g,'~');
|
||||
try{tok=decodeURIComponent(tok);}catch{}
|
||||
if(!jsIsObj(cur)&&!Array.isArray(cur))return undefined;
|
||||
if(!Object.hasOwn(cur,tok))return undefined;
|
||||
cur=cur[tok];
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
const msHasRefInside=s=>JSON.stringify(s).includes('"$ref"');
|
||||
|
||||
function msValueType(v) {
|
||||
if(v===null)return 'null';
|
||||
switch(typeof v){
|
||||
case 'string':return 'string';
|
||||
case 'boolean':return 'boolean';
|
||||
case 'number':return Number.isInteger(v)?'integer':'number';
|
||||
}
|
||||
return Array.isArray(v)?'array':'object';
|
||||
}
|
||||
|
||||
// the type an enum of vals is given: the one all non-null values have, with
|
||||
// "null" when a null is among them; undefined when there are none or they
|
||||
// are of more than one kind
|
||||
function msEnumType(vals) {
|
||||
let t,nul=false;
|
||||
for(const v of vals) {
|
||||
const vt=msValueType(v);
|
||||
if(vt==='null'){nul=true;continue;}
|
||||
if(vt==='array'||vt==='object')return undefined;
|
||||
if(t===undefined||t===vt)t=vt;
|
||||
else if((t==='integer'&&vt==='number')||(t==='number'&&vt==='integer'))t='number';
|
||||
else return undefined;
|
||||
}
|
||||
if(t===undefined)return undefined;
|
||||
return nul?[t,'null']:t;
|
||||
}
|
||||
|
||||
// the types s can have, as its type, keywords, values or branches say;
|
||||
// undefined when they don't say
|
||||
function msSchemaTypes(root,s,depth=0) {
|
||||
if(depth>16||!jsIsObj(s))return undefined;
|
||||
if('type' in s)return new Set([].concat(s.type).map(String));
|
||||
if('$ref' in s){const t=msRefTarget(root,s.$ref);return t===undefined?undefined:msSchemaTypes(root,t,depth+1);}
|
||||
if(Array.isArray(s.enum)||'const' in s)return new Set(('const' in s?[s.const]:s.enum).map(msValueType));
|
||||
for(const k of ['oneOf','anyOf','allOf']) {
|
||||
if(!Array.isArray(s[k]))continue;
|
||||
const ts=new Set();
|
||||
for(const b of s[k]) {
|
||||
const bt=msSchemaTypes(root,b,depth+1);
|
||||
if(!bt){if(k!=='allOf')return undefined;continue;}
|
||||
for(const t of bt)ts.add(t);
|
||||
}
|
||||
if(ts.size)return ts;
|
||||
}
|
||||
const has=(...ks)=>ks.some(k=>k in s);
|
||||
if(has('properties','required','additionalProperties','patternProperties','minProperties','maxProperties','propertyNames','dependentRequired','dependentSchemas','unevaluatedProperties'))return new Set(['object']);
|
||||
if(has('items','prefixItems','minItems','maxItems','uniqueItems','contains','unevaluatedItems'))return new Set(['array']);
|
||||
if(has('minLength','maxLength','pattern','format','contentEncoding','contentMediaType'))return new Set(['string']);
|
||||
if(has('minimum','maximum','exclusiveMinimum','exclusiveMaximum','multipleOf'))return new Set(['number']);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function msTypeFor(root,s) {
|
||||
if(Array.isArray(s.enum))return msEnumType(s.enum);
|
||||
if('const' in s)return msEnumType([s.const]);
|
||||
const ts=msSchemaTypes(root,s);
|
||||
if(!ts||!ts.size)return [...msALL_TYPES];
|
||||
if(ts.has('integer')&&ts.has('number'))ts.delete('integer');
|
||||
const names=msALL_TYPES.filter(t=>ts.has(t));
|
||||
return names.length===1?names[0]:names;
|
||||
}
|
||||
|
||||
// the same object with type written first, as an agent would have
|
||||
const msWithType=(s,type)=>{const rest={...s};delete rest.type;for(const k of Object.keys(s))delete s[k];Object.assign(s,{type},rest);};
|
||||
|
||||
function moonshotSchema(root) {
|
||||
let changed=false;
|
||||
// a $ref beside a type, and a type beside an anyOf
|
||||
msEachSchema(root,s=>{
|
||||
if('$ref' in s&&'type' in s) {
|
||||
const t=msRefTarget(root,s.$ref);
|
||||
if(jsIsObj(t)&&!msHasRefInside(t)) {
|
||||
const own={...s};delete own.$ref;
|
||||
for(const k of Object.keys(s))delete s[k];
|
||||
Object.assign(s,structuredClone(t),own);
|
||||
} else delete s.type;
|
||||
changed=true;
|
||||
}
|
||||
if(Array.isArray(s.anyOf)&&'type' in s){delete s.type;changed=true;}
|
||||
});
|
||||
// an enum or const with no type
|
||||
msEachSchema(root,s=>{
|
||||
if('type' in s||!(Array.isArray(s.enum)||'const' in s))return;
|
||||
const t=msEnumType(Array.isArray(s.enum)?s.enum:[s.const]);
|
||||
if(t!==undefined){msWithType(s,t);changed=true;}
|
||||
});
|
||||
// a $ref's target with no type
|
||||
msEachSchema(root,s=>{
|
||||
if(typeof s.$ref!=='string')return;
|
||||
const t=msRefTarget(root,s.$ref);
|
||||
if(!jsIsObj(t)||'type' in t||'anyOf' in t||'$ref' in t||!Object.keys(t).length)return;
|
||||
const typ=msTypeFor(root,t);
|
||||
if(typ!==undefined){msWithType(t,typ);changed=true;}
|
||||
});
|
||||
return changed;
|
||||
}
|
||||
|
||||
|
||||
const moonshotModel = (...names) => names.some((n) => /kimi|moonshot/i.test(String(n ?? "")))
|
||||
|
||||
// nativeTools are the tools as Trae names them: parameters a JSON string.
|
||||
// moonshot is whether a Kimi model takes them (moonshotSchema)
|
||||
const nativeTools = (tools, moonshot = false) =>
|
||||
tools.map((t) => {
|
||||
const f = t.function ?? t
|
||||
return { type: "function", function: { name: f.name, description: f.description ?? "", parameters: typeof f.parameters === "string" ? f.parameters : JSON.stringify(f.parameters ?? {}) } }
|
||||
let p = f.parameters
|
||||
if (moonshot && jsIsObj(p)) {
|
||||
p = structuredClone(p)
|
||||
moonshotSchema(p)
|
||||
}
|
||||
return { type: "function", function: { name: f.name, description: f.description ?? "", parameters: typeof p === "string" ? p : JSON.stringify(p ?? {}) } }
|
||||
})
|
||||
|
||||
// SESSION carries the conversation magpie (or OpenCode) names a request by,
|
||||
@@ -1225,7 +1371,7 @@ function chatBody(req, fn, modelName, most = 0, max = null, session = "", sees =
|
||||
}
|
||||
if (typeof req.temperature === "number") body.temperature = req.temperature
|
||||
if (Array.isArray(req.tools) && req.tools.length && req.tool_choice !== "none") {
|
||||
body.tools = nativeTools(req.tools)
|
||||
body.tools = nativeTools(req.tools, moonshotModel(config, modelName, req.model))
|
||||
const c = req.tool_choice
|
||||
if (c && typeof c === "object") body.tool_choice = c.function?.name || c.name || "auto"
|
||||
else if (typeof c === "string") body.tool_choice = c
|
||||
@@ -3396,4 +3542,4 @@ const makePlugin = (site) => async ({ client }) => {
|
||||
export const TraeCNAuthPlugin = makePlugin(SITES["trae-cn"])
|
||||
export const TraeGlobalAuthPlugin = makePlugin(SITES["trae-global"])
|
||||
|
||||
export const _internal = { ownClient, clientStoragePaths, clientDevice, clientDecode, thisMachine, traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, nameCall, toolNamed, unwrapped, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, ugDevice, proofOf, SITES, SESSION, conversationID, LEVELS, levelsOf, variantsOf, effortOf }
|
||||
export const _internal = { ownClient, clientStoragePaths, clientDevice, clientDecode, thisMachine, traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, nameCall, toolNamed, unwrapped, traeMessages, chatBody, nativeTools, moonshotSchema, credits, dollarUsageOf, whenOf, newDevice, ugDevice, proofOf, SITES, SESSION, conversationID, LEVELS, levelsOf, variantsOf, effortOf }
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// Moonshot (Kimi) refuses a tool schema whose property has no type (Trae code
|
||||
// 4027, "type is not defined"): the tools sent for a Kimi model are given one.
|
||||
import "./nonet.mjs"
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { TraeCNAuthPlugin, _internal } from "./index.mjs"
|
||||
import { fakeTrae, signedIn, sse } from "./fake.mjs"
|
||||
|
||||
const { chatBody, nativeTools } = _internal
|
||||
|
||||
// Claude Code's shape: an enum with no type, in an array's items
|
||||
const ENUM_ONLY = {
|
||||
type: "object",
|
||||
properties: { ops: { type: "array", items: { type: "object", properties: { op: { enum: ["add", "remove"] }, n: { enum: [1, 2] }, f: { enum: [1, 2.5] }, b: { const: true } } } } },
|
||||
}
|
||||
const tool = (parameters) => [{ type: "function", function: { name: "edit", description: "d", parameters } }]
|
||||
const sent = (tools, model = "kimi-k3.1-pro-max") => JSON.parse(chatBody({ model, messages: [], tools }, "chat_v3", "").tools[0].function.parameters)
|
||||
|
||||
let f
|
||||
afterEach(() => f?.close())
|
||||
|
||||
test("an enum or const with no type gets the one its values have", () => {
|
||||
const p = sent(tool(ENUM_ONLY)).properties.ops.items.properties
|
||||
expect(p.op).toEqual({ type: "string", enum: ["add", "remove"] })
|
||||
expect(p.n).toEqual({ type: "integer", enum: [1, 2] })
|
||||
expect(p.f).toEqual({ type: "number", enum: [1, 2.5] })
|
||||
expect(p.b).toEqual({ type: "boolean", const: true })
|
||||
})
|
||||
|
||||
test("the request's own tools are not changed", () => {
|
||||
const tools = tool(ENUM_ONLY)
|
||||
const before = JSON.stringify(tools)
|
||||
sent(tools)
|
||||
expect(JSON.stringify(tools)).toBe(before)
|
||||
})
|
||||
|
||||
test("a model that is not Kimi or Moonshot is sent the schema as it is", () => {
|
||||
for (const model of ["glm-5", "DeepSeek-V4.1-Flash-1017"]) expect(sent(tool(ENUM_ONLY), model)).toEqual(ENUM_ONLY)
|
||||
expect(sent(tool(ENUM_ONLY), "Kimi-K3")).not.toEqual(ENUM_ONLY)
|
||||
expect(sent(tool(ENUM_ONLY), "moonshot-v1")).not.toEqual(ENUM_ONLY)
|
||||
})
|
||||
|
||||
test("a schema Kimi takes goes byte for byte", () => {
|
||||
const ok = { type: "object", properties: { a: { type: "string", enum: ["x"] }, b: { anyOf: [{ type: "string" }, { type: "null" }] } } }
|
||||
expect(nativeTools(tool(ok), true)[0].function.parameters).toBe(JSON.stringify(ok))
|
||||
expect(nativeTools(tool(ok), false)[0].function.parameters).toBe(JSON.stringify(ok))
|
||||
})
|
||||
|
||||
test("a $ref beside a type and a type beside an anyOf are written as Kimi holds them", () => {
|
||||
const p = {
|
||||
type: "object",
|
||||
properties: { n: { type: "integer", maximum: 5, $ref: "#/$defs/s0" }, u: { type: "string", anyOf: [{ type: "string" }, { type: "null" }] } },
|
||||
$defs: { s0: { type: "number" } },
|
||||
}
|
||||
const out = sent(tool(p))
|
||||
expect(out.properties.n).toEqual({ type: "integer", maximum: 5 })
|
||||
expect(out.properties.u).toEqual({ anyOf: [{ type: "string" }, { type: "null" }] })
|
||||
})
|
||||
|
||||
test("the Kimi request that carried the enum-only tool reaches Trae with a typed schema", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]]))
|
||||
const hooks = await TraeCNAuthPlugin({ client: {} })
|
||||
const opts = await hooks.auth.loader(async () => signedIn())
|
||||
await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model: "kimi-k2.6", tools: tool(ENUM_ONLY), messages: [{ role: "user", content: "hi" }] }) })
|
||||
const op = JSON.parse(f.seen[0].json.tools[0].function.parameters).properties.ops.items.properties.op
|
||||
expect(op.type).toBe("string")
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-trae-auth",
|
||||
"version": "0.2.23",
|
||||
"version": "0.2.24",
|
||||
"description": "OpenCode provider plugins for Trae: Trae CN (trae.cn) and Trae Global (trae.ai), free tier included, with Trae's own browser sign-in",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user