diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index b439ff1..3e6cb01 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 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. +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. 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 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. +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. 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 7d68c94..ebd0602 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -18,6 +18,18 @@ const CONFIG = 'https://www.kimi.com/apiv2/kimi.gateway.config.v1.ConfigService/ const KIMI_CODE_VERSION = '0.36.0'; const DAIMON_VERSION = '0.6.10'; const UA = 'kimi-code-cli/' + KIMI_CODE_VERSION; +// What Kimi's desktop sends www.kimi.com/apiv2 besides the sign-in (its +// Connect interceptor: x-msh-platform "mac" or "windows" on the desktop, +// "web" otherwise, x-msh-version the desktop's version, R-Timezone). They +// are not decoration: asked without them DescribeKimiWorkConfig answers +// with the web menu (k3-agent, k3-agent-swarm, k2d8-preview), and asked as +// 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'; +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'}; +} const ascii = (v, fallback = 'unknown') => String(v ?? '').replace(/[^\x20-\x7e]/g, '').trim() || fallback; function deviceModel() { const t = os.type(), r = os.release(), a = os.arch(); @@ -287,11 +299,12 @@ 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 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'}, // 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}, + limit:{context:Math.min(max,262144),output}, capabilities:{reasoning:thinking,toolcall:true,attachment:image, input:{text:true,image,video:false,audio:false,pdf:false},output:{text:true}}, variants}; @@ -299,7 +312,7 @@ function workConfigRows(payload) { return out; } -function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch}={}) { +function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platform=process.platform}={}) { const current=auth=>{ const session=readSession(); if(auth?.source!=='kimi-work-desktop'||auth.uid!==session.uid)throw expired(); @@ -307,7 +320,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch}={}) { }; 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):{'User-Agent':UA}),'Accept':'application/json', + headers:{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(); @@ -405,4 +418,4 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch}={}) { } export default async function KimiWorkProvider(){return createPlugin();} -export const _internal={createPlugin,moonshotTools,moonshotSchema,readDesktop,desktopFile,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA,workHeaders,readDeviceId}; +export const _internal={createPlugin,moonshotTools,moonshotSchema,readDesktop,desktopFile,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA,workHeaders,webHeaders,readDeviceId}; diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index 1dbc419..4df485e 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.8", + "version": "0.1.9", "type": "module", "main": "./index.mjs", "files": [ diff --git a/packages/kimi-work/tests/fixtures/work-config.mac.json b/packages/kimi-work/tests/fixtures/work-config.mac.json new file mode 100644 index 0000000..46a4d1e --- /dev/null +++ b/packages/kimi-work/tests/fixtures/work-config.mac.json @@ -0,0 +1 @@ +{"models":[{"key":"k3d1-agent","requestParams":{"modelId":"k3d1-agent","scenario":"SCENARIO_OK_COMPUTER","kimiPlusId":"ok-computer","agentMode":"TYPE_NORMAL","defaultReasoningEffort":"REASONING_EFFORT_HIGH","reasoningEffortOptions":[{"effort":"REASONING_EFFORT_LOW","displayName":"Standard"},{"effort":"REASONING_EFFORT_HIGH","displayName":"High"},{"effort":"REASONING_EFFORT_MAX","displayName":"Max","description":"Consumes more credits"}],"contextLength":1000000,"maxTokens":32768,"temperature":0.6,"topP":1,"contextLengthOptions":[{"contextLength":"CONTEXT_LENGTH_L","displayName":"Standard","available":true},{"contextLength":"CONTEXT_LENGTH_XL","displayName":"Extra Long","description":"Up to 1M tokens; consumes more credits","label":"Available for Allegro/Max members and above","minMembershipLevel":"LEVEL_ADVANCED"}],"defaultContextLength":"CONTEXT_LENGTH_L"},"display":{"displayName":"K3.1 Pro","description":"Complex tasks and professional work, all-around flagship","inputPlaceholder":"Ask anything, or task an agent..."},"switchableTo":["k2d8-preview","k3-agent"],"daimonModelConfig":{"maxContextSize":1000000,"capabilities":["thinking","image_in","video_in","dynamically_loaded_tools"],"supportEfforts":["low","high","max"],"defaultEffort":"max"},"retryOptions":[{"retryCount":3,"minMembershipLevel":"LEVEL_BASIC"}],"legacyIds":["k3-agent"],"moonPhase":"MOON_PHASE_WAXING_GIBBOUS","swarm":{"enabled":true,"minMembershipLevel":"LEVEL_BASIC"},"speedOptions":[{"speedValue":"standard","displayName":"Standard","available":true},{"speedValue":"fast","displayName":"High","description":"Switching will result in 2x or more usage","label":"Allegretto/Pro plan and above","minMembershipLevel":"LEVEL_INTERMEDIATE"}],"defaultSpeedValue":"standard"},{"key":"k2d8-preview","requestParams":{"modelId":"k2d8-preview","scenario":"SCENARIO_OK_COMPUTER","kimiPlusId":"ok-computer","agentMode":"TYPE_NORMAL","defaultReasoningEffort":"REASONING_EFFORT_HIGH","reasoningEffortOptions":[{"effort":"REASONING_EFFORT_LOW","displayName":"Standard"},{"effort":"REASONING_EFFORT_HIGH","displayName":"High"},{"effort":"REASONING_EFFORT_MAX","displayName":"Max","description":"Consumes more credits"}],"contextLength":1000000,"maxTokens":32768,"temperature":0.6,"topP":1,"contextLengthOptions":[{"contextLength":"CONTEXT_LENGTH_L","displayName":"Standard","available":true},{"contextLength":"CONTEXT_LENGTH_XL","displayName":"Extra Long","description":"Up to 1M tokens; consumes more credits","label":"Available for Allegro/Max members and above","minMembershipLevel":"LEVEL_ADVANCED"}],"defaultContextLength":"CONTEXT_LENGTH_L"},"display":{"displayName":"K2.8 Preview","description":"Well-rounded and efficient for everyday tasks","inputPlaceholder":"Ask anything, or task an agent..."},"switchableTo":["k3d1-agent","k3-agent"],"daimonModelConfig":{"maxContextSize":1000000,"capabilities":["thinking","image_in","video_in","dynamically_loaded_tools"],"supportEfforts":["low","high","max"],"defaultEffort":"max"},"retryOptions":[{"retryCount":3,"minMembershipLevel":"LEVEL_BASIC"}],"legacyIds":["k2d6-agent"],"moonPhase":"MOON_PHASE_FIRST_QUARTER","swarm":{"enabled":true,"minMembershipLevel":"LEVEL_BASIC"}}],"defaultModelKey":"k3d1-agent","cacheTtlSeconds":"300","moreModels":[{"key":"k3-agent","requestParams":{"modelId":"k3-agent","scenario":"SCENARIO_OK_COMPUTER","kimiPlusId":"ok-computer","agentMode":"TYPE_NORMAL","defaultReasoningEffort":"REASONING_EFFORT_HIGH","reasoningEffortOptions":[{"effort":"REASONING_EFFORT_LOW","displayName":"Standard"},{"effort":"REASONING_EFFORT_HIGH","displayName":"High"},{"effort":"REASONING_EFFORT_MAX","displayName":"Max","description":"Consumes more credits"}],"contextLength":1000000,"maxTokens":32768,"temperature":0.6,"topP":1,"contextLengthOptions":[{"contextLength":"CONTEXT_LENGTH_L","displayName":"Standard","available":true},{"contextLength":"CONTEXT_LENGTH_XL","displayName":"Extra Long","description":"Up to 1M tokens; consumes more credits","label":"Available for Allegro/Max members and above","minMembershipLevel":"LEVEL_ADVANCED"}],"defaultContextLength":"CONTEXT_LENGTH_L"},"display":{"displayName":"K3","inputPlaceholder":"Ask anything, or task an agent..."},"switchableTo":["k3d1-agent","k2d8-preview"],"daimonModelConfig":{"maxContextSize":1000000,"capabilities":["thinking","image_in","video_in","dynamically_loaded_tools"],"supportEfforts":["low","high","max"],"defaultEffort":"max"},"retryOptions":[{"retryCount":3,"minMembershipLevel":"LEVEL_BASIC"}],"legacyIds":["k3","k3-agent-ultra","k3-agent-swarm"],"swarm":{"enabled":true,"minMembershipLevel":"LEVEL_BASIC"}}]} \ No newline at end of file diff --git a/packages/kimi-work/tests/fixtures/work-config.web.json b/packages/kimi-work/tests/fixtures/work-config.web.json new file mode 100644 index 0000000..14fa6f8 --- /dev/null +++ b/packages/kimi-work/tests/fixtures/work-config.web.json @@ -0,0 +1 @@ +{"models":[{"key":"k3-agent","requestParams":{"modelId":"k3-agent","scenario":"SCENARIO_OK_COMPUTER","kimiPlusId":"ok-computer","agentMode":"TYPE_NORMAL","defaultReasoningEffort":"REASONING_EFFORT_HIGH","reasoningEffortOptions":[{"effort":"REASONING_EFFORT_LOW","displayName":"Standard"},{"effort":"REASONING_EFFORT_HIGH","displayName":"High"},{"effort":"REASONING_EFFORT_MAX","displayName":"Max","description":"Consumes more credits"}],"contextLength":1000000,"maxTokens":32768,"temperature":0.6,"topP":1,"contextLengthOptions":[{"contextLength":"CONTEXT_LENGTH_L","displayName":"Standard","available":true},{"contextLength":"CONTEXT_LENGTH_XL","displayName":"Extra Long","description":"Up to 1M tokens; consumes more credits","label":"Available for Allegro/Max members and above","minMembershipLevel":"LEVEL_ADVANCED"}],"defaultContextLength":"CONTEXT_LENGTH_L"},"display":{"displayName":"K3","description":"Chat & Agent, flagship all-rounder","inputPlaceholder":"Ask anything, or task an agent..."},"switchableTo":["k3-agent-ultra"],"daimonModelConfig":{"maxContextSize":1000000,"capabilities":["thinking","image_in","video_in","dynamically_loaded_tools"],"supportEfforts":["low","high","max"],"defaultEffort":"max"},"retryOptions":[{"retryCount":3,"minMembershipLevel":"LEVEL_BASIC"}],"legacyIds":["k3","k3-agent-ultra","k3-agent-swarm"]},{"key":"k3-agent-ultra","requestParams":{"modelId":"k3-agent-swarm","scenario":"SCENARIO_OK_COMPUTER","kimiPlusId":"ok-computer","agentMode":"TYPE_ULTRA","defaultReasoningEffort":"REASONING_EFFORT_HIGH","reasoningEffortOptions":[{"effort":"REASONING_EFFORT_LOW","displayName":"Standard"},{"effort":"REASONING_EFFORT_HIGH","displayName":"High"},{"effort":"REASONING_EFFORT_MAX","displayName":"Max","description":"Consumes more credits"}],"contextLength":1000000,"maxTokens":32768,"temperature":0.6,"topP":1,"contextLengthOptions":[{"contextLength":"CONTEXT_LENGTH_L","displayName":"Standard","available":true},{"contextLength":"CONTEXT_LENGTH_XL","displayName":"Extra Long","description":"Up to 1M tokens; consumes more credits","label":"Available for Allegro/Max members and above","minMembershipLevel":"LEVEL_ADVANCED"}],"defaultContextLength":"CONTEXT_LENGTH_L"},"display":{"displayName":"K3 Swarm","description":"Massive search, batch processing, and more in one go","inputPlaceholder":"Assign a task to your AI team..."},"switchableTo":["k3-agent"],"daimonModelConfig":{"maxContextSize":1000000,"capabilities":["thinking","image_in","video_in","dynamically_loaded_tools"],"supportEfforts":["low","high","max"],"defaultEffort":"max"},"retryOptions":[{"retryCount":3,"minMembershipLevel":"LEVEL_BASIC"}]},{"key":"k2d8-preview","requestParams":{"modelId":"k2d8-preview","scenario":"SCENARIO_OK_COMPUTER","kimiPlusId":"ok-computer","agentMode":"TYPE_NORMAL","defaultReasoningEffort":"REASONING_EFFORT_HIGH","reasoningEffortOptions":[{"effort":"REASONING_EFFORT_LOW","displayName":"Standard"},{"effort":"REASONING_EFFORT_HIGH","displayName":"High"},{"effort":"REASONING_EFFORT_MAX","displayName":"Max","description":"Consumes more credits"}],"contextLength":1000000,"maxTokens":32768,"temperature":0.6,"topP":1,"contextLengthOptions":[{"contextLength":"CONTEXT_LENGTH_L","displayName":"Standard","available":true},{"contextLength":"CONTEXT_LENGTH_XL","displayName":"Extra Long","description":"Up to 1M tokens; consumes more credits","label":"Available for Allegro/Max members and above","minMembershipLevel":"LEVEL_ADVANCED"}],"defaultContextLength":"CONTEXT_LENGTH_L"},"display":{"displayName":"K2.8 Preview","description":"Well-rounded and efficient for everyday tasks","inputPlaceholder":"Ask anything, or task an agent..."},"daimonModelConfig":{"maxContextSize":1000000,"capabilities":["thinking","image_in","video_in","dynamically_loaded_tools"],"supportEfforts":["low","high","max"],"defaultEffort":"max"},"retryOptions":[{"retryCount":3,"minMembershipLevel":"LEVEL_BASIC"}],"legacyIds":["k2d6-agent"],"swarm":{"enabled":true,"minMembershipLevel":"LEVEL_BASIC"}}],"defaultModelKey":"k2d8-preview","cacheTtlSeconds":"300"} \ No newline at end of file diff --git a/packages/kimi-work/tests/provider.test.mjs b/packages/kimi-work/tests/provider.test.mjs index 7fc4aa0..77190c5 100644 --- a/packages/kimi-work/tests/provider.test.mjs +++ b/packages/kimi-work/tests/provider.test.mjs @@ -168,3 +168,36 @@ test('either list failing leaves the other; both failing throws so the last good 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(); }); + +// DescribeKimiWorkConfig's literal replies, captured 2026-10-24 from +// www.kimi.com without a sign-in: the desktop's menu (x-msh-platform: mac; +// "windows" answers the same) and the web's (x-msh-platform: web, or none). +// Only the desktop's has K3.1 Pro, k3d1-agent (泠夜Soul's 99 plan, Discord). +const fixture=name=>JSON.parse(fs.readFileSync(new URL('./fixtures/'+name,import.meta.url),'utf8')); +const deskMenu=fixture('work-config.mac.json'),webMenu=fixture('work-config.web.json'); +test('the menu is asked as the desktop asks it, so K3.1 Pro (k3d1-agent) is listed',async()=>{ + for(const [platform,said] of [['darwin','mac'],['win32','windows']]) { + const seen=[]; + // Answers as www.kimi.com does: the desktop's menu only for its platforms. + const p=I.createPlugin({platform,readSession:()=>session,fetchImpl:async(url,init)=>{ + if(url!==I.CONFIG)return json(modelPayload); + const h=init.headers['x-msh-platform'];seen.push(init.headers); + return json(h==='mac'||h==='windows'?deskMenu:webMenu);}}); + const models=await p.provider.models({models:{}},{auth:account}); + expect(Object.keys(models)).toEqual(['k3d1-agent','k2d8-preview','k3-agent']); + expect(models['k3d1-agent']).toMatchObject({id:'k3d1-agent',name:'K3.1 Pro',api:{id:'k3d1-agent',url:I.BASE}, + limit:{context:262144,output:32768},capabilities:{reasoning:true,attachment:true}}); + expect(Object.keys(models['k3d1-agent'].variants)).toEqual(['low','high','max']); + expect(seen[0]).toMatchObject({'x-msh-platform':said,'x-msh-version':'3.2.20',Authorization:'Bearer '+session.webToken}); + } +}); + +test('the platform is the desktop\'s on macOS and Windows, and agent-gw gets none of the web headers',()=>{ + expect(I.webHeaders('darwin')['x-msh-platform']).toBe('mac'); + expect(I.webHeaders('win32')['x-msh-platform']).toBe('windows'); + expect(I.webHeaders('linux')['x-msh-platform']).toBe('web'); + expect(I.workHeaders('d')).not.toHaveProperty('x-msh-version'); + expect(I.workHeaders('d')['X-Msh-Platform']).toBe('kimi-code-cli'); + // 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']); +});