kimi-work 0.1.5: tool schemas Kimi's moonshot check refuses go in a shape it takes (#287)
chai-j: every Codex message on Kimi Work failed, 400 "tools.function.
parameters is not a valid moonshot flavored json schema, details: <At
path '$defs.__schema20': when using $ref, type should be defined in the
referenced schema instead of the parent schema>". The plugin passed the
body through as sent. Codex's MCP and app tools are zod's toJSONSchema
with reused schemas as $defs, and zod 4 writes a schema derived from a
reused one as a $ref beside what it changed: z.number().min(0) reused,
then .int() and reused itself, is $defs.__schema1 =
{"type":"integer","maximum":…,"$ref":"#/$defs/__schema0"}. Reproduced
with zod 4.6.7; the fixture is its output.
magpie's own Kimi rewrites (kimiToolEnumTypes, kimiToolRefTypes) are
scoped to api.kimi.com/moonshot hosts and presets, so a plugin's
agent-gw.kimi.com requests never got them. moonshotTools does the class
in the plugin, on tools[].function.parameters only:
- $ref beside a type: a target with no $ref of its own is written in its
place with the parent's keywords over it (what zod's derived schema
means: .int() of min(0) is {type:integer,minimum:0,maximum}); otherwise
the parent's type is left out.
- type beside anyOf is left out (Kimi: "type should be defined in anyOf
items instead of the parent schema", measured in magpie 129d8b08a).
- enum/const with no type gets its values' type, [T,"null"] with a null
(magpie #886).
- an untyped $ref target gets the type its keywords or branches say
(magpie 129d8b08a). Unlike magpie's kimiToolRefTypes, a target that is
itself a $ref with keywords beside it (Codex App's
{"format":"uuid","$ref":…}) is left alone, so no type is put beside a
$ref.
A body with none of these goes byte for byte; a rewrite is deterministic,
so a cached prefix stays one. A Request or byte body is read as text.
Tests: tests/schema.test.mjs, with the zod fixture and Codex App's
automation_update parameters (magpie testdata) checked against the
refusal rules; 4 of its 7 tests fail on 0.1.4's index.mjs (the other
three guard the fixtures and pass-through). Package: 25 pass. Whole repo
the way CI runs it, HOME=$(mktemp -d) bun test at this head: 2056 pass,
0 fail. bun scripts/check.mjs kimi-work: ok.
Not tried: a real Kimi Work account (none here), so the rewritten tools
were never sent to agent-gw.kimi.com's validator, and the reporter's
literal __schema20 wasn't captured; the shape comes from zod's output
and the error text.
This commit is contained in:
@@ -13,7 +13,7 @@ Open Kimi desktop and sign in to Work on the same computer first. Choose **使
|
||||
|
||||
The account's models and reasoning options come from `https://agent-gw.kimi.com/coding/v1/models`. Chat completions, streaming, tool calls and cancellation use the same Work gateway. The request uses this plugin's own User-Agent; it does not impersonate Kimi's desktop client. It never uses `api.kimi.com` or a Kimi Code API key.
|
||||
|
||||
Version 0.1.4 preserves the calling agent's shared instructions, prompts, history and tools unchanged. Instructions, MCP and skills are assigned to that agent in Magpie's Library; the provider does not create a second target or enable resources on its own. The ordinary Kimi agent's Library support starts at `@magpie-community/agent-kimi-desktop` 0.1.1.
|
||||
Version 0.1.4 preserves the calling agent's shared instructions, prompts, history and tools unchanged. Since 0.1.5 one exception: tool schemas Kimi's "moonshot flavored json schema" check refuses are rewritten to an equivalent it takes (#287). A `$ref` beside a `type`, as zod writes a schema derived from a reused one, gets its target written in; a `type` beside an `anyOf` is left out; an untyped `enum`, `const` or `$ref` target gets the type its values or keywords say. A request with none of these goes byte for byte. Instructions, MCP and skills are assigned to that agent in Magpie's Library; the provider does not create a second target or enable resources on its own. The ordinary Kimi agent's Library support starts at `@magpie-community/agent-kimi-desktop` 0.1.1.
|
||||
|
||||
An inference HTTP 401 marks the provider sign-in as expired (`kimi_work_login_expired`). Sign in to desktop Work if needed, then **reconnect Kimi Work in Magpie** (or run `magpie plugin login kimi-work`); signing in to the desktop alone does not reconnect the provider. Other HTTP errors, including 429 and 5xx, pass through unchanged with Kimi's status, headers, body and Retry-After. This preserves the distinction between concurrency limits and exhausted allowance, including any upstream reset details. Network failures use `kimi_work_connection_failed` and retain the underlying cause code or fetch error message for diagnosis. Rate limits and service failures do not invalidate the desktop sign-in. Cancellation stays cancellation. No automatic retry sends a conversation twice or falls back to Code.
|
||||
|
||||
|
||||
@@ -12,6 +12,168 @@ const expired = () => Object.assign(Error('请先在本机 Kimi 桌面版登录
|
||||
const unavailable = error => Object.assign(Error('Kimi Work 连接失败:' + (error?.cause?.code || error?.message || '未知网络错误'), {cause:error}), {code:'kimi_work_connection_failed'});
|
||||
const percent = x => typeof x === 'number' && Number.isFinite(x) ? Math.max(0,Math.min(100,x*100)) : undefined;
|
||||
|
||||
// Kimi Work validates tools against Moonshot's "moonshot flavored json
|
||||
// schema" and refuses the whole request, 400 "tools.function.parameters is
|
||||
// not a valid moonshot flavored json schema", for shapes a JSON Schema
|
||||
// allows and agents send (#287). Codex's MCP and app tools are zod's
|
||||
// toJSONSchema with reused schemas as $defs (__schema0, __schema1 …), and
|
||||
// zod writes a schema derived from a reused one as a $ref beside what it
|
||||
// changed: z.number() reused, then .int(), is {"type":"integer","maximum":…,
|
||||
// "$ref":"#/$defs/__schema0"}, refused "when using $ref, type should be
|
||||
// defined in the referenced schema instead of the parent schema". The tools
|
||||
// are rewritten for the rules Kimi has been seen to hold:
|
||||
// - a $ref beside a type: the target, when it has no $ref of its own, is
|
||||
// written in its place with the parent's keywords over it (what zod's
|
||||
// derived schema means); otherwise the parent's type is left out;
|
||||
// - a type beside an anyOf ("type should be defined in anyOf items instead
|
||||
// of the parent schema") is left out;
|
||||
// - an enum or const with no type gets the one its values have, or it and
|
||||
// "null" ("type is not defined");
|
||||
// - a $ref's target with no type gets the one its keywords or branches say
|
||||
// ("detected infinite recursion without termination condition").
|
||||
// A body Kimi takes as it is goes byte for byte; a rewrite is the same for
|
||||
// the same tools, so a cached prefix stays one.
|
||||
const isObj=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
||||
const MAP_KEYS=['properties','$defs','definitions','dependentSchemas','patternProperties'];
|
||||
const SUB_KEYS=['items','additionalProperties','contains','propertyNames','not','if','then','else','allOf','anyOf','oneOf','prefixItems','unevaluatedProperties','unevaluatedItems','contentSchema'];
|
||||
const NOTES=new Set(['$ref','description','title','default','examples','$comment','deprecated','readOnly','writeOnly']);
|
||||
const ALL_TYPES=['string','number','integer','boolean','object','array','null'];
|
||||
|
||||
function eachSchema(node,f) {
|
||||
if(Array.isArray(node)) {for(const v of node)eachSchema(v,f);return;}
|
||||
if(!isObj(node))return;
|
||||
f(node);
|
||||
for(const k of MAP_KEYS) if(isObj(node[k])) for(const v of Object.values(node[k])) eachSchema(v,f);
|
||||
for(const k of SUB_KEYS) if(k in node) eachSchema(node[k],f);
|
||||
}
|
||||
|
||||
function refTarget(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(!isObj(cur)&&!Array.isArray(cur))return undefined;
|
||||
if(!Object.hasOwn(cur,tok))return undefined;
|
||||
cur=cur[tok];
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
const hasRefInside=s=>JSON.stringify(s).includes('"$ref"');
|
||||
|
||||
function valueType(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 enumType(vals) {
|
||||
let t,nul=false;
|
||||
for(const v of vals) {
|
||||
const vt=valueType(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 schemaTypes(root,s,depth=0) {
|
||||
if(depth>16||!isObj(s))return undefined;
|
||||
if('type' in s)return new Set([].concat(s.type).map(String));
|
||||
if('$ref' in s){const t=refTarget(root,s.$ref);return t===undefined?undefined:schemaTypes(root,t,depth+1);}
|
||||
if(Array.isArray(s.enum)||'const' in s)return new Set(('const' in s?[s.const]:s.enum).map(valueType));
|
||||
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=schemaTypes(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 typeFor(root,s) {
|
||||
if(Array.isArray(s.enum))return enumType(s.enum);
|
||||
if('const' in s)return enumType([s.const]);
|
||||
const ts=schemaTypes(root,s);
|
||||
if(!ts||!ts.size)return [...ALL_TYPES];
|
||||
if(ts.has('integer')&&ts.has('number'))ts.delete('integer');
|
||||
const names=ALL_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 withType=(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
|
||||
eachSchema(root,s=>{
|
||||
if('$ref' in s&&'type' in s) {
|
||||
const t=refTarget(root,s.$ref);
|
||||
if(isObj(t)&&!hasRefInside(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
|
||||
eachSchema(root,s=>{
|
||||
if('type' in s||!(Array.isArray(s.enum)||'const' in s))return;
|
||||
const t=enumType(Array.isArray(s.enum)?s.enum:[s.const]);
|
||||
if(t!==undefined){withType(s,t);changed=true;}
|
||||
});
|
||||
// a $ref's target with no type
|
||||
eachSchema(root,s=>{
|
||||
if(typeof s.$ref!=='string')return;
|
||||
const t=refTarget(root,s.$ref);
|
||||
if(!isObj(t)||'type' in t||'anyOf' in t||'$ref' in t||!Object.keys(t).length)return;
|
||||
const typ=typeFor(root,t);
|
||||
if(typ!==undefined){withType(t,typ);changed=true;}
|
||||
});
|
||||
return changed;
|
||||
}
|
||||
|
||||
// body with each tool's parameters as Kimi takes them; the same string when
|
||||
// nothing had to change or it isn't a chat body with tools
|
||||
function moonshotTools(body) {
|
||||
if(typeof body!=='string'||!body.includes('"tools"'))return body;
|
||||
let doc;
|
||||
try{doc=JSON.parse(body);}catch{return body;}
|
||||
if(!isObj(doc)||!Array.isArray(doc.tools))return body;
|
||||
let changed=false;
|
||||
for(const tool of doc.tools) {
|
||||
const p=tool?.function?.parameters;
|
||||
if(isObj(p)&&moonshotSchema(p))changed=true;
|
||||
}
|
||||
return changed?JSON.stringify(doc):body;
|
||||
}
|
||||
|
||||
function desktopFile({home=os.homedir(), platform=process.platform, appdata=process.env.APPDATA}={}) {
|
||||
const parent=platform==='win32' ? appdata || path.join(home,'AppData','Roaming')
|
||||
: platform==='darwin' ? path.join(home,'Library','Application Support') : path.join(home,'.config');
|
||||
@@ -113,9 +275,15 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch}={}) {
|
||||
headers.set('Authorization','Bearer '+s.workToken);
|
||||
headers.set('User-Agent',UA);
|
||||
headers.set('Content-Type','application/json');
|
||||
// Preserve messages, tools, stream and abort signal. There is no
|
||||
// Preserve messages, stream and abort signal, and tools but for
|
||||
// the schema shapes Kimi refuses (moonshotTools). There is no
|
||||
// fallback to api.kimi.com, a Code API key, or another provider.
|
||||
const options=request?{...init,body:request.body,signal:request.signal,duplex:'half'}:init;
|
||||
const raw=request?request.body:init.body;
|
||||
let body=raw;
|
||||
if(raw!=null&&typeof raw!=='string')body=await new Response(raw).text();
|
||||
if(body!=null)body=moonshotTools(body);
|
||||
const options={...init,body,signal:request?request.signal:init.signal};
|
||||
if(body==null)delete options.body;
|
||||
let response;
|
||||
try { response=await fetchImpl(BASE+'/chat/completions',{...options,method:'POST',headers,redirect:'error'}); }
|
||||
catch(error) { if(options.signal?.aborted)throw error; throw unavailable(error); }
|
||||
@@ -142,4 +310,4 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch}={}) {
|
||||
}
|
||||
|
||||
export default async function KimiWorkProvider(){return createPlugin();}
|
||||
export const _internal={createPlugin,readDesktop,desktopFile,modelRows,BASE,MEMBER,UA};
|
||||
export const _internal={createPlugin,moonshotTools,moonshotSchema,readDesktop,desktopFile,modelRows,BASE,MEMBER,UA};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-kimi-work-auth",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.5",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
"files": [
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"const": "view"
|
||||
},
|
||||
"id": {
|
||||
"$ref": "#/$defs/__schema0"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"mode",
|
||||
"id"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"$ref": "#/$defs/__schema2"
|
||||
},
|
||||
"prompt": {
|
||||
"$ref": "#/$defs/__schema3"
|
||||
},
|
||||
"rrule": {
|
||||
"$ref": "#/$defs/__schema4"
|
||||
},
|
||||
"status": {
|
||||
"$ref": "#/$defs/__schema5"
|
||||
},
|
||||
"notificationPolicy": {
|
||||
"$ref": "#/$defs/__schema6"
|
||||
},
|
||||
"kind": {
|
||||
"$ref": "#/$defs/__schema7"
|
||||
},
|
||||
"projectId": {
|
||||
"$ref": "#/$defs/__schema8"
|
||||
},
|
||||
"model": {
|
||||
"$ref": "#/$defs/__schema9"
|
||||
},
|
||||
"reasoningEffort": {
|
||||
"$ref": "#/$defs/__schema10"
|
||||
},
|
||||
"mode": {
|
||||
"$ref": "#/$defs/__schema11"
|
||||
},
|
||||
"destination": {
|
||||
"type": "string",
|
||||
"const": "local"
|
||||
},
|
||||
"executionEnvironment": {
|
||||
"type": "string",
|
||||
"const": "local"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"prompt",
|
||||
"rrule",
|
||||
"status",
|
||||
"kind",
|
||||
"projectId",
|
||||
"model",
|
||||
"reasoningEffort",
|
||||
"mode",
|
||||
"executionEnvironment"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"$ref": "#/$defs/__schema2"
|
||||
},
|
||||
"prompt": {
|
||||
"$ref": "#/$defs/__schema3"
|
||||
},
|
||||
"rrule": {
|
||||
"$ref": "#/$defs/__schema4"
|
||||
},
|
||||
"status": {
|
||||
"$ref": "#/$defs/__schema5"
|
||||
},
|
||||
"notificationPolicy": {
|
||||
"$ref": "#/$defs/__schema6"
|
||||
},
|
||||
"kind": {
|
||||
"$ref": "#/$defs/__schema12"
|
||||
},
|
||||
"destination": {
|
||||
"$ref": "#/$defs/__schema13"
|
||||
},
|
||||
"targetThreadId": {
|
||||
"$ref": "#/$defs/__schema14"
|
||||
},
|
||||
"mode": {
|
||||
"$ref": "#/$defs/__schema11"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"prompt",
|
||||
"rrule",
|
||||
"status",
|
||||
"kind",
|
||||
"mode"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"$ref": "#/$defs/__schema2"
|
||||
},
|
||||
"prompt": {
|
||||
"$ref": "#/$defs/__schema3"
|
||||
},
|
||||
"rrule": {
|
||||
"$ref": "#/$defs/__schema15"
|
||||
},
|
||||
"status": {
|
||||
"$ref": "#/$defs/__schema5"
|
||||
},
|
||||
"notificationPolicy": {
|
||||
"$ref": "#/$defs/__schema6"
|
||||
},
|
||||
"kind": {
|
||||
"$ref": "#/$defs/__schema7"
|
||||
},
|
||||
"projectId": {
|
||||
"$ref": "#/$defs/__schema8"
|
||||
},
|
||||
"model": {
|
||||
"$ref": "#/$defs/__schema9"
|
||||
},
|
||||
"reasoningEffort": {
|
||||
"$ref": "#/$defs/__schema10"
|
||||
},
|
||||
"mode": {
|
||||
"$ref": "#/$defs/__schema16"
|
||||
},
|
||||
"id": {
|
||||
"$ref": "#/$defs/__schema0"
|
||||
},
|
||||
"destination": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"local",
|
||||
"worktree"
|
||||
]
|
||||
},
|
||||
"executionEnvironment": {
|
||||
"description": "env",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"worktree",
|
||||
"local"
|
||||
]
|
||||
},
|
||||
"localEnvironmentConfigPath": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"prompt",
|
||||
"rrule",
|
||||
"status",
|
||||
"kind",
|
||||
"projectId",
|
||||
"model",
|
||||
"reasoningEffort",
|
||||
"mode",
|
||||
"id",
|
||||
"executionEnvironment"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"$ref": "#/$defs/__schema2"
|
||||
},
|
||||
"prompt": {
|
||||
"$ref": "#/$defs/__schema3"
|
||||
},
|
||||
"rrule": {
|
||||
"$ref": "#/$defs/__schema15"
|
||||
},
|
||||
"status": {
|
||||
"$ref": "#/$defs/__schema5"
|
||||
},
|
||||
"notificationPolicy": {
|
||||
"$ref": "#/$defs/__schema6"
|
||||
},
|
||||
"kind": {
|
||||
"$ref": "#/$defs/__schema12"
|
||||
},
|
||||
"destination": {
|
||||
"$ref": "#/$defs/__schema13"
|
||||
},
|
||||
"targetThreadId": {
|
||||
"$ref": "#/$defs/__schema14"
|
||||
},
|
||||
"mode": {
|
||||
"$ref": "#/$defs/__schema16"
|
||||
},
|
||||
"id": {
|
||||
"$ref": "#/$defs/__schema0"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"prompt",
|
||||
"rrule",
|
||||
"status",
|
||||
"kind",
|
||||
"mode",
|
||||
"id"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"const": "delete"
|
||||
},
|
||||
"id": {
|
||||
"$ref": "#/$defs/__schema0"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"mode",
|
||||
"id"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
],
|
||||
"$defs": {
|
||||
"__schema0": {
|
||||
"description": "Automation id.",
|
||||
"$ref": "#/$defs/__schema1"
|
||||
},
|
||||
"__schema1": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"__schema2": {
|
||||
"description": "name",
|
||||
"$ref": "#/$defs/__schema1"
|
||||
},
|
||||
"__schema3": {
|
||||
"description": "prompt",
|
||||
"$ref": "#/$defs/__schema1"
|
||||
},
|
||||
"__schema4": {
|
||||
"description": "rrule create",
|
||||
"$ref": "#/$defs/__schema1"
|
||||
},
|
||||
"__schema5": {
|
||||
"description": "status",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"ACTIVE",
|
||||
"PAUSED"
|
||||
]
|
||||
},
|
||||
"__schema6": {
|
||||
"description": "np",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"all",
|
||||
"failed_runs_only"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"__schema7": {
|
||||
"description": "cron",
|
||||
"type": "string",
|
||||
"const": "cron"
|
||||
},
|
||||
"__schema8": {
|
||||
"description": "project",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"__schema9": {
|
||||
"description": "model",
|
||||
"$ref": "#/$defs/__schema1"
|
||||
},
|
||||
"__schema10": {
|
||||
"description": "effort",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"minimal",
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"xhigh",
|
||||
"max",
|
||||
"ultra"
|
||||
]
|
||||
},
|
||||
"__schema11": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"create",
|
||||
"suggested_create"
|
||||
]
|
||||
},
|
||||
"__schema12": {
|
||||
"description": "hb",
|
||||
"type": "string",
|
||||
"const": "heartbeat"
|
||||
},
|
||||
"__schema13": {
|
||||
"description": "dest",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"local",
|
||||
"thread"
|
||||
]
|
||||
},
|
||||
"__schema14": {
|
||||
"format": "uuid",
|
||||
"description": "tt",
|
||||
"$ref": "#/$defs/__schema1"
|
||||
},
|
||||
"__schema15": {
|
||||
"description": "rrule",
|
||||
"$ref": "#/$defs/__schema1"
|
||||
},
|
||||
"__schema16": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"update",
|
||||
"suggested_update"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"offset":{"$ref":"#/$defs/__schema0"},"limit":{"$ref":"#/$defs/__schema1"},"pageSize":{"minimum":0,"description":"page size","$ref":"#/$defs/__schema1"},"threadId":{"$ref":"#/$defs/__schema2"},"runId":{"type":"string","minLength":1,"format":"uuid","pattern":"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$","description":"run","$ref":"#/$defs/__schema2"},"kind":{"type":"string","enum":["a","b"]},"mode":{"anyOf":[{"type":"string","const":"x"},{"type":"string","const":"y"}]},"retries":{"anyOf":[{"$ref":"#/$defs/__schema1"},{"type":"null"}]}},"required":["offset","limit","pageSize","threadId","runId","mode","retries"],"additionalProperties":false,"$defs":{"__schema0":{"type":"number","minimum":0},"__schema1":{"type":"integer","maximum":9007199254740991,"$ref":"#/$defs/__schema0"},"__schema2":{"type":"string","minLength":1}}}
|
||||
@@ -0,0 +1,110 @@
|
||||
// #287: Kimi Work refused every Codex request, 400 "tools.function.parameters
|
||||
// is not a valid moonshot flavored json schema, details: <At path
|
||||
// '$defs.__schema20': when using $ref, type should be defined in the
|
||||
// referenced schema instead of the parent schema>".
|
||||
import {test,expect} from 'bun:test';
|
||||
import fs from 'node:fs';
|
||||
import {_internal as I} from '../index.mjs';
|
||||
|
||||
const fixture=name=>JSON.parse(fs.readFileSync(new URL('./fixtures/'+name,import.meta.url),'utf8'));
|
||||
// zod 4.6.7's toJSONSchema({reused:'ref'}) of a tool whose z.number().min(0)
|
||||
// is reused and then derived with .int(), itself reused: $defs.__schema1 is
|
||||
// {"type":"integer",…,"$ref":"#/$defs/__schema0"}, the shape refused.
|
||||
const zodDerived=fixture('zod-derived-refs.json');
|
||||
// Codex App's automation_update parameters (magpie's testdata).
|
||||
const automation=fixture('codex-automation-update.json');
|
||||
|
||||
const SUB=['items','additionalProperties','contains','propertyNames','not','if','then','else','allOf','anyOf','oneOf','prefixItems','unevaluatedProperties','unevaluatedItems','contentSchema'];
|
||||
const MAP=['properties','$defs','definitions','dependentSchemas','patternProperties'];
|
||||
// the rules Kimi has been seen to refuse, as paths a refusal would name
|
||||
function refusals(root) {
|
||||
const out=[];
|
||||
const walk=(s,at)=>{
|
||||
if(Array.isArray(s)){s.forEach((v,i)=>walk(v,at+'.'+i));return;}
|
||||
if(!s||typeof s!=='object')return;
|
||||
if('$ref' in s&&'type' in s)out.push(at+': type beside $ref');
|
||||
if('anyOf' in s&&'type' in s)out.push(at+': type beside anyOf');
|
||||
if((Array.isArray(s.enum)||'const' in s)&&!('type' in s))out.push(at+': enum without type');
|
||||
if(typeof s.$ref==='string'&&s.$ref.startsWith('#/')) {
|
||||
const t=s.$ref.split('/').slice(1).reduce((c,k)=>c?.[k],root);
|
||||
if(t&&typeof t==='object'&&!('type' in t)&&!('anyOf' in t)&&!('$ref' in t)&&Object.keys(t).length)out.push(at+': untyped $ref target');
|
||||
}
|
||||
for(const k of MAP)if(s[k]&&typeof s[k]==='object')for(const [n,v] of Object.entries(s[k]))walk(v,(at?at+'.':'')+k+'.'+n);
|
||||
for(const k of SUB)if(k in s)walk(s[k],(at?at+'.':'')+k);
|
||||
};
|
||||
walk(root,'');
|
||||
return out;
|
||||
}
|
||||
const bodyOf=parameters=>JSON.stringify({model:'k3-agent',stream:true,messages:[{role:'user',content:'hi'}],
|
||||
tools:[{type:'function',function:{name:'tool',description:'d',parameters}}]});
|
||||
const sent=body=>JSON.parse(I.moonshotTools(body)).tools[0].function.parameters;
|
||||
|
||||
test('the fixtures have the shapes Kimi refuses',()=>{
|
||||
expect(refusals(zodDerived)).toContain('$defs.__schema1: type beside $ref');
|
||||
expect(refusals(zodDerived)).toContain('properties.runId: type beside $ref');
|
||||
});
|
||||
|
||||
test("zod's derived $refs go with the target written in, and nothing Kimi refuses is left",()=>{
|
||||
const p=sent(bodyOf(zodDerived));
|
||||
expect(refusals(p)).toEqual([]);
|
||||
// .int() of z.number().min(0): both constraints kept, the derived type wins
|
||||
expect(p.$defs.__schema1).toEqual({type:'integer',minimum:0,maximum:9007199254740991});
|
||||
expect(p.properties.runId).toMatchObject({type:'string',minLength:1,format:'uuid',description:'run'});
|
||||
expect(p.properties.runId.$ref).toBeUndefined();
|
||||
// a $ref with only notes or keywords beside it is as zod wrote it
|
||||
expect(p.properties.pageSize).toEqual(zodDerived.properties.pageSize);
|
||||
expect(p.properties.offset).toEqual({$ref:'#/$defs/__schema0'});
|
||||
});
|
||||
|
||||
test('a $ref beside a type whose target has refs of its own keeps the ref and loses the type',()=>{
|
||||
const schema={type:'object',properties:{n:{type:'object',$ref:'#/$defs/node'}},
|
||||
$defs:{node:{type:'object',properties:{next:{$ref:'#/$defs/node'}}}}};
|
||||
const p=sent(bodyOf(schema));
|
||||
expect(p.properties.n).toEqual({$ref:'#/$defs/node'});
|
||||
expect(refusals(p)).toEqual([]);
|
||||
});
|
||||
|
||||
test("Codex App's automation_update goes with nothing Kimi refuses added, such as a type beside its format-and-$ref defs",()=>{
|
||||
const p=sent(bodyOf(automation));
|
||||
expect(refusals(p)).toEqual([]);
|
||||
});
|
||||
|
||||
test('a type beside an anyOf, an untyped enum and an untyped oneOf target are given what Kimi takes',()=>{
|
||||
const schema={type:'object',properties:{
|
||||
a:{type:'string',anyOf:[{type:'string'},{type:'null'}]},
|
||||
b:{enum:['x','y']},c:{enum:['x',null]},d:{const:3},
|
||||
e:{$ref:'#/$defs/__schema0'},f:{$ref:'#/$defs/__schema1'}},
|
||||
$defs:{__schema0:{oneOf:[{type:'string'},{type:'number'}]},__schema1:{description:'anything'}}};
|
||||
const p=sent(bodyOf(schema));
|
||||
expect(p.properties.a).toEqual({anyOf:[{type:'string'},{type:'null'}]});
|
||||
expect(p.properties.b).toEqual({type:'string',enum:['x','y']});
|
||||
expect(p.properties.c).toEqual({type:['string','null'],enum:['x',null]});
|
||||
expect(p.properties.d).toEqual({type:'integer',const:3});
|
||||
expect(p.$defs.__schema0.type).toEqual(['string','number']);
|
||||
expect(p.$defs.__schema1.type).toEqual(['string','number','integer','boolean','object','array','null']);
|
||||
expect(refusals(p)).toEqual([]);
|
||||
});
|
||||
|
||||
test('a body Kimi takes goes byte for byte, and a rewrite is the same each time',()=>{
|
||||
const ok=bodyOf({type:'object',properties:{a:{type:'string'},b:{$ref:'#/$defs/x'}},$defs:{x:{type:'number'}}});
|
||||
expect(I.moonshotTools(ok)).toBe(ok);
|
||||
const bad=bodyOf(zodDerived);
|
||||
expect(I.moonshotTools(bad)).toBe(I.moonshotTools(bad));
|
||||
for(const b of ['', 'not json', '{"tools":"x"}', JSON.stringify({messages:[]})])expect(I.moonshotTools(b)).toBe(b);
|
||||
});
|
||||
|
||||
test('the request Kimi Work is sent carries the rewritten tools, from a string or a Request',async()=>{
|
||||
const session={uid:'fixture-account',workToken:'synthetic-work-token',webToken:'synthetic-web-token'};
|
||||
const bodies=[];
|
||||
const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{bodies.push(init.body);return new Response('{}');}});
|
||||
const loader=await p.auth.loader(async()=>({source:'kimi-work-desktop',uid:session.uid}));
|
||||
const body=bodyOf(zodDerived);
|
||||
await loader.fetch(I.BASE+'/chat/completions',{method:'POST',body});
|
||||
await loader.fetch(new Request(I.BASE+'/chat/completions',{method:'POST',body}));
|
||||
await loader.fetch(I.BASE+'/chat/completions',{method:'POST',body:new TextEncoder().encode(body)});
|
||||
expect(bodies.length).toBe(3);
|
||||
for(const b of bodies) {
|
||||
expect(typeof b).toBe('string');
|
||||
expect(refusals(JSON.parse(b).tools[0].function.parameters)).toEqual([]);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user