From 08e3ba899003f94c3efe89de59a1ea578df31f1e Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 28 Oct 2026 21:02:21 +0800 Subject: [PATCH] kimi-work 0.1.14: a spent allowance's 403 goes out as a 429 (#465) Kimi answers an account whose allowance is used up with a 403 ("You've reached your usage limit for this billing cycle", resource_exhausted "insufficient balance"). The plugin passed it through, magpie read a 403 as a key fault, never rested the account, and kept routing to it while another account with quota sat idle (kongbai01203: 6+ requests in 20 minutes to the spent one after the other answered 200). A 403 whose body says resource_exhausted, usage limit, billing cycle, insufficient balance or quota now goes to magpie as a 429 with Kimi's body and headers (content-encoding/length dropped, the text is decoded), the pattern Devin's, Qoder's, Kiro's and Cline's plugins use for a spent quota. magpie's quotaStatus counts 429 as spent and moves on. Any other 403 stays a 403 with its body. Run (on mote, HOME=$(mktemp -d) bun test in packages/kimi-work): 69 pass, 0 fail. bun scripts/check.mjs: exit 0. Broken by hand: status:spent?429:403 changed to status:403; the three new spent-allowance tests went red (66 pass, 3 fail), green again with the fix back. Not tried: a real spent Kimi Work account. The issue gives Kimi's words but not the JSON around them, so the fixtures try them in an OpenAI-style error, a Connect body and a nested Connect error. Not checked end to end that magpie then rests the account until the cycle resets (Kimi sends no reset time; magpie's own rest length applies). --- packages/kimi-work/README.md | 2 +- packages/kimi-work/index.mjs | 17 +++++++++++++++- packages/kimi-work/kimi-work.test.mjs | 29 +++++++++++++++++++++++++++ packages/kimi-work/package.json | 2 +- 4 files changed, 47 insertions(+), 3 deletions(-) diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index 517cf96..b9aacf4 100644 --- a/packages/kimi-work/README.md +++ b/packages/kimi-work/README.md @@ -15,7 +15,7 @@ The account's models and reasoning options come from the two lists Kimi's deskto Version 0.1.4 preserves the calling agent's shared instructions, prompts, history and tools unchanged. Since 0.1.5 one exception: tool schemas Kimi's "moonshot flavored json schema" check refuses are rewritten to an equivalent it takes (#287). A `$ref` beside a `type`, as zod writes a schema derived from a reused one, gets its target written in; a `type` beside an `anyOf` is left out; an untyped `enum`, `const` or `$ref` target gets the type its values or keywords say. A request with none of these goes byte for byte. Instructions, MCP and skills are assigned to that agent in Magpie's Library; the provider does not create a second target or enable resources on its own. The ordinary Kimi agent's Library support starts at `@magpie-community/agent-kimi-desktop` 0.1.1. -An inference HTTP 401 marks the provider sign-in as expired (`kimi_work_login_expired`). Sign in to desktop Work if needed, then **reconnect Kimi Work in Magpie** (or run `magpie plugin login kimi-work`); signing in to the desktop alone does not reconnect the provider. Other HTTP errors, including 429 and 5xx, pass through unchanged with Kimi's status, headers, body and Retry-After. This preserves the distinction between concurrency limits and exhausted allowance, including any upstream reset details. Network failures use `kimi_work_connection_failed` and retain the underlying cause code or fetch error message for diagnosis. Rate limits and service failures do not invalidate the desktop sign-in. Cancellation stays cancellation. No automatic retry sends a conversation twice or falls back to Code. +An inference HTTP 401 marks the provider sign-in as expired (`kimi_work_login_expired`). Sign in to desktop Work if needed, then **reconnect Kimi Work in Magpie** (or run `magpie plugin login kimi-work`); signing in to the desktop alone does not reconnect the provider. A 403 whose body says the allowance is spent (Kimi's "You've reached your usage limit for this billing cycle", `resource_exhausted` "insufficient balance") goes to Magpie as a 429 with Kimi's body and headers, so Magpie rests that account until its allowance is back and asks another one (#465); any other 403 passes through as a 403. Other HTTP errors, including 429 and 5xx, pass through unchanged with Kimi's status, headers, body and Retry-After. This preserves the distinction between concurrency limits and exhausted allowance, including any upstream reset details. Network failures use `kimi_work_connection_failed` and retain the underlying cause code or fetch error message for diagnosis. Rate limits and service failures do not invalidate the desktop sign-in. Cancellation stays cancellation. No automatic retry sends a conversation twice or falls back to Code. Models use standard context, capped at 262,144 tokens, rather than silently enabling the higher-priced XL context. The reply limit is the menu's `maxTokens` (32,768 for every model it lists today). Until the signed-in account's live catalog is read, and when it can't be, the models offered are `kimi-work/k3-agent` and `kimi-work/k2d8-preview`, the two ids Work's `/models` has listed; the live catalog replaces them, so a model Kimi adds to the account (such as K3.1 Pro) shows under the id the menu gives it. Since 0.1.6 a model whose reasoning levels come in a shape not seen before keeps the levels that can be read, rather than the whole catalog failing over to the fallback. diff --git a/packages/kimi-work/index.mjs b/packages/kimi-work/index.mjs index 037400e..0f6e8a5 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -58,6 +58,9 @@ const notHere = (revoked=false) => Object.assign(Error(revoked : '这个 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'}); +// spentQuota is a 403 body saying the account's allowance is used up, not +// that the token or the model is refused (#465). +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; // Kimi Work validates tools against Moonshot's "moonshot flavored json @@ -498,6 +501,18 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo 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.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; @@ -549,4 +564,4 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo } export default async function KimiWorkProvider(){return createPlugin();} -export const _internal={createPlugin,moonshotTools,moonshotSchema,readDesktop,readKeys,desktopFile,shareDir,userDataDir,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA,workHeaders,webHeaders,readDeviceId}; +export const _internal={createPlugin,spentQuota,moonshotTools,moonshotSchema,readDesktop,readKeys,desktopFile,shareDir,userDataDir,modelRows,workConfigRows,BASE,MEMBER,CONFIG,UA,workHeaders,webHeaders,readDeviceId}; diff --git a/packages/kimi-work/kimi-work.test.mjs b/packages/kimi-work/kimi-work.test.mjs index 693881d..8ffb907 100644 --- a/packages/kimi-work/kimi-work.test.mjs +++ b/packages/kimi-work/kimi-work.test.mjs @@ -117,3 +117,32 @@ test('the Work token goes only to the official Work chat endpoint', async () => await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'GET'})).rejects.toThrow('仅接受官方'); expect(called).toBe(0); }); + +// #465 (kongbai01203): Kimi answered a spent account with a 403, which magpie +// took for a key fault and kept routing to. The words are the reporter's own +// (usage.jsonl and `magpie provider test kimi-work`); the issue doesn't show +// the JSON around them, so both an OpenAI-style and a Connect-style body are +// tried. +for (const body of [ + JSON.stringify({error: {message: "You've reached your usage limit for this billing cycle.", type: 'permission_denied_error'}}), + JSON.stringify({code: 'resource_exhausted', message: 'insufficient balance'}), + JSON.stringify({error: {code: 'resource_exhausted', message: 'insufficient balance'}}), +]) test('a spent allowance\'s 403 goes out as a 429 with Kimi\'s words: ' + body, async () => { + const p = I.createPlugin({readSession: () => session, fetchImpl: async () => new Response(body, + {status: 403, headers: {'Content-Type': 'application/json', 'Retry-After': '3600'}})}); + const loader = await p.auth.loader(async () => auth); + const response = await loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body: '{}'}); + expect(response.status).toBe(429); + expect(response.headers.get('retry-after')).toBe('3600'); + expect(response.headers.get('content-type')).toBe('application/json'); + expect(await response.text()).toBe(body); +}); + +test('a 403 that is not about the allowance stays a 403', async () => { + const body = JSON.stringify({error: {message: 'Access denied for this model', type: 'permission_denied_error'}}); + const p = I.createPlugin({readSession: () => session, fetchImpl: async () => new Response(body, {status: 403})}); + const loader = await p.auth.loader(async () => auth); + const response = await loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body: '{}'}); + expect(response.status).toBe(403); + expect(await response.text()).toBe(body); +}); diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index f8726d8..36dd959 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.13", + "version": "0.1.14", "type": "module", "main": "./index.mjs", "files": [