diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index 60d8463..b439ff1 100644 --- a/packages/kimi-work/README.md +++ b/packages/kimi-work/README.md @@ -11,13 +11,13 @@ Open Kimi desktop and sign in to Work on the same computer first. Choose **使 ## Models and requests -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. +The account's models and reasoning options come from the two lists Kimi's desktop reads: Work's model menu, `kimi.gateway.config.v1.ConfigService/DescribeKimiWorkConfig` on `www.kimi.com` (asked with the desktop's web sign-in), and `https://agent-gw.kimi.com/coding/v1/models`. The menu lists the models a membership tier adds (K3.1 Pro on the 99 plan) that `/models` leaves out; since 0.1.7 both are listed, the menu's names first, and either one failing leaves the other. 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. 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. -Models use standard context, capped at 262,144 tokens, rather than silently enabling the higher-priced XL context. 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 its own id. 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. +Models use standard context, capped at 262,144 tokens, rather than silently enabling the higher-priced XL context. 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. Usage comes from Kimi's membership `GetSubscriptionStats` endpoint and is labelled **shared membership allowance**, not a separate free Work allowance. No reset time is reported: `subscriptionBalance.expireTime` and `upcomingExpiration.timestamp` are expiration fields, and have not been verified to describe allowance resets. An observed Windows request was classified by Kimi as `FEATURE_WORK` while the Code five-hour and weekly ratios stayed unchanged. This is an observation, not a promise about future quota accounting: Kimi controls billing, shared allowances, access and rate limits. diff --git a/packages/kimi-work/index.mjs b/packages/kimi-work/index.mjs index 71803a5..223dc94 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -6,6 +6,11 @@ import {createHash} from 'node:crypto'; const ID = 'kimi-work'; const BASE = 'https://agent-gw.kimi.com/coding/v1'; const MEMBER = 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/'; +// Kimi's desktop builds its Work model menu from this call, not from +// agent-gw's /models: models plus moreModels, each with the id Work's +// gateway takes (requestParams.modelId). An account's tier models, K3.1 Pro +// on the 99 plan among them, are listed here and not in /models. +const CONFIG = 'https://www.kimi.com/apiv2/kimi.gateway.config.v1.ConfigService/DescribeKimiWorkConfig'; const {version} = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')); const UA = 'Magpie Kimi Work provider/' + version; const expired = () => Object.assign(Error('请先在本机 Kimi 桌面版登录 Work,再重新连接 Kimi Work 供应商。'), {signIn:'expired',code:'kimi_work_login_expired'}); @@ -223,6 +228,49 @@ function modelRows(payload) { return out; } +// DescribeKimiWorkConfig's reply, Connect JSON (camelCase, or the proto's +// own snake_case names, which the desktop asks for). +const pick=(o,a,b)=>isObj(o)?(o[a]??o[b]):undefined; +const EFFORTS=new Set(['off','low','medium','high','xhigh','max']); +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={}; + 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'); + const id=String(pick(rp,'modelId','model_id')??'').trim(); + if(!id||id.length>256||/[\x00-\x20/]/.test(id)||out[id])continue; + const variants=Object.create(null); + // The levels requestParams lists, else the daimon's supportEfforts, as + // the desktop does; "off" is REASONING_EFFORT_NONE there. + const opts=pick(rp,'reasoningEffortOptions','reasoning_effort_options'); + for(const x of Array.isArray(opts)?opts:[]) { + const effort=String(pick(x,'reasoningEffort','reasoning_effort')||pick(x,'effort','effort')||'').trim().replace(/^REASONING_EFFORT_/,'').toLowerCase(); + if(/^[a-z][a-z0-9_-]{0,63}$/.test(effort)&&effort!=='unspecified')variants[effort]={reasoningEffort:effort}; + } + const support=pick(dc,'supportEfforts','support_efforts'); + if(!Object.keys(variants).length)for(const x of Array.isArray(support)?support:[]) { + const effort=String(x).trim().toLowerCase(); + if(EFFORTS.has(effort))variants[effort==='off'?'none':effort]={reasoningEffort:effort==='off'?'none':effort}; + } + const caps=pick(dc,'capabilities','capabilities'); + 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; + out[id]={id,name:String(pick(display,'displayName','display_name')||'').trim()||id, + api:{id,url:BASE,npm:'@ai-sdk/openai-compatible'}, + // Standard context, as /models' rows: XL is a header the desktop + // sends only when the user picks it. + limit:{context:Math.min(max,262144),output:32768}, + capabilities:{reasoning:thinking,toolcall:true,attachment:image, + input:{text:true,image,video:false,audio:false,pdf:false},output:{text:true}}, + variants}; + } + return out; +} + function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch}={}) { const current=auth=>{ const session=readSession(); @@ -309,10 +357,22 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch}={}) { }, provider:{id:ID,models:async(provider,{auth}={})=>{ if(auth?.source!=='kimi-work-desktop')return provider.models; - const s=current(auth);return modelRows(await jsonRequest(BASE+'/models',s.workToken)); + const s=current(auth); + // 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([ + s.webToken?jsonRequest(CONFIG,s.webToken,{}).then(workConfigRows):Promise.reject(Error('no web token')), + jsonRequest(BASE+'/models',s.workToken).then(modelRows)]); + const a=cfgList.status==='fulfilled'?cfgList.value:{},b=gw.status==='fulfilled'?gw.value:{}; + 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; + return out; }}, }; } export default async function KimiWorkProvider(){return createPlugin();} -export const _internal={createPlugin,moonshotTools,moonshotSchema,readDesktop,desktopFile,modelRows,BASE,MEMBER,UA}; +export const _internal={createPlugin,moonshotTools,moonshotSchema,readDesktop,desktopFile,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA}; diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index eedeec6..7de6252 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.6", + "version": "0.1.7", "type": "module", "main": "./index.mjs", "files": [ diff --git a/packages/kimi-work/tests/fixtures/work-config.shape.json b/packages/kimi-work/tests/fixtures/work-config.shape.json new file mode 100644 index 0000000..df9317d --- /dev/null +++ b/packages/kimi-work/tests/fixtures/work-config.shape.json @@ -0,0 +1,40 @@ +{ + "_source": "Shape of kimi.gateway.config.v1.ConfigService/DescribeKimiWorkConfig's reply, from the proto descriptor and the mapping in Kimi desktop 3.2.20's main bundle (field names, nesting, enums as the desktop reads them). No reply was captured from an account: k3-agent and k2d8-preview are ids Work's /models lists; k3d1-pro is a placeholder for the tier model a 99-plan account's menu shows as Kimi K3.1 Pro.", + "models": [ + { + "key": "k3-agent", + "requestParams": {"modelId": "k3-agent", "scenario": "SCENARIO_K2D5", "agentMode": "TYPE_UNSPECIFIED", + "defaultReasoningEffort": "REASONING_EFFORT_HIGH", + "reasoningEffortOptions": [ + {"effort": "REASONING_EFFORT_LOW", "reasoningEffort": "low", "displayName": "Standard", "description": ""}, + {"effort": "REASONING_EFFORT_HIGH", "reasoningEffort": "high", "displayName": "High", "description": ""}, + {"effort": "REASONING_EFFORT_MAX", "reasoningEffort": "max", "displayName": "Max", "description": ""}], + "contextLengthOptions": [], "defaultContextLength": "CONTEXT_LENGTH_UNSPECIFIED"}, + "display": {"displayName": "K3", "description": "", "inputPlaceholder": "", "label": []}, + "switchableTo": [], "capabilities": [], + "daimonModelConfig": {"maxContextSize": 262144, "capabilities": ["thinking", "image_in"], "supportEfforts": ["low", "high", "max"], "defaultEffort": "high", "protocol": "", "betaApi": false, "reasoningKey": ""}, + "legacyIds": [], "moonPhase": "MOON_PHASE_UNSPECIFIED", "speedOptions": [], "defaultSpeedValue": "" + }, + { + "key": "k3d1-pro", + "requestParams": {"modelId": "k3d1-pro", "reasoningEffortOptions": [], + "contextLengthOptions": [{"contextLength": "CONTEXT_LENGTH_L"}, {"contextLength": "CONTEXT_LENGTH_XL"}], "defaultContextLength": "CONTEXT_LENGTH_L"}, + "display": {"displayName": "Kimi K3.1 Pro", "description": "", "inputPlaceholder": "", "label": ["99"]}, + "switchableTo": [], "capabilities": [], + "daimonModelConfig": {"maxContextSize": 1000000, "capabilities": ["thinking", "image_in"], "supportEfforts": ["off", "high", "max"], "defaultEffort": "high", "protocol": "", "betaApi": false, "reasoningKey": ""}, + "legacyIds": [], "speedOptions": [{"speedValue": "fast", "displayName": "Fast", "available": true}], "defaultSpeedValue": "fast" + } + ], + "defaultModelKey": "k3-agent", + "cacheTtlSeconds": "3600", + "moreModels": [ + { + "key": "k2d8-preview", + "requestParams": {"modelId": "k2d8-preview"}, + "display": {"displayName": "K2.8 Preview", "label": []}, + "daimonModelConfig": {"maxContextSize": 262144, "capabilities": [], "supportEfforts": [], "defaultEffort": ""}, + "switchableTo": [], "legacyIds": [], "speedOptions": [], "defaultSpeedValue": "" + } + ], + "debugPanelEnabled": false +} diff --git a/packages/kimi-work/tests/provider.test.mjs b/packages/kimi-work/tests/provider.test.mjs index 949d4cf..05cf81c 100644 --- a/packages/kimi-work/tests/provider.test.mjs +++ b/packages/kimi-work/tests/provider.test.mjs @@ -68,7 +68,7 @@ test('models come from Work; usage reports only the shared membership allowance' 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.find(x=>x.url.endsWith('GetSubscriptionStats')).init.headers.Authorization).toBe('Bearer '+session.webToken); expect(calls.every(x=>!x.url.includes('api.kimi.com'))).toBe(true); }); @@ -134,3 +134,37 @@ test('before the account list is read, both models Work has listed are offered', 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)); }); + +const workConfig=JSON.parse(fs.readFileSync(new URL('./fixtures/work-config.shape.json',import.meta.url),'utf8')); +const snake=x=>Array.isArray(x)?x.map(snake):x&&typeof x==='object'?Object.fromEntries(Object.entries(x).map(([k,v])=>[k.replace(/[A-Z]/g,c=>'_'+c.toLowerCase()),snake(v)])):x; + +test('the desktop menu\'s models are listed: a tier model /models leaves out shows under its own id',async()=>{ + 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(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. + expect(Object.keys(models['k3d1-pro'].variants)).toEqual(['none','high','max']); + expect(models['k2d8-preview'].name).toBe('K2.8 Preview'); + // An id both list keeps /models' row under the menu's name. + expect(models['k3-agent']).toMatchObject({name:'K3',variants:{high:{reasoningEffort:'high'}}}); + const c=calls.find(x=>x.url===I.CONFIG); + expect(c.init).toMatchObject({method:'POST',body:'{}'}); + expect(c.init.headers).toMatchObject({Authorization:'Bearer '+session.webToken,'Connect-Protocol-Version':'1','Content-Type':'application/json'}); + expect(calls.find(x=>x.url===I.BASE+'/models').init.headers.Authorization).toBe('Bearer '+session.workToken); +}); + +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(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']); + 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(); +});