From 00642d4c6b47bd99eda09909a9a3314a8337265a Mon Sep 17 00:00:00 2001 From: yishu <153627025+yishu-ziyu@users.noreply.github.com> Date: Thu, 5 Nov 2026 01:42:35 +0800 Subject: [PATCH] kimi-work 0.1.17: Work's fast output speed, as K3.1 Pro Fast and a Fast switch (#728) Kimi Work's "High" output speed is a speedOption of a model in the signed-in Work menu. A model whose option has `speedValue: "fast"` and `available: true` gets a `-fast` row ("K3.1 Pro Fast") and magpie's Fast switch (`service_tier: priority`). A request on either goes out with `X-Kimi-Model-Speed: fast`, the header Kimi's own desktop client sends. The menu is now read with the membership sign-in magpie renews, and the unsigned menu never offers fast. A `-fast` suffix comes off only ids the plugin listed itself. Header checked against the vendor's client. Kimi 3.2.24 macOS was downloaded from kimi.com's own download link, a Developer ID build from Beijing Moonshot Technology (2J9472RW75); dmg sha256 e40df5954aacdfe69f5e56f9d679ef86a7d25f9134769ffe1b7ea382c77ca8fd. In its app.asar: - `out/renderer/assets/common-DLYgMFK1.js` builds request headers with `x&&(a[uy]=x),t&&(a[fy]=t)`, where `uy="X-Kimi-Context-Length"` and `fy=c(2634)`. - Decoded with a decoder of our own (the string table is read as data and rotated to the bundle's checksum; no vendor function was run): `c(2634)="X-Kimi-Model-Speed"`. - The value comes from `DM`: the chosen speedOption's `speedValue` (`c(1967)`), from options the account can select (`"select"`). - `kimi-agent-Dw2t9ioO.js` passes it as `modelSpeedHeaderValue` into `llmRequestHeaders`, and the daimon bundle carries `llmRequestHeaders` into the turn. - No wire capture: not taken by the author or by the review. Run at 69adea99 on a macOS box: - `bun test packages/kimi-work`: 103 pass, 0 fail. - `bun scripts/check.mjs kimi-work`: ok. Broken by hand, each red: - header value "fast" changed to "high": 1 fail; - `available===true` dropped: 4 fail; - header name changed: 1 fail. The six breaks from the earlier round, at 45dd499 (code unchanged since, comments only), were each red too. Not tried: a real request from this review's side (no Kimi Work account here), a lower-tier account's menu, and what a fast request costs. --- packages/kimi-work/README.md | 2 + packages/kimi-work/index.mjs | 86 ++++++++++++++++++++-- packages/kimi-work/package.json | 2 +- packages/kimi-work/tests/provider.test.mjs | 78 +++++++++++++++++++- 4 files changed, 156 insertions(+), 12 deletions(-) diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index 914cd78..8bc9544 100644 --- a/packages/kimi-work/README.md +++ b/packages/kimi-work/README.md @@ -23,6 +23,8 @@ An inference HTTP 401 marks the provider sign-in as expired (`kimi_work_login_ex Models use standard context, capped at 262,144 tokens, rather than silently enabling the higher-priced XL context. The reply limit is the menu's `maxTokens` (32,768 for every model it lists today). Until the signed-in account's live catalog is read, and when it can't be, the models offered are `kimi-work/k3-agent` and `kimi-work/k2d8-preview`, the two ids Work's `/models` has listed; the live catalog replaces them, so a model Kimi adds to the account (such as K3.1 Pro) shows under the id the menu gives it. Since 0.1.6 a model whose reasoning levels come in a shape not seen before keeps the levels that can be read, rather than the whole catalog failing over to the fallback. +Since 0.1.17 a model whose entry in the signed-in account's menu has the `fast` speed `available` (K3.1 Pro today, on Allegretto/Pro and above, at 2x or more of the allowance by Kimi's own words) is served at `priority`, so Magpie offers its Fast switch and takes it as a routing group's `:fast` member. The same speed is listed as a model of its own, `-fast` (K3.1 Pro Fast), to tick on the provider and pick by name. The menu asked without a sign-in doesn't say `available`, so neither shows until an account's own menu is read. A request for that row, or with `service_tier` `priority` or `fast` on that model, goes to Kimi as `` with `X-Kimi-Model-Speed: fast`, as the desktop's High speed does, without that suffix or field; any other request is unchanged. + Usage comes from Kimi's membership `GetSubscriptionStats` endpoint. The card's **月度共享额度** heading and single **本月** meter report `subscriptionBalance.amountUsedRatio`, the fraction used of the shared monthly membership pool. If returned, `subscriptionBalance.kimiCodeUsedRatio` appears only as **Code 已用 …%(占总额)** in the meter's text and tooltip: Code's share of the entire monthly pool, not another allowance or the fraction of the used portion. It is never another window/ring, because Magpie renders even informational `aside` windows as separate remaining allowances. Code's share does not constrain Work routing. Missing monthly data stays unknown; Code's five-hour/weekly limits are never substituted. No reset time is reported: `subscriptionBalance.expireTime` and `upcomingExpiration.timestamp` are expiration fields, and have not been verified to describe allowance resets. Magpie's compact card currently labels a window with no reset time as "Not used yet" even when usage is nonzero; that host wording does not mean the monthly pool is unused. An observed Windows request was classified by Kimi as `FEATURE_WORK` while the Code five-hour and weekly ratios stayed unchanged. Kimi controls billing, shared allowances, access and rate limits. Every reasoning-effort value returned by `/models` is retained, including `STANDARD` if listed. The checked Windows catalog in `tests/fixtures/work-models.redacted.json` lists `LOW` (displayed by Kimi as **Standard**), `HIGH` and `MAX`; the plugin sends the advertised effort value instead of guessing from the display label. diff --git a/packages/kimi-work/index.mjs b/packages/kimi-work/index.mjs index ad6bc80..eda93ad 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -28,6 +28,16 @@ const UA = 'kimi-code-cli/' + KIMI_CODE_VERSION; // the desktop asks with its own (k3d1-agent, K3.1 Pro, first), so through // 0.1.8 K3.1 Pro was never listed (tests/fixtures/work-config.*.json). const DESKTOP_VERSION = '3.2.20'; +// Work's "High" output speed is no model of its own: the menu lists it among +// a model's speedOptions, and the desktop asks for it with this header (Kimi +// 3.2.24, out/renderer/assets/common-DLYgMFK1.js, modelSpeedHeaderValue). +const SPEED_HEADER = 'X-Kimi-Model-Speed'; +// How a model says it has that speed: magpie offers its Fast switch on a model +// served at priority, and sends such a request with that service_tier. +const FAST_ROW = {serviceTiers:['priority']}; +// The same speed as a model to tick and pick by itself: k3d1-agent-fast, which +// Kimi hears as k3d1-agent with the header. +const FAST_SUFFIX = '-fast'; function webHeaders(platform=process.platform) { return {'User-Agent':UA,'x-msh-platform':platform==='darwin'?'mac':platform==='win32'?'windows':'web', 'x-msh-version':DESKTOP_VERSION,'R-Timezone':Intl.DateTimeFormat().resolvedOptions().timeZone||'UTC'}; @@ -249,6 +259,38 @@ function moonshotTools(body) { return changed?JSON.stringify(doc):body; } +// The ids an account can ask for fast, each with the id Kimi knows it by: the +// models it has that speed on, and the rows the plugin listed for them. +function fastIds(rows) { + const out=new Map(); + for(const [id,row] of Object.entries(rows)) { + if(row.serviceTiers?.includes('priority'))out.set(id,id); + if(row.fastOf)out.set(id,row.fastOf); + } + return out; +} + +const asksFast=body=>typeof body==='string'&&(body.includes('"service_tier"')||body.includes(FAST_SUFFIX+'"')); + +// A model the account has fast on, asked with a service_tier of priority or +// fast (magpie's Fast, an agent's own), or by the row the plugin listed for it, +// is asked of Kimi by header, and the body says neither. Any other request goes +// as is: Kimi takes the header on a model without that speed, and doesn't go +// faster for it. +function fastSpeed(body,offered) { + if(!asksFast(body))return {body,fast:false}; + let doc; + try{doc=JSON.parse(body);}catch{return {body,fast:false};} + const id=isObj(doc)?offered.get(doc.model):undefined; + if(!id)return {body,fast:false}; + const named=id!==doc.model; + const tier=doc.service_tier==='priority'||doc.service_tier==='fast'; + if(!named&&!tier)return {body,fast:false}; + if(tier)delete doc.service_tier; + doc.model=id; + return {body:JSON.stringify(doc),fast:true}; +} + // Schema conversion reads the body before fetch; cancellation must cover that // read too, including a producer that never sends another chunk. async function bodyText(body,signal) { @@ -392,7 +434,7 @@ function workConfigRows(payload) { const list=[...(Array.isArray(pick(payload,'models','models'))?pick(payload,'models','models'):[]), ...(Array.isArray(pick(payload,'moreModels','more_models'))?pick(payload,'moreModels','more_models'):[])]; if(list.length>100)throw Error('Kimi Work 模型目录暂不可用。'); - const out={}; + const out={},fast=[]; for(const m of list) { const rp=pick(m,'requestParams','request_params'),display=pick(m,'display','display'); const dc=pick(m,'daimonModelConfig','daimon_model_config'); @@ -415,6 +457,10 @@ function workConfigRows(payload) { const has=c=>Array.isArray(caps)&&caps.includes(c); const image=has('image_in'),thinking=has('thinking')||Object.keys(variants).length>0; const max=Number(pick(dc,'maxContextSize','max_context_size'))||262144; + const speeds=pick(m,'speedOptions','speed_options'); + // Only the signed-in menu says available: asked without a sign-in it leaves + // that out, for accounts with the plan and without it alike. + if(Array.isArray(speeds)&&speeds.some(x=>pick(x,'speedValue','speed_value')==='fast'&&x.available===true))fast.push(id); const output=Number(pick(rp,'maxTokens','max_tokens'))||32768; out[id]={id,name:String(pick(display,'displayName','display_name')||'').trim()||id, api:{id,url:BASE,npm:'@ai-sdk/openai-compatible'}, @@ -425,6 +471,13 @@ function workConfigRows(payload) { input:{text:true,image,video:false,audio:false,pdf:false},output:{text:true}}, variants}; } + // After the loop: a model Kimi itself calls -fast keeps its own row. + for(const id of fast) { + const row=out[id],fastId=id+FAST_SUFFIX; + // fastOf is for fastIds alone: magpie's host reads only the fields it knows. + if(!out[fastId])out[fastId]={...row,id:fastId,name:row.name+' Fast',api:{...row.api,id:fastId},fastOf:id}; + Object.assign(row,FAST_ROW); + } return out; } @@ -523,11 +576,15 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo // Through 0.1.9 a failed ask was dropped without a word, so the list was // /models' alone (k3-agent, k2d8-preview) and K3.1 Pro was missing with // nothing in the log. Each failure is logged now, without the token. - async function menu(s) { + async function menu(s,auth) { let why='no web sign-in'; - if(s.webToken) { + // The membership sign-in magpie renews, where the account has one; the + // desktop's own can be long expired. The fallback below, with no sign-in, + // never says available, so it never offers fast. + const token=hasPair(auth)?auth.access:s.webToken; + if(token) { try { - const rows=workConfigRows(await jsonRequest(CONFIG,s.webToken,{})); + const rows=workConfigRows(await jsonRequest(CONFIG,token,{})); if(Object.keys(rows).length)return rows; why='a reply with no models'; } catch(error) {why=error?.status?'HTTP '+error.status:(error?.name==='TimeoutError'?'timed out':error?.cause?.code||error?.message||String(error));} @@ -539,6 +596,15 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo throw error; } } + // What each account's menu offers fast on. Read again with the models, and + // here for a fast request that comes before them, as after a restart. + const offered=new Map(); + async function fastOffered(s,auth) { + if(offered.has(s.uid))return offered.get(s.uid); + const ids=fastIds(await menu(s,auth).catch(()=>({}))); + offered.set(s.uid,ids); + return ids; + } return { config:async cfg=>{ cfg.provider??={}; @@ -594,7 +660,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo ||url.username||url.password||url.search||url.hash||(request?.method||init.method||'POST')!=='POST') { throw Error('Kimi Work 仅接受官方 Work 网关的模型请求。'); } - const s=current(await getAuth()); + const auth=await getAuth(),s=current(auth); const headers=new Headers(request?request.headers:init.headers); for(const key of ['authorization','x-api-key','cookie','host','content-length','origin'])headers.delete(key); // magpie's own x-magpie-* hints are for the plugin, not for Kimi. @@ -611,6 +677,9 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo if(raw!=null&&typeof raw!=='string')body=await bodyText(raw,signal); signal?.throwIfAborted(); if(body!=null)body=moonshotTools(body); + const speed=fastSpeed(body,asksFast(body)?await fastOffered(s,auth):new Map()); + body=speed.body; + if(speed.fast)headers.set(SPEED_HEADER,'fast'); const options={...init,body,signal}; if(body==null)delete options.body; let response; @@ -672,18 +741,19 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo // Both lists, the desktop's menu first. Either one failing leaves the // other; both failing throws, so the last good list is kept. const [cfgList,gw]=await Promise.allSettled([ - menu(s), + menu(s,auth), jsonRequest(BASE+'/models',s.workToken,undefined,undefined,s.deviceId).then(modelRows)]); const a=cfgList.status==='fulfilled'?cfgList.value:{},b=gw.status==='fulfilled'?gw.value:{}; + if(cfgList.status==='fulfilled')offered.set(s.uid,fastIds(a)); if(gw.status==='rejected'&&!Object.keys(a).length)throw gw.reason; const out={...a}; // An id both list keeps /models' row (the gateway's own context and // image flags) under the desktop's name for it. - for(const [id,row] of Object.entries(b))out[id]=out[id]?{...row,name:out[id].name}:row; + for(const [id,row] of Object.entries(b))out[id]=out[id]?{...row,name:out[id].name,...(out[id].serviceTiers?FAST_ROW:{})}:row; return out; }}, }; } export default async function KimiWorkProvider(){return createPlugin();} -export const _internal={createPlugin,spentQuota,moonshotTools,moonshotSchema,readDesktop,readKeys,desktopFile,shareDir,userDataDir,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA,workHeaders,webHeaders,refreshHeaders,readDeviceId,REFRESH,REFRESH_LEAD,expiry}; +export const _internal={createPlugin,fastSpeed,fastIds,spentQuota,moonshotTools,moonshotSchema,readDesktop,readKeys,desktopFile,shareDir,userDataDir,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA,workHeaders,webHeaders,refreshHeaders,readDeviceId,REFRESH,REFRESH_LEAD,expiry}; diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index 8f33624..fe1ab33 100644 --- a/packages/kimi-work/package.json +++ b/packages/kimi-work/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kimi-work-auth", - "version": "0.1.16", + "version": "0.1.17", "type": "module", "main": "./opencode.mjs", "files": [ diff --git a/packages/kimi-work/tests/provider.test.mjs b/packages/kimi-work/tests/provider.test.mjs index 4676403..b21dd56 100644 --- a/packages/kimi-work/tests/provider.test.mjs +++ b/packages/kimi-work/tests/provider.test.mjs @@ -175,7 +175,7 @@ test('the desktop menu\'s models are listed: a tier model /models leaves out sho const calls=[];const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{ calls.push({url,init});return url===I.CONFIG?json(workConfig):json(modelPayload);}}); const models=await p.provider.models({models:{}},{auth:account}); - expect(Object.keys(models)).toEqual(['k3-agent','k3d1-pro','k2d8-preview']); + expect(Object.keys(models)).toEqual(['k3-agent','k3d1-pro','k2d8-preview','k3d1-pro-fast']); expect(models['k3d1-pro']).toMatchObject({id:'k3d1-pro',name:'Kimi K3.1 Pro',api:{id:'k3d1-pro',url:I.BASE},limit:{context:262144}}); expect(models['k3d1-pro'].capabilities).toMatchObject({reasoning:true,attachment:true}); // supportEfforts' "off" is the desktop's REASONING_EFFORT_NONE. @@ -190,14 +190,14 @@ test('the desktop menu\'s models are listed: a tier model /models leaves out sho }); test('the menu is read in the proto\'s own field names too',()=>{ - expect(Object.keys(I.workConfigRows(snake(workConfig)))).toEqual(['k3-agent','k3d1-pro','k2d8-preview']); + expect(Object.keys(I.workConfigRows(snake(workConfig)))).toEqual(['k3-agent','k3d1-pro','k2d8-preview','k3d1-pro-fast']); expect(I.workConfigRows(snake(workConfig))['k3d1-pro'].name).toBe('Kimi K3.1 Pro'); }); test('either list failing leaves the other; both failing throws so the last good list stays',async()=>{ const run=f=>I.createPlugin({readSession:()=>session,fetchImpl:f}).provider.models({models:{}},{auth:account}); expect(Object.keys(await run(async url=>url===I.CONFIG?new Response('{}',{status:500}):json(modelPayload)))).toEqual(['k3-agent']); - expect(Object.keys(await run(async url=>url===I.CONFIG?json(workConfig):new Response('{}',{status:502})))).toEqual(['k3-agent','k3d1-pro','k2d8-preview']); + expect(Object.keys(await run(async url=>url===I.CONFIG?json(workConfig):new Response('{}',{status:502})))).toEqual(['k3-agent','k3d1-pro','k2d8-preview','k3d1-pro-fast']); await expect(run(async()=>new Response('{}',{status:502}))).rejects.toThrow(); await expect(run(async url=>url===I.CONFIG?json({models:[]}):new Response('{}',{status:502}))).rejects.toThrow(); }); @@ -265,3 +265,75 @@ test('a menu the web sign-in can\'t get is asked again without it, so K3.1 Pro i expect(seen.length).toBe(1);expect(logged).toEqual([]); } finally {console.warn=warn;} }); + +const speedMenu={models:[ + {requestParams:{modelId:'k3d1-agent'},speedOptions:[{speedValue:'standard',available:true},{speedValue:'fast',available:true,minMembershipLevel:'LEVEL_INTERMEDIATE'}]}, + {requestParams:{modelId:'k3-agent'}}, + {requestParams:{modelId:'k2d8-preview'},speedOptions:[{speedValue:'standard',available:true},{speedValue:'fast',available:false}]}, + {requestParams:{modelId:'k9-agent'},speedOptions:[{speedValue:'fast',minMembershipLevel:'LEVEL_INTERMEDIATE'}]}, + {requestParams:{modelId:'k8-agent'},speedOptions:[{speedValue:'fast',available:true}]}, + {requestParams:{modelId:'k8-agent-fast'}}, + {requestParams:{modelId:'k7-agent-fast'},speedOptions:[{speedValue:'fast',available:true}]}, +]}; + +test('only a fast speed the menu says is available is offered, as a tier and a row of its own',async()=>{ + const rows=I.workConfigRows(speedMenu); + expect(rows['k3d1-agent'].serviceTiers).toEqual(['priority']); + expect(rows['k3d1-agent'].fast).toBeUndefined(); + expect(rows['k3d1-agent-fast']).toMatchObject({id:'k3d1-agent-fast',name:'k3d1-agent Fast',api:{id:'k3d1-agent-fast'},fastOf:'k3d1-agent'}); + expect(rows['k3d1-agent-fast'].serviceTiers).toBeUndefined(); + // None said, as the menu without a sign-in; said no; no fast at all. + for(const id of ['k9-agent','k2d8-preview','k3-agent']) { + expect(rows[id].serviceTiers).toBeUndefined(); + expect(rows[id+'-fast']).toBeUndefined(); + } + // A model Kimi itself calls -fast keeps its row. + expect(rows['k8-agent-fast'].fastOf).toBeUndefined(); + expect(Object.fromEntries(I.fastIds(rows))).toEqual({'k3d1-agent':'k3d1-agent','k3d1-agent-fast':'k3d1-agent','k8-agent':'k8-agent', + 'k7-agent-fast':'k7-agent-fast','k7-agent-fast-fast':'k7-agent-fast'}); + const p=I.createPlugin({readSession:()=>session,fetchImpl:async url=>String(url).includes('DescribeKimiWorkConfig')?json(speedMenu) + :json({data:[{id:'k3d1-agent',display_name:'K3.1',context_length:262144}]})}); + const models=await p.provider.models({},{auth:account}); + expect(models['k3d1-agent'].serviceTiers).toEqual(['priority']); +}); + +test('the menu is asked with the sign-in magpie renews, not the desktop\'s own',async()=>{ + const seen=[]; + const p=I.createPlugin({readSession:()=>({...session,webToken:'expired-desktop-token'}),fetchImpl:async(url,init)=>{ + if(String(url).includes('DescribeKimiWorkConfig')){seen.push(init.headers.Authorization);return json(speedMenu);} + return json(modelPayload);}}); + await p.provider.models({},{auth:account}); + expect(seen).toEqual(['Bearer '+account.access]); +}); + +test('the header goes only with a model the account has fast on; any other request is unchanged',async()=>{ + const calls=[];let menus=0; + const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{ + if(String(url).includes('DescribeKimiWorkConfig')){menus++;return json(speedMenu);} + calls.push(init);return json({});}}); + const loader=await p.auth.loader(async()=>account); + const send=async body=>{await loader.fetch(I.BASE+'/chat/completions',{method:'POST',body});const c=calls.at(-1);return {body:c.body,speed:c.headers.get('X-Kimi-Model-Speed')};}; + // No model list read yet, as after a restart: the menu is read for it, once. + for(const tier of ['priority','fast']) + expect(await send(JSON.stringify({model:'k3d1-agent',service_tier:tier}))).toEqual({body:'{"model":"k3d1-agent"}',speed:'fast'}); + expect(await send('{"model":"k3d1-agent-fast"}')).toEqual({body:'{"model":"k3d1-agent"}',speed:'fast'}); + expect(menus).toBe(1); + // A model of Kimi's own that ends in -fast keeps its name. + expect(await send('{"model":"k7-agent-fast","service_tier":"priority"}')).toEqual({body:'{"model":"k7-agent-fast"}',speed:'fast'}); + for(const body of ['{"model":"k3d1-agent","service_tier":"default"}','{"model":"k3d1-agent"}','{"note":"service_tier"}', + '{"model":"k3-agent","service_tier":"priority"}','{"model":"k9-agent","service_tier":"priority"}','{"model":"k2d8-preview-fast"}', + '{"model":"k8-agent-fast"}','{"model":"k7-agent-fast"}','{"model":"someone-elses-fast"}']) + expect(await send(body)).toEqual({body,speed:null}); +}); + +test('a menu that can\'t be read leaves fast off and the request as it is',async()=>{ + const calls=[]; + const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{ + if(String(url).includes('DescribeKimiWorkConfig'))return new Response('{}',{status:500}); + calls.push(init);return json({});}}); + const loader=await p.auth.loader(async()=>account); + const body='{"model":"k3d1-agent","service_tier":"priority"}'; + await loader.fetch(I.BASE+'/chat/completions',{method:'POST',body}); + expect(calls[0].body).toBe(body); + expect(calls[0].headers.get('X-Kimi-Model-Speed')).toBeNull(); +});