kimi-work: apply each account plan concurrency
Report each account Agent-task limit through auth.accountConcurrency, with five-minute caching, per-account credentials, failure retention and manual override documentation. Verification: node --check packages/kimi-work/index.mjs; npx --yes bun test packages/kimi-work (123 pass, 0 fail, 599 assertions); npx --yes bun scripts/check.mjs kimi-work. The six new concurrency tests fail on 0.1.19 because planConcurrency and the hook are absent. The repository-wide Bun run also completed but is not green on this Windows checkout because of unrelated CRLF, symlink permission, process cleanup and other package failures.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
# Kimi Work 0.1.15 compatibility
|
||||
# Kimi Work 0.1.20 compatibility
|
||||
|
||||
## Scope
|
||||
|
||||
@@ -6,6 +6,12 @@ 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.
|
||||
|
||||
## Plan-based concurrency (0.1.20)
|
||||
|
||||
`auth.accountConcurrency` reads `MembershipService/GetSubscription` with the account's own membership access and maps its `subscription.plan` to the Agent-task limits: Free/Andante/Go 1, Moderato/Plus and Allegretto/Pro 2, Allegro/Max/Ultra 4. The observed `LEVEL_BASIC` and `LEVEL_INTERMEDIATE` values map to 2 and `LEVEL_ADVANCED` to 4; no other numeric enum is guessed. A name/level conflict uses the smaller value. Unknown plans, missing tokens and failed reads use 1 unless a last successful value is available.
|
||||
|
||||
Values are cached by UID for five minutes, failures back off for one minute, and same-account concurrent reads share one request. A reference-only account uses the desktop token only while it is the current desktop user; an away account returns its cached value or 1. This auxiliary read does not rotate or invalidate credentials and does not alter inference errors. Magpie applies account manual, provider manual, account automatic, then static default 1, in that order. The synthetic tests cover every mapping, per-account tokens, caching, request coalescing, failure retention and away-account isolation; they do not establish a new upstream concurrency entitlement beyond the observed plan table.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -9,6 +9,10 @@ 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.20** reports each account's Agent-task concurrency to Magpie through `auth.accountConcurrency`. Free, Andante and Go allow 1; Moderato/Plus and Allegretto/Pro allow 2; Allegro/Max and Ultra allow 4. The known numeric plan levels map Basic and Intermediate to 2 and Advanced to 4. If a name and level disagree, the smaller limit wins; an unknown plan or unavailable membership read falls back to 1, with the last successful value retained during temporary failures. Successful plan reads are cached per UID for five minutes, failures back off for one minute, and concurrent reads share one request. An away reference-only desktop account never borrows the current desktop user's membership token.
|
||||
|
||||
Magpie's precedence is **account manual limit → provider-wide manual limit → account plan value → plugin default 1**. Leave the provider's **Requests at once** field empty for plan-based automatic limits, or enter a number to override every account. Each account's own concurrency menu can override either setting; choosing **Automatic** removes only that account override. The automatic hook requires the matching Magpie core update; older Magpie versions continue using the plugin's static default of 1.
|
||||
|
||||
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.
|
||||
@@ -94,4 +98,4 @@ bun test packages/kimi-work
|
||||
bun scripts/check.mjs kimi-work
|
||||
```
|
||||
|
||||
Tests use synthetic sessions and fake HTTP responses: credential separation/rotation, read-only compatibility for reference-only accounts, concurrent renewal by credential lineage, host-save retry recovery, process restart, rejected/transient refreshes, read-only local import/usage, account changes, endpoint restrictions, streaming/tool preservation, model discovery and monthly shared-usage accounting. No account, token, prompt, conversation or vendor binary is distributed. No runtime dependencies.
|
||||
Tests use synthetic sessions and fake HTTP responses: credential separation/rotation, read-only compatibility for reference-only accounts, concurrent renewal by credential lineage, host-save retry recovery, process restart, rejected/transient refreshes, read-only local import/usage, account changes, endpoint restrictions, streaming/tool preservation, model discovery, monthly shared-usage accounting, and per-account plan concurrency with cache/failure behavior. No account, token, prompt, conversation or vendor binary is distributed. No runtime dependencies.
|
||||
|
||||
@@ -8,6 +8,8 @@ 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
|
||||
@@ -500,6 +502,14 @@ function modelRows(payload) {
|
||||
// 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;
|
||||
}
|
||||
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'):[]),
|
||||
@@ -643,6 +653,42 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo
|
||||
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 value if membership is temporarily unavailable, and never let
|
||||
// this auxiliary read invalidate or block the independent Work credential.
|
||||
const planLimits=new Map(),planRuns=new Map(),planFailures=new Map();
|
||||
async function accountConcurrency(getAuth,{signal}={}) {
|
||||
const auth=await getAuth();
|
||||
if(!valid(auth))return 1;
|
||||
const uid=auth.uid,cached=planLimits.get(uid),at=now();
|
||||
if(cached&&at-cached.at<PLAN_CACHE)return cached.value;
|
||||
const failed=planFailures.get(uid);
|
||||
if(failed!==undefined&&failed+PLAN_RETRY>at)return cached?.value??1;
|
||||
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 cached?.value??1;
|
||||
token=s.webToken;
|
||||
}
|
||||
if(!token)return cached?.value??1;
|
||||
const j=await jsonRequest(MEMBER+'GetSubscription',token,{},signal);
|
||||
const subscription=pick(j,'subscription','subscription'),plan=pick(subscription,'plan','plan');
|
||||
const value=planConcurrency(plan);
|
||||
planLimits.set(uid,{value,at:now()});planFailures.delete(uid);
|
||||
return value;
|
||||
} 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 concurrency');
|
||||
return cached?.value??1;
|
||||
}
|
||||
})();
|
||||
planRuns.set(uid,run);
|
||||
try{return await run;}finally{if(planRuns.get(uid)===run)planRuns.delete(uid);}
|
||||
}
|
||||
// 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
|
||||
@@ -727,6 +773,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo
|
||||
auth:{
|
||||
provider:ID,
|
||||
maxConcurrency:1,
|
||||
accountConcurrency,
|
||||
importFrom:IMPORT_FROM.en,
|
||||
importFroms:IMPORT_FROM.froms,
|
||||
import:(texts,{signal}={})=>importFiles(texts,signal),
|
||||
@@ -879,4 +926,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,capOutputTokens,stableDeviceId,readDesktop,readKeys,desktopFile,shareDir,userDataDir,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA,workHeaders,webHeaders,refreshHeaders,readDeviceId,REFRESH,REFRESH_LEAD,expiry};
|
||||
export const _internal={createPlugin,planConcurrency,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};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-kimi-work-auth",
|
||||
"version": "0.1.19",
|
||||
"version": "0.1.20",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
"files": [
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import {test,expect} from 'bun:test';
|
||||
import {_internal as I} from '../index.mjs';
|
||||
|
||||
const auth=(uid,token='web-'+uid)=>({source:'kimi-work-desktop',uid,access:token,refresh:'refresh-'+uid,expires:0});
|
||||
const reply=plan=>Response.json({subscription:{plan}});
|
||||
|
||||
test('every current and legacy Kimi Work plan maps to its Agent task concurrency',()=>{
|
||||
const cases=[
|
||||
[{name:'Free'},1],[{name:'Andante'},1],[{name:'Go'},1],
|
||||
[{name:'Moderato'},2],[{name:'Plus'},2],
|
||||
[{name:'Allegretto'},2],[{name:'Pro'},2],
|
||||
[{name:'Allegro'},4],[{name:'Max'},4],[{name:'Ultra'},4],
|
||||
[{level:'LEVEL_BASIC'},2],[{level:'LEVEL_INTERMEDIATE'},2],[{level:'LEVEL_ADVANCED'},4],
|
||||
[{level:'LEVEL_ADVANCED',name:'Moderato'},2],
|
||||
[{level:'LEVEL_FUTURE',name:'Unannounced'},1],[{},1],[null,1],
|
||||
];
|
||||
for(const [plan,want] of cases)expect(I.planConcurrency(plan)).toBe(want);
|
||||
});
|
||||
|
||||
test('each account reads its own subscription and caches a successful result for five minutes',async()=>{
|
||||
let clock=1000;const calls=[];
|
||||
const p=I.createPlugin({now:()=>clock,fetchImpl:async(url,init)=>{
|
||||
calls.push({url,token:new Headers(init.headers).get('authorization')});
|
||||
const token=new Headers(init.headers).get('authorization');
|
||||
return reply(token==='Bearer web-a'?{name:'Moderato'}:{name:'Allegro'});
|
||||
}});
|
||||
const [a,b]=await Promise.all([
|
||||
p.auth.accountConcurrency(async()=>auth('a')),
|
||||
p.auth.accountConcurrency(async()=>auth('b')),
|
||||
]);
|
||||
expect([a,b]).toEqual([2,4]);
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls.every(c=>c.url===I.MEMBER+'GetSubscription')).toBe(true);
|
||||
clock+=4*60*1000;
|
||||
expect(await p.auth.accountConcurrency(async()=>auth('a'))).toBe(2);
|
||||
expect(calls).toHaveLength(2);
|
||||
clock+=60*1000;
|
||||
expect(await p.auth.accountConcurrency(async()=>auth('a'))).toBe(2);
|
||||
expect(calls).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('concurrent reads for one account share one subscription request',async()=>{
|
||||
let calls=0,release;const held=new Promise(resolve=>{release=resolve;});
|
||||
const p=I.createPlugin({fetchImpl:async()=>{calls++;await held;return reply({name:'Plus'});}});
|
||||
const reads=Promise.all(Array.from({length:8},()=>p.auth.accountConcurrency(async()=>auth('same'))));
|
||||
await new Promise(resolve=>setTimeout(resolve,0));release();
|
||||
expect(await reads).toEqual(Array(8).fill(2));expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
test('a failed refresh keeps the last known limit, and an unknown account stays at one',async()=>{
|
||||
let clock=0,fail=false,calls=0;
|
||||
const p=I.createPlugin({now:()=>clock,fetchImpl:async()=>{calls++;if(fail)return new Response('{}',{status:503});return reply({name:'Pro'});}});
|
||||
const getAuth=async()=>auth('known');
|
||||
expect(await p.auth.accountConcurrency(getAuth)).toBe(2);
|
||||
clock+=5*60*1000;fail=true;
|
||||
expect(await p.auth.accountConcurrency(getAuth)).toBe(2);
|
||||
expect(await p.auth.accountConcurrency(getAuth)).toBe(2);
|
||||
expect(calls).toBe(2,'a failure backs off for one minute');
|
||||
expect(await p.auth.accountConcurrency(async()=>auth('unknown'))).toBe(1);
|
||||
});
|
||||
|
||||
test('an away desktop account never borrows the current user web token',async()=>{
|
||||
let calls=0;
|
||||
const p=I.createPlugin({readSession:()=>({uid:'current',workToken:'work-current',webToken:'web-current',keys:{away:'work-away'}}),fetchImpl:async()=>{calls++;return reply({name:'Max'});}});
|
||||
expect(await p.auth.accountConcurrency(async()=>({source:'kimi-work-desktop',uid:'away'}))).toBe(1);
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
|
||||
test('camelCase and snake_case subscription replies are both accepted',async()=>{
|
||||
for(const body of [{subscription:{plan:{name:'Moderato'}}},{subscription:{plan:{level:'LEVEL_ADVANCED'}}}]) {
|
||||
const p=I.createPlugin({fetchImpl:async()=>Response.json(body)});
|
||||
expect(await p.auth.accountConcurrency(async()=>auth('shape'))).toBe(body.subscription.plan.name?2:4);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user