Files
plugins/packages/kimi-work/tests/provider.test.mjs
T
yetone 663ce131cb kimi-work 0.1.6: one model's unreadable effort list no longer drops the whole catalog; K2.8 Preview in the fallback
泠夜Soul (Discord #help, 10-24) sees only "K3 · Work" in magpie, while the
Kimi app lists K3.1 Pro and K2.8 Preview for the same membership. "K3 · Work"
is the name of this plugin's static fallback; the live /models catalog names
k3-agent "K3". So the account's live list was not used: the models hook
threw or fell back, and magpie kept the config's one model.

The plugin already lists models from agent-gw's /models, so a model Kimi
adds to the account shows under its own id with no hard-coded list. What
changed:

- modelRows no longer throws the whole catalog away when one model's
  reasoningEffortOptions isn't an array, or an option has no string
  effort or one that isn't a plain word: that model keeps the levels that
  can be read (only levels Kimi lists, none guessed). A non-object entry
  is skipped like an id that can't be used. K3.1 Pro went live on
  2026-10-23, the day before the report, so a new entry in a shape not
  seen before is one way the catalog could have failed. It is not the
  confirmed cause: the user's provider.models error line has not been
  seen.
- The fallback (shown before the list is read, and kept when it can't be)
  offers k2d8-preview beside k3-agent. Both ids come from Work's own
  /models: tests/fixtures/work-models.redacted.json and the 10-17 macOS
  record in COMPATIBILITY.md, and #350 ran real Work requests on both.

Not added: a K3.1 Pro id. Kimi Code's docs name it k3.1-pro, but that is
api.kimi.com/coding's catalog (where K2.8 Preview is kimi-for-coding and
K3 is k3, not k3-agent), not the Work gateway's. Work's id for K3.1 Pro is
not in any vendor source found, so none is invented; the live catalog
will show it once read.

Run: bun test packages/kimi-work (43 pass, 0 fail); the two new tests
fail on origin/main's index.mjs (41 pass, 2 fail) and pass with this one;
bun scripts/check.mjs kimi-work ok; git diff --check clean.
Not tried: a real Work account (none on this machine), so the live
catalog with K3.1 Pro has not been seen.
2026-10-24 15:11:15 +08:00

137 lines
8.9 KiB
JavaScript

import {test,expect} from 'bun:test';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {_internal as I} from '../index.mjs';
const session={uid:'fixture-account',workToken:'synthetic-work-token',webToken:'synthetic-web-token'};
const account={source:'kimi-work-desktop',uid:session.uid};
const json=x=>Response.json(x);
const modelPayload={data:[{id:'k3-agent',display_name:'K3',context_length:1000000,supports_image_in:true,
supports_reasoning:true,reasoningEffortOptions:[{effort:'REASONING_EFFORT_HIGH'}]}]};
test('desktop import reads only the Work credential origin and supports a redirected agent configuration',()=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'kimi-work-fixture-'));
const file=path.join(dir,'config.json');
const doc={credentials:{kimiCode:{apiKey:'synthetic-work',baseUrl:I.BASE},kimiWeb:{accessToken:'synthetic-web',userId:'fixture-user'}},
model:{providers:{'daimon-kimi-code':{baseUrl:'http://127.0.0.1:1234/v1'}}}};
try{
fs.writeFileSync(file,JSON.stringify(doc));const raw=fs.readFileSync(file);
expect(I.readDesktop(file).workToken).toBe('synthetic-work');
expect(fs.readFileSync(file)).toEqual(raw);
doc.credentials.kimiCode.baseUrl='https://api.kimi.com/coding/v1';fs.writeFileSync(file,JSON.stringify(doc));
expect(()=>I.readDesktop(file)).toThrow();
}finally{fs.rmSync(dir,{recursive:true,force:true});}
});
test('sign-in persists an account reference without either actual token',async()=>{
const p=I.createPlugin({readSession:()=>session,fetchImpl:async()=>json(modelPayload)});
const flow=await p.auth.methods[0].authorize(),auth=await flow.callback();
expect(auth).toMatchObject({type:'success',source:'kimi-work-desktop',uid:session.uid});
expect(JSON.stringify(auth)).not.toContain(session.workToken);
expect(JSON.stringify(auth)).not.toContain(session.webToken);
});
test('inference always uses the Work gateway and live Work credential, preserving stream, tools and cancellation',async()=>{
const calls=[];let live={...session};
const sse='data: {"choices":[{"delta":{"tool_calls":[{"id":"fixture","function":{"name":"Read","arguments":"{}"}}]}}]}\n\ndata: [DONE]\n\n';
const p=I.createPlugin({readSession:()=>live,fetchImpl:async(url,init)=>{calls.push({url,init});return new Response(sse,{headers:{'Content-Type':'text/event-stream'}});}});
const loader=await p.auth.loader(async()=>account),signal=new AbortController().signal;
const body=JSON.stringify({model:'k3-agent',stream:true,messages:[{role:'user',content:'fixture'}],tools:[{type:'function',function:{name:'Read'}}]});
const init={method:'POST',body,signal,headers:{Authorization:'Bearer synthetic-code-key','x-api-key':'synthetic-other-key',cookie:'synthetic-cookie'}};
expect(await (await loader.fetch(I.BASE+'/chat/completions',init)).text()).toBe(sse);
expect(calls[0].url).toBe(I.BASE+'/chat/completions');
expect(calls[0].init.headers.get('authorization')).toBe('Bearer '+session.workToken);
expect(calls[0].init.headers.get('x-api-key')).toBeNull();expect(calls[0].init.headers.get('cookie')).toBeNull();
expect(calls[0].init.headers.get('user-agent')).toBe(I.UA);
expect(calls[0].init.body).toBe(body);expect(calls[0].init.signal).toBe(signal);expect(calls[0].init.redirect).toBe('error');
live={...live,workToken:'synthetic-rotated-work-token'};await loader.fetch(I.BASE+'/chat/completions',init);
expect(calls[1].init.headers.get('authorization')).toBe('Bearer synthetic-rotated-work-token');
});
test('refuses foreign URLs and changed desktop accounts before sending credentials',async()=>{
let calls=0,live={...session};const p=I.createPlugin({readSession:()=>live,fetchImpl:async()=>{calls++;return json({});}});
const loader=await p.auth.loader(async()=>account);
await expect(loader.fetch('https://example.invalid/chat/completions',{method:'POST'})).rejects.toThrow();
live={...session,uid:'different-fixture-account'};
await expect(loader.fetch(I.BASE+'/chat/completions',{method:'POST'})).rejects.toMatchObject({signIn:'expired'});
expect(calls).toBe(0);
});
test('models come from Work; usage reports only the shared membership allowance',async()=>{
const calls=[];const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{
calls.push({url,init});return url.endsWith('/models')?json(modelPayload):json({subscriptionBalance:{amountUsedRatio:0.42,expireTime:'2030-01-01T00:00:00Z'},ratelimitCode5h:{ratio:1},ratelimitCode7d:{ratio:1}});
}});
const models=await p.provider.models({models:{}},{auth:account});
expect(Object.keys(models)).toEqual(['k3-agent']);expect(models['k3-agent'].limit.context).toBe(262144);
expect(models['k3-agent'].capabilities.input.image).toBe(true);
const usage=await p.auth.usage(async()=>account);expect(usage.windows).toHaveLength(1);expect(usage.windows[0].used).toBe(42);
expect(usage.windows[0]).not.toHaveProperty('resetsAt');
expect(usage.windows[0].name).toBe('会员共享额度');
expect(calls[1].init.headers.Authorization).toBe('Bearer '+session.webToken);
expect(calls.every(x=>!x.url.includes('api.kimi.com'))).toBe(true);
});
test('an upstream usage refusal does not incorrectly invalidate the desktop sign-in',async()=>{
const p=I.createPlugin({readSession:()=>session,fetchImpl:async()=>new Response('{}',{status:403})});
try{await p.auth.usage(async()=>account);throw Error('expected upstream refusal');}
catch(error){expect(error.signIn).toBeUndefined();expect(error.message).toContain('403');}
});
test('the real redacted catalog and additional advertised reasoning levels are preserved',()=>{
const payload=JSON.parse(fs.readFileSync(new URL('./fixtures/work-models.redacted.json',import.meta.url),'utf8'));
const rows=I.modelRows(payload);
for(const m of payload.data) {
expect(Object.keys(rows[m.id].variants)).toEqual(m.reasoningEffortOptions.map(x=>x.effort.replace('REASONING_EFFORT_','').toLowerCase()));
}
const additional={...payload.data[0],reasoningEffortOptions:[
{effort:'REASONING_EFFORT_STANDARD'},{effort:'REASONING_EFFORT_ULTRA'},
]};
expect(I.modelRows({data:[additional]})[additional.id].variants).toEqual({
standard:{reasoningEffort:'standard'},ultra:{reasoningEffort:'ultra'},
});
});
test('Request inputs preserve body, safe headers and cancellation while replacing desktop credentials',async()=>{
const calls=[];
const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{
calls.push({url,init,body:await new Response(init.body).text()});return json({choices:[]});
}});
const loader=await p.auth.loader(async()=>account),abort=new AbortController();
const body=JSON.stringify({model:'k3-agent',messages:[{role:'user',content:'synthetic Request'}],stream:true});
const request=new Request(I.BASE+'/chat/completions',{method:'POST',body,signal:abort.signal,
headers:{Authorization:'Bearer synthetic-wrong-key',Cookie:'synthetic-cookie','X-Request-Tag':'synthetic-tag'}});
await loader.fetch(request);
expect(calls[0].url).toBe(I.BASE+'/chat/completions');
expect(calls[0].body).toBe(body);
expect(calls[0].init.headers.get('authorization')).toBe('Bearer '+session.workToken);
expect(calls[0].init.headers.get('cookie')).toBeNull();
expect(calls[0].init.headers.get('x-request-tag')).toBe('synthetic-tag');
abort.abort();expect(calls[0].init.signal.aborted).toBe(true);
await expect(loader.fetch(new Request('https://example.invalid/chat/completions',{method:'POST',body:'{}'}))).rejects.toThrow();
await expect(loader.fetch(new Request(I.BASE+'/chat/completions',{method:'GET'}))).rejects.toThrow();
expect(calls).toHaveLength(1);
});
test('one model with effort levels in an unseen shape does not cost the account its catalog',()=>{
const payload=JSON.parse(fs.readFileSync(new URL('./fixtures/work-models.redacted.json',import.meta.url),'utf8'));
const odd=[
{...payload.data[0],id:'synthetic-no-effort',reasoningEffortOptions:[{displayName:'Max'},null,{effort:'REASONING_EFFORT_MAX'}]},
{...payload.data[0],id:'synthetic-object-efforts',reasoningEffortOptions:{low:true}},
null,'k3-agent',
];
const rows=I.modelRows({data:[...payload.data,...odd]});
expect(Object.keys(rows)).toEqual(['k3-agent','k2d8-preview','synthetic-no-effort','synthetic-object-efforts']);
expect(rows['synthetic-no-effort'].variants).toEqual({max:{reasoningEffort:'max'}});
expect(rows['synthetic-object-efforts'].variants).toEqual({});
expect(Object.keys(rows['k2d8-preview'].variants)).toEqual(['low','high','max']);
});
test('before the account list is read, both models Work has listed are offered',async()=>{
const p=I.createPlugin({readSession:()=>session,fetchImpl:async()=>{throw Error('no network in tests');}});
const cfg={};await p.config(cfg);
expect(Object.keys(cfg.provider['kimi-work'].models)).toEqual(['k3-agent','k2d8-preview']);
const payload=JSON.parse(fs.readFileSync(new URL('./fixtures/work-models.redacted.json',import.meta.url),'utf8'));
expect(Object.keys(cfg.provider['kimi-work'].models)).toEqual(payload.data.map(m=>m.id));
});