Verification: npx --yes bun test packages/kimi-work (123 pass, 0 fail, 608 assertions) and npx --yes bun scripts/check.mjs kimi-work passed. The new plan/cache tests failed on the old implementation with 'I.planName is not a function' and 'p.auth.accountPlan is not a function'. Real NAS account, GUI and SSE verification are not yet run.
944 lines
54 KiB
JavaScript
944 lines
54 KiB
JavaScript
import fs from 'node:fs';
|
||
import os from 'node:os';
|
||
import path from 'node:path';
|
||
import {createHash, randomUUID} 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/';
|
||
const REFRESH = 'https://auth.kimi.com/api/account.gateway.v1.AuthService/RefreshToken';
|
||
const REFRESH_LEAD = 60000;
|
||
const PLAN_CACHE = 5 * 60 * 1000;
|
||
const PLAN_RETRY = 60 * 1000;
|
||
// 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';
|
||
// 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/<version>" (no daimon caller passes a suffix), and the
|
||
// X-Msh device headers beside it (magpie-community/plugins#353).
|
||
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,
|
||
// "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.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).
|
||
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'};
|
||
}
|
||
// AuthService is a desktop Connect client, not the Work/Code gateway. These
|
||
// 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=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';
|
||
return {...webHeaders(platform),'x-msh-version':AUTH_VERSION,
|
||
'User-Agent':`Mozilla/5.0 (${system}) AppleWebKit/537.36 (KHTML, like Gecko) kimi-desktop/${AUTH_VERSION} Chrome/150.0.7871.250 Electron/43.7.3 Safari/537.36`,
|
||
'X-Language':Intl.DateTimeFormat().resolvedOptions().locale||'en-US'};
|
||
}
|
||
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();
|
||
if (t === 'Darwin') return 'macOS ' + r + ' ' + a;
|
||
if (t === 'Windows_NT') return 'Windows ' + r + ' ' + a;
|
||
return (t + ' ' + r + ' ' + a).trim();
|
||
}
|
||
function workHeaders(deviceId) {
|
||
return {'User-Agent':UA,...(deviceId?{'X-Msh-Device-Id':deviceId}:{}),
|
||
'X-Msh-Device-Model':ascii(deviceModel()),'X-Msh-Device-Name':ascii(os.hostname()),'X-Msh-Os-Version':ascii(os.release()),
|
||
'X-Msh-Platform':'kimi-code-cli','X-Msh-Version':KIMI_CODE_VERSION,'X-Msh-Daimon-Version':DAIMON_VERSION};
|
||
}
|
||
// 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
|
||
// signed out ("kept"), and the message names the folder (#444). Kimi makes
|
||
// the folder again only when it starts, so signing in again in a running
|
||
// Kimi doesn't bring it back; putting it back does, at once.
|
||
const shareMissing = dir => Object.assign(Error('Kimi Work 的数据目录不存在:' + dir
|
||
+ '。如果移动或删除过它,把它放回原处即可恢复,无需重新登录;否则请完全退出并重新打开 Kimi 桌面版(它会重建这个目录),再登录 Work。'),
|
||
{signIn:'kept',code:'kimi_work_share_missing',file:dir,shareMissing:true});
|
||
// An account signed in here that Kimi has since switched away from, with no
|
||
// Work key of its own left in Kimi's key store (#440).
|
||
const notHere = (revoked=false) => Object.assign(Error(revoked
|
||
? '这个 Kimi Work 账号在本机的 Work 密钥已失效。请在 Kimi 桌面版切换到这个账号进入一次 Work,Kimi 会换一把新的。'
|
||
: '这个 Kimi Work 账号已不是 Kimi 桌面版当前登录的账号,本机也没有它的 Work 密钥。请在 Kimi 桌面版切换到这个账号进入一次 Work,之后切回别的账号它也能继续用。'),
|
||
{signIn:'expired',code:'kimi_work_account_not_here'});
|
||
const unavailable = error => Object.assign(Error('Kimi Work 连接失败:' + (error?.cause?.code || error?.message || '未知网络错误'), {cause:error}), {code:'kimi_work_connection_failed'});
|
||
const importExpired = () => Object.assign(Error('导入的 Kimi Work 密钥已失效,请重新选择 Kimi 桌面版的 daimon/config.json 导入。'), {signIn:'expired',code:'kimi_work_login_expired'});
|
||
const IMPORT_FROM = {
|
||
en: "Choose Kimi desktop's daimon/config.json from a computer signed in to Work. The imported account works here without Kimi installed. Its credentials are kept in magpie's auth store; import it again if its Work key expires.",
|
||
froms: {
|
||
zh: '选择已登录 Work 的 Kimi 桌面版 daimon/config.json。导入后本机无需安装 Kimi。文件包含敏感凭据,会保存在 magpie 认证库中;Work 密钥失效后需重新导入。',
|
||
'zh-TW': '選擇已登入 Work 的 Kimi 桌面版 daimon/config.json。匯入後本機無需安裝 Kimi。檔案包含敏感憑證,會保存在 magpie 認證庫中;Work 金鑰失效後需重新匯入。',
|
||
ja: 'Work にサインインした Kimi デスクトップの daimon/config.json を選択します。インポート後、このPCに Kimi は不要です。機密情報は magpie の認証ストアに保存されます。Work キーが失効したら再インポートしてください。',
|
||
de: 'Wähle daimon/config.json eines bei Work angemeldeten Kimi-Desktops. Danach ist Kimi hier nicht nötig. Die sensiblen Zugangsdaten werden in magpies Auth-Speicher abgelegt; nach Ablauf des Work-Schlüssels erneut importieren.',
|
||
},
|
||
};
|
||
const IMPORT_METHOD = {
|
||
label:'导入 Kimi Work 凭据(粘贴 config.json)',
|
||
labels:{
|
||
en:'Import Kimi Work credentials (paste config.json)',
|
||
'zh-TW':'匯入 Kimi Work 憑證(貼上 config.json)',
|
||
ja:'Kimi Work 認証情報をインポート(config.json を貼り付け)',
|
||
de:'Kimi-Work-Zugangsdaten importieren (config.json einfügen)',
|
||
},
|
||
message:'粘贴 daimon/config.json 的完整 JSON 内容。Windows 默认路径:%APPDATA%\\kimi-desktop\\daimon-share\\daimon\\config.json;如果移动过 Kimi 存储位置,真实路径以 %APPDATA%\\kimi-desktop\\daimon-storage.json 中的 shareDir 为准。',
|
||
messages:{
|
||
en:'Paste the complete JSON contents of daimon/config.json. Windows default: %APPDATA%\\kimi-desktop\\daimon-share\\daimon\\config.json; if you moved Kimi storage, use shareDir from %APPDATA%\\kimi-desktop\\daimon-storage.json.',
|
||
'zh-TW':'貼上 daimon/config.json 的完整 JSON 內容。Windows 預設路徑:%APPDATA%\\kimi-desktop\\daimon-share\\daimon\\config.json;如果移動過 Kimi 儲存位置,真實路徑以 %APPDATA%\\kimi-desktop\\daimon-storage.json 中的 shareDir 為準。',
|
||
ja:'daimon/config.json の完全な JSON 内容を貼り付けてください。Windows のデフォルト: %APPDATA%\\kimi-desktop\\daimon-share\\daimon\\config.json。Kimi の保存場所を移動した場合は、%APPDATA%\\kimi-desktop\\daimon-storage.json の shareDir を参照してください。',
|
||
de:'Füge den vollständigen JSON-Inhalt von daimon/config.json ein. Windows-Standard: %APPDATA%\\kimi-desktop\\daimon-share\\daimon\\config.json; bei verschobenem Kimi-Speicher gilt shareDir aus %APPDATA%\\kimi-desktop\\daimon-storage.json.',
|
||
},
|
||
};
|
||
// 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;
|
||
|
||
function tokenClaims(token) {
|
||
try {
|
||
const claims=JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
|
||
return claims && typeof claims==='object' ? claims : {};
|
||
} catch {return {};}
|
||
}
|
||
const expiry = token => Number(tokenClaims(token).exp) * 1000 || 0;
|
||
|
||
// Kimi Work validates tools against Moonshot's "moonshot flavored json
|
||
// schema" and refuses the whole request, 400 "tools.function.parameters is
|
||
// not a valid moonshot flavored json schema", for shapes a JSON Schema
|
||
// allows and agents send (#287). Codex's MCP and app tools are zod's
|
||
// toJSONSchema with reused schemas as $defs (__schema0, __schema1 …), and
|
||
// zod writes a schema derived from a reused one as a $ref beside what it
|
||
// changed: z.number() reused, then .int(), is {"type":"integer","maximum":…,
|
||
// "$ref":"#/$defs/__schema0"}, refused "when using $ref, type should be
|
||
// defined in the referenced schema instead of the parent schema". The tools
|
||
// are rewritten for the rules Kimi has been seen to hold:
|
||
// - a $ref beside a type: the target, when it has no $ref of its own, is
|
||
// written in its place with the parent's keywords over it (what zod's
|
||
// derived schema means); otherwise the parent's type is left out;
|
||
// - a type beside an anyOf ("type should be defined in anyOf items instead
|
||
// of the parent schema") is left out;
|
||
// - an enum or const with no type gets the one its values have, or it and
|
||
// "null" ("type is not defined");
|
||
// - a $ref's target with no type gets the one its keywords or branches say
|
||
// ("detected infinite recursion without termination condition").
|
||
// A body Kimi takes as it is goes byte for byte; a rewrite is the same for
|
||
// the same tools, so a cached prefix stays one.
|
||
const isObj=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
||
const MAP_KEYS=['properties','$defs','definitions','dependentSchemas','patternProperties'];
|
||
const SUB_KEYS=['items','additionalProperties','contains','propertyNames','not','if','then','else','allOf','anyOf','oneOf','prefixItems','unevaluatedProperties','unevaluatedItems','contentSchema'];
|
||
const NOTES=new Set(['$ref','description','title','default','examples','$comment','deprecated','readOnly','writeOnly']);
|
||
const ALL_TYPES=['string','number','integer','boolean','object','array','null'];
|
||
|
||
function eachSchema(node,f) {
|
||
if(Array.isArray(node)) {for(const v of node)eachSchema(v,f);return;}
|
||
if(!isObj(node))return;
|
||
f(node);
|
||
for(const k of MAP_KEYS) if(isObj(node[k])) for(const v of Object.values(node[k])) eachSchema(v,f);
|
||
for(const k of SUB_KEYS) if(k in node) eachSchema(node[k],f);
|
||
}
|
||
|
||
function refTarget(root,ref) {
|
||
if(typeof ref!=='string'||(ref!=='#'&&!ref.startsWith('#/')))return undefined;
|
||
let cur=root;
|
||
for(let tok of ref.split('/').slice(1)) {
|
||
tok=tok.replace(/~1/g,'/').replace(/~0/g,'~');
|
||
try{tok=decodeURIComponent(tok);}catch{}
|
||
if(!isObj(cur)&&!Array.isArray(cur))return undefined;
|
||
if(!Object.hasOwn(cur,tok))return undefined;
|
||
cur=cur[tok];
|
||
}
|
||
return cur;
|
||
}
|
||
|
||
const hasRefInside=s=>JSON.stringify(s).includes('"$ref"');
|
||
|
||
function valueType(v) {
|
||
if(v===null)return 'null';
|
||
switch(typeof v){
|
||
case 'string':return 'string';
|
||
case 'boolean':return 'boolean';
|
||
case 'number':return Number.isInteger(v)?'integer':'number';
|
||
}
|
||
return Array.isArray(v)?'array':'object';
|
||
}
|
||
|
||
// the type an enum of vals is given: the one all non-null values have, with
|
||
// "null" when a null is among them; undefined when there are none or they
|
||
// are of more than one kind
|
||
function enumType(vals) {
|
||
let t,nul=false;
|
||
for(const v of vals) {
|
||
const vt=valueType(v);
|
||
if(vt==='null'){nul=true;continue;}
|
||
if(vt==='array'||vt==='object')return undefined;
|
||
if(t===undefined||t===vt)t=vt;
|
||
else if((t==='integer'&&vt==='number')||(t==='number'&&vt==='integer'))t='number';
|
||
else return undefined;
|
||
}
|
||
if(t===undefined)return undefined;
|
||
return nul?[t,'null']:t;
|
||
}
|
||
|
||
// the types s can have, as its type, keywords, values or branches say;
|
||
// undefined when they don't say
|
||
function schemaTypes(root,s,depth=0) {
|
||
if(depth>16||!isObj(s))return undefined;
|
||
if('type' in s)return new Set([].concat(s.type).map(String));
|
||
if('$ref' in s){const t=refTarget(root,s.$ref);return t===undefined?undefined:schemaTypes(root,t,depth+1);}
|
||
if(Array.isArray(s.enum)||'const' in s)return new Set(('const' in s?[s.const]:s.enum).map(valueType));
|
||
for(const k of ['oneOf','anyOf','allOf']) {
|
||
if(!Array.isArray(s[k]))continue;
|
||
const ts=new Set();
|
||
for(const b of s[k]) {
|
||
const bt=schemaTypes(root,b,depth+1);
|
||
if(!bt){if(k!=='allOf')return undefined;continue;}
|
||
for(const t of bt)ts.add(t);
|
||
}
|
||
if(ts.size)return ts;
|
||
}
|
||
const has=(...ks)=>ks.some(k=>k in s);
|
||
if(has('properties','required','additionalProperties','patternProperties','minProperties','maxProperties','propertyNames','dependentRequired','dependentSchemas','unevaluatedProperties'))return new Set(['object']);
|
||
if(has('items','prefixItems','minItems','maxItems','uniqueItems','contains','unevaluatedItems'))return new Set(['array']);
|
||
if(has('minLength','maxLength','pattern','format','contentEncoding','contentMediaType'))return new Set(['string']);
|
||
if(has('minimum','maximum','exclusiveMinimum','exclusiveMaximum','multipleOf'))return new Set(['number']);
|
||
return undefined;
|
||
}
|
||
|
||
function typeFor(root,s) {
|
||
if(Array.isArray(s.enum))return enumType(s.enum);
|
||
if('const' in s)return enumType([s.const]);
|
||
const ts=schemaTypes(root,s);
|
||
if(!ts||!ts.size)return [...ALL_TYPES];
|
||
if(ts.has('integer')&&ts.has('number'))ts.delete('integer');
|
||
const names=ALL_TYPES.filter(t=>ts.has(t));
|
||
return names.length===1?names[0]:names;
|
||
}
|
||
|
||
// the same object with type written first, as an agent would have
|
||
const withType=(s,type)=>{const rest={...s};delete rest.type;for(const k of Object.keys(s))delete s[k];Object.assign(s,{type},rest);};
|
||
|
||
function moonshotSchema(root) {
|
||
let changed=false;
|
||
// a $ref beside a type, and a type beside an anyOf
|
||
eachSchema(root,s=>{
|
||
if('$ref' in s&&'type' in s) {
|
||
const t=refTarget(root,s.$ref);
|
||
if(isObj(t)&&!hasRefInside(t)) {
|
||
const own={...s};delete own.$ref;
|
||
for(const k of Object.keys(s))delete s[k];
|
||
Object.assign(s,structuredClone(t),own);
|
||
} else delete s.type;
|
||
changed=true;
|
||
}
|
||
if(Array.isArray(s.anyOf)&&'type' in s){delete s.type;changed=true;}
|
||
});
|
||
// an enum or const with no type
|
||
eachSchema(root,s=>{
|
||
if('type' in s||!(Array.isArray(s.enum)||'const' in s))return;
|
||
const t=enumType(Array.isArray(s.enum)?s.enum:[s.const]);
|
||
if(t!==undefined){withType(s,t);changed=true;}
|
||
});
|
||
// a $ref's target with no type
|
||
eachSchema(root,s=>{
|
||
if(typeof s.$ref!=='string')return;
|
||
const t=refTarget(root,s.$ref);
|
||
if(!isObj(t)||'type' in t||'anyOf' in t||'$ref' in t||!Object.keys(t).length)return;
|
||
const typ=typeFor(root,t);
|
||
if(typ!==undefined){withType(t,typ);changed=true;}
|
||
});
|
||
return changed;
|
||
}
|
||
|
||
// body with each tool's parameters as Kimi takes them; the same string when
|
||
// nothing had to change or it isn't a chat body with tools
|
||
function moonshotTools(body) {
|
||
if(typeof body!=='string'||!body.includes('"tools"'))return body;
|
||
let doc;
|
||
try{doc=JSON.parse(body);}catch{return body;}
|
||
if(!isObj(doc)||!Array.isArray(doc.tools))return body;
|
||
let changed=false;
|
||
for(const tool of doc.tools) {
|
||
const p=tool?.function?.parameters;
|
||
if(isObj(p)&&moonshotSchema(p))changed=true;
|
||
}
|
||
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};
|
||
}
|
||
|
||
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) {
|
||
const reader=new Response(body).body.getReader(),decoder=new TextDecoder();
|
||
const abort=()=>{void reader.cancel(signal.reason).catch(()=>{});};
|
||
signal?.addEventListener('abort',abort,{once:true});
|
||
try {
|
||
if(signal?.aborted)abort();
|
||
let text='';
|
||
for(;;) {
|
||
signal?.throwIfAborted();
|
||
const {done,value}=await reader.read();
|
||
signal?.throwIfAborted();
|
||
if(done)return text+decoder.decode();
|
||
text+=decoder.decode(value,{stream:true});
|
||
}
|
||
} finally {
|
||
signal?.removeEventListener('abort',abort);
|
||
reader.releaseLock();
|
||
}
|
||
}
|
||
|
||
const readSmall=file=>{if(fs.statSync(file).size>64*1024)throw Error('too large');return fs.readFileSync(file,'utf8');};
|
||
// Kimi's userData (Electron's, named for the package "kimi-desktop").
|
||
function userDataDir({home=os.homedir(), platform=process.platform, appdata=process.env.APPDATA}={}) {
|
||
const P=platform==='win32'?path.win32:path.posix;
|
||
const parent=platform==='win32' ? appdata || P.join(home,'AppData','Roaming')
|
||
: platform==='darwin' ? P.join(home,'Library','Application Support') : P.join(home,'.config');
|
||
return P.join(parent,'kimi-desktop');
|
||
}
|
||
// Where Kimi keeps daimon-share, as Kimi 3.2.21 finds it: the shareDir
|
||
// <userData>/daimon-storage.json names ({"version":1,"shareDir":<absolute>}),
|
||
// else <userData>/daimon-share. On Windows Kimi writes that pointer for a
|
||
// new user who installed it on another drive than %APPDATA%'s
|
||
// (D:\KimiData\daimon-share), and on any system when the user moves its
|
||
// storage. A pointer Kimi itself wouldn't take (unreadable, not JSON, not
|
||
// an absolute path) leaves the default, as it does in Kimi (#425).
|
||
function shareDir(opts={}) {
|
||
const P=(opts.platform??process.platform)==='win32'?path.win32:path.posix, data=userDataDir(opts);
|
||
try {
|
||
const dir=JSON.parse((opts.read??readSmall)(P.join(data,'daimon-storage.json')).replace(/^\uFEFF/,''))?.shareDir;
|
||
if(typeof dir==='string'&&dir.trim()&&P.isAbsolute(dir))return P.resolve(dir);
|
||
} catch {}
|
||
return P.join(data,'daimon-share');
|
||
}
|
||
function desktopFile(opts={}) {
|
||
const P=(opts.platform??process.platform)==='win32'?path.win32:path.posix;
|
||
return P.join(shareDir(opts),'daimon','config.json');
|
||
}
|
||
|
||
// The install id Kimi's daimon made for its Kimi Code home
|
||
// (<daimon>/runtime/kimi-code/home/device_id, a randomUUID it writes once)
|
||
// and sends as X-Msh-Device-Id. It is read, never made or written here: the
|
||
// desktop app owns it, and without it the header is left out.
|
||
function readDeviceId(file) {
|
||
try {
|
||
const id=fs.readFileSync(path.join(path.dirname(file),'runtime','kimi-code','home','device_id'),'utf8').trim();
|
||
return /^[\x21-\x7e]{1,128}$/.test(id)?id:undefined;
|
||
} catch {return undefined;}
|
||
}
|
||
|
||
const accountUid = userId => createHash('sha256').update('kimi-work-account\0'+userId).digest('hex');
|
||
// The Work keys Kimi minted, one per Kimi user that has used Work on this
|
||
// computer: <daimon>/kimi-code-key.json, {"v":2,"keys":[{userId,apiKey,
|
||
// keyId?}]}, the user in use first (Kimi 3.2.21's DaimonProvision). Kimi
|
||
// keeps a user's entry when it switches to another user, and reuses it when
|
||
// it switches back; it drops one only when agent-gw answers it 401. So an
|
||
// account Kimi has switched away from still has its key here (#440). Read
|
||
// as Kimi reads it: any other version, or an entry without both strings,
|
||
// is none. Keyed by the account's hashed uid; the first entry for a user
|
||
// wins, as Kimi's find does.
|
||
function readKeys(file) {
|
||
const out=Object.create(null);
|
||
try {
|
||
if(fs.statSync(file).size>1024*1024)return out;
|
||
const doc=JSON.parse(fs.readFileSync(file,'utf8').replace(/^\uFEFF/,''));
|
||
if(doc?.v!==2||!Array.isArray(doc.keys))return out;
|
||
for(const k of doc.keys)
|
||
if(typeof k?.userId==='string'&&k.userId&&typeof k.apiKey==='string'&&k.apiKey)out[accountUid(k.userId)]??=k.apiKey;
|
||
} catch {}
|
||
return out;
|
||
}
|
||
|
||
// A Windows path is taken apart as one wherever the plugin runs (tests).
|
||
const pathOf = f => /^(?:[A-Za-z]:[\\/]|\\\\)/.test(f)?path.win32:path;
|
||
|
||
function desktopCredentials(doc) {
|
||
const work=doc?.credentials?.kimiCode, web=doc?.credentials?.kimiWeb;
|
||
if(typeof work?.apiKey!=='string'||!work.apiKey || typeof web?.accessToken!=='string'||!web.accessToken
|
||
|| typeof web.userId!=='string'||!web.userId || work.baseUrl?.replace(/\/$/,'')!==BASE) throw expired();
|
||
return {workToken:work.apiKey,webToken:web.accessToken,
|
||
webRefresh:typeof web.refreshToken==='string' ? web.refreshToken : '',uid:accountUid(web.userId)};
|
||
}
|
||
// Read a local account's Work credentials live. Only explicit sign-in or file
|
||
// import copies credentials; reference-only usage rereads its web access token.
|
||
// Kimi owns these files; this plugin never writes them.
|
||
function readDesktop(file=desktopFile()) {
|
||
const P=pathOf(file),daimon=P.dirname(file),share=P.dirname(daimon);
|
||
if(!fs.existsSync(file)) {
|
||
if(!fs.existsSync(share))throw shareMissing(share);
|
||
throw Object.assign(expired(),{file,missing:true});
|
||
}
|
||
try {
|
||
const st=fs.statSync(file);
|
||
if(!st.isFile() || st.size>8*1024*1024) throw expired();
|
||
const doc=JSON.parse(fs.readFileSync(file,'utf8').replace(/^\uFEFF/,''));
|
||
return {...desktopCredentials(doc),deviceId:readDeviceId(file),keys:readKeys(P.join(daimon,'kimi-code-key.json'))};
|
||
} catch {throw Object.assign(expired(),{file});}
|
||
}
|
||
function parseDesktopImport(text) {
|
||
try {
|
||
if(typeof text!=='string'||Buffer.byteLength(text)>8*1024*1024)throw Error('invalid import');
|
||
return desktopCredentials(JSON.parse(text.replace(/^\uFEFF/,'')));
|
||
} catch {throw Error('文件不是有效的 Kimi Work daimon/config.json,未找到可用的 Work 和会员凭据。');}
|
||
}
|
||
|
||
function modelRows(payload) {
|
||
if(!Array.isArray(payload?.data)||payload.has_more||payload.data.length>100) throw Error('Kimi Work 模型目录暂不可用。');
|
||
const out={};
|
||
for(const m of payload.data) {
|
||
if(!isObj(m)||typeof m.id!=='string'||!m.id||m.id.length>256||/[\x00-\x20/]/.test(m.id)) continue;
|
||
// One model's effort list in a shape not seen before costs that model
|
||
// its unreadable levels, not the account its whole catalog: a throw
|
||
// here left only the fallback k3-agent listed. Only levels Kimi lists
|
||
// are kept, so none is guessed.
|
||
const variants=Object.create(null);
|
||
for(const x of Array.isArray(m.reasoningEffortOptions)?m.reasoningEffortOptions:[]) {
|
||
const effort=String(isObj(x)&&typeof x.effort==='string'?x.effort:'').replace(/^REASONING_EFFORT_/,'').toLowerCase();
|
||
if(/^[a-z][a-z0-9_-]{0,63}$/.test(effort))variants[effort]={reasoningEffort:effort};
|
||
}
|
||
out[m.id]={id:m.id,name:m.display_name||m.id,
|
||
api:{id:m.id,url:BASE,npm:'@ai-sdk/openai-compatible'},
|
||
// The server lists the plan's maximum XL context; default to standard
|
||
// context rather than silently asking for a more expensive XL session.
|
||
limit:{context:Math.min(Number(m.context_length)||262144,262144),output:32768},
|
||
capabilities:{reasoning:!!m.supports_reasoning,toolcall:true,attachment:!!m.supports_image_in,
|
||
input:{text:true,image:!!m.supports_image_in,video:false,audio:false,pdf:false},output:{text:true}},
|
||
variants};
|
||
}
|
||
if(!Object.keys(out).length)throw Error('Kimi Work 模型目录为空。');
|
||
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;
|
||
function planConcurrency(plan) {
|
||
const name=String(pick(plan,'name','name')??'').trim().toLowerCase();
|
||
const level=String(pick(plan,'level','level')??'').trim().toUpperCase();
|
||
const names={free:1,andante:1,go:1,moderato:2,plus:2,allegretto:2,pro:2,allegro:4,max:4,ultra:4};
|
||
const levels={LEVEL_BASIC:2,LEVEL_INTERMEDIATE:2,LEVEL_ADVANCED:4};
|
||
const known=[names[name],levels[level]].filter(Number.isInteger);
|
||
return known.length?Math.min(...known):1;
|
||
}
|
||
function planName(plan) {
|
||
const name=String(pick(plan,'name','name')??'').trim();
|
||
if(name)return name;
|
||
const level=String(pick(plan,'level','level')??'').trim().toUpperCase();
|
||
return {LEVEL_BASIC:'Basic',LEVEL_INTERMEDIATE:'Intermediate',LEVEL_ADVANCED:'Advanced'}[level]||'';
|
||
}
|
||
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={},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');
|
||
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;
|
||
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'},
|
||
// 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},
|
||
capabilities:{reasoning:thinking,toolcall:true,attachment:image,
|
||
input:{text:true,image,video:false,audio:false,pdf:false},output:{text:true}},
|
||
variants};
|
||
}
|
||
// After the loop: a model Kimi itself calls <id>-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;
|
||
}
|
||
|
||
function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platform=process.platform,now=Date.now}={}) {
|
||
// An imported account uses its saved Work key. A local account uses Kimi's
|
||
// own sign-in when current, else its Work key from Kimi's key store, with no
|
||
// web sign-in (Kimi keeps only the current user's), so its allowance
|
||
// can't be read (#440).
|
||
const current=auth=>{
|
||
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,
|
||
deviceId:importedDeviceId(auth.deviceId,auth.uid),imported:true};
|
||
}
|
||
const session=readSession();
|
||
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: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',
|
||
headers:{...(token?{Authorization:'Bearer '+token}:{}),...(url===REFRESH?refreshHeaders(platform):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 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 响应格式无效。');}
|
||
}
|
||
// Only auth.refresh rotates. Magpie commits its return value under the auth
|
||
// store lock, checking that the original access/refresh pair still stands.
|
||
// A plugin-side getAuth + auth.set cannot make that check atomic.
|
||
// Remember rotations after a failed host save, by exact input pair rather
|
||
// than uid: a reconnect can have the same uid and independent credentials.
|
||
const renewing=new Map(), renewed=new Map();
|
||
const valid=auth=>auth?.source==='kimi-work-desktop' && typeof auth.uid==='string' && !!auth.uid;
|
||
const hasPair=auth=>valid(auth) && typeof auth.access==='string' && !!auth.access
|
||
&& typeof auth.refresh==='string' && !!auth.refresh;
|
||
const credentialKey=auth=>JSON.stringify([auth.uid,auth.access,auth.refresh]);
|
||
const latest=auth=>{
|
||
const seen=new Set();let a=auth;
|
||
for(let key=credentialKey(a);renewed.has(key)&&!seen.has(key);key=credentialKey(a)) {
|
||
seen.add(key);a={...a,...renewed.get(key)};
|
||
}
|
||
return a;
|
||
};
|
||
const remember=(key,pair)=>{
|
||
// A server-expired replacement refresh token cannot recover that entry.
|
||
for(const [k,v] of renewed) {
|
||
const until=expiry(v.refresh);
|
||
if(until>0 && until<=now())renewed.delete(k);
|
||
}
|
||
renewed.set(key,pair);
|
||
};
|
||
const due=auth=>auth.expires>0 && auth.expires<=now()+REFRESH_LEAD;
|
||
async function renew(auth) {
|
||
const a=latest(auth);
|
||
if(!due(a))return a;
|
||
// A reconnect is a new token lineage even when it has the same user id.
|
||
// It must not wait for (or inherit an error from) the previous login.
|
||
const key=credentialKey(a);
|
||
let run=renewing.get(key);
|
||
if(!run)run=(async()=>{
|
||
let j;
|
||
try {j=await jsonRequest(REFRESH,undefined,{refresh_token:a.refresh});}
|
||
catch(error) {
|
||
// Membership and Work have independent credentials. The host treats
|
||
// "expired" as the whole provider account lapsing, even if usage later
|
||
// says "kept". Throw a membership-only failure to retain retry backoff
|
||
// and the working Work key; reconnect remains an explicit action.
|
||
if(error?.status===401)throw Object.assign(Error('Kimi Work 会员登录续期被拒绝,请重新连接 Kimi Work(magpie plugin login kimi-work)以恢复自动续期。'),
|
||
{signIn:'kept',code:'kimi_work_membership_expired',status:401});
|
||
throw Error('Kimi Work 登录续期暂不可用,请稍后重试。');
|
||
}
|
||
const access=j?.access_token??j?.accessToken,refresh=j?.refresh_token??j?.refreshToken;
|
||
const expires=expiry(access),oldSub=tokenClaims(a.access).sub,newSub=tokenClaims(access).sub;
|
||
if(typeof access!=='string'||!access||typeof refresh!=='string'||!refresh||expires<=now()||!Number.isFinite(expires)
|
||
|| (oldSub && newSub && oldSub!==newSub))throw Error('Kimi Work 续期响应格式无效。');
|
||
return {access,refresh,expires};
|
||
})();
|
||
renewing.set(key,run);
|
||
try {
|
||
const pair=await run;
|
||
// Also advance an older stored input when its cached access token has
|
||
// expired during a continuing save failure. Its refresh must stay live.
|
||
remember(key,pair);
|
||
renewed.set(credentialKey(auth),pair);
|
||
return {...auth,...pair};
|
||
} finally {if(renewing.get(key)===run)renewing.delete(key);}
|
||
}
|
||
// A plan's Agent task allowance is one request lane in magpie. Keep the
|
||
// last good name and value if membership is temporarily unavailable, and
|
||
// never let this auxiliary read invalidate or block the Work credential.
|
||
const planLimits=new Map(),planRuns=new Map(),planFailures=new Map();
|
||
async function planDetails(getAuth,{signal}={}) {
|
||
const fallback=cached=>({value:cached?.value??1,name:cached?.name??''});
|
||
const auth=await getAuth();
|
||
if(!valid(auth))return fallback();
|
||
const uid=auth.uid,cached=planLimits.get(uid),at=now();
|
||
if(cached&&at-cached.at<PLAN_CACHE)return cached;
|
||
const failed=planFailures.get(uid);
|
||
if(failed!==undefined&&failed+PLAN_RETRY>at)return fallback(cached);
|
||
let run=planRuns.get(uid);
|
||
if(!run)run=(async()=>{
|
||
try {
|
||
let token;
|
||
if(hasPair(auth))token=auth.access;
|
||
else {
|
||
const s=current(auth);
|
||
if(s.away)return fallback(cached);
|
||
token=s.webToken;
|
||
}
|
||
if(!token)return fallback(cached);
|
||
const j=await jsonRequest(MEMBER+'GetSubscription',token,{},signal);
|
||
const subscription=pick(j,'subscription','subscription'),plan=pick(subscription,'plan','plan');
|
||
const details={value:planConcurrency(plan),name:planName(plan),at:now()};
|
||
planLimits.set(uid,details);planFailures.delete(uid);
|
||
return details;
|
||
} catch(error) {
|
||
planFailures.set(uid,now());
|
||
console.warn('kimi-work: GetSubscription failed ('+(error?.status?'HTTP '+error.status:error?.message||String(error))+'); using the last known plan details');
|
||
return fallback(cached);
|
||
}
|
||
})();
|
||
planRuns.set(uid,run);
|
||
try{return await run;}finally{if(planRuns.get(uid)===run)planRuns.delete(uid);}
|
||
}
|
||
async function accountConcurrency(getAuth,options) {
|
||
return (await planDetails(getAuth,options)).value;
|
||
}
|
||
async function accountPlan(getAuth,options) {
|
||
return (await planDetails(getAuth,options)).name;
|
||
}
|
||
// 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,auth) {
|
||
let why='no web sign-in';
|
||
// 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,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));}
|
||
}
|
||
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;
|
||
}
|
||
}
|
||
// 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(),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 rows=await menu(s,auth).catch(()=>({}));
|
||
rememberModels(s.uid,rows);
|
||
return offered.get(s.uid);
|
||
}
|
||
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,deviceId:importedDeviceId(deviceId,s.uid)}:{})};
|
||
}
|
||
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,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,deviceId);
|
||
}
|
||
async function importFiles(texts,signal) {
|
||
const out=[];
|
||
for(const text of Array.isArray(texts)?texts:[texts]) {
|
||
signal?.throwIfAborted();
|
||
out.push(await importFile(text,signal));
|
||
}
|
||
return out;
|
||
}
|
||
return {
|
||
config:async cfg=>{
|
||
cfg.provider??={};
|
||
cfg.provider[ID]??={name:'Kimi Work',npm:'@ai-sdk/openai-compatible',api:BASE,
|
||
// Shown until the account's own list is read, and kept when it can't
|
||
// be: the two ids Work's /models has listed (tests/fixtures).
|
||
models:{'k3-agent':{name:'K3 · Work',limit:{context:262144,output:32768},tool_call:true,reasoning:true},
|
||
'k2d8-preview':{name:'K2.8 Preview · Work',limit:{context:262144,output:32768},tool_call:true,reasoning:true}}};
|
||
},
|
||
auth:{
|
||
provider:ID,
|
||
maxConcurrency:1,
|
||
accountConcurrency,
|
||
accountPlan,
|
||
importFrom:IMPORT_FROM.en,
|
||
importFroms:IMPORT_FROM.froms,
|
||
import:(texts,{signal}={})=>importFiles(texts,signal),
|
||
methods:[{type:'oauth',label:'使用本机 Kimi Work 登录',authorize:async()=>({
|
||
url:'',method:'auto',instructions:'读取本机 Kimi Work 登录;支持会员续期,不修改桌面配置。',
|
||
callback:async()=>{
|
||
let s;
|
||
try{s=readSession();}
|
||
catch(error){
|
||
// Which file was read goes in the message, so a report says
|
||
// where Kimi's sign-in was looked for (#425); never a value.
|
||
if(error?.shareMissing)return {type:'failed',error:error.message};
|
||
return {type:'failed',error:'没有可用的本机 Kimi Work 登录,请先打开 Kimi 并登录 Work。'
|
||
+(error?.file?(error.missing?'(未找到 ':'(无法读取 ')+error.file+')':'')};
|
||
}
|
||
try{await jsonRequest(BASE+'/models',s.workToken,undefined,undefined,s.deviceId);}
|
||
catch(error){
|
||
if(error?.status===401)return {type:'failed',error:'本机 Kimi Work 登录已过期,请打开 Kimi 桌面版进入 Work 刷新登录后再试。'};
|
||
const why=error?.status?'HTTP '+error.status:error?.name==='TimeoutError'?'超时':error?.cause?.code||error?.message||'未知网络错误';
|
||
return {type:'failed',error:'已找到本机 Kimi Work 登录,但连接 Kimi Work 失败('+why+'),请检查网络后再试。'};
|
||
}
|
||
// A user keeps a separate account id (#440). Import a complete web
|
||
// pair when available; older desktops still get a reference account.
|
||
return signedIn(s);
|
||
},
|
||
})},{
|
||
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 的内容'},
|
||
{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,inputs?.deviceId?.trim()||undefined),
|
||
}),
|
||
}],
|
||
refreshLead:REFRESH_LEAD,
|
||
async refresh(auth) {
|
||
if(!hasPair(auth))return;
|
||
const next=await renew(auth);
|
||
if(next.access!==auth.access || next.refresh!==auth.refresh)
|
||
return {access:next.access,refresh:next.refresh,expires:next.expires};
|
||
},
|
||
loader:async getAuth=>({
|
||
baseURL:BASE,apiKey:'local-desktop-session',
|
||
async fetch(input,init={}) {
|
||
const request=input instanceof Request?new Request(input,init):null;
|
||
const url=new URL(request?request.url:String(input));
|
||
if(url.origin!==new URL(BASE).origin||url.pathname!=='/coding/v1/chat/completions'
|
||
||url.username||url.password||url.search||url.hash||(request?.method||init.method||'POST')!=='POST') {
|
||
throw Error('Kimi Work 仅接受官方 Work 网关的模型请求。');
|
||
}
|
||
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.
|
||
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
|
||
// fallback to api.kimi.com, a Code API key, or another provider.
|
||
const signal=request?request.signal:init.signal;
|
||
const raw=request?request.body:init.body;
|
||
let body=raw;
|
||
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=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;
|
||
let response;
|
||
try { response=await fetchImpl(BASE+'/chat/completions',{...options,method:'POST',headers,redirect:'error'}); }
|
||
catch(error) { if(options.signal?.aborted)throw error; throw unavailable(error); }
|
||
if(response.status===401) { await response.body?.cancel(); throw s.imported?importExpired():s.away?notHere(true):expired(); }
|
||
// Kimi says a spent allowance with a 403 ("You've reached your
|
||
// usage limit for this billing cycle", resource_exhausted
|
||
// "insufficient balance"), which magpie reads as a key fault and
|
||
// keeps sending to the spent account (#465). Like Devin's and
|
||
// Qoder's, a spent quota goes out as a 429, so magpie rests that
|
||
// account and asks the next; Kimi's body and headers are kept.
|
||
if(response.status===403) {
|
||
const text=await response.text(),spent=spentQuota(text),h=new Headers(response.headers);
|
||
// The text is already decoded: its old length and encoding no longer hold.
|
||
h.delete('content-encoding');h.delete('content-length');
|
||
return new Response(text,{status:spent?429:403,statusText:spent?'Too Many Requests':response.statusText,headers:h});
|
||
}
|
||
// Magpie classifies rate vs quota from the upstream response. Keep
|
||
// its wording, reset details and Retry-After instead of guessing.
|
||
return response;
|
||
},
|
||
}),
|
||
// Paired accounts use the host's saved access token. Reference-only
|
||
// accounts keep upstream's read-only desktop path, without migration or
|
||
// refresh consumption; away accounts never borrow the current user's web
|
||
// sign-in. Membership failures leave the independent Work key usable.
|
||
usage:async getAuth=>{
|
||
const auth=await getAuth(),paired=hasPair(auth),plan='月度共享额度';
|
||
let token;
|
||
if(paired)token=auth.access;
|
||
else {
|
||
const s=current(auth);
|
||
if(s.away)return {plan,windows:[],error:'这个账号不是 Kimi 桌面版当前登录的账号,切换到它后才能读取会员额度(对话不受影响)',signIn:'kept'};
|
||
token=s.webToken;
|
||
}
|
||
let j;
|
||
try {j=await jsonRequest(MEMBER+'GetSubscriptionStats',token,{});}
|
||
catch(error) {
|
||
const why=error?.status===401?(paired
|
||
? 'Kimi 会员登录已过期,请重新连接 Kimi Work 以恢复额度读取(对话不受影响)'
|
||
: 'Kimi 网页登录已过期,打开一次 Kimi 桌面版即可刷新额度(对话不受影响)')
|
||
:error?.name==='TimeoutError'?'读取 Kimi 会员额度超时':String(error?.message||error);
|
||
console.warn('kimi-work: GetSubscriptionStats failed ('+(error?.status?'HTTP '+error.status:why)+')');
|
||
return {plan,windows:[],error:why,signIn:'kept'};
|
||
}
|
||
// Connect JSON leaves a zero out: a balance with no ratio is 0% used.
|
||
const b=pick(j,'subscriptionBalance','subscription_balance'),used=isObj(b)?percent(pick(b,'amountUsedRatio','amount_used_ratio')??0):undefined;
|
||
if(used===undefined)return {plan,windows:[],error:'Kimi 会员额度回复里没有共享额度(subscriptionBalance)',signIn:'kept'};
|
||
const windows=[{name:'本月',used}],code=percent(pick(b,'kimiCodeUsedRatio','kimi_code_used_ratio'));
|
||
// Code is a share of the same pool, not a second remaining allowance.
|
||
if(code!==undefined)windows[0].display='Code 已用 '+Number(code.toFixed(2))+'%(占总额)';
|
||
return {plan,windows};
|
||
},
|
||
},
|
||
provider:{id:ID,models:async(provider,{auth}={})=>{
|
||
if(auth?.source!=='kimi-work-desktop')return provider.models;
|
||
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([
|
||
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')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
|
||
// 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,...(out[id].serviceTiers?FAST_ROW:{})}:row;
|
||
return out;
|
||
}},
|
||
};
|
||
}
|
||
|
||
export default async function KimiWorkProvider(){return createPlugin();}
|
||
export const _internal={createPlugin,planConcurrency,planName,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};
|