diff --git a/packages/kimi-work/COMPATIBILITY.md b/packages/kimi-work/COMPATIBILITY.md index 78e69de..bca48e0 100644 --- a/packages/kimi-work/COMPATIBILITY.md +++ b/packages/kimi-work/COMPATIBILITY.md @@ -1,5 +1,13 @@ # macOS compatibility record +## Upgrade 0.1.4 + +On Windows 11, 2026-10-17, the upgraded provider read the existing ordinary desktop Work sign-in and live model catalog/usage. An isolated adapter inserted a shared instruction and passed its messages through this provider unchanged to the real Work service. The streamed response was HTTP 200 with `[DONE]` and the exact marker present only in that instruction. The live desktop applications and their configurations were not switched for this request. Synthetic regression tests cover credential rotation, account binding, Request bodies, prompt/tool/stream preservation, expired sign-in, unchanged concurrency/quota/5xx responses, network diagnostics, cancellation and read-only desktop import. + +On macOS 26.6.2 arm64, Kimi 3.2.17 build 3.2.17.4, at 2026-10-17 04:37 UTC, version 0.1.4 again read the existing Work sign-in, discovered `k3-agent` and `k2d8-preview`, and returned one shared membership window. This upgrade probe did not submit a Mac desktop conversation; the earlier streamed macOS inference evidence below remains a separate record. + +At **2026-10-17 05:31 UTC**, the corrected 0.1.4 provider was also tested through the user's active Mac profile: ordinary Kimi's authenticated loopback adapter → official Magpie 0.1.1276 → Kimi Work `k3-agent`. The Agent was the community-published 0.1.1; the provider was a persistent local source pending this PR. One synthetic streamed request returned HTTP 200, `[DONE]` and exactly `KIMI_MAC_ROUTED_OK`, with a newly appended Magpie usage record identifying `agent: kimi-desktop`, `provider: kimi-work`, `model: k3-agent`, `status: 200`. Desktop credentials, provider settings, general settings and plugin auth were verified unchanged. This request was sent by an HTTP probe, not submitted through the desktop UI. The 429/5xx/network failure cases were tested with synthetic responses, not forced against Kimi's live service. + Observed at **2026-10-16 20:09 UTC** (2026-10-17 04:09 UTC+8). | Component | Observed version | diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index 9dff5f4..a65a119 100644 --- a/packages/kimi-work/README.md +++ b/packages/kimi-work/README.md @@ -13,6 +13,10 @@ Open Kimi desktop and sign in to Work on the same computer first. Choose **使 The account's models and reasoning options come from `https://agent-gw.kimi.com/coding/v1/models`. Chat completions, streaming, tool calls and cancellation use the same Work gateway. The request uses this plugin's own User-Agent; it does not impersonate Kimi's desktop client. It never uses `api.kimi.com` or a Kimi Code API key. +Version 0.1.4 preserves the calling agent's shared instructions, prompts, history and tools unchanged. Instructions, MCP and skills are assigned to that agent in Magpie's Library; the provider does not create a second target or enable resources on its own. The ordinary Kimi agent's Library support starts at `@magpie-community/agent-kimi-desktop` 0.1.1. + +An inference HTTP 401 marks the provider sign-in as expired (`kimi_work_login_expired`). Sign in to desktop Work if needed, then **reconnect Kimi Work in Magpie** (or run `magpie plugin login kimi-work`); signing in to the desktop alone does not reconnect the provider. Other HTTP errors, including 429 and 5xx, pass through unchanged with Kimi's status, headers, body and Retry-After. This preserves the distinction between concurrency limits and exhausted allowance, including any upstream reset details. Network failures use `kimi_work_connection_failed` and retain the underlying cause code or fetch error message for diagnosis. Rate limits and service failures do not invalidate the desktop sign-in. Cancellation stays cancellation. No automatic retry sends a conversation twice or falls back to Code. + Models use standard context, capped at 262,144 tokens, rather than silently enabling the higher-priced XL context. The fallback model is `kimi-work/k3-agent`; the signed-in account's live catalog replaces it. Usage comes from Kimi's membership `GetSubscriptionStats` endpoint and is labelled **shared membership allowance**, not a separate free Work allowance. No reset time is reported: `subscriptionBalance.expireTime` and `upcomingExpiration.timestamp` are expiration fields, and have not been verified to describe allowance resets. An observed Windows request was classified by Kimi as `FEATURE_WORK` while the Code five-hour and weekly ratios stayed unchanged. This is an observation, not a promise about future quota accounting: Kimi controls billing, shared allowances, access and rate limits. diff --git a/packages/kimi-work/index.mjs b/packages/kimi-work/index.mjs index 83e9bae..9f6dc3b 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -8,7 +8,8 @@ const BASE = 'https://agent-gw.kimi.com/coding/v1'; const MEMBER = 'https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/'; const {version} = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')); const UA = 'Magpie Kimi Work provider/' + version; -const expired = () => Object.assign(Error('请先在本机 Kimi 桌面版登录 Work,再重新连接 Kimi Work 供应商。'), {signIn:'expired'}); +const expired = () => Object.assign(Error('请先在本机 Kimi 桌面版登录 Work,再重新连接 Kimi Work 供应商。'), {signIn:'expired',code:'kimi_work_login_expired'}); +const unavailable = error => Object.assign(Error('Kimi Work 连接失败:' + (error?.cause?.code || error?.message || '未知网络错误'), {cause:error}), {code:'kimi_work_connection_failed'}); const percent = x => typeof x === 'number' && Number.isFinite(x) ? Math.max(0,Math.min(100,x*100)) : undefined; function desktopFile({home=os.homedir(), platform=process.platform, appdata=process.env.APPDATA}={}) { @@ -39,6 +40,7 @@ function modelRows(payload) { for(const m of payload.data) { if(typeof m.id!=='string'||!m.id||m.id.length>256||/[\x00-\x20/]/.test(m.id)) continue; const variants=Object.create(null); + if(m.reasoningEffortOptions!==undefined&&!Array.isArray(m.reasoningEffortOptions))throw Error('Kimi Work 思考档位格式无效。'); for(const x of m.reasoningEffortOptions||[]) { const effort=String(x.effort||'').replace(/^REASONING_EFFORT_/,'').toLowerCase(); if(!/^[a-z][a-z0-9_-]{0,63}$/.test(effort))throw Error('Kimi Work 思考档位格式无效。'); @@ -114,7 +116,13 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch}={}) { // Preserve messages, tools, stream and abort signal. There is no // fallback to api.kimi.com, a Code API key, or another provider. const options=request?{...init,body:request.body,signal:request.signal,duplex:'half'}:init; - return fetchImpl(BASE+'/chat/completions',{...options,method:'POST',headers,redirect:'error'}); + 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 expired(); } + // Magpie classifies rate vs quota from the upstream response. Keep + // its wording, reset details and Retry-After instead of guessing. + return response; }, }), usage:async getAuth=>{ diff --git a/packages/kimi-work/kimi-work.test.mjs b/packages/kimi-work/kimi-work.test.mjs new file mode 100644 index 0000000..4f6fee5 --- /dev/null +++ b/packages/kimi-work/kimi-work.test.mjs @@ -0,0 +1,107 @@ +import {test, expect} from 'bun:test'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {_internal as I} from './index.mjs'; + +const session = {uid: 'synthetic-account', workToken: 'synthetic-work-token', webToken: 'synthetic-web-token'}; +const auth = {source: 'kimi-work-desktop', uid: session.uid}; +const models = {data: [{id: 'k3-agent', display_name: 'K3', context_length: 1000000, + supports_image_in: true, supports_reasoning: true, reasoningEffortOptions: [{effort: 'REASONING_EFFORT_LOW'}, {effort: 'REASONING_EFFORT_MAX'}]}]}; + +test('sign-in saves an account reference and dynamic models/usage retain Work accounting', async () => { + const calls = []; + const p = I.createPlugin({readSession: () => session, fetchImpl: async (url, init) => { + calls.push({url, init}); + return Response.json(url.endsWith('/models') ? models : {subscriptionBalance: {amountUsedRatio: 0.42}, ratelimitCode5h: {ratio: 1}}); + }}); + const result = await (await p.auth.methods[0].authorize()).callback(); + expect(result).toMatchObject({type: 'success', source: auth.source, uid: auth.uid}); + expect(JSON.stringify(result)).not.toContain(session.workToken); + const catalog = await p.provider.models({models: {}}, {auth}); + expect(catalog['k3-agent'].limit.context).toBe(262144); + expect(Object.keys(catalog['k3-agent'].variants)).toEqual(['low', 'max']); + expect((await p.auth.usage(async () => auth)).windows).toEqual([{name: '会员共享额度', used: 42}]); + expect(calls.at(-1).init.headers.Authorization).toBe('Bearer ' + session.webToken); +}); + +test('requests preserve prompts, tools, streaming and cancellation while rotating only Work credentials', async () => { + let live = {...session}; const calls = []; + const p = I.createPlugin({readSession: () => live, fetchImpl: async (url, init) => { + calls.push({url, init}); return new Response('data: [DONE]\n\n', {headers: {'Content-Type': 'text/event-stream'}}); + }}); + const loader = await p.auth.loader(async () => auth); + const body = JSON.stringify({model: 'k3-agent', messages: [{role: 'system', content: 'synthetic shared instruction'}], + tools: [{type: 'function', function: {name: 'Read', parameters: {type: 'object'}}}], stream: true}); + const signal = new AbortController().signal; + const request = new Request(I.BASE + '/chat/completions', {method: 'POST', body, signal, + headers: {Authorization: 'Bearer synthetic-code-token', Cookie: 'synthetic-cookie'}}); + expect(await (await loader.fetch(request)).text()).toBe('data: [DONE]\n\n'); + expect(await new Response(calls[0].init.body).text()).toBe(body); + expect(calls[0].init.headers.get('authorization')).toBe('Bearer ' + session.workToken); + expect(calls[0].init.headers.get('cookie')).toBeNull(); + expect(calls[0].init.signal.aborted).toBe(false); + live.workToken = 'synthetic-rotated'; + await loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body, signal}); + expect(calls[1].init.headers.get('authorization')).toBe('Bearer synthetic-rotated'); + live.uid = 'different-account'; + await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body})).rejects.toMatchObject({signIn: 'expired'}); + expect(calls).toHaveLength(2); +}); + +test('a rejected desktop token requires reconnecting the provider', async () => { + const p = I.createPlugin({readSession: () => session, fetchImpl: async () => new Response('{}', {status: 401})}); + const loader = await p.auth.loader(async () => auth); + await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'POST'})) + .rejects.toMatchObject({signIn: 'expired', code: 'kimi_work_login_expired'}); +}); + +for (const {name, status, body, type} of [ + {name: 'concurrency 429 retains rate-limit wording without adding quota wording', status: 429, + body: JSON.stringify({error: {type: 'rate_limit_error', code: 'concurrency_limit', message: 'Too many requests'}}), type: 'application/json'}, + {name: 'quota 429 retains the upstream allowance and reset details', status: 429, + body: JSON.stringify({error: {type: 'quota_exceeded', message: 'Plan quota exhausted', resetsAt: '2030-01-01T00:00:00Z'}}), type: 'application/json'}, + {name: '5xx retains even a non-JSON upstream failure', status: 502, body: 'Bad gateway: upstream unavailable', type: 'text/plain'}, +]) test(name, async () => { + const upstream = new Response(body, {status, statusText: 'Upstream failure', headers: {'Retry-After': '30', 'Content-Type': type}}); + const p = I.createPlugin({readSession: () => session, fetchImpl: async () => upstream}); + const loader = await p.auth.loader(async () => auth); + const response = await loader.fetch(I.BASE + '/chat/completions', {method: 'POST', body: '{}'}); + expect(response).toBe(upstream); + expect(response.status).toBe(status); + expect(response.headers.get('retry-after')).toBe('30'); + expect(response.headers.get('content-type')).toBe(type); + expect(await response.text()).toBe(body); +}); + +test('network failures keep diagnostic causes and ordinary fetch messages', async () => { + for (const error of [Error('fetch failed', {cause: {code: 'ENOTFOUND'}}), Error('proxy connection refused')]) { + const p = I.createPlugin({readSession: () => session, fetchImpl: async () => {throw error;}}); + const loader = await p.auth.loader(async () => auth); + await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'POST'})).rejects.toMatchObject({ + code: 'kimi_work_connection_failed', cause: error, + message: 'Kimi Work 连接失败:' + (error.cause?.code || error.message), + }); + } +}); + +test('cancellation keeps the original abort error', async () => { + const controller = new AbortController(), error = new DOMException('Cancelled', 'AbortError'); + const p = I.createPlugin({readSession: () => session, fetchImpl: async () => {controller.abort(); throw error;}}); + const loader = await p.auth.loader(async () => auth); + await expect(loader.fetch(I.BASE + '/chat/completions', {method: 'POST', signal: controller.signal})).rejects.toBe(error); +}); + +test('desktop import is read-only and never substitutes a Code endpoint', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kimi-provider-fixture-')); + const file = path.join(dir, 'config.json'); + const doc = {credentials: {kimiCode: {apiKey: session.workToken, baseUrl: I.BASE}, + kimiWeb: {accessToken: session.webToken, userId: 'synthetic-user'}}}; + try { + fs.writeFileSync(file, JSON.stringify(doc)); const before = fs.readFileSync(file); + expect(I.readDesktop(file).workToken).toBe(session.workToken); + expect(fs.readFileSync(file)).toEqual(before); + doc.credentials.kimiCode.baseUrl = 'https://api.kimi.com/coding/v1'; fs.writeFileSync(file, JSON.stringify(doc)); + expect(() => I.readDesktop(file)).toThrow(); + } finally {fs.rmSync(dir, {recursive: true, force: true});} +}); diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index dd6a616..5f77058 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.3", + "version": "0.1.4", "type": "module", "main": "./index.mjs", "files": [