diff --git a/packages/kimi-work/COMPATIBILITY.md b/packages/kimi-work/COMPATIBILITY.md index bca48e0..ae60db5 100644 --- a/packages/kimi-work/COMPATIBILITY.md +++ b/packages/kimi-work/COMPATIBILITY.md @@ -1,75 +1,69 @@ -# macOS compatibility record +# Kimi Work 0.1.15 compatibility -## Upgrade 0.1.4 +## Scope -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. +This candidate incorporates upstream `3b3209e0ddd2c47ee5c8f77b5541131e0aa178fe` (kimi-work 0.1.14), including storage-pointer discovery, separate missing-session/401/connection errors, per-user account IDs and retained Work keys, membership-card errors/omitted-zero parsing, and spent-quota 403→429 mapping. Reference-only accounts retain read-only desktop usage without forced reconnect. The interfaces remain undocumented and can change. -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. +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. -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. +## RefreshToken request comparison -Observed at **2026-10-16 20:09 UTC** (2026-10-17 04:09 UTC+8). +Endpoint: `POST https://auth.kimi.com/api/account.gateway.v1.AuthService/RefreshToken`. The official native request was observed at **2026-10-24 15:14:47 UTC**, HTTP **200**, producing changed access and refresh tokens. The full request-header names below come from Electron's send-headers event; private values were redacted in memory before recording. -| Component | Observed version | -|---|---| -| macOS | 26.6.2, Apple silicon / arm64 | -| Ordinary Kimi desktop | 3.2.17, build 3.2.17.4, `com.moonshot.kimichat` | -| Official Magpie | 0.1.1276 | -| Bun | 1.4.3, temporary test runtime | -| Provider code | `d5f84153116a28dcffb89f61a0f4435093d0483e`, package 0.1.3 | +| Header | Official desktop 3.2.17 | Plugin's explicit request | +| --- | --- | --- | +| `Authorization`, `Cookie` | Both absent | Both absent; regression asserted | +| `User-Agent` | Chromium UA containing `kimi-desktop/3.2.17 Chrome/150.0.7871.250 Electron/43.7.3` | Same captured macOS UA; OS portion follows platform | +| `x-msh-platform` | `mac` | `mac` on macOS, `windows` on Windows, `web` otherwise | +| `x-msh-version` | `3.2.17` | `3.2.17` for AuthService only | +| `R-Timezone` | `Asia/Singapore` | Runtime timezone (`Asia/Singapore` in this run) | +| `X-Language` | `zh-CN`, from the native desktop locale | Runtime locale (`en-US` in this run) | +| `Connect-Protocol-Version` | `1` | `1` | +| `Content-Type` | `application/proto` | `application/json` | +| `x-msh-device-id`, `x-msh-session-id`, `x-msh-shield-data` | Present; values redacted | Omitted; no browser identity/signature copied | +| `X-Traffic-Id` | Absent before token import; present on the later signed-in renewal, value redacted | Omitted; no account identifier copied | +| `Sec-Fetch-Site`, `Sec-Fetch-Mode`, `Sec-Fetch-Dest` | `none`, `no-cors`, `empty` | Only `Sec-Fetch-Mode: cors`, generated by Node | +| `Accept-Encoding` | `gzip, deflate, br, zstd` | `br, gzip, deflate, zstd`, generated by Node | +| `Accept-Language` | Chromium's Chinese/English preference list | `*`, generated by Node; no browser preferences imported | +| `Accept` | Not explicitly present in the capture | `application/json` | -The official Apple-silicon Kimi desktop application was installed; the user signed in personally and opened Work. The provider was installed and signed in using `magpie plugin add ` and `magpie plugin login kimi-work` in an isolated `XDG_CONFIG_HOME`, while retaining the real macOS home for read-only desktop-session discovery. `MAGPIE_BUN` selected the temporary runtime. The user's everyday Magpie profile was not replaced or restarted. +The request bodies use the same `RefreshTokenRequest.refresh_token` field. The original SDK selects protobuf by default and also implements Connect JSON with `useProtoFieldName: true` when its `KIMI_CAPTURE` option is set. The plugin uses that JSON representation, rather than adding a protobuf runtime. The official interceptor adds device/session/shield fields only when available; the plugin does not mint or reuse those browser-owned values. These are intentional differences, not a claim of byte-identical requests. The real plugin request at **15:21:07 UTC** was accepted with **200**, changed both tokens, and read `GetSubscriptionStats` with **200** at **15:21:08 UTC** without those optional fields. -## File and fields actually observed +Plugin transport-generated fields above were observed through Node's `undici:request:create` event on the **15:36:50 UTC** real renewal, in addition to the explicit fetch options. The observer redacted non-allowlisted values before recording. Native `X-Language` is corroborated by the original locale getter/interceptor; no private header value is included here. The complete official `Accept-Language` value was `zh-CN,zh;q=0.9;q=0.9,en-US;q=0.8;q=0.8,en;q=0.7;q=0.7`. -The file exists at: +`refreshHeaders` is used only for the exact AuthService URL. Work gateway requests retain upstream's `kimi-code-cli/0.36.0` and daimon 0.6.10 device headers. www.kimi.com requests retain upstream's 3.2.20 desktop-menu metadata; the separate www User-Agent discussion remains #363. -```text -~/Library/Application Support/kimi-desktop/daimon-share/daimon/config.json -``` +## Shared refresh lineage: both directions -All four credential values were present and nonempty. This fragment shows field names only; **every value is redacted**: +All times are **2026-10-24 UTC**. The two consumers begin with the same pair from the new temporary login. The plugin uses the actual production `auth.refresh`/`auth.usage` hooks in an isolated harness; the desktop uses its original AuthService and TokenStore. This run does not exercise Magpie's credential-file commit path. -```json -{ - "credentials": { - "kimiCode": { - "apiKey": "", - "baseUrl": "" - }, - "kimiWeb": { - "accessToken": "", - "userId": "" - } - } -} -``` +| Time | Operation and observation | +| --- | --- | +| 15:14:47 | The official native RPC returns the shared starting pair. Desktop access expires at 15:29:47. | +| 15:21:07–08 | Plugin rotates that pair; both tokens change and monthly stats return 200. Only this initial round forces the hook's expiry metadata to start promptly. The desktop still holds the original pair. | +| 15:29:53–54 | After the desktop access expires naturally, its original `TokenStore.ensureValidToken()` uses the retained old refresh and receives 200/new access/new refresh. This is over eight minutes after the plugin's rotation, rather than an immediate replay. | +| 15:30:06 | The native desktop's renewed access reads membership stats with 200; the Work key in its own temporary daemon file reads `/models` with 200. | +| 15:36:50 | The plugin's previously retained access expired naturally at 15:36:07. Calling `auth.refresh` with its unmodified stored expiry rotates its own retained refresh successfully (200), then monthly stats return 200. No desktop re-import occurs; the desktop pair remains unchanged and fresh. The temporary browser has already been closed. | +| 15:37:30 | Native membership stats and the temporary desktop's Work `/models` still return 200. | -The Work credential's origin matched the exact Work origin required by `readDesktop`. No actual value, account identifier, raw config or auth file was exported. +This session therefore did **not** show single-use rotation that immediately invalidates the other consumer. Both retained branches renewed successfully over the observed interval. It does not establish an unlimited reuse/grace period, future revocation behavior or months of coexistence. If either saved branch is later rejected, the provider shows an explicit reconnect hint; it does not silently switch accounts or rewrite the desktop's credentials. -## Executed checks +## Account storage and compatibility -- Desktop sign-in succeeded, saving only the provider's account reference in the isolated Magpie profile. -- Live model discovery returned `k3-agent` and `k2d8-preview`, each with `low`, `high` and `max` reasoning variants. -- Membership usage was read successfully. The result had one shared-allowance window and no `resetsAt`. -- Calling the provider's sign-in, model and usage hooks left Kimi's configuration byte-for-byte unchanged. -- One real, synthetic streamed inference was sent through the Kimi Agent adapter, the isolated official Magpie gateway and this provider to the real Work service. It returned HTTP 200, `[DONE]`, and exactly `KIMI_WORK_MAC_OK`. +Existing reference-only accounts through 0.1.14 continue using the desktop webToken after checking the saved uid. The access token is reread on each usage call, without writing auth state, consuming the desktop refresh token or silently importing a pair. If Kimi has switched users, upstream's retained Work keys still serve chat; legacy membership usage shows the switch-account hint and never borrows the current user's membership token. -Magpie's resulting route record, projected to non-sensitive fields: +Explicit sign-in imports a complete membership pair when available; a desktop without refresh still produces a usable reference-only account. New account IDs retain upstream's `Kimi Work · ` plus the first six characters of the hashed uid. The upgrade neither renames nor deletes old entries. Paired accounts read their own host-saved membership access independently of the current desktop user. Only `auth.refresh` rotates a pair and returns fields for the host's conditional commit; usage never saves or rotates. Magpie checks the expected access/refresh pair under the auth-store lock. Pending exchanges and cached rotations are keyed by exact credentials, including independent reconnects for the same user. -```json -{ - "agent": "kimi-desktop", - "provider": "kimi-work", - "model": "k3-agent", - "requested": "kimi-work/k3-agent", - "served": "k3-agent", - "status": 200 -} -``` +Membership failures keep the independent Work sign-in: a legacy 401 says to open Kimi desktop, a paired 401 gives an explicit reconnect hint, and HTTP/timeout/missing-balance errors are returned on the card. An AuthService 401 throws a membership-only `signIn: kept` error with a reconnect/CLI hint. It preserves the host retry backoff and does not mark the independent Work account expired; a Work gateway 401 retains its original expired semantics. The plugin creates no token file or desktop backup and never writes Kimi's configuration. Magpie's credential file uses atomic flushed writes and mode `0600`; it is private plaintext, not an encrypted vault. -The inference was initiated by a synthetic HTTP client at the adapter's authenticated loopback endpoint. It was **not** a message submitted through Kimi's desktop UI. The control API/runtime, Magpie gateway, provider and Work service were real, not mock servers. No response was substituted. This run did not measure Kimi's billing classification or reset schedule. +## Regression validation -After the adapter test, its original service address, current model, native catalog, credentials and unrelated settings were verified restored. The temporary model snapshot was removed, and the separate test gateway was stopped. The user's Kimi login remained in place. +Run `bun test packages/kimi-work`, full `bun test`, and `bun scripts/check.mjs kimi-work` with a disposable HOME/XDG profile. Current coverage includes upstream's storage pointers, callback error categories, distinct account IDs and retained keys, spent/non-spent 403 handling, omitted zero/snake_case membership balances, and the renewal/body-cancellation cases. Added legacy cases assert successful quota reads, no reconnect/migration/refresh, and rereading desktop access after rotation. Results, independent review and fork workflow evidence are tied to the final commit in PR #218. -This record covers this Apple-silicon/macOS/Kimi build. Intel macOS, Linux, desktop UI turns, sleep/wake, natural token expiry and future Kimi releases remain outside this run. Synthetic rotation/account-change/error cases remain in the package's unit tests. +The historical live sequence above covers one shared-lineage cycle. Its temporary credential profiles were removed after that run. No second real coexistence cycle or new 0.1.15 live sign-in/renewal is claimed by the current synthetic regression tests. + +## Limits + +The monthly meter reports `subscriptionBalance.amountUsedRatio`; Code's share is text from `subscriptionBalance.kimiCodeUsedRatio`, never a second allowance. Expiration fields are not asserted to be reset times. Inference continues to read the local desktop Work key and enforce its exact gateway origin/account binding. Membership renewal does not replace a revoked Work key. + +The historical live test covered renewal and read-only membership/model access, not an inference or desktop UI conversation at the current revision. Previous macOS and Windows streaming checks are historical coverage. Windows refresh, Linux, Intel macOS, long sleep/offline intervals, months of continuous renewal and future server revocation policy remain unverified. Automatic renewal does not guarantee a permanent session. diff --git a/packages/kimi-work/README.md b/packages/kimi-work/README.md index b9aacf4..914cd78 100644 --- a/packages/kimi-work/README.md +++ b/packages/kimi-work/README.md @@ -7,7 +7,11 @@ magpie plugin add @magpie-community/opencode-kimi-work-auth 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. There is no browser sign-in or API-key fallback in this package. It cannot sign in on a headless machine without an existing desktop session file. +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.15** adds membership renewal and a single shared monthly meter to upstream 0.1.14. It retains the storage-pointer and sign-in diagnostics fixes (#425/#444), distinct account IDs and per-user Work keys (#440), and spent-quota 403→429 handling (#465), alongside the earlier menu/header fixes. **Existing reference-only accounts through 0.1.14 continue to read quota without reconnecting.** They do not silently migrate or spend the desktop refresh token. Explicitly reconnect only to opt into host-managed renewal when a desktop refresh token is available. Accounts already saved with a pair keep their format. + +Request-body buffering for schema conversion also follows the caller's abort signal: cancelling while a stream is still being read cancels that read and returns the original cancellation reason before any upstream request is sent. ## Models and requests @@ -19,13 +23,13 @@ An inference HTTP 401 marks the provider sign-in as expired (`kimi_work_login_ex 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. -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. +Usage comes from Kimi's membership `GetSubscriptionStats` endpoint. The card's **月度共享额度** heading and single **本月** meter report `subscriptionBalance.amountUsedRatio`, the fraction used of the shared monthly membership pool. If returned, `subscriptionBalance.kimiCodeUsedRatio` appears only as **Code 已用 …%(占总额)** in the meter's text and tooltip: Code's share of the entire monthly pool, not another allowance or the fraction of the used portion. It is never another window/ring, because Magpie renders even informational `aside` windows as separate remaining allowances. Code's share does not constrain Work routing. Missing monthly data stays unknown; Code's five-hour/weekly limits are never substituted. No reset time is reported: `subscriptionBalance.expireTime` and `upcomingExpiration.timestamp` are expiration fields, and have not been verified to describe allowance resets. Magpie's compact card currently labels a window with no reset time as "Not used yet" even when usage is nonzero; that host wording does not mean the monthly pool is unused. An observed Windows request was classified by Kimi as `FEATURE_WORK` while the Code five-hour and weekly ratios stayed unchanged. Kimi controls billing, shared allowances, access and rate limits. Every reasoning-effort value returned by `/models` is retained, including `STANDARD` if listed. The checked Windows catalog in `tests/fixtures/work-models.redacted.json` lists `LOW` (displayed by Kimi as **Standard**), `HIGH` and `MAX`; the plugin sends the advertised effort value instead of guessing from the display label. ## Sign-in and local files -The plugin reads only the desktop app's `daimon/config.json`, and since 0.1.13 its `daimon/kimi-code-key.json`, in its `daimon-share` folder. That folder is where Kimi's own `daimon-storage.json` points (`shareDir`), or, with no such file, `daimon-share` itself, in Kimi's data folder: +The plugin reads Kimi's `daimon/config.json`, `daimon/kimi-code-key.json` and optional `daimon/runtime/kimi-code/home/device_id` in its `daimon-share` folder. That folder is where Kimi's own `daimon-storage.json` points (`shareDir`), or, without a valid pointer, `daimon-share` inside Kimi's data folder: - Windows: `%APPDATA%/kimi-desktop/` - macOS: `~/Library/Application Support/kimi-desktop/` @@ -33,13 +37,23 @@ The plugin reads only the desktop app's `daimon/config.json`, and since 0.1.13 i Kimi 3.2.21 on Windows, installed on another drive than `%APPDATA%`'s, keeps it there (`D:\KimiData\daimon-share` for an install on D:), and Kimi writes the same pointer on any system when its storage is moved. When the sign-in can't be found, the error names the file it looked for. Since 0.1.13, when the `daimon-share` folder itself is gone (moved, deleted, or on a drive that isn't mounted), the error names that folder instead (`kimi_work_share_missing`) and does not mark the account signed out: the sign-in in it isn't known to have lapsed. Putting the folder back makes the account work again at once, with no new sign-in. Kimi makes the folder again only when it starts, so signing in again in a running Kimi doesn't bring it back; quit and reopen Kimi, then sign in to Work. -The internal Work credential is named `credentials.kimiCode`, but its origin must be exactly `https://agent-gw.kimi.com/coding/v1`. `credentials.kimiWeb` supplies the membership sign-in. The plugin rejects missing credentials and other origins. It saves only a hashed account reference in Magpie/OpenCode's auth store; the actual tokens remain in Kimi's own files (`config.json`, and `kimi-code-key.json` for an account Kimi has switched away from) and are reread on each operation. It never reads Magpie's credential files, writes Kimi configuration, consumes refresh tokens, or stores copies of desktop credentials. +The internal Work credential is named `credentials.kimiCode`, but its origin must be exactly `https://agent-gw.kimi.com/coding/v1`. Work credentials stay in Kimi's files and are reread for inference/model discovery. `credentials.kimiWeb.accessToken`, optional `refreshToken` and `userId` supply membership access. Only explicit sign-in can copy a complete membership pair to the host. The plugin never writes Kimi's configuration or creates a separate credential file. -Kimi desktop remains responsible for refreshing its sign-in. If it expires, sign in there and reconnect this provider. Each synced device must have its own Kimi desktop sign-in. +Reference-only accounts continue to read the desktop webToken on each quota request, after checking the saved account reference. They never consume a desktop refresh token or write auth state. A legacy membership 401 tells the user to open Kimi desktop to refresh membership access and keeps the Work sign-in. Paired accounts use their own saved access without reading desktop membership state; a membership 401 shows a reconnect hint while leaving Work usable. HTTP failures, timeouts and missing membership balances are reported on the quota card, rather than being treated as a revoked Work key. ### Several Kimi accounts -Since 0.1.13 each Kimi user signed in here is an account of its own (named `Kimi Work · ` and the start of its hashed id), and requests never switch silently from one to another. To add a second one, switch Kimi desktop to that user, open Work once, and sign in to this provider again. Both keep working after Kimi switches back and forth: Kimi keeps one minted Work key per user in `daimon/kimi-code-key.json` (`{"v":2,"keys":[{userId,apiKey,keyId?}]}`, Kimi 3.2.21) and reuses a user's key when it switches back to them; it drops one only when the Work gateway refuses it. The account Kimi is signed in to uses `config.json`'s key; any other uses its key from that file. Only the user Kimi is signed in to has a web sign-in, so the shared membership allowance can be read only for that account; the others show that they need switching to in Kimi, and chat is unaffected. An account whose key is no longer in Kimi's file, or whose key the gateway refuses, is marked signed out (`kimi_work_account_not_here`) until Kimi is switched to it and opens Work. Kimi signed out entirely (no Work sign-in in `config.json`) serves none of them. Accounts signed in before 0.1.13 are named `Kimi Work (local)`; signing in to the same user again adds it under the new name, and the old entry can be removed. +Since 0.1.13 each Kimi user signed in here has a distinct account ID (`Kimi Work · ` plus the first six characters of its hashed uid). To add another account, switch Kimi desktop to that user, open Work once and sign in to this provider again. Inference retains upstream's per-user key lookup in `daimon/kimi-code-key.json` (`{"v":2,"keys":[{userId,apiKey,keyId?}]}`): the current user takes `config.json`'s key; another takes its own retained key. A missing or refused retained key prompts switching to that user in Kimi, and a missing share folder is reported without marking it signed out. A reference-only away account cannot read another user's membership quota; it shows the switch-account hint while chat stays usable. An account with an imported membership pair reads its own saved membership quota even after Kimi switches users. Old `Kimi Work (local)` entries remain usable; this upgrade does not rename or delete them. Future sign-ins use the distinct hashed account label. + +## Membership renewal and storage + +When explicitly imported, the membership pair is saved by Magpie in its account-scoped `plugin-auth.json`, using flushed atomic writes and mode `0600`; OpenCode owns its own auth store. This is a private credential file, not an encrypted vault. No separate token file or desktop credential backup is created. Host-managed renewal is optional for reference-only accounts; a desktop without refresh continues to work in reference mode. + +Magpie calls `auth.refresh` before models, usage and requests when access is within one minute of its JWT expiry. The hook returns rotated access/refresh fields. **Magpie owns the commit:** under its auth-store lock it checks that the original pair still stands before saving, so a late renewal cannot restore logout or overwrite a replacement login. The plugin never calls `client.auth.set` from renewal or usage. Pending work and cached rotations use exact credentials, keeping independent same-user reconnects separate. A failed host save can retry the rotated pair in the same plugin process; restarting before it is saved may require reconnecting. A rejected membership refresh gives a reconnect hint and keeps the Work sign-in; it throws a membership-only failure so the host retains retry backoff without marking the provider account expired. Network/429/5xx failures retain the stored login. + +RefreshToken uses its own observed desktop User-Agent/platform/version/timezone/language headers, with Connect JSON and no Authorization or Cookie. Browser device/session identifiers and ShieldData are not copied. Work requests keep upstream's Kimi Code 0.36.0/daimon 0.6.10 headers; www.kimi.com keeps upstream's desktop-menu metadata. The [compatibility record](COMPATIBILITY.md) compares the requests and preserves the dated 2026-10-24 single-cycle coexistence evidence; this revision does not claim a second real coexistence cycle. + +Usage never rotates, writes or silently imports credentials, for either account format. `auth.refresh` and `auth.usage` are Magpie hooks ignored by OpenCode. Inference still depends on a valid per-account local Work key; membership renewal cannot replace a revoked Work key. Server expiry/revocation can require human sign-in, and automatic renewal does not guarantee a permanent session. ## Origin and provider-id conflict @@ -49,11 +63,11 @@ The separate MIT-licensed [`kimi-work-opencode`](https://www.npmjs.com/package/k ## Compatibility and validation -These are undocumented desktop interfaces, not a supported public Kimi API. Windows and Apple-silicon macOS have been tested with real Work inference, including streaming. The [macOS record](COMPATIBILITY.md) includes the Kimi build, observed file/fields, real Magpie route and test limits. Linux and Intel macOS remain unverified. Changed desktop layouts stop with a sign-in error; changed upstream schemas stop model discovery or usage with an error. Inference failures are returned without retrying against Code or another service. Users remain responsible for their subscription's terms. +These are undocumented desktop interfaces, not a supported public Kimi API. Windows and Apple-silicon macOS have historical real Work inference coverage, including streaming. The [compatibility record](COMPATIBILITY.md) includes the tested Kimi build, renewal request comparison, observed coexistence interval and test limits; current renewal checks and historical inference coverage are distinguished there. Linux and Intel macOS remain unverified. Changed desktop layouts stop with a sign-in error; changed upstream schemas stop model discovery or usage with an error. Inference failures are returned without retrying against Code or another service. Users remain responsible for their subscription's terms. ```sh bun test packages/kimi-work bun scripts/check.mjs kimi-work ``` -Tests use synthetic sessions and fake HTTP responses: credential separation/rotation, read-only local import, account changes, endpoint restrictions, streaming/tool preservation, model discovery and 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 and monthly shared-usage accounting. No account, token, prompt, conversation or vendor binary is distributed. No runtime dependencies. diff --git a/packages/kimi-work/index.mjs b/packages/kimi-work/index.mjs index 0f6e8a5..ad6bc80 100644 --- a/packages/kimi-work/index.mjs +++ b/packages/kimi-work/index.mjs @@ -6,6 +6,8 @@ import {createHash} 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; // 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 @@ -30,6 +32,18 @@ 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 come from an observed Kimi 3.2.17 RefreshToken call. +// Connect's JSON representation is also used by that SDK (KIMI_CAPTURE mode). +// Browser-owned device/session IDs and ShieldData are deliberately not copied. +const AUTH_VERSION='3.2.17'; +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(); @@ -42,7 +56,9 @@ function workHeaders(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}; } -const expired = () => Object.assign(Error('请先在本机 Kimi 桌面版登录 Work,再重新连接 Kimi Work 供应商。'), {signIn:'expired',code:'kimi_work_login_expired'}); +// The host's quota RPC preserves message alone; this marker selects its +// localized signed-out card and the account's reconnect action. +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 @@ -63,6 +79,14 @@ const unavailable = error => Object.assign(Error('Kimi Work 连接失败:' + ( 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 @@ -225,6 +249,28 @@ function moonshotTools(body) { 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}={}) { @@ -289,9 +335,9 @@ function readKeys(file) { // A Windows path is taken apart as one wherever the plugin runs (tests). const pathOf = f => /^(?:[A-Za-z]:[\\/]|\\\\)/.test(f)?path.win32:path; -// Read the live Work sign-in, including after rotation. Never consume its -// refresh token or write the desktop app's configuration. The internal field -// is called kimiCode, but this credential is issued for agent-gw (Work). +// Read Work credentials live. Only explicit sign-in can import the web pair; +// usage of a reference-only account just 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)) { @@ -306,6 +352,7 @@ function readDesktop(file=desktopFile()) { 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,deviceId:readDeviceId(file), + webRefresh:typeof web.refreshToken==='string' ? web.refreshToken : '', uid:accountUid(web.userId),keys:readKeys(P.join(daimon,'kimi-code-key.json'))}; } catch {throw Object.assign(expired(),{file});} } @@ -381,7 +428,7 @@ function workConfigRows(payload) { return out; } -function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platform=process.platform}={}) { +function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platform=process.platform,now=Date.now}={}) { // The account's session: Kimi's own sign-in when the account is the one // Kimi is signed in to, else its Work key from Kimi's key store, with no // web sign-in (Kimi keeps only the current user's), so its allowance @@ -396,7 +443,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo }; async function jsonRequest(url,token,body,signal,deviceId) { const response=await fetchImpl(url,{method:body===undefined?'GET':'POST', - headers:{...(token?{Authorization:'Bearer '+token}:{}),...(url.startsWith(BASE)?workHeaders(deviceId):webHeaders(platform)),'Accept':'application/json', + 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}); @@ -406,6 +453,67 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo 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);} + } // 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 @@ -444,7 +552,7 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo provider:ID, maxConcurrency:1, methods:[{type:'oauth',label:'使用本机 Kimi Work 登录',authorize:async()=>({ - url:'',method:'auto',instructions:'读取本机 Kimi 桌面版的 Work 登录;不会使用 Kimi Code API Key。', + url:'',method:'auto',instructions:'读取本机 Kimi Work 登录;支持会员续期,不修改桌面配置。', callback:async()=>{ let s; try{s=readSession();} @@ -461,16 +569,22 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo const why=error?.status?'HTTP '+error.status:error?.name==='TimeoutError'?'超时':error?.cause?.code||error?.message||'未知网络错误'; return {type:'failed',error:'已找到本机 Kimi Work 登录,但连接 Kimi Work 失败('+why+'),请检查网络后再试。'}; } - // Only an account reference is saved in Magpie. Actual credentials - // stay in Kimi's own files and are reread for every operation. - // Each Kimi user is an account of its own, named by the start of - // its hashed uid, so a second one signed in sits beside the first - // (magpie keeps one per accountId and uid) and the two are told - // apart (#440). - return {type:'success',access:'',refresh:'',expires:0,source:'kimi-work-desktop', + // A user keeps a separate account id (#440). Import a complete web + // pair when available; older desktops still get a reference account. + const pair=typeof s.webRefresh==='string'&&s.webRefresh + ? {access:s.webToken,refresh:s.webRefresh,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}; }, })}], + 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={}) { @@ -491,11 +605,13 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo // 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 new Response(raw).text(); + if(raw!=null&&typeof raw!=='string')body=await bodyText(raw,signal); + signal?.throwIfAborted(); if(body!=null)body=moonshotTools(body); - const options={...init,body,signal:request?request.signal:init.signal}; + 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'}); } @@ -518,22 +634,25 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo return response; }, }), - // The allowance is read with Kimi's web sign-in (kimiWeb), not the - // Work one: the desktop rewrites it in its file only while it runs, so - // a closed desktop leaves a token www.kimi.com answers 401 "Session - // expired". Through 0.1.10 every failure was thrown, which magpie - // shows as a bare "暂时无法获取额度" with the reason only in a tooltip, - // and a 401 marked the Work account signed out though chat (Work's - // own token) still worked. A failure is now the card's error, and - // the Work sign-in is kept. + // 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 s=current(await getAuth()); - const plan='Kimi Work · 会员共享额度'; - if(s.away)return {plan,windows:[],error:'这个账号不是 Kimi 桌面版当前登录的账号,切换到它后才能读取会员额度(对话不受影响)',signIn:'kept'}; + 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',s.webToken,{});} + try {j=await jsonRequest(MEMBER+'GetSubscriptionStats',token,{});} catch(error) { - const why=error?.status===401?'Kimi 网页登录已过期,打开一次 Kimi 桌面版即可刷新额度(对话不受影响)' + 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'}; @@ -541,7 +660,10 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo // 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'}; - return {plan,windows:[{name:'会员共享额度',used}]}; + 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}={})=>{ @@ -564,4 +686,4 @@ function createPlugin({readSession=readDesktop,fetchImpl=globalThis.fetch,platfo } export default async function KimiWorkProvider(){return createPlugin();} -export const _internal={createPlugin,spentQuota,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,refreshHeaders,readDeviceId,REFRESH,REFRESH_LEAD,expiry}; diff --git a/packages/kimi-work/kimi-work.test.mjs b/packages/kimi-work/kimi-work.test.mjs index 8ffb907..4ae78e9 100644 --- a/packages/kimi-work/kimi-work.test.mjs +++ b/packages/kimi-work/kimi-work.test.mjs @@ -4,12 +4,12 @@ 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 session = {uid: 'synthetic-account', workToken: 'synthetic-work-token', webToken: 'synthetic-web-token', webRefresh:'synthetic-refresh-token'}; +const auth = {source: 'kimi-work-desktop', uid: session.uid,access:session.webToken,refresh:session.webRefresh,expires:0}; 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 () => { +test('sign-in imports web renewal credentials and dynamic models/usage retain Work accounting', async () => { const calls = []; const p = I.createPlugin({readSession: () => session, fetchImpl: async (url, init) => { calls.push({url, init}); @@ -18,10 +18,11 @@ test('sign-in saves an account reference and dynamic models/usage retain Work ac 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); + expect(result).toMatchObject({access:session.webToken,refresh:session.webRefresh}); 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((await p.auth.usage(async () => auth)).windows).toEqual([{name: '本月', used: 42}]); expect(calls.at(-1).init.headers.Authorization).toBe('Bearer ' + session.webToken); }); diff --git a/packages/kimi-work/no-magpie.test.mjs b/packages/kimi-work/no-magpie.test.mjs index aa194c9..62e20b3 100644 --- a/packages/kimi-work/no-magpie.test.mjs +++ b/packages/kimi-work/no-magpie.test.mjs @@ -8,8 +8,8 @@ import os from 'node:os'; import path from 'node:path'; import {_internal as I} from './index.mjs'; -const account={type:'oauth',source:'kimi-work-desktop',uid:'fixture-account'}; -const session={uid:'fixture-account',workToken:'synthetic-work-token',webToken:'synthetic-web-token',deviceId:'0f8fad5b-d9cb-469f-a165-70867728950e'}; +const account={type:'oauth',source:'kimi-work-desktop',uid:'fixture-account',access:'synthetic-web-token',refresh:'synthetic-web-refresh',expires:0}; +const session={uid:'fixture-account',workToken:'synthetic-work-token',webToken:account.access,webRefresh:account.refresh,deviceId:'0f8fad5b-d9cb-469f-a165-70867728950e'}; function record() { const sent=[]; diff --git a/packages/kimi-work/package.json b/packages/kimi-work/package.json index 36dd959..ca677bc 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.14", + "version": "0.1.15", "type": "module", "main": "./index.mjs", "files": [ diff --git a/packages/kimi-work/renewal.test.mjs b/packages/kimi-work/renewal.test.mjs new file mode 100644 index 0000000..dad3f1c --- /dev/null +++ b/packages/kimi-work/renewal.test.mjs @@ -0,0 +1,239 @@ +import {test,expect} from 'bun:test'; +import {_internal as I} from './index.mjs'; + +const NOW=1900000000000; +const jwt=(sub,exp,tag='fixture')=>'fixture.'+Buffer.from(JSON.stringify({sub,exp:exp/1000,tag})).toString('base64url')+'.fixture'; +const account=(uid='fixture-account',tag='old')=>({type:'oauth',source:'kimi-work-desktop',uid, + access:jwt(uid,NOW-1000,tag),refresh:'synthetic-refresh-'+uid+'-'+tag,expires:NOW-1000}); +const rotated=(uid='fixture-account',tag='new',clock=NOW)=>({access_token:jwt(uid,clock+900000,tag),refresh_token:'synthetic-rotated-'+uid+'-'+tag}); +const fields=p=>({access:p.access_token,refresh:p.refresh_token,expires:I.expiry(p.access_token)}); +const stats={subscriptionBalance:{amountUsedRatio:0.4515,kimiCodeUsedRatio:0.2422,expireTime:'2035-01-01T00:00:00Z'}, + ratelimitCode5h:{ratio:1},ratelimitCode7d:{ratio:1}}; +function deferred() { + let resolve;const promise=new Promise(done=>{resolve=done;});return {promise,resolve}; +} +function plugin(fetchImpl,extra={}) { + return I.createPlugin({now:()=>NOW,readSession:()=>{throw Error('No desktop or browser in this fixture');},fetchImpl,...extra}); +} + +test('host renewal returns only rotated fields and never calls the blind auth.set',async()=>{ + const calls=[];let writes=0; + const p=plugin(async(url,init)=>{ + calls.push(url);expect(url).toBe(I.REFRESH); + expect(init.method).toBe('POST');expect(init.redirect).toBe('error'); + expect(new Headers(init.headers).has('authorization')).toBe(false); + expect(new Headers(init.headers).has('cookie')).toBe(false); + const headers=new Headers(init.headers); + expect(headers.get('content-type')).toBe('application/json'); + expect(headers.get('connect-protocol-version')).toBe('1'); + expect(headers.get('user-agent')).toContain('kimi-desktop/3.2.17'); + expect(headers.get('user-agent')).not.toContain('kimi-code-cli'); + expect(headers.get('x-msh-platform')).toBe('mac'); + expect(headers.get('x-msh-version')).toBe('3.2.17'); + expect(headers.get('r-timezone')).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone); + expect(headers.get('x-language')).toBeTruthy(); + for(const key of ['x-msh-device-id','x-msh-session-id','x-msh-shield-data'])expect(headers.has(key)).toBe(false); + expect(JSON.parse(init.body)).toEqual({refresh_token:account().refresh}); + return Response.json(rotated()); + },{platform:'darwin',client:{auth:{set:async()=>{writes++;throw Error('Blind writes are forbidden');}}}}); + expect(await p.auth.refresh(account())).toEqual(fields(rotated())); + expect(calls).toEqual([I.REFRESH]);expect(writes).toBe(0); +}); + +test('host-save retries reuse the rotated pair without spending the saved old token again',async()=>{ + let calls=0; + const p=plugin(async()=>{calls++;return Response.json(rotated());}); + expect(await p.auth.refresh(account())).toEqual(fields(rotated())); + expect(await p.auth.refresh(account())).toEqual(fields(rotated())); + expect(calls).toBe(1); +}); + +test('continuing host-save failure advances from the cached refresh even after its access expires',async()=>{ + let clock=NOW;const spent=[]; + const p=plugin(async(url,init)=>{ + spent.push(JSON.parse(init.body).refresh_token); + return Response.json(rotated('fixture-account','rotation-'+spent.length,clock)); + },{now:()=>clock}); + const first=await p.auth.refresh(account()); + clock+=900000; + const second=await p.auth.refresh(account()); + expect(spent).toEqual([account().refresh,first.refresh]); + expect(await p.auth.refresh(account())).toEqual(second); + expect(await p.auth.refresh({...account(),...first})).toEqual(second); + expect(spent).toHaveLength(2); +}); + +test('concurrent renewal of the exact input pair shares one exchange',async()=>{ + const gate=deferred(),entered=deferred();let calls=0; + const p=plugin(async()=>{calls++;entered.resolve();await gate.promise;return Response.json(rotated());}); + const one=p.auth.refresh(account());await entered.promise; + const two=p.auth.refresh(account());gate.resolve(); + expect(await one).toEqual(fields(rotated()));expect(await two).toEqual(fields(rotated())); + expect(calls).toBe(1); +}); + +test('same-uid reconnects with independent due credentials have independent pending work and caches',async()=>{ + const gate=deferred(),entered=deferred(),old=account(),reconnected=account('fixture-account','reconnected'); + const spent=[]; + const p=plugin(async(url,init)=>{ + const token=JSON.parse(init.body).refresh_token;spent.push(token); + if(token===old.refresh){entered.resolve();await gate.promise;return Response.json(rotated('fixture-account','old-lineage'));} + return Response.json(rotated('fixture-account','new-lineage')); + }); + const oldRun=p.auth.refresh(old);await entered.promise; + const fresh=await p.auth.refresh(reconnected);gate.resolve();const previous=await oldRun; + expect(fresh).toEqual(fields(rotated('fixture-account','new-lineage'))); + expect(previous).toEqual(fields(rotated('fixture-account','old-lineage'))); + expect(await p.auth.refresh(reconnected)).toEqual(fresh); + expect(await p.auth.refresh(old)).toEqual(previous); + expect(spent).toEqual([old.refresh,reconnected.refresh]); +}); + +test('old pending 401 does not block or expire a same-uid fresh reconnect',async()=>{ + const gate=deferred(),entered=deferred(),old=account(); + const fresh={...old,...fields(rotated('fixture-account','reconnected'))}; + let reads=0; + const p=plugin(async url=>{ + if(url!==I.REFRESH){reads++;return Response.json(stats);} + entered.resolve();await gate.promise;return new Response('{}',{status:401}); + }); + const oldRun=p.auth.refresh(old).catch(error=>error);await entered.promise; + const outcome=await Promise.race([ + Promise.all([p.auth.refresh(fresh),p.auth.usage(async()=>fresh)]).then(value=>({value})), + new Promise(resolve=>setTimeout(()=>resolve({blocked:true}),50)), + ]); + gate.resolve();const oldError=await oldRun; + expect(outcome.blocked).toBeUndefined();expect(outcome.value[0]).toBeUndefined(); + expect(outcome.value[1].windows[0].used).toBe(45.15);expect(reads).toBe(1); + expect(oldError).toMatchObject({signIn:'kept',code:'kimi_work_membership_expired'}); +}); + +test('paired usage keeps Work signed in and asks to reconnect after a membership 401 without rotation or writes',async()=>{ + let writes=0;const calls=[]; + const fresh={...account(),...fields(rotated())}; + const p=plugin(async url=>{calls.push(url);return new Response('{}',{status:401});}, + {client:{auth:{set:async()=>{writes++;}}}}); + const usage=await p.auth.usage(async()=>fresh); + expect(usage).toMatchObject({signIn:'kept',windows:[]}); + expect(usage.error).toContain('重新连接 Kimi Work'); + expect(usage.error).not.toMatch(/sign-in has (expired|lapsed)|sign in again/i); + expect(calls).toEqual([I.MEMBER+'GetSubscriptionStats']);expect(writes).toBe(0); +}); + +test('completion after logout or replacement only returns fields for the host conditional commit',async()=>{ + for(const replacement of [undefined,account('fixture-account','replacement')]) { + const gate=deferred(),entered=deferred();let saved=account(),writes=0; + const p=plugin(async()=>{entered.resolve();await gate.promise;return Response.json(rotated());}, + {client:{auth:{set:async({body})=>{saved=body;writes++;}}}}); + const pending=p.auth.refresh(saved);await entered.promise;saved=replacement;gate.resolve(); + expect(await pending).toEqual(fields(rotated())); + expect(saved).toEqual(replacement);expect(writes).toBe(0); + } +}); + +for(const fields of [{},{access:'',refresh:'',expires:0}]) + test('reference-only legacy usage reads desktop webToken without reconnect, migration or rotation: '+JSON.stringify(fields),async()=>{ + let reads=0,writes=0;const calls=[]; + const legacy={type:'oauth',source:'kimi-work-desktop',uid:account().uid,...fields},before=structuredClone(legacy); + const desktopAccess=rotated('fixture-account','desktop').access_token; + const p=plugin(async(url,init)=>{calls.push(url);expect(init.headers.Authorization).toBe('Bearer '+desktopAccess);return Response.json(stats);},{ + readSession:()=>{reads++;return {uid:legacy.uid,webToken:desktopAccess,webRefresh:'unspent-desktop-refresh'};}, + client:{auth:{set:async()=>{writes++;}}}, + }); + expect(await p.auth.refresh(legacy)).toBeUndefined(); + expect(reads).toBe(0);expect(calls).toEqual([]); + const usage=await p.auth.usage(async()=>legacy); + expect(usage).toEqual({plan:'月度共享额度',windows:[{name:'本月',used:45.15,display:'Code 已用 24.22%(占总额)'}]}); + expect(legacy).toEqual(before);expect(reads).toBe(1);expect(writes).toBe(0); + expect(calls).toEqual([I.MEMBER+'GetSubscriptionStats']); + }); + +test('legacy usage rereads the desktop access after a rotation without copying its refresh',async()=>{ + const legacy={type:'oauth',source:'kimi-work-desktop',uid:'fixture-account'};let token='synthetic-desktop-first'; + const sent=[];const p=plugin(async(url,init)=>{expect(url).toBe(I.MEMBER+'GetSubscriptionStats');sent.push(init.headers.Authorization);return Response.json(stats);},{ + readSession:()=>({uid:legacy.uid,webToken:token,webRefresh:'unspent-desktop-refresh'}), + }); + await p.auth.usage(async()=>legacy);token='synthetic-desktop-next';await p.auth.usage(async()=>legacy); + expect(sent).toEqual(['Bearer synthetic-desktop-first','Bearer synthetic-desktop-next']); + expect(legacy).toEqual({type:'oauth',source:'kimi-work-desktop',uid:'fixture-account'}); +}); + +test('a desktop without refresh still signs in as a usable reference-only account',async()=>{ + const session={uid:'fixture-account',workToken:'synthetic-work-key',webToken:'synthetic-web-access'},calls=[]; + const p=plugin(async(url,init)=>{calls.push(url);return Response.json(url===I.BASE+'/models'?{data:[]}:stats);},{readSession:()=>session}); + const auth=await (await p.auth.methods[0].authorize()).callback(); + expect(auth).toMatchObject({type:'success',source:'kimi-work-desktop',uid:session.uid,accountId:'Kimi Work · fixtur',access:'',refresh:'',expires:0}); + expect((await p.auth.usage(async()=>auth)).windows[0].used).toBe(45.15); + expect(calls).toEqual([I.BASE+'/models',I.MEMBER+'GetSubscriptionStats']); +}); + +test('another plugin instance reads the pair persisted by the host without desktop or browser access',async()=>{ + const p=plugin(async()=>Response.json(rotated())); + const saved={...account(),...await p.auth.refresh(account())}; + const next=plugin(async(url,init)=>{ + expect(url).toBe(I.MEMBER+'GetSubscriptionStats'); + expect(init.headers.Authorization).toBe('Bearer '+saved.access);return Response.json(stats); + }); + expect(await next.auth.refresh(saved)).toBeUndefined(); + const usage=await next.auth.usage(async()=>saved); + expect(usage.plan).toBe('月度共享额度'); + expect(usage.windows).toEqual([{name:'本月',used:45.15,display:'Code 已用 24.22%(占总额)'}]); + expect(usage.windows.every(w=>!('resetsAt' in w))).toBe(true); +}); + +for(const status of [429,503])test('transient refresh HTTP '+status+' does not declare the login expired',async()=>{ + const p=plugin(async()=>new Response('synthetic secret response',{status})); + try {await p.auth.refresh(account());throw Error('expected failure');} + catch(error) {expect(error.signIn).toBeUndefined();expect(error.message).not.toContain('synthetic secret');} +}); + +test('refused membership renewal and usage keep the independent Work credential usable',async()=>{ + const auth=account(),before=structuredClone(auth),calls=[];let writes=0; + const p=plugin(async(url,init)=>{ + calls.push(url); + if(url===I.REFRESH||url===I.MEMBER+'GetSubscriptionStats')return new Response('synthetic secret response',{status:401}); + expect(url).toBe(I.BASE+'/chat/completions'); + expect(new Headers(init.headers).get('authorization')).toBe('Bearer synthetic-work-key'); + return new Response('synthetic Work answer'); + },{readSession:()=>({uid:auth.uid,workToken:'synthetic-work-key'}),client:{auth:{set:async()=>{writes++;}}}}); + const error=await p.auth.refresh(auth).catch(error=>error); + expect(error).toMatchObject({signIn:'kept',code:'kimi_work_membership_expired',status:401}); + expect(error.message).not.toMatch(/sign-in has (expired|lapsed)|sign in again/i); + expect(error.message).toContain('重新连接 Kimi Work'); + expect(error.message).toContain('magpie plugin login kimi-work'); + expect(error.message).not.toContain('synthetic secret response'); + expect(await p.auth.usage(async()=>auth)).toMatchObject({signIn:'kept',windows:[]}); + const loader=await p.auth.loader(async()=>auth); + expect(await (await loader.fetch(I.BASE+'/chat/completions',{method:'POST',body:'{}'})).text()).toBe('synthetic Work answer'); + expect(calls).toEqual([I.REFRESH,I.MEMBER+'GetSubscriptionStats',I.BASE+'/chat/completions']); + expect(auth).toEqual(before);expect(writes).toBe(0); +}); + +test('network errors during refresh do not reveal request credentials',async()=>{ + const p=plugin(async()=>{throw Error('synthetic secret request');}); + await expect(p.auth.refresh(account())).rejects.toThrow('登录续期暂不可用'); +}); + +for(const [name,payload] of [['missing refresh',{access_token:rotated().access_token}],['other account',rotated('different-account')], + ['expired access',{access_token:jwt(account().uid,NOW-1),refresh_token:'synthetic expired'}],['null response',null], + ['null JWT claims',{access_token:'fixture.'+Buffer.from('null').toString('base64url')+'.fixture',refresh_token:'synthetic'}]]) + test('invalid rotated pair is rejected: '+name,async()=>{ + const p=plugin(async()=>Response.json(payload)); + await expect(p.auth.refresh(account())).rejects.toThrow('续期响应格式无效'); + }); + +test('different accounts renew independently',async()=>{ + const spent=[]; + const p=plugin(async(url,init)=>{ + const token=JSON.parse(init.body).refresh_token;spent.push(token); + return Response.json(rotated(token.includes('account-a')?'account-a':'account-b')); + }); + const results=await Promise.all(['account-a','account-b'].map(uid=>p.auth.refresh(account(uid)))); + expect(spent).toHaveLength(2); + expect(results.map(x=>x.refresh)).toEqual(['account-a','account-b'].map(uid=>rotated(uid).refresh_token)); +}); + +test('missing monthly data stays unknown instead of using Code short-window counters',async()=>{ + const p=plugin(async()=>Response.json({ratelimitCode5h:{ratio:0.5},ratelimitCode7d:{ratio:0.8}})); + expect((await p.auth.usage(async()=>({...account(),...fields(rotated())}))).windows).toEqual([]); +}); diff --git a/packages/kimi-work/tests/body-abort.test.mjs b/packages/kimi-work/tests/body-abort.test.mjs new file mode 100644 index 0000000..f63d4f9 --- /dev/null +++ b/packages/kimi-work/tests/body-abort.test.mjs @@ -0,0 +1,50 @@ +import {test,expect} from 'bun:test'; +import {_internal as I} from '../index.mjs'; + +const session={uid:'synthetic-account',workToken:'synthetic-work',webToken:'synthetic-web'}; +const tick=()=>new Promise(resolve=>setImmediate(resolve)); + +for(const kind of ['stream','request'])test('aborting a buffered '+kind+' ends the read without sending the request',async()=>{ + let calls=0,producer,cancelled; + const p=I.createPlugin({readSession:()=>session,fetchImpl:async()=>{calls++;return new Response('{}');}}); + const loader=await p.auth.loader(async()=>({source:'kimi-work-desktop',uid:session.uid})); + const abort=new AbortController(); + const body=new ReadableStream({start(c){producer=c;c.enqueue(new TextEncoder().encode('{"messages":['));}, + cancel(reason){cancelled=reason;}}); + const init={method:'POST',body,signal:abort.signal,duplex:'half'}; + const pending=(kind==='request'?loader.fetch(new Request(I.BASE+'/chat/completions',init)) + :loader.fetch(I.BASE+'/chat/completions',init)).then(value=>({value}),error=>({error})); + // Let the initial chunk be consumed, leaving the next read waiting. + await tick();await tick(); + const reason=kind==='stream'?Error('synthetic custom cancellation'):new DOMException('synthetic cancellation','AbortError'); + abort.abort(reason); + let timer; + const result=await Promise.race([pending,new Promise(resolve=>{timer=setTimeout(()=>resolve({timedOut:true}),250);})]); + clearTimeout(timer); + if(result.timedOut){producer.close();await pending;} + expect(result.timedOut).toBeUndefined(); + expect(result.error).toBe(reason); + expect(calls).toBe(0); + // Request's stream wrapper may defer source cancellation across runtimes. + if(kind==='stream')expect(cancelled).toBe(reason); +}); + +test('a previously cancelled body retains the abort reason and is not sent',async()=>{ + let calls=0; + const p=I.createPlugin({readSession:()=>session,fetchImpl:async()=>{calls++;return new Response('{}');}}); + const loader=await p.auth.loader(async()=>({source:'kimi-work-desktop',uid:session.uid})); + const abort=new AbortController(),reason=Error('synthetic early cancellation'); + abort.abort(reason); + await expect(loader.fetch(I.BASE+'/chat/completions',{method:'POST',body:'{"messages":[]}',signal:abort.signal})).rejects.toBe(reason); + expect(calls).toBe(0); +}); + +test('a buffered UTF-8 body keeps characters split between chunks',async()=>{ + const original=JSON.stringify({messages:[{role:'user',content:'中文 🐦'}]}); + const bytes=new TextEncoder().encode(original);let sent; + const body=new ReadableStream({start(c){for(const byte of bytes)c.enqueue(Uint8Array.of(byte));c.close();}}); + const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{sent=init.body;return new Response('{}');}}); + const loader=await p.auth.loader(async()=>({source:'kimi-work-desktop',uid:session.uid})); + await loader.fetch(I.BASE+'/chat/completions',{method:'POST',body}); + expect(sent).toBe(original); +}); diff --git a/packages/kimi-work/tests/desktop-path.test.mjs b/packages/kimi-work/tests/desktop-path.test.mjs index 2243a67..6c1b927 100644 --- a/packages/kimi-work/tests/desktop-path.test.mjs +++ b/packages/kimi-work/tests/desktop-path.test.mjs @@ -76,3 +76,18 @@ test('a failed sign-in says which file it looked for, and a failed Work check is const gone=I.createPlugin({readSession:()=>session,fetchImpl:async()=>new Response('{}',{status:401})}); expect((await (await gone.auth.methods[0].authorize()).callback()).error).toContain('过期'); }); + +for(const [label,fail,detail] of [ + ['HTTP 503',()=>new Response('{}',{status:503}),'HTTP 503'], + ['timeout',()=>{throw new DOMException('synthetic request timed out','TimeoutError');},'超时'], +])test('a found session with '+label+' is a connection failure, not a missing or expired sign-in',async()=>{ + const session={uid:'fixture-user',workToken:'synthetic-work-key',webToken:'synthetic-web',webRefresh:'synthetic-refresh'}; + let calls=0; + const p=I.createPlugin({readSession:()=>session,fetchImpl:async()=>{calls++;return fail();}}); + const result=await (await p.auth.methods[0].authorize()).callback(); + expect(result.type).toBe('failed');expect(result.error).toContain(detail); + expect(result.error).toContain('已找到本机 Kimi Work 登录'); + expect(result.error).not.toContain('没有可用');expect(result.error).not.toContain('登录已过期'); + expect(result.error).not.toContain(session.workToken);expect(result.error).not.toContain(session.webRefresh); + expect(calls).toBe(1); +}); diff --git a/packages/kimi-work/tests/provider.test.mjs b/packages/kimi-work/tests/provider.test.mjs index 56a3d89..4676403 100644 --- a/packages/kimi-work/tests/provider.test.mjs +++ b/packages/kimi-work/tests/provider.test.mjs @@ -4,8 +4,8 @@ import os from 'node:os'; import path from 'node:path'; import {_internal as I} from '../index.mjs'; -const session={uid:'fixture-account',workToken:'synthetic-work-token',webToken:'synthetic-web-token'}; -const account={source:'kimi-work-desktop',uid:session.uid}; +const session={uid:'fixture-account',workToken:'synthetic-work-token',webToken:'synthetic-web-token',webRefresh:'synthetic-refresh-token',deviceId:'fixture-device-id'}; +const account={source:'kimi-work-desktop',uid:session.uid,access:session.webToken,refresh:session.webRefresh,expires:0}; const json=x=>Response.json(x); const modelPayload={data:[{id:'k3-agent',display_name:'K3',context_length:1000000,supports_image_in:true, supports_reasoning:true,reasoningEffortOptions:[{effort:'REASONING_EFFORT_HIGH'}]}]}; @@ -13,23 +13,31 @@ const modelPayload={data:[{id:'k3-agent',display_name:'K3',context_length:100000 test('desktop import reads only the Work credential origin and supports a redirected agent configuration',()=>{ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'kimi-work-fixture-')); const file=path.join(dir,'config.json'); - const doc={credentials:{kimiCode:{apiKey:'synthetic-work',baseUrl:I.BASE},kimiWeb:{accessToken:'synthetic-web',userId:'fixture-user'}}, + const doc={credentials:{kimiCode:{apiKey:'synthetic-work',baseUrl:I.BASE},kimiWeb:{accessToken:'synthetic-web',refreshToken:'synthetic-refresh',userId:'fixture-user'}}, model:{providers:{'daimon-kimi-code':{baseUrl:'http://127.0.0.1:1234/v1'}}}}; try{ fs.writeFileSync(file,JSON.stringify(doc));const raw=fs.readFileSync(file); - expect(I.readDesktop(file).workToken).toBe('synthetic-work'); + fs.mkdirSync(path.join(dir,'runtime','kimi-code','home'),{recursive:true}); + const deviceFile=path.join(dir,'runtime','kimi-code','home','device_id'); + fs.writeFileSync(deviceFile,'fixture-device-id\n'); + expect(I.readDesktop(file)).toMatchObject({workToken:'synthetic-work',webRefresh:'synthetic-refresh',deviceId:'fixture-device-id'}); expect(fs.readFileSync(file)).toEqual(raw); + expect(fs.readFileSync(deviceFile,'utf8')).toBe('fixture-device-id\n'); 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});} }); -test('sign-in persists an account reference without either actual token',async()=>{ - const p=I.createPlugin({readSession:()=>session,fetchImpl:async()=>json(modelPayload)}); +test('sign-in imports web credentials without copying the Work API key',async()=>{ + const p=I.createPlugin({readSession:()=>session,fetchImpl:async(url,init)=>{ + expect(url).toBe(I.BASE+'/models'); + expect(init.headers['X-Msh-Device-Id']).toBe(session.deviceId); + return json(modelPayload); + }}); const flow=await p.auth.methods[0].authorize(),auth=await flow.callback(); expect(auth).toMatchObject({type:'success',source:'kimi-work-desktop',uid:session.uid}); expect(JSON.stringify(auth)).not.toContain(session.workToken); - expect(JSON.stringify(auth)).not.toContain(session.webToken); + expect(auth).toMatchObject({access:session.webToken,refresh:session.webRefresh}); }); test('inference always uses the Work gateway and live Work credential, preserving stream, tools and cancellation',async()=>{ @@ -67,7 +75,7 @@ test('models come from Work; usage reports only the shared membership allowance' expect(models['k3-agent'].capabilities.input.image).toBe(true); const usage=await p.auth.usage(async()=>account);expect(usage.windows).toHaveLength(1);expect(usage.windows[0].used).toBe(42); expect(usage.windows[0]).not.toHaveProperty('resetsAt'); - expect(usage.windows[0].name).toBe('会员共享额度'); + expect(usage.windows[0].name).toBe('本月'); expect(calls.find(x=>x.url.endsWith('GetSubscriptionStats')).init.headers.Authorization).toBe('Bearer '+session.webToken); expect(calls.every(x=>!x.url.includes('api.kimi.com'))).toBe(true); }); @@ -84,7 +92,7 @@ const sessionExpired={"code":"unauthenticated","details":[{"type":"common.error. test('a stale web sign-in is said on the card and keeps the Work sign-in',async()=>{ const p=I.createPlugin({readSession:()=>session,fetchImpl:async()=>Response.json(sessionExpired,{status:401})}); - const u=await p.auth.usage(async()=>account); + const u=await p.auth.usage(async()=>({source:account.source,uid:account.uid})); expect(u.windows).toEqual([]);expect(u.signIn).toBe('kept'); expect(u.error).toContain('Kimi 网页登录已过期'); // magpie's signInGone would mark the account signed out on these words @@ -95,9 +103,9 @@ test('a stale web sign-in is said on the card and keeps the Work sign-in',async( test('a balance with nothing used, its zero left out, reads 0%; no balance is said',async()=>{ let reply={subscriptionBalance:{expireTime:'2030-01-01T00:00:00Z'}}; const p=I.createPlugin({readSession:()=>session,fetchImpl:async()=>Response.json(reply)}); - expect((await p.auth.usage(async()=>account)).windows).toEqual([{name:'会员共享额度',used:0}]); + expect((await p.auth.usage(async()=>account)).windows).toEqual([{name:'本月',used:0}]); reply={subscription_balance:{amount_used_ratio:0.5}}; - expect((await p.auth.usage(async()=>account)).windows).toEqual([{name:'会员共享额度',used:50}]); + expect((await p.auth.usage(async()=>account)).windows).toEqual([{name:'本月',used:50}]); reply={overdrawn:false}; const u=await p.auth.usage(async()=>account); expect(u.windows).toEqual([]);expect(u.error).toContain('subscriptionBalance');