diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index 3e6cb01..004c9c2 100644 --- a/packages/kimi-work/README.md +++ b/packages/kimi-work/README.md @@ -11,7 +11,7 @@ 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 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. Since 0.1.9 the menu is asked with the headers the desktop sends it (`x-msh-platform` `mac` or `windows`, `x-msh-version`, `R-Timezone`): asked without them, Kimi answers with the web menu, which has no K3.1 Pro (`k3d1-agent`). Chat completions, streaming, tool calls and cancellation use the same Work gateway, with the headers Kimi's own Work client sends it (0.1.8). 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. Since 0.1.9 the menu is asked with the headers the desktop sends it (`x-msh-platform` `mac` or `windows`, `x-msh-version`, `R-Timezone`): asked without them, Kimi answers with the web menu, which has no K3.1 Pro (`k3d1-agent`). Since 0.1.10, when the menu can't be had with the web sign-in (Kimi's file holds a web sign-in www.kimi.com no longer takes, answered 401, or another failure or an empty reply), it is asked again without one, as the desktop asks it before signing in, which gives the same desktop menu; each failure is written to Magpie's log, without the token. Chat completions, streaming, tool calls and cancellation use the same Work gateway, with the headers Kimi's own Work client sends it (0.1.8). 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. diff --git a/packages/kimi-work/index.mjs b/packages/kimi-work/index.mjs index ebd0602..3970803 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -320,16 +320,41 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo }; async function jsonRequest(url,token,body,signal,deviceId) { const response=await fetchImpl(url,{method:body===undefined?'GET':'POST', - headers:{Authorization:'Bearer '+token,...(url.startsWith(BASE)?workHeaders(deviceId):webHeaders(platform)),'Accept':'application/json', + headers:{...(token?{Authorization:'Bearer '+token}:{}),...(url.startsWith(BASE)?workHeaders(deviceId):webHeaders(platform)),'Accept':'application/json', ...(body===undefined?{}:{'Content-Type':'application/json','Connect-Protocol-Version':'1'})}, ...(body===undefined?{}:{body:JSON.stringify(body)}),signal:signal||AbortSignal.timeout(15000),redirect:'error'}); - if(response.status===401)throw expired(); - if(!response.ok)throw Error('Kimi Work 服务暂不可用(HTTP '+response.status+')。'); + if(response.status===401)throw Object.assign(expired(),{status:401}); + if(!response.ok)throw Object.assign(Error('Kimi Work 服务暂不可用(HTTP '+response.status+')。'),{status:response.status}); if(Number(response.headers.get('content-length')||0)>2*1024*1024)throw Error('Kimi Work 响应过大。'); const text=await response.text(); if(Buffer.byteLength(text)>2*1024*1024)throw Error('Kimi Work 响应过大。'); try{return JSON.parse(text);}catch{throw Error('Kimi Work 响应格式无效。');} } + // Work's menu, as the desktop asks it with its web sign-in. When that + // ask fails (the web sign-in in Kimi's file has gone stale, which + // www.kimi.com answers 401 "invalid user token"; any other status; a + // reply with no models), the menu is asked again with no sign-in, as the + // desktop asks it before one: www.kimi.com answers that with the same + // desktop menu (tests/fixtures/work-config.mac.json, K3.1 Pro first). + // 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) { + let why='no web sign-in'; + if(s.webToken) { + try { + const rows=workConfigRows(await jsonRequest(CONFIG,s.webToken,{})); + 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));} + } + console.warn('kimi-work: DescribeKimiWorkConfig with the web sign-in failed ('+why+'); asking it without one'); + try {return workConfigRows(await jsonRequest(CONFIG,'',{}));} + catch(error) { + console.warn('kimi-work: DescribeKimiWorkConfig without a sign-in failed ('+(error?.status?'HTTP '+error.status:error?.message||String(error))+'); listing /models alone'); + throw error; + } + } return { config:async cfg=>{ cfg.provider??={}; @@ -404,7 +429,7 @@ 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([ - s.webToken?jsonRequest(CONFIG,s.webToken,{}).then(workConfigRows):Promise.reject(Error('no web token')), + menu(s), 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(gw.status==='rejected'&&!Object.keys(a).length)throw gw.reason; diff --git a/packages/kimi-work/no-magpie.test.mjs b/packages/kimi-work/no-magpie.test.mjs index 7329039..aa194c9 100644 --- a/packages/kimi-work/no-magpie.test.mjs +++ b/packages/kimi-work/no-magpie.test.mjs @@ -17,7 +17,8 @@ function record() { const headers=Object.fromEntries(new Headers(init.headers)); sent.push({url:String(url),headers,body:typeof init.body==='string'?init.body:''}); if(String(url).endsWith('/models'))return Response.json({data:[{id:'k3-agent',context_length:262144}]}); - if(String(url).includes('DescribeKimiWorkConfig'))return Response.json({}); + // a menu with models: an empty one is asked again without the sign-in + if(String(url).includes('DescribeKimiWorkConfig'))return new Response(fs.readFileSync(new URL('./tests/fixtures/work-config.mac.json',import.meta.url)),{headers:{'Content-Type':'application/json'}}); if(String(url).includes('GetSubscriptionStats'))return Response.json({subscriptionBalance:{amountUsedRatio:0.25}}); return new Response('data: [DONE]\n\n',{headers:{'Content-Type':'text/event-stream'}}); }; diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index 4df485e..add1600 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.9", + "version": "0.1.10", "type": "module", "main": "./index.mjs", "files": [ diff --git a/packages/kimi-work/tests/provider.test.mjs b/packages/kimi-work/tests/provider.test.mjs index 77190c5..5f673b0 100644 --- a/packages/kimi-work/tests/provider.test.mjs +++ b/packages/kimi-work/tests/provider.test.mjs @@ -201,3 +201,34 @@ test('the platform is the desktop\'s on macOS and Windows, and agent-gw gets non // The web menu, as a reply without the platform is, has no K3.1 Pro. expect(Object.keys(I.workConfigRows(webMenu))).toEqual(['k3-agent','k3-agent-swarm','k2d8-preview']); }); + +// www.kimi.com's literal answer to a web sign-in it no longer takes (seen +// 2026-10-24 with a token it can't verify): 401, Connect "unauthenticated". +const staleToken={code:'unauthenticated',message:'invalid user token: token signature is invalid: signature is invalid', + details:[{type:'common.error.v1.ErrorDetail',value:'CGQSLgoFZW4tVVMSJVNlc3Npb24gZXhwaXJlZC4gUGxlYXNlIGxvZyBpbiBhZ2Fpbi4',debug:{reason:'REASON_INVALID_AUTH_TOKEN'}}]}; +test('a menu the web sign-in can\'t get is asked again without it, so K3.1 Pro is still listed, and the failure is logged',async()=>{ + const seen=[],logged=[];const warn=console.warn;console.warn=(...x)=>logged.push(x.join(' ')); + try { + for(const reply of [()=>Response.json(staleToken,{status:401}),()=>new Response('',{status:503}),()=>json({models:[]})]) { + seen.length=0;logged.length=0; + // Answers as www.kimi.com does: the sign-in refused, the menu given + // to the desktop without one. + const p=I.createPlugin({platform:'darwin',readSession:()=>session,fetchImpl:async(url,init)=>{ + if(url!==I.CONFIG)return json(modelPayload); + seen.push(init.headers); + return init.headers.Authorization?reply():json(deskMenu);}}); + const models=await p.provider.models({models:{}},{auth:account}); + expect(Object.keys(models)).toEqual(['k3d1-agent','k2d8-preview','k3-agent']); + expect(models['k3d1-agent'].name).toBe('K3.1 Pro'); + expect(seen.map(h=>h.Authorization)).toEqual(['Bearer '+session.webToken,undefined]); + expect(seen[1]).toMatchObject({'x-msh-platform':'mac','x-msh-version':'3.2.20'}); + expect(logged.join('\n')).toContain('DescribeKimiWorkConfig'); + expect(logged.join('\n')).not.toContain(session.webToken); + } + // A sign-in it takes is asked once, and nothing is logged. + seen.length=0;logged.length=0; + await I.createPlugin({platform:'darwin',readSession:()=>session,fetchImpl:async(url,init)=>{ + if(url!==I.CONFIG)return json(modelPayload);seen.push(init.headers);return json(deskMenu);}}).provider.models({models:{}},{auth:account}); + expect(seen.length).toBe(1);expect(logged).toEqual([]); + } finally {console.warn=warn;} +});