From 8430d83306a0c5d7e56a96bc2909b32999a2ddc6 Mon Sep 17 00:00:00 2001 From: antior <131586786+aantior@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:17:32 +0800 Subject: [PATCH] kimi-work 0.1.19: align requests with the official client Match Kimi Code 0.5.1, daimon 1.0.14 and desktop 3.2.28 headers. Add standard context, Work tag, traceparent, stable account device IDs and model output caps. Verified: node --check packages/kimi-work/index.mjs; npx --yes bun test packages/kimi-work (117 pass); npx --yes bun scripts/check.mjs kimi-work. --- packages/kimi-work/COMPATIBILITY.md | 10 +- packages/kimi-work/README.md | 8 +- packages/kimi-work/import.test.mjs | 26 ++++- packages/kimi-work/index.mjs | 100 +++++++++++++++----- packages/kimi-work/no-magpie.test.mjs | 4 +- packages/kimi-work/official-compat.test.mjs | 57 +++++++++++ packages/kimi-work/package.json | 2 +- packages/kimi-work/renewal.test.mjs | 4 +- packages/kimi-work/tests/provider.test.mjs | 6 +- 9 files changed, 177 insertions(+), 40 deletions(-) create mode 100644 packages/kimi-work/official-compat.test.mjs diff --git a/packages/kimi-work/COMPATIBILITY.md b/packages/kimi-work/COMPATIBILITY.md index 7ac6cd1..93f7548 100644 --- a/packages/kimi-work/COMPATIBILITY.md +++ b/packages/kimi-work/COMPATIBILITY.md @@ -6,6 +6,14 @@ This candidate incorporates upstream `3b3209e0ddd2c47ee5c8f77b5541131e0aa178fe` The historical 2026-10-24 live renewal test at `f67d742` used Apple-silicon macOS and official Kimi Desktop **3.2.17** (build 3.2.17.4). A fresh, user-completed login belongs to disposable profiles. The installed application and everyday Magpie/Kimi profiles are not the test credential source. A temporary application copy keeps the original `app.asar` byte-for-byte; its main-source SHA-256 is `6a37077974207f7b501add47d9756eaff8d41eb87347e05b11f59f7b2386c439`. Test-only launch instrumentation redirects profile paths and exposes the original AuthService and TokenStore methods for invocation/observation; no refresh response is substituted. +## Current Work request alignment (0.1.19) + +The Work gateway's explicit client identifiers now match the installed official Kimi **3.2.28**, daimon **1.0.14**, and Kimi Code **0.5.1** runtime. Inference sends `X-Kimi-Context-Length: 262144` by default for Standard context, preserves a caller-supplied context header, and adds `X-KimiWork-Tag: normal` and a W3C `traceparent`. Output token fields are capped at the model catalog's limit, with 32,768 as the fallback; smaller values and non-JSON bodies are unchanged. + +Local accounts prefer the desktop's official `device_id`. Imported accounts can retain an explicitly pasted official UUID or use a deterministic UUIDv5 derived from the account UID in the RFC URL namespace. Existing imported records without the field derive it at request time. The fallback is account-scoped, not machine-scoped: multiple installations serving the same account intentionally present the same device identity. + +The synthetic request tests verify these headers, identifier stability, and body limits. They do not by themselves establish upstream acceptance, a particular first-token latency, or resolution of client-side cancellation. XL remains opt-in through an explicit caller header; no automatic retry or timeout change is introduced. + ## RefreshToken request comparison Endpoint: `POST https://auth.kimi.com/api/account.gateway.v1.AuthService/RefreshToken`. The official native request was observed at **2026-10-24 15:14:47 UTC**, HTTP **200**, producing changed access and refresh tokens. The full request-header names below come from Electron's send-headers event; private values were redacted in memory before recording. @@ -31,7 +39,7 @@ The request bodies use the same `RefreshTokenRequest.refresh_token` field. The o Plugin transport-generated fields above were observed through Node's `undici:request:create` event on the **15:36:50 UTC** real renewal, in addition to the explicit fetch options. The observer redacted non-allowlisted values before recording. Native `X-Language` is corroborated by the original locale getter/interceptor; no private header value is included here. The complete official `Accept-Language` value was `zh-CN,zh;q=0.9;q=0.9,en-US;q=0.8;q=0.8,en;q=0.7;q=0.7`. -`refreshHeaders` is used only for the exact AuthService URL. Work gateway requests retain upstream's `kimi-code-cli/0.36.0` and daimon 0.6.10 device headers. www.kimi.com requests retain upstream's 3.2.20 desktop-menu metadata; the separate www User-Agent discussion remains #363. +`refreshHeaders` is used only for the exact AuthService URL. At the historical 0.1.15 revision, Work gateway requests used upstream's `kimi-code-cli/0.36.0` and daimon 0.6.10 device headers, while www.kimi.com used 3.2.20 desktop-menu metadata. Version 0.1.19 supersedes those identifiers as described above; the separate www User-Agent discussion remains #363. ## Shared refresh lineage: both directions diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index 92d348a..1401ead 100644 --- a/packages/kimi-work/README.md +++ b/packages/kimi-work/README.md @@ -9,11 +9,15 @@ magpie plugin login kimi-work Open Kimi desktop and sign in to Work on the same computer first. Choose **使用本机 Kimi Work 登录** in the provider's sign-in menu. If the desktop provides a membership access/refresh pair, explicit sign-in imports it into the host's auth store and Magpie renews it directly with Kimi near expiry, including while the browser and desktop app are closed. Older desktops without a refresh token still sign in as reference-only accounts and read membership access from the desktop file. This package does not capture browser cookies or offer an API-key fallback. +Version **0.1.19** aligns Work inference with the installed official Kimi 3.2.28 / daimon 1.0.14 / Kimi Code 0.5.1 runtime. It sends `X-Kimi-Context-Length: 262144` for Standard context unless the caller explicitly supplies another value, adds `X-KimiWork-Tag: normal` and a W3C `traceparent`, and caps `max_tokens`/`max_completion_tokens` at the live model catalog's output limit (32,768 by default) without increasing smaller values. These changes do not add retries, change the caller's timeout, or guarantee a particular time to first token. + +Work requests now always have a stable `X-Msh-Device-Id`. Local sign-in prefers the official desktop `device_id`. Paste import offers an optional device-ID field; direct file import and an empty field generate a deterministic UUIDv5 from the account UID, so the same account keeps the same ID across plugin versions and installations. Existing imported accounts without a saved ID need no reconnect. This account-level fallback deliberately makes multiple Magpie installations for one account share an upstream device identity; paste the official ID instead when exact desktop identity is required. + Version **0.1.18** adds two credential-import routes in Magpie. The provider's sign-in menu now offers **导入 Kimi Work 凭据(粘贴 config.json)** beside local sign-in; **Import accounts from a file…** in the accounts area chooses a file directly. Both take `daimon/config.json` from a trusted computer signed in to Kimi Work. Unlike local sign-in, they explicitly import both the Work key and membership credentials, so the computer running Magpie does not need Kimi installed or the desktop data folder mounted. The file's `credentials.kimiCode`, `credentials.kimiWeb` and exact official Work origin are checked, then the Work key is verified with `/models` before the account is saved. Existing local/reference accounts are unchanged and are not migrated. The file-import hook is Magpie-only; OpenCode ignores it, while the paste sign-in method uses the standard provider auth hooks. On Windows, the paste sign-in prompt shows the Explorer-ready default `%APPDATA%\kimi-desktop\daimon-share\daimon\config.json`. If Kimi's storage was moved in its settings, the real folder is the `shareDir` in `%APPDATA%\kimi-desktop\daimon-storage.json`. -The imported file contains sensitive Work and membership credentials, which are saved in Magpie's private plaintext `plugin-auth.json` (mode `0600`, not an encrypted vault). Import only into a trusted Magpie instance. Membership renewal continues as below, but it cannot renew the Work key: a Work 401 asks for a fresh `config.json` import. No desktop device ID or `kimi-code-key.json` is needed for an imported account. +The imported file contains sensitive Work and membership credentials, which are saved in Magpie's private plaintext `plugin-auth.json` (mode `0600`, not an encrypted vault). Import only into a trusted Magpie instance. Membership renewal continues as below, but it cannot renew the Work key: a Work 401 asks for a fresh `config.json` import. No desktop data folder or `kimi-code-key.json` is needed for an imported account. Paste sign-in can optionally use the UUID in `daimon/runtime/kimi-code/home/device_id`; otherwise the account-level stable ID above is generated automatically. Version **0.1.15** adds membership renewal and a single shared monthly meter to upstream 0.1.14. It retains the storage-pointer and sign-in diagnostics fixes (#425/#444), distinct account IDs and per-user Work keys (#440), and spent-quota 403→429 handling (#465), alongside the earlier menu/header fixes. **Existing reference-only accounts through 0.1.14 continue to read quota without reconnecting.** They do not silently migrate or spend the desktop refresh token. Explicitly reconnect only to opt into host-managed renewal when a desktop refresh token is available. Accounts already saved with a pair keep their format. @@ -71,7 +75,7 @@ When explicitly imported, the membership pair is saved by Magpie in its account- Magpie calls `auth.refresh` before models, usage and requests when access is within one minute of its JWT expiry. The hook returns rotated access/refresh fields. **Magpie owns the commit:** under its auth-store lock it checks that the original pair still stands before saving, so a late renewal cannot restore logout or overwrite a replacement login. The plugin never calls `client.auth.set` from renewal or usage. Pending work and cached rotations use exact credentials, keeping independent same-user reconnects separate. A failed host save can retry the rotated pair in the same plugin process; restarting before it is saved may require reconnecting. A rejected membership refresh gives a reconnect hint and keeps the Work sign-in; it throws a membership-only failure so the host retains retry backoff without marking the provider account expired. Network/429/5xx failures retain the stored login. -RefreshToken uses its own observed desktop User-Agent/platform/version/timezone/language headers, with Connect JSON and no Authorization or Cookie. Browser device/session identifiers and ShieldData are not copied. Work requests keep upstream's Kimi Code 0.36.0/daimon 0.6.10 headers; www.kimi.com keeps upstream's desktop-menu metadata. The [compatibility record](COMPATIBILITY.md) compares the requests and preserves the dated 2026-10-24 single-cycle coexistence evidence; this revision does not claim a second real coexistence cycle. +RefreshToken uses its own observed desktop User-Agent/platform/version/timezone/language headers, with Connect JSON and no Authorization or Cookie. Browser device/session identifiers and ShieldData are not copied. Work requests use the Kimi Code 0.5.1/daimon 1.0.14 headers observed in Kimi 3.2.28; www.kimi.com uses the same desktop version for menu metadata. The [compatibility record](COMPATIBILITY.md) compares the requests and preserves the dated 2026-10-24 single-cycle coexistence evidence; this revision does not claim a second real coexistence cycle. Usage never rotates, writes or silently imports credentials, for any account format. `auth.refresh`, `auth.usage` and `auth.import` are Magpie hooks ignored by OpenCode. Inference still depends on a valid per-account local or imported Work key; membership renewal cannot replace a revoked Work key. Server expiry/revocation can require human sign-in or a fresh file import, and automatic renewal does not guarantee a permanent session. diff --git a/packages/kimi-work/import.test.mjs b/packages/kimi-work/import.test.mjs index 597253e..f79db8b 100644 --- a/packages/kimi-work/import.test.mjs +++ b/packages/kimi-work/import.test.mjs @@ -33,6 +33,11 @@ test('magpie offers a guided config.json import in every window language',async( expect(p.auth.methods[1].prompts[0].message).toContain('shareDir'); expect(p.auth.methods[1].prompts[0].validate('')).toBeTruthy(); expect(p.auth.methods[1].prompts[0].validate(file())).toBeUndefined(); + expect(p.auth.methods[1].prompts[1]).toMatchObject({key:'deviceId',required:false}); + expect(p.auth.methods[1].prompts[1].message).toContain('daimon/runtime/kimi-code/home/device_id'); + expect(p.auth.methods[1].prompts[1].validate('')).toBeUndefined(); + expect(p.auth.methods[1].prompts[1].validate('not-a-uuid')).toBeTruthy(); + expect(p.auth.methods[1].prompts[1].validate('0f8fad5b-d9cb-469f-a165-70867728950e')).toBeUndefined(); }); test('the sign-in menu also accepts pasted config.json content without reading the desktop',async()=>{ @@ -41,10 +46,10 @@ test('the sign-in menu also accepts pasted config.json content without reading t expect(new Headers(init.headers).get('authorization')).toBe('Bearer '+workToken); return Response.json(catalog); }); - const flow=await p.auth.methods[1].authorize({config:file()}); + const flow=await p.auth.methods[1].authorize({config:file(),deviceId:'0f8fad5b-d9cb-469f-a165-70867728950e'}); expect(flow).toMatchObject({url:'',method:'auto'}); const auth=await flow.callback(); - expect(auth).toMatchObject({type:'success',imported:true,workToken,access:webToken}); + expect(auth).toMatchObject({type:'success',imported:true,workToken,access:webToken,deviceId:'0f8fad5b-d9cb-469f-a165-70867728950e'}); expect(desktopReads()).toBe(0); }); @@ -64,7 +69,7 @@ test('a selected config.json is validated and explicitly imports both Work and m expect(desktopReads()).toBe(0); }); -test('an imported account lists models, reads usage and chats without any desktop file or device id',async()=>{ +test('an imported account and its pre-0.1.19 saved form use a stable generated device id',async()=>{ const calls=[]; const {p,desktopReads}=fixture(async(url,init)=>{ calls.push({url:String(url),headers:new Headers(init.headers)}); @@ -75,6 +80,9 @@ test('an imported account lists models, reads usage and chats without any deskto throw Error('unexpected request '+url); }); const [auth]=await p.auth.import([file()]); + expect(auth.deviceId).toBe(I.stableDeviceId(auth.uid)); + const deviceId=auth.deviceId; + delete auth.deviceId; calls.length=0; expect(await p.auth.refresh(auth)).toBeUndefined(); const models=await p.provider.models({models:{}},{auth}); @@ -86,7 +94,7 @@ test('an imported account lists models, reads usage and chats without any deskto expect(calls.find(c=>c.url===I.MEMBER+'GetSubscriptionStats').headers.get('authorization')).toBe('Bearer '+webToken); for(const c of calls.filter(c=>c.url.startsWith(I.BASE))) { expect(c.headers.get('authorization')).toBe('Bearer '+workToken); - expect(c.headers.has('x-msh-device-id')).toBe(false); + expect(c.headers.get('x-msh-device-id')).toBe(deviceId); } }); @@ -105,6 +113,16 @@ test('a config.json without a membership refresh token still works independently expect(desktopReads()).toBe(0); }); +test('an invalid optional device id is refused before any request',async()=>{ + let calls=0; + const {p}=fixture(async()=>{calls++;return Response.json(catalog);}); + const flow=await p.auth.methods[1].authorize({config:file(),deviceId:'not-a-uuid'}); + const auth=await flow.callback(); + expect(auth.type).toBe('failed'); + expect(auth.error).toContain('device_id'); + expect(calls).toBe(0); +}); + test('bad JSON, missing credentials and a non-Work origin are refused without a request or secret leakage',async()=>{ let calls=0; const {p,desktopReads}=fixture(async()=>{calls++;return Response.json(catalog);}); diff --git a/packages/kimi-work/index.mjs b/packages/kimi-work/index.mjs index 9248927..c3713fa 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -1,7 +1,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import {createHash} from 'node:crypto'; +import {createHash, randomUUID} from 'node:crypto'; const ID = 'kimi-work'; const BASE = 'https://agent-gw.kimi.com/coding/v1'; @@ -13,12 +13,12 @@ const REFRESH_LEAD = 60000; // 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'; -// What Kimi's own Work client sends agent-gw (Kimi 3.2.20's daimon 0.6.10, +// What Kimi's own Work client sends agent-gw (Kimi 3.2.28's daimon 1.0.14, // createDaimonKimiCodeRequestHeaders): the vendored Kimi Code's version as // "kimi-code-cli/" (no daimon caller passes a suffix), and the // X-Msh device headers beside it (magpie-community/plugins#353). -const KIMI_CODE_VERSION = '0.36.0'; -const DAIMON_VERSION = '0.6.10'; +const KIMI_CODE_VERSION = '0.5.1'; +const DAIMON_VERSION = '1.0.14'; 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, @@ -27,7 +27,12 @@ const UA = 'kimi-code-cli/' + KIMI_CODE_VERSION; // 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'; +const DESKTOP_VERSION = '3.2.28'; +// Work's default context, sent explicitly like the desktop's Standard mode. +// A caller that deliberately selects XL can override this header itself. +const CONTEXT_HEADER = 'X-Kimi-Context-Length'; +const STANDARD_CONTEXT = 262144; +const WORK_TAG_HEADER = 'X-KimiWork-Tag'; // 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). @@ -43,10 +48,10 @@ function webHeaders(platform=process.platform) { 'x-msh-version':DESKTOP_VERSION,'R-Timezone':Intl.DateTimeFormat().resolvedOptions().timeZone||'UTC'}; } // AuthService is a desktop Connect client, not the Work/Code gateway. These -// public client fields come from an observed Kimi 3.2.17 RefreshToken call. -// Connect's JSON representation is also used by that SDK (KIMI_CAPTURE mode). +// public client fields follow the installed desktop version, as its own +// RefreshToken call does. Connect's JSON representation is also used by that SDK (KIMI_CAPTURE mode). // Browser-owned device/session IDs and ShieldData are deliberately not copied. -const AUTH_VERSION='3.2.17'; +const AUTH_VERSION=DESKTOP_VERSION; function refreshHeaders(platform=process.platform) { const system=platform==='darwin'?'Macintosh; Intel Mac OS X 10_15_7' :platform==='win32'?'Windows NT 10.0; Win64; x64':'X11; Linux x86_64'; @@ -68,6 +73,18 @@ function workHeaders(deviceId) { } // The host's quota RPC preserves message alone; this marker selects its // localized signed-out card and the account's reconnect action. +const DEVICE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +const DEVICE_NAMESPACE=Buffer.from('6ba7b8119dad11d180b400c04fd430c8','hex'); +// UUIDv5 gives an imported account one stable identity without a desktop file. +// Deliberately account-scoped: all Magpie installations for this account share it. +function stableDeviceId(uid) { + const digest=createHash('sha1').update(DEVICE_NAMESPACE).update('kimi-work/'+String(uid)).digest(); + digest[6]=(digest[6]&0x0f)|0x50;digest[8]=(digest[8]&0x3f)|0x80; + const hex=digest.toString('hex'); + return hex.slice(0,8)+'-'+hex.slice(8,12)+'-'+hex.slice(12,16)+'-'+hex.slice(16,20)+'-'+hex.slice(20,32); +} +const importedDeviceId=(value,uid)=>typeof value==='string'&&DEVICE_ID_PATTERN.test(value)?value.toLowerCase():stableDeviceId(uid); +const newTraceparent=()=>'00-'+randomUUID().replaceAll('-','')+'-'+randomUUID().replaceAll('-','').slice(0,16)+'-01'; const expired = () => Object.assign(Error('Kimi Work sign-in has expired. Sign in to Kimi desktop Work if needed, then reconnect Kimi Work (magpie plugin login kimi-work).'), {signIn:'expired',code:'kimi_work_login_expired'}); // Kimi's daimon-share itself is gone (moved, deleted, a drive not mounted): // the sign-in in it isn't known to have lapsed, so the account is not marked @@ -112,6 +129,13 @@ const IMPORT_METHOD = { }; // spentQuota is a 403 body saying the account's allowance is used up, not // that the token or the model is refused (#465). +const DEVICE_ID_MESSAGE='可选:粘贴 Kimi 官方 device_id,使 NAS 与桌面版使用同一设备标识。留空则按账号生成固定 UUID。文件位置:daimon/runtime/kimi-code/home/device_id。'; +const DEVICE_ID_MESSAGES={ + en:'Optional: paste the official device_id to share the desktop device identity. Leave empty for a deterministic account UUID. File: daimon/runtime/kimi-code/home/device_id.', + 'zh-TW':'可選:貼上 Kimi 官方 device_id,讓 NAS 與桌面版使用同一裝置識別。留空則按帳號產生固定 UUID。檔案:daimon/runtime/kimi-code/home/device_id。', + ja:'任意:公式 device_id を貼り付けるとデスクトップと同じデバイス ID を使います。空欄の場合はアカウントから固定 UUID を生成します。ファイル:daimon/runtime/kimi-code/home/device_id。', + de:'Optional: offizielle device_id einfügen, um dieselbe Gerätekennung wie der Desktop zu verwenden. Leer lassen für eine deterministische UUID pro Konto. Datei: daimon/runtime/kimi-code/home/device_id.', +}; const spentQuota = text => /resource_exhausted|usage limit|billing cycle|insufficient balance|quota/i.test(String(text??'')); const percent = x => typeof x === 'number' && Number.isFinite(x) ? Math.max(0,Math.min(100,x*100)) : undefined; @@ -317,6 +341,19 @@ function fastSpeed(body,offered) { return {body:JSON.stringify(doc),fast:true}; } +function capOutputTokens(body,limits={}) { + if(typeof body!=='string'||!body.includes('token'))return body; + let doc; + try{doc=JSON.parse(body);}catch{return body;} + if(!isObj(doc))return body; + const limit=Number(limits[doc.model])||32768; + let changed=false; + for(const key of ['max_tokens','max_completion_tokens']) { + if(typeof doc[key]==='number'&&doc[key]>limit){doc[key]=limit;changed=true;} + } + return changed?JSON.stringify(doc):body; +} + // 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) { @@ -524,13 +561,14 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo if(auth?.source!=='kimi-work-desktop')throw expired(); if(auth.imported===true) { if(typeof auth.workToken!=='string'||!auth.workToken)throw importExpired(); - return {workToken:auth.workToken,webToken:typeof auth.access==='string'?auth.access:'',uid:auth.uid,imported:true}; + return {workToken:auth.workToken,webToken:typeof auth.access==='string'?auth.access:'',uid:auth.uid, + deviceId:importedDeviceId(auth.deviceId,auth.uid),imported:true}; } const session=readSession(); - if(auth.uid===session.uid)return session; + if(auth.uid===session.uid)return {...session,deviceId:importedDeviceId(session.deviceId,session.uid)}; const key=typeof auth.uid==='string'?session.keys?.[auth.uid]:undefined; if(!key)throw notHere(); - return {workToken:key,webToken:'',deviceId:session.deviceId,uid:auth.uid,away:true}; + return {workToken:key,webToken:'',deviceId:importedDeviceId(session.deviceId,auth.uid),uid:auth.uid,away:true}; }; async function jsonRequest(url,token,body,signal,deviceId) { const response=await fetchImpl(url,{method:body===undefined?'GET':'POST', @@ -636,32 +674,38 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo } // 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(); + const offered=new Map(),outputLimits=new Map(); + function rememberModels(uid,rows) { + offered.set(uid,fastIds(rows)); + outputLimits.set(uid,Object.fromEntries(Object.entries(rows).map(([id,row])=>[id,row.limit?.output]))); + } 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; + const rows=await menu(s,auth).catch(()=>({})); + rememberModels(s.uid,rows); + return offered.get(s.uid); } - function signedIn(s,imported=false) { + function signedIn(s,imported=false,deviceId) { const pair=s.webRefresh ? {access:s.webToken,refresh:s.webRefresh,expires:expiry(s.webToken)} : imported ? {access:s.webToken,refresh:'',expires:expiry(s.webToken)} : {access:'',refresh:'',expires:0}; return {type:'success',...pair,source:'kimi-work-desktop', accountId:'Kimi Work · '+s.uid.slice(0,6),uid:s.uid, - ...(imported?{imported:true,workToken:s.workToken}:{})}; + ...(imported?{imported:true,workToken:s.workToken,deviceId:importedDeviceId(deviceId,s.uid)}:{})}; } - async function importFile(text,signal) { + async function importFile(text,signal,deviceId) { + if(deviceId!==undefined&&deviceId!==''&&!DEVICE_ID_PATTERN.test(deviceId)) + return {type:'failed',error:'device_id 格式无效,请粘贴 daimon/runtime/kimi-code/home/device_id 中的 UUID,或留空自动生成。'}; let s; try{s=parseDesktopImport(text);} catch(error){return {type:'failed',error:error.message};} - try{await jsonRequest(BASE+'/models',s.workToken,undefined,signal);} + try{await jsonRequest(BASE+'/models',s.workToken,undefined,signal,importedDeviceId(deviceId,s.uid));} catch(error){ if(error?.status===401)return {type:'failed',error:'文件中的 Kimi Work 密钥已失效,请在 Kimi 桌面版重新进入 Work 后选择新的 config.json。'}; const why=error?.status?'HTTP '+error.status:error?.name==='TimeoutError'?'超时':error?.cause?.code||error?.message||'未知网络错误'; return {type:'failed',error:'已读取文件中的 Kimi Work 登录,但连接 Kimi Work 失败('+why+'),请检查网络后再试。'}; } - return signedIn(s,true); + return signedIn(s,true,deviceId); } async function importFiles(texts,signal) { const out=[]; @@ -711,10 +755,13 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo })},{ type:'oauth',label:IMPORT_METHOD.label,labels:IMPORT_METHOD.labels, prompts:[{type:'password',key:'config',message:IMPORT_METHOD.message,messages:IMPORT_METHOD.messages, - placeholder:'{"credentials":{…}}',validate:v=>v&&v.trim()?undefined:'请粘贴 daimon/config.json 的内容'}], + placeholder:'{"credentials":{…}}',validate:v=>v&&v.trim()?undefined:'请粘贴 daimon/config.json 的内容'}, + {type:'password',key:'deviceId',message:DEVICE_ID_MESSAGE,messages:DEVICE_ID_MESSAGES,required:false, + placeholder:'0f8fad5b-d9cb-469f-a165-70867728950e', + validate:v=>!v||DEVICE_ID_PATTERN.test(v)?undefined:'device_id 必须是 UUID;也可以留空自动生成'}], authorize:async inputs=>({ url:'',method:'auto',instructions:'验证导入的 Kimi Work 凭据。', - callback:async(_,{signal}={})=>importFile(inputs?.config,signal), + callback:async(_,{signal}={})=>importFile(inputs?.config,signal,inputs?.deviceId?.trim()||undefined), }), }], refreshLead:REFRESH_LEAD, @@ -740,6 +787,9 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo for(const key of [...headers.keys()])if(key.startsWith('x-magpie-'))headers.delete(key); headers.set('Authorization','Bearer '+s.workToken); for(const [k,v] of Object.entries(workHeaders(s.deviceId)))headers.set(k,v); + if(!headers.has(CONTEXT_HEADER))headers.set(CONTEXT_HEADER,String(STANDARD_CONTEXT)); + if(!headers.has('traceparent'))headers.set('traceparent',newTraceparent()); + headers.set(WORK_TAG_HEADER,'normal'); headers.set('Content-Type','application/json'); // Preserve messages, stream and abort signal, and tools but for // the schema shapes Kimi refuses (moonshotTools). There is no @@ -751,7 +801,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo signal?.throwIfAborted(); if(body!=null)body=moonshotTools(body); const speed=fastSpeed(body,asksFast(body)?await fastOffered(s,auth):new Map()); - body=speed.body; + body=capOutputTokens(speed.body,outputLimits.get(s.uid)); if(speed.fast)headers.set(SPEED_HEADER,'fast'); const options={...init,body,signal}; if(body==null)delete options.body; @@ -817,7 +867,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo 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(cfgList.status==='fulfilled')rememberModels(s.uid,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 @@ -829,4 +879,4 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo } export default async function KimiWorkProvider(){return createPlugin();} -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}; +export const _internal={createPlugin,fastSpeed,fastIds,spentQuota,moonshotTools,moonshotSchema,capOutputTokens,stableDeviceId,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/no-magpie.test.mjs b/packages/kimi-work/no-magpie.test.mjs index 62e20b3..01b8204 100644 --- a/packages/kimi-work/no-magpie.test.mjs +++ b/packages/kimi-work/no-magpie.test.mjs @@ -37,9 +37,9 @@ test('no request to Kimi names magpie: models, the Work menu, chat and membershi expect(sent.length).toBe(4); for(const s of sent)expect(JSON.stringify(s)).not.toMatch(/magpie/i); for(const s of sent.filter(s=>s.url.startsWith(I.BASE))){ - expect(s.headers['user-agent']).toBe('kimi-code-cli/0.36.0'); + expect(s.headers['user-agent']).toBe('kimi-code-cli/0.5.1'); expect(s.headers['x-msh-platform']).toBe('kimi-code-cli'); - expect(s.headers['x-msh-version']).toBe('0.36.0'); + expect(s.headers['x-msh-version']).toBe('0.5.1'); expect(s.headers['x-msh-device-id']).toBe(session.deviceId); } }); diff --git a/packages/kimi-work/official-compat.test.mjs b/packages/kimi-work/official-compat.test.mjs new file mode 100644 index 0000000..df7762f --- /dev/null +++ b/packages/kimi-work/official-compat.test.mjs @@ -0,0 +1,57 @@ +import {test,expect} from 'bun:test'; +import {_internal as I} from './index.mjs'; + +const session={uid:'fixture-account',workToken:'synthetic-work-token',webToken:'synthetic-web-token',webRefresh:'synthetic-refresh-token'}; +const account={source:'kimi-work-desktop',uid:session.uid,access:session.webToken,refresh:session.webRefresh,expires:0}; + +test('chat matches the current official device, context, Work and trace headers',async()=>{ + const calls=[]; + const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{calls.push(init);return new Response('data: [DONE]\n\n');}}); + const loader=await p.auth.loader(async()=>account); + await loader.fetch(I.BASE+'/chat/completions',{method:'POST',body:'{"model":"k3-agent","messages":[]}'}); + const first=new Headers(calls[0].headers),device=I.stableDeviceId(session.uid); + expect(first.get('user-agent')).toBe('kimi-code-cli/0.5.1'); + expect(first.get('x-msh-version')).toBe('0.5.1'); + expect(first.get('x-msh-daimon-version')).toBe('1.0.14'); + expect(first.get('x-msh-device-id')).toBe(device); + expect(first.get('x-kimi-context-length')).toBe('262144'); + expect(first.get('x-kimiwork-tag')).toBe('normal'); + expect(first.get('traceparent')).toMatch(/^00-[0-9a-f]{32}-[0-9a-f]{16}-01$/); + await loader.fetch(I.BASE+'/chat/completions',{method:'POST',body:'{"model":"k3-agent","messages":[]}',headers:{ + 'X-Kimi-Context-Length':'1000000',traceparent:'00-0123456789abcdef0123456789abcdef-0123456789abcdef-01'}}); + const second=new Headers(calls[1].headers); + expect(second.get('x-kimi-context-length')).toBe('1000000'); + expect(second.get('traceparent')).toBe('00-0123456789abcdef0123456789abcdef-0123456789abcdef-01'); + expect(second.get('x-msh-device-id')).toBe(device); +}); + +test('the account UUID is deterministic, namespaced and version 5',()=>{ + const id=I.stableDeviceId('fixture-account'); + expect(id).toBe(I.stableDeviceId('fixture-account')); + expect(id).not.toBe(I.stableDeviceId('another-account')); + expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); +}); + +test('only output tokens above the model catalog limit are capped',()=>{ + expect(I.capOutputTokens('{"model":"k3d1-agent","max_tokens":79472}',{'k3d1-agent':32768})) + .toBe('{"model":"k3d1-agent","max_tokens":32768}'); + expect(I.capOutputTokens('{"model":"k3d1-agent","max_completion_tokens":40000}',{'k3d1-agent':32768})) + .toBe('{"model":"k3d1-agent","max_completion_tokens":32768}'); + const small='{"model":"k3d1-agent","max_tokens":32000}'; + expect(I.capOutputTokens(small,{'k3d1-agent':32768})).toBe(small); + expect(I.capOutputTokens('not json',{})).toBe('not json'); +}); + +test('a catalog read supplies the output cap used by later chat requests',async()=>{ + const bodies=[]; + const menu={models:[{requestParams:{modelId:'k3d1-agent',maxTokens:32768},display:{displayName:'K3.1 Pro'},daimonModelConfig:{maxContextSize:1000000}}]}; + const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{ + if(url===I.CONFIG)return Response.json(menu); + if(url===I.BASE+'/models')return Response.json({data:[]}); + bodies.push(await new Response(init.body).text());return new Response('data: [DONE]\n\n'); + }}); + await p.provider.models({models:{}},{auth:account}); + const loader=await p.auth.loader(async()=>account); + await loader.fetch(I.BASE+'/chat/completions',{method:'POST',body:'{"model":"k3d1-agent","max_tokens":79472}'}); + expect(JSON.parse(bodies[0]).max_tokens).toBe(32768); +}); diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index d890607..c3e758d 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.18", + "version": "0.1.19", "type": "module", "main": "./opencode.mjs", "files": [ diff --git a/packages/kimi-work/renewal.test.mjs b/packages/kimi-work/renewal.test.mjs index dad3f1c..f403047 100644 --- a/packages/kimi-work/renewal.test.mjs +++ b/packages/kimi-work/renewal.test.mjs @@ -26,10 +26,10 @@ test('host renewal returns only rotated fields and never calls the blind auth.se const headers=new Headers(init.headers); expect(headers.get('content-type')).toBe('application/json'); expect(headers.get('connect-protocol-version')).toBe('1'); - expect(headers.get('user-agent')).toContain('kimi-desktop/3.2.17'); + expect(headers.get('user-agent')).toContain('kimi-desktop/3.2.28'); expect(headers.get('user-agent')).not.toContain('kimi-code-cli'); expect(headers.get('x-msh-platform')).toBe('mac'); - expect(headers.get('x-msh-version')).toBe('3.2.17'); + expect(headers.get('x-msh-version')).toBe('3.2.28'); expect(headers.get('r-timezone')).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone); expect(headers.get('x-language')).toBeTruthy(); for(const key of ['x-msh-device-id','x-msh-session-id','x-msh-shield-data'])expect(headers.has(key)).toBe(false); diff --git a/packages/kimi-work/tests/provider.test.mjs b/packages/kimi-work/tests/provider.test.mjs index b21dd56..2d052bd 100644 --- a/packages/kimi-work/tests/provider.test.mjs +++ b/packages/kimi-work/tests/provider.test.mjs @@ -51,7 +51,7 @@ test('inference always uses the Work gateway and live Work credential, preservin 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('kimi-code-cli/0.36.0'); + expect(calls[0].init.headers.get('user-agent')).toBe('kimi-code-cli/0.5.1'); 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'); @@ -221,7 +221,7 @@ test('the menu is asked as the desktop asks it, so K3.1 Pro (k3d1-agent) is list 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}); + expect(seen[0]).toMatchObject({'x-msh-platform':said,'x-msh-version':'3.2.28',Authorization:'Bearer '+session.webToken}); } }); @@ -254,7 +254,7 @@ test('a menu the web sign-in can\'t get is asked again without it, so K3.1 Pro i 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(seen[1]).toMatchObject({'x-msh-platform':'mac','x-msh-version':'3.2.28'}); expect(logged.join('\n')).toContain('DescribeKimiWorkConfig'); expect(logged.join('\n')).not.toContain(session.webToken); }