Fix Kimi usage refresh, 5 hour session limit, and reasoning levels (#2743)
* Refresh expired Kimi usage tokens * Test Kimi usage token refresh * Harden Kimi usage token refresh Follow-up review of the refresh path added in f6ce001a. Credential reads no longer depend on the shape of fields this provider only writes back: declaring expires_at and friends as required numbers meant a null or stringified value threw away the access token sitting next to them, turning a working Kimi quota bar into "unavailable" with no way back. Those fields are nullish and coerced now. Refreshed tokens are merged into a re-read of the credential file rather than the copy the request started with, so a write by Kimi Code during the refresh round-trip survives, and a file deleted in that window stays deleted instead of being resurrected with fresh credentials. A failed write logs at warn: Kimi rotates the refresh token, so losing that write silently logs the user out of Kimi Code. Only 401 triggers a refresh. A 403 means authenticated but not entitled, which no refresh fixes, and refreshing anyway rotated the user's refresh token on every poll. Also: floor expires_at to whole seconds, indent the file the way Kimi Code does, derive the temp file name from the real basename, and split out fetchUsageResponse, which is what puts fetchUsage back under the complexity limit — the original passed neither lint nor the formatter. * Keep CLI-rotated Kimi credentials during refresh The Kimi CLI shares the credential file the quota fetcher writes. A refresh read the file, merged its new tokens, and renamed over it, so a rotation that landed while the refresh was in flight was replaced with stale tokens and the CLI's session broke until credentials were recreated. Thread the refresh token that was actually spent into the persistence step and skip the write when the file no longer carries it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(kimi): normalize additional usage windows * fix(kimi): preserve custom auth while parsing limit windows * test(kimi): cover additional usage windows * test(kimi): move usage-window tests into service.test.ts Every other quota provider is tested in service.test.ts; kimi.test.ts was the only provider with a standalone collocated test file. * fix(kimi): resolve reasoning-effort options per model, not per catalog probe deriveModelDefinitionsFromACP derived thinkingOptions once from whichever model happened to be active in the one-off catalog probe session, then copied that same array onto every model. Kimi's ACP adapter only reports thinking levels for the currently selected model, so K2.7/K2.7-coding-fast (boolean on/off) and K3 (off/low/medium/high) ended up with identical, often-wrong options depending on which model the probe defaulted to. fetchCatalog now reuses the single probe session to switch through each candidate model and read back its real thought_level options, falling back to the default options if an individual model's probe fails. Skips entirely when there's one model or no thinking picker, so providers without per-model effort levels pay no extra round trips. * refactor(kimi): merge kimi-usage.ts back into kimi.ts kimi.ts was the only quota provider split across two files; every other provider (including claude.ts at 503 lines, larger than the merged Kimi file) stays in one. Also fixes a nested-ternary lint error surfaced by the merge. * fix(kimi): re-validate credentials immediately before the rename Greptile flagged that saveRefreshedCredentials read the credential file, checked its refresh token against a stale snapshot, then did async writeFile work before an unconditional rename — leaving a window where the Kimi CLI could rotate the file after the check and have its newer tokens clobbered by our stale merge. The refresh-token-only comparison also missed a CLI access-token rotation that kept the same refresh token. Re-read the file immediately before the rename and compare both tokens against the snapshot the merge was built from, discarding the merge if anything changed. Narrows the check-then-write gap to the smallest window possible without cross-process file locking. * refactor(acp): make per-model catalog probing an injectable resolver Catalog discovery in ACPAgentClient.fetchCatalog ran sequential setSessionConfigOption model switches for every multi-model ACP with a thought_level picker, so a slow or nonconforming agent could stall any provider's catalog probe under the shared 60s timeout. Replace the built-in resolvePerModelThinkingOptions with an optional ACPCatalogModelResolver injected through ACPAgentClientOptions (threaded through GenericACPAgentClient like the existing transformer/parser deps). The base client ships no resolver, so catalog discovery derives models from the initial session response and never switches models. Export the config-option helpers a resolver needs. The base regression test pins that a plain ACPAgentClient with multiple models and a thinking picker never calls setSessionConfigOption. * feat(kimi): resolve per-model thinking options via KimiACPAgentClient Kimi exposes different thinking-effort levels per model but only reports the currently selected model's levels, so the catalog probe must switch through each model to read them back. Move that logic off the shared ACP adapter and onto a Kimi-specific client. Add resolveKimiCatalogModels (the sequential setSessionConfigOption probe, fallback, and warning) and KimiACPAgentClient, which injects it via the new catalogModelResolver dependency. Select it for providerId "kimi" in the registry alongside cursor/kiro/traecli, so only Kimi pays the extra round trips; every other ACP provider skips model switching entirely. Tests cover the four probe behaviors on KimiACPAgentClient and the registry dispatch to it. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,31 +1,276 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { existsSync, promises as fs } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import type { Logger } from "pino";
|
||||
import { z } from "zod";
|
||||
import type { ProviderUsage } from "../../../server/messages.js";
|
||||
import type { ProviderUsage, ProviderUsageWindow } from "../../../server/messages.js";
|
||||
import type { ProviderApiFetch, ProviderUsageFetcher } from "../provider.js";
|
||||
import {
|
||||
ApiNumberSchema,
|
||||
ApiOptionalStringSchema,
|
||||
fetchProviderApi,
|
||||
toneFromUsedPct,
|
||||
unavailableUsage,
|
||||
windowFromUsedPct,
|
||||
} from "../usage.js";
|
||||
|
||||
const KimiUsageResponseSchema = z.object({
|
||||
usage: z
|
||||
.object({
|
||||
limit: ApiOptionalStringSchema,
|
||||
remaining: ApiOptionalStringSchema,
|
||||
resetTime: ApiOptionalStringSchema,
|
||||
})
|
||||
.nullish(),
|
||||
const KIMI_CLIENT_ID = "17e5f671-d194-4dfb-9706-5516cb48c098";
|
||||
const KIMI_USAGE_URL = "https://api.kimi.com/coding/v1/usages";
|
||||
const KIMI_TOKEN_URL = "https://auth.kimi.com/api/oauth/token";
|
||||
|
||||
const KimiUsageFieldsSchema = z.object({
|
||||
limit: ApiOptionalStringSchema,
|
||||
used: ApiOptionalStringSchema,
|
||||
remaining: ApiOptionalStringSchema,
|
||||
resetTime: ApiOptionalStringSchema,
|
||||
resetAt: ApiOptionalStringSchema,
|
||||
reset_time: ApiOptionalStringSchema,
|
||||
reset_at: ApiOptionalStringSchema,
|
||||
name: ApiOptionalStringSchema,
|
||||
title: ApiOptionalStringSchema,
|
||||
scope: ApiOptionalStringSchema,
|
||||
duration: z.unknown().optional(),
|
||||
timeUnit: ApiOptionalStringSchema,
|
||||
});
|
||||
|
||||
const KimiAuthSchema = z.object({
|
||||
access_token: z.string().optional(),
|
||||
const KimiUsageLimitSchema = z
|
||||
.object({
|
||||
window: z.unknown().optional(),
|
||||
detail: z.unknown().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const KimiUsageResponseSchema = z.object({
|
||||
usage: z.unknown().nullish(),
|
||||
limits: z.unknown().nullish(),
|
||||
});
|
||||
|
||||
type KimiUsageFields = z.infer<typeof KimiUsageFieldsSchema>;
|
||||
type KimiUsageLimit = z.infer<typeof KimiUsageLimitSchema>;
|
||||
|
||||
function parseUsageFields(value: unknown): KimiUsageFields | null {
|
||||
const parsed = KimiUsageFieldsSchema.safeParse(value);
|
||||
return parsed.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
function usedPctFromFields(fields: KimiUsageFields): number | null {
|
||||
const limit = fields.limit === undefined ? null : Number(fields.limit);
|
||||
const used = fields.used === undefined ? null : Number(fields.used);
|
||||
const remaining = fields.remaining === undefined ? null : Number(fields.remaining);
|
||||
|
||||
if (limit === null || !Number.isFinite(limit) || limit <= 0) return null;
|
||||
|
||||
let usedValue: number | null = null;
|
||||
if (used !== null && Number.isFinite(used)) {
|
||||
usedValue = used;
|
||||
} else if (remaining !== null && Number.isFinite(remaining)) {
|
||||
usedValue = limit - remaining;
|
||||
}
|
||||
|
||||
return usedValue === null ? null : Math.max(0, Math.min(100, (usedValue / limit) * 100));
|
||||
}
|
||||
|
||||
function resetTimeFromFields(fields: KimiUsageFields): string | null {
|
||||
return fields.resetTime ?? fields.resetAt ?? fields.reset_time ?? fields.reset_at ?? null;
|
||||
}
|
||||
|
||||
function explicitUsageLabel(...fields: Array<KimiUsageFields | null>): string | null {
|
||||
for (const field of fields) {
|
||||
if (!field) continue;
|
||||
const label = field.name ?? field.title ?? field.scope;
|
||||
if (label?.trim()) return label.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function durationFrom(value: unknown): number | null {
|
||||
const duration = Number(value);
|
||||
return Number.isFinite(duration) && duration > 0 ? duration : null;
|
||||
}
|
||||
|
||||
function durationLabel(duration: number, timeUnit: string | undefined): string | null {
|
||||
if (!timeUnit) return null;
|
||||
|
||||
const normalizedUnit = timeUnit.replace(/^TIME_UNIT_/i, "").toUpperCase();
|
||||
if (normalizedUnit.includes("MINUTE")) {
|
||||
if (duration % 60 === 0) return `${duration / 60}-hour limit`;
|
||||
return `${duration}-minute limit`;
|
||||
}
|
||||
if (normalizedUnit.includes("HOUR")) return `${duration}-hour limit`;
|
||||
if (normalizedUnit.includes("DAY")) return `${duration}-day limit`;
|
||||
if (normalizedUnit.includes("WEEK")) return `${duration}-week limit`;
|
||||
if (normalizedUnit.includes("SECOND")) return `${duration}-second limit`;
|
||||
return null;
|
||||
}
|
||||
|
||||
function idPart(value: string | number): string {
|
||||
return String(value)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "_")
|
||||
.replace(/^_+|_+$/g, "");
|
||||
}
|
||||
|
||||
function hasUsageData(fields: KimiUsageFields | null): fields is KimiUsageFields {
|
||||
return (
|
||||
fields !== null &&
|
||||
(fields.limit !== undefined || fields.used !== undefined || fields.remaining !== undefined)
|
||||
);
|
||||
}
|
||||
|
||||
function limitFields(limit: KimiUsageLimit): {
|
||||
fields: KimiUsageFields | null;
|
||||
metadata: KimiUsageFields | null;
|
||||
} {
|
||||
const metadata = parseUsageFields(limit);
|
||||
const detail = parseUsageFields(limit.detail);
|
||||
return {
|
||||
fields: hasUsageData(detail) ? detail : metadata,
|
||||
metadata,
|
||||
};
|
||||
}
|
||||
|
||||
function windowMetadata(limit: KimiUsageLimit): KimiUsageFields | null {
|
||||
return parseUsageFields(limit.window);
|
||||
}
|
||||
|
||||
function limitIdentity(input: {
|
||||
metadata: KimiUsageFields | null;
|
||||
fields: KimiUsageFields;
|
||||
window: KimiUsageFields | null;
|
||||
index: number;
|
||||
}): { id: string; label: string } {
|
||||
const label = explicitUsageLabel(input.metadata, input.fields);
|
||||
const duration = durationFrom(
|
||||
input.window?.duration ?? input.metadata?.duration ?? input.fields.duration,
|
||||
);
|
||||
const timeUnit = input.window?.timeUnit ?? input.metadata?.timeUnit ?? input.fields.timeUnit;
|
||||
const generatedLabel = duration === null ? null : durationLabel(duration, timeUnit);
|
||||
|
||||
if (duration !== null && timeUnit) {
|
||||
return {
|
||||
id: `coding_limit_${idPart(duration)}_${idPart(timeUnit)}`,
|
||||
label: label ?? generatedLabel ?? `Limit ${input.index + 1}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (label) {
|
||||
return { id: `coding_limit_${idPart(label)}`, label };
|
||||
}
|
||||
|
||||
return {
|
||||
id: `coding_limit_${input.index + 1}`,
|
||||
label: generatedLabel ?? `Limit ${input.index + 1}`,
|
||||
};
|
||||
}
|
||||
|
||||
function windowFromFields(input: {
|
||||
id: string;
|
||||
label: string;
|
||||
fields: KimiUsageFields;
|
||||
}): ProviderUsageWindow {
|
||||
const usedPct = usedPctFromFields(input.fields);
|
||||
return windowFromUsedPct({
|
||||
id: input.id,
|
||||
label: input.label,
|
||||
utilizationPct: usedPct,
|
||||
resetsAt: resetTimeFromFields(input.fields),
|
||||
tone: toneFromUsedPct(usedPct),
|
||||
});
|
||||
}
|
||||
|
||||
function uniqueWindowId(baseId: string, seenIds: Set<string>): string {
|
||||
let id = baseId;
|
||||
let suffix = 2;
|
||||
while (seenIds.has(id)) {
|
||||
id = `${baseId}_${suffix}`;
|
||||
suffix += 1;
|
||||
}
|
||||
seenIds.add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
function kimiUsageWindowsFromPayload(
|
||||
payload: unknown,
|
||||
logger: Pick<Logger, "debug">,
|
||||
): ProviderUsageWindow[] {
|
||||
const response = KimiUsageResponseSchema.parse(payload);
|
||||
const windows: ProviderUsageWindow[] = [];
|
||||
const seenWindowIds = new Set<string>();
|
||||
const usage = parseUsageFields(response.usage);
|
||||
|
||||
if (hasUsageData(usage)) {
|
||||
windows.push(
|
||||
windowFromFields({
|
||||
id: uniqueWindowId("coding_usage", seenWindowIds),
|
||||
label: explicitUsageLabel(usage) ?? "Weekly limit",
|
||||
fields: usage,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const limits = Array.isArray(response.limits) ? response.limits : [];
|
||||
for (const [index, rawLimit] of limits.entries()) {
|
||||
const parsedLimit = KimiUsageLimitSchema.safeParse(rawLimit);
|
||||
if (!parsedLimit.success) {
|
||||
logger.debug({ index }, "Ignoring malformed Kimi usage limit window");
|
||||
continue;
|
||||
}
|
||||
|
||||
const limit = parsedLimit.data;
|
||||
const { fields, metadata } = limitFields(limit);
|
||||
if (!hasUsageData(fields)) {
|
||||
logger.debug({ index }, "Ignoring malformed Kimi usage limit window");
|
||||
continue;
|
||||
}
|
||||
|
||||
const window = windowMetadata(limit);
|
||||
const identity = limitIdentity({ metadata, fields, window, index });
|
||||
windows.push(
|
||||
windowFromFields({
|
||||
id: uniqueWindowId(identity.id, seenWindowIds),
|
||||
label: identity.label,
|
||||
fields,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return windows;
|
||||
}
|
||||
|
||||
const KimiAuthSchema = z
|
||||
.object({
|
||||
access_token: z.string().nullish(),
|
||||
refresh_token: z.string().nullish(),
|
||||
expires_at: ApiNumberSchema.nullish(),
|
||||
expires_in: ApiNumberSchema.nullish(),
|
||||
scope: z.string().nullish(),
|
||||
token_type: z.string().nullish(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const KimiTokenRefreshSchema = z.object({
|
||||
access_token: z.string(),
|
||||
refresh_token: z.string().nullish(),
|
||||
expires_in: ApiNumberSchema.nullish(),
|
||||
scope: z.string().nullish(),
|
||||
token_type: z.string().nullish(),
|
||||
});
|
||||
|
||||
type KimiAuth = z.infer<typeof KimiAuthSchema>;
|
||||
type KimiTokenRefresh = z.infer<typeof KimiTokenRefreshSchema>;
|
||||
|
||||
interface KimiCredentialRecord {
|
||||
credentials: KimiAuth & { access_token: string };
|
||||
filePath: string | null;
|
||||
}
|
||||
|
||||
interface SaveRefreshedCredentialsOptions {
|
||||
filePath: string;
|
||||
refreshTokenUsed: string;
|
||||
refreshed: KimiTokenRefresh;
|
||||
}
|
||||
|
||||
interface KimiQuotaProviderOptions {
|
||||
logger: Logger;
|
||||
fetch?: ProviderApiFetch;
|
||||
@@ -41,63 +286,163 @@ export class KimiQuotaProvider implements ProviderUsageFetcher {
|
||||
private readonly homeDir?: string;
|
||||
|
||||
constructor(options: KimiQuotaProviderOptions) {
|
||||
this.logger = options.logger;
|
||||
this.logger = options.logger.child({ module: "kimi-quota-provider" });
|
||||
this.fetchApi = options.fetch ?? fetch;
|
||||
this.homeDir = options.homeDir;
|
||||
}
|
||||
|
||||
async fetchUsage(): Promise<ProviderUsage> {
|
||||
const token =
|
||||
process.env["KIMI_TOKEN"] || process.env["KIMI_API_KEY"] || (await this.readKimiToken());
|
||||
const credentials = await this.readCredentials();
|
||||
if (!credentials) return unavailableUsage(this);
|
||||
|
||||
if (!token) return unavailableUsage(this);
|
||||
|
||||
const res = await fetchProviderApi(this.fetchApi, "https://api.kimi.com/coding/v1/usages", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
const res = await this.fetchUsageResponse(credentials);
|
||||
|
||||
if (!res.ok) {
|
||||
this.logger.debug({ status: res.status }, "Kimi usage fetch failed");
|
||||
return unavailableUsage(this);
|
||||
}
|
||||
|
||||
const resp = KimiUsageResponseSchema.parse(await res.json());
|
||||
const limit = resp.usage?.limit === undefined ? null : Number(resp.usage.limit);
|
||||
const remaining = resp.usage?.remaining === undefined ? null : Number(resp.usage.remaining);
|
||||
const hasFiniteLimit = typeof limit === "number" && Number.isFinite(limit) && limit > 0;
|
||||
const hasFiniteRemaining = typeof remaining === "number" && Number.isFinite(remaining);
|
||||
const usedPct =
|
||||
hasFiniteLimit && hasFiniteRemaining
|
||||
? Math.max(0, Math.min(100, ((limit - remaining) / limit) * 100))
|
||||
: null;
|
||||
const windows = kimiUsageWindowsFromPayload(await res.json(), this.logger);
|
||||
|
||||
return {
|
||||
providerId: this.providerId,
|
||||
displayName: this.displayName,
|
||||
status: "available",
|
||||
planLabel: null,
|
||||
windows: [
|
||||
{
|
||||
id: "coding_usage",
|
||||
label: "Coding usage",
|
||||
usedPct,
|
||||
remainingPct: usedPct === null ? null : Math.max(0, 100 - usedPct),
|
||||
resetsAt: resp.usage?.resetTime ?? null,
|
||||
tone: toneFromUsedPct(usedPct),
|
||||
},
|
||||
],
|
||||
windows,
|
||||
balances: [],
|
||||
details: [],
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
|
||||
private async readKimiToken(): Promise<string | null> {
|
||||
private async fetchUsageResponse(record: KimiCredentialRecord): Promise<Response> {
|
||||
const { credentials, filePath } = record;
|
||||
const res = await this.callUsageApi(credentials.access_token);
|
||||
|
||||
if (res.status !== 401 || !filePath || !credentials.refresh_token) return res;
|
||||
|
||||
const latest = await this.readCredentialFile(filePath);
|
||||
const retried =
|
||||
latest?.access_token && latest.access_token !== credentials.access_token
|
||||
? await this.callUsageApi(latest.access_token)
|
||||
: res;
|
||||
if (retried.status !== 401) return retried;
|
||||
|
||||
const refreshTokenUsed = latest?.refresh_token ?? credentials.refresh_token;
|
||||
const refreshed = await this.refreshToken(refreshTokenUsed);
|
||||
if (!refreshed) return retried;
|
||||
|
||||
await this.saveRefreshedCredentials({ filePath, refreshTokenUsed, refreshed });
|
||||
return this.callUsageApi(refreshed.access_token);
|
||||
}
|
||||
|
||||
private async callUsageApi(token: string): Promise<Response> {
|
||||
return fetchProviderApi(this.fetchApi, KIMI_USAGE_URL, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshToken(refreshToken: string): Promise<KimiTokenRefresh | null> {
|
||||
const body = new URLSearchParams({
|
||||
client_id: KIMI_CLIENT_ID,
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: refreshToken,
|
||||
});
|
||||
const res = await fetchProviderApi(this.fetchApi, KIMI_TOKEN_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
if (!res.ok) {
|
||||
this.logger.debug({ status: res.status }, "Kimi token refresh failed");
|
||||
return null;
|
||||
}
|
||||
const parsed = KimiTokenRefreshSchema.safeParse(await res.json());
|
||||
return parsed.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
private async saveRefreshedCredentials(options: SaveRefreshedCredentialsOptions): Promise<void> {
|
||||
const { filePath, refreshTokenUsed, refreshed } = options;
|
||||
const existing = await this.readCredentialFile(filePath);
|
||||
if (!existing) return;
|
||||
|
||||
// The Kimi CLI owns this file too. If its refresh token no longer matches the one we
|
||||
// just spent, the CLI rotated the credentials while our refresh was in flight and its
|
||||
// copy is newer than ours — writing our merge would strand the CLI on dead tokens.
|
||||
if (existing.refresh_token !== refreshTokenUsed) {
|
||||
this.logger.debug("Kimi credentials rotated during refresh; keeping the file on disk");
|
||||
return;
|
||||
}
|
||||
|
||||
const expiresIn = refreshed.expires_in ?? existing.expires_in;
|
||||
const merged: KimiAuth = {
|
||||
...existing,
|
||||
access_token: refreshed.access_token,
|
||||
refresh_token: refreshed.refresh_token ?? existing.refresh_token,
|
||||
expires_in: expiresIn,
|
||||
expires_at:
|
||||
expiresIn == null ? existing.expires_at : Math.floor(Date.now() / 1000) + expiresIn,
|
||||
scope: refreshed.scope ?? existing.scope,
|
||||
token_type: refreshed.token_type ?? existing.token_type,
|
||||
};
|
||||
|
||||
const tempPath = join(
|
||||
dirname(filePath),
|
||||
`.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,
|
||||
);
|
||||
try {
|
||||
await fs.writeFile(tempPath, JSON.stringify(merged, null, 2), { mode: 0o600 });
|
||||
|
||||
// writeFile above is async I/O that gives the CLI a window to rotate the file on
|
||||
// its own. Re-read right before the rename and confirm nothing changed since the
|
||||
// guard above — the check-then-write gap this closes is what the file-level guard
|
||||
// couldn't cover, since it ran before the write, not right before the replace.
|
||||
const beforeRename = await this.readCredentialFile(filePath);
|
||||
if (!this.credentialsUnchangedSince(existing, beforeRename)) {
|
||||
this.logger.debug("Kimi credentials rotated during refresh; discarding stale merge");
|
||||
await fs.rm(tempPath, { force: true }).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
await fs.rename(tempPath, filePath);
|
||||
} catch (error) {
|
||||
this.logger.warn({ err: error }, "Failed to persist refreshed Kimi credentials");
|
||||
await fs.rm(tempPath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
private credentialsUnchangedSince(baseline: KimiAuth, candidate: KimiAuth | null): boolean {
|
||||
return (
|
||||
candidate?.access_token === baseline.access_token &&
|
||||
candidate?.refresh_token === baseline.refresh_token
|
||||
);
|
||||
}
|
||||
|
||||
private async readCredentials(): Promise<KimiCredentialRecord | null> {
|
||||
const environmentToken = process.env["KIMI_TOKEN"] || process.env["KIMI_API_KEY"];
|
||||
if (environmentToken) {
|
||||
return { credentials: { access_token: environmentToken }, filePath: null };
|
||||
}
|
||||
|
||||
for (const path of this.credentialPaths()) {
|
||||
const credentials = await this.readCredentialFile(path);
|
||||
if (credentials?.access_token) {
|
||||
return {
|
||||
credentials: { ...credentials, access_token: credentials.access_token },
|
||||
filePath: path,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private credentialPaths(): string[] {
|
||||
const homeDir = this.homeDir ?? homedir();
|
||||
const paths = [
|
||||
return [
|
||||
join(
|
||||
process.env["KIMI_CODE_HOME"] || join(homeDir, ".kimi-code"),
|
||||
"credentials",
|
||||
@@ -105,16 +450,14 @@ export class KimiQuotaProvider implements ProviderUsageFetcher {
|
||||
),
|
||||
join(homeDir, ".kimi", "credentials", "kimi-code.json"),
|
||||
];
|
||||
}
|
||||
|
||||
for (const path of paths) {
|
||||
if (!existsSync(path)) continue;
|
||||
try {
|
||||
const credentials = KimiAuthSchema.parse(JSON.parse(await fs.readFile(path, "utf8")));
|
||||
if (credentials.access_token) return credentials.access_token;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
private async readCredentialFile(path: string): Promise<KimiAuth | null> {
|
||||
if (!existsSync(path)) return null;
|
||||
try {
|
||||
return KimiAuthSchema.parse(JSON.parse(await fs.readFile(path, "utf8")));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { promises as fsPromises } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -37,16 +38,22 @@ function writeCodexAuth(dir: string, accessToken: string, refreshToken = "rt_cod
|
||||
);
|
||||
}
|
||||
|
||||
function writeKimiCredentials(dir: string, accessToken: string): void {
|
||||
function kimiCredentialPath(dir: string): string {
|
||||
return join(dir, "credentials", "kimi-code.json");
|
||||
}
|
||||
|
||||
function writeKimiCredentials(dir: string, accessToken: string, overrides: object = {}): void {
|
||||
mkdirSync(join(dir, "credentials"), { recursive: true });
|
||||
writeFileSync(
|
||||
join(dir, "credentials", "kimi-code.json"),
|
||||
kimiCredentialPath(dir),
|
||||
JSON.stringify({
|
||||
access_token: accessToken,
|
||||
refresh_token: "rt_kimi",
|
||||
expires_at: 1_798_812_800,
|
||||
expires_in: 900,
|
||||
scope: "kimi-code",
|
||||
token_type: "Bearer",
|
||||
...overrides,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -397,7 +404,9 @@ describe("real provider usage fetchers", () => {
|
||||
new KimiQuotaProvider({
|
||||
logger,
|
||||
fetch: fetchThroughTestDouble,
|
||||
homeDir: options.kimiHomeDir,
|
||||
// Never leave this undefined: the provider would fall back to os.homedir() and
|
||||
// read — and now write — the developer's real Kimi credentials.
|
||||
homeDir: options.kimiHomeDir ?? homeDir,
|
||||
}),
|
||||
new MiniMaxQuotaProvider({
|
||||
logger,
|
||||
@@ -921,6 +930,226 @@ describe("real provider usage fetchers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reads Kimi credentials whose optional fields are null", async () => {
|
||||
writeKimiCredentials(join(homeDir, ".kimi-code"), "kimi_cli_token", {
|
||||
expires_at: null,
|
||||
expires_in: null,
|
||||
scope: null,
|
||||
token_type: null,
|
||||
});
|
||||
fetchApi = mockFetch(
|
||||
new Map([
|
||||
[
|
||||
"https://api.kimi.com/coding/v1/usages",
|
||||
() => jsonResponse({ usage: { limit: "100", remaining: "60" } }),
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
const kimi = findProvider(await service({ kimiHomeDir: homeDir }).listUsage(), "kimi");
|
||||
|
||||
expect(kimi.status).toBe("available");
|
||||
});
|
||||
|
||||
it("persists refreshed Kimi tokens to the credential file that was read", async () => {
|
||||
writeKimiCredentials(join(homeDir, ".kimi-code"), "at_kimi_expired", {
|
||||
preserved_field: "keep-me",
|
||||
});
|
||||
const authorization: Array<string | null> = [];
|
||||
let usageCalls = 0;
|
||||
fetchApi = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => {
|
||||
const endpoint = url.toString();
|
||||
if (endpoint === "https://api.kimi.com/coding/v1/usages") {
|
||||
usageCalls += 1;
|
||||
authorization.push(
|
||||
(init?.headers as Record<string, string> | undefined)?.Authorization ?? null,
|
||||
);
|
||||
if (usageCalls === 1) return new Response(null, { status: 401 });
|
||||
return jsonResponse({ usage: { limit: "100", remaining: "74" } });
|
||||
}
|
||||
if (endpoint === "https://auth.kimi.com/api/oauth/token") {
|
||||
expect(init?.method).toBe("POST");
|
||||
expect(init?.body?.toString()).toContain("grant_type=refresh_token");
|
||||
expect(init?.body?.toString()).toContain("refresh_token=rt_kimi");
|
||||
return jsonResponse({
|
||||
access_token: "at_kimi_fresh",
|
||||
refresh_token: "rt_kimi_rotated",
|
||||
expires_in: 900,
|
||||
});
|
||||
}
|
||||
throw new Error(`Unmocked fetch: ${endpoint}`);
|
||||
}) as never;
|
||||
|
||||
const result = await service({ kimiHomeDir: homeDir }).listUsage();
|
||||
const persisted = JSON.parse(
|
||||
readFileSync(kimiCredentialPath(join(homeDir, ".kimi-code")), "utf8"),
|
||||
);
|
||||
|
||||
expect(findProvider(result, "kimi").status).toBe("available");
|
||||
expect(authorization).toEqual(["Bearer at_kimi_expired", "Bearer at_kimi_fresh"]);
|
||||
expect(persisted).toMatchObject({
|
||||
access_token: "at_kimi_fresh",
|
||||
refresh_token: "rt_kimi_rotated",
|
||||
expires_in: 900,
|
||||
scope: "kimi-code",
|
||||
preserved_field: "keep-me",
|
||||
});
|
||||
expect(persisted.expires_at).toBeGreaterThan(Date.now() / 1000);
|
||||
});
|
||||
|
||||
it("prefers a Kimi token rewritten on disk over refreshing again", async () => {
|
||||
const kimiHome = join(homeDir, ".kimi-code");
|
||||
writeKimiCredentials(kimiHome, "at_kimi_old");
|
||||
let usageCalls = 0;
|
||||
fetchApi = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => {
|
||||
const endpoint = url.toString();
|
||||
if (endpoint === "https://api.kimi.com/coding/v1/usages") {
|
||||
usageCalls += 1;
|
||||
if (usageCalls === 1) {
|
||||
writeKimiCredentials(kimiHome, "at_kimi_rewritten");
|
||||
return new Response(null, { status: 401 });
|
||||
}
|
||||
expect((init?.headers as Record<string, string> | undefined)?.Authorization).toBe(
|
||||
"Bearer at_kimi_rewritten",
|
||||
);
|
||||
return jsonResponse({ usage: { limit: "100", remaining: "50" } });
|
||||
}
|
||||
throw new Error(`Unmocked fetch: ${endpoint}`);
|
||||
}) as never;
|
||||
|
||||
const result = await service({ kimiHomeDir: homeDir }).listUsage();
|
||||
|
||||
expect(findProvider(result, "kimi").status).toBe("available");
|
||||
expect(usageCalls).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps Kimi credentials rotated by the CLI during the refresh", async () => {
|
||||
const kimiHome = join(homeDir, ".kimi-code");
|
||||
writeKimiCredentials(kimiHome, "at_kimi_expired");
|
||||
fetchApi = mockFetch(
|
||||
new Map([
|
||||
["https://api.kimi.com/coding/v1/usages", () => new Response(null, { status: 401 })],
|
||||
[
|
||||
"https://auth.kimi.com/api/oauth/token",
|
||||
() => {
|
||||
writeKimiCredentials(kimiHome, "at_kimi_cli", { refresh_token: "rt_kimi_cli" });
|
||||
return jsonResponse({
|
||||
access_token: "at_kimi_fresh",
|
||||
refresh_token: "rt_kimi_rotated",
|
||||
expires_in: 900,
|
||||
});
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
await service({ kimiHomeDir: homeDir }).listUsage();
|
||||
const persisted = JSON.parse(readFileSync(kimiCredentialPath(kimiHome), "utf8"));
|
||||
|
||||
expect(persisted).toMatchObject({
|
||||
access_token: "at_kimi_cli",
|
||||
refresh_token: "rt_kimi_cli",
|
||||
});
|
||||
});
|
||||
|
||||
it("discards a refreshed Kimi merge if the CLI rotates credentials after the guard but before the rename", async () => {
|
||||
const kimiHome = join(homeDir, ".kimi-code");
|
||||
writeKimiCredentials(kimiHome, "at_kimi_expired");
|
||||
fetchApi = mockFetch(
|
||||
new Map([
|
||||
["https://api.kimi.com/coding/v1/usages", () => new Response(null, { status: 401 })],
|
||||
[
|
||||
"https://auth.kimi.com/api/oauth/token",
|
||||
() =>
|
||||
jsonResponse({
|
||||
access_token: "at_kimi_fresh",
|
||||
refresh_token: "rt_kimi_fresh",
|
||||
expires_in: 900,
|
||||
}),
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
// The credential-file guard runs, passes, and only then does the CLI rotate the file
|
||||
// — simulated by mutating the file as a side effect of the temp-file write, which is
|
||||
// the async I/O step that sits between the guard read and the final rename.
|
||||
const realWriteFile = fsPromises.writeFile;
|
||||
const writeFileSpy = vi
|
||||
.spyOn(fsPromises, "writeFile")
|
||||
.mockImplementationOnce(async (...args: Parameters<typeof fsPromises.writeFile>) => {
|
||||
writeKimiCredentials(kimiHome, "at_kimi_cli", { refresh_token: "rt_kimi_cli" });
|
||||
return realWriteFile(...args);
|
||||
});
|
||||
|
||||
await service({ kimiHomeDir: homeDir }).listUsage();
|
||||
const persisted = JSON.parse(readFileSync(kimiCredentialPath(kimiHome), "utf8"));
|
||||
|
||||
expect(persisted).toMatchObject({
|
||||
access_token: "at_kimi_cli",
|
||||
refresh_token: "rt_kimi_cli",
|
||||
});
|
||||
|
||||
writeFileSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("does not recreate a Kimi credential file deleted during the refresh", async () => {
|
||||
const credentialPath = kimiCredentialPath(join(homeDir, ".kimi-code"));
|
||||
writeKimiCredentials(join(homeDir, ".kimi-code"), "at_kimi_expired");
|
||||
fetchApi = mockFetch(
|
||||
new Map([
|
||||
["https://api.kimi.com/coding/v1/usages", () => new Response(null, { status: 401 })],
|
||||
[
|
||||
"https://auth.kimi.com/api/oauth/token",
|
||||
() => {
|
||||
rmSync(credentialPath, { force: true });
|
||||
return jsonResponse({ access_token: "at_kimi_fresh", expires_in: 900 });
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await service({ kimiHomeDir: homeDir }).listUsage();
|
||||
|
||||
expect(findProvider(result, "kimi").status).toBe("unavailable");
|
||||
expect(existsSync(credentialPath)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns unavailable Kimi usage when the token refresh is rejected", async () => {
|
||||
writeKimiCredentials(join(homeDir, ".kimi-code"), "at_kimi_expired");
|
||||
fetchApi = mockFetch(
|
||||
new Map([
|
||||
["https://api.kimi.com/coding/v1/usages", () => new Response(null, { status: 401 })],
|
||||
["https://auth.kimi.com/api/oauth/token", () => new Response(null, { status: 400 })],
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await service({ kimiHomeDir: homeDir }).listUsage();
|
||||
|
||||
expect(findProvider(result, "kimi").status).toBe("unavailable");
|
||||
});
|
||||
|
||||
it("does not refresh Kimi tokens read from the environment", async () => {
|
||||
process.env["KIMI_TOKEN"] = "kimi_test_token";
|
||||
const usageFetch = vi.fn(async () => new Response(null, { status: 401 }));
|
||||
fetchApi = usageFetch as never;
|
||||
|
||||
const result = await service().listUsage();
|
||||
|
||||
expect(findProvider(result, "kimi").status).toBe("unavailable");
|
||||
expect(usageFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not refresh Kimi tokens on a 403", async () => {
|
||||
writeKimiCredentials(join(homeDir, ".kimi-code"), "at_kimi_forbidden");
|
||||
const usageFetch = vi.fn(async () => new Response(null, { status: 403 }));
|
||||
fetchApi = usageFetch as never;
|
||||
|
||||
const result = await service({ kimiHomeDir: homeDir }).listUsage();
|
||||
|
||||
expect(findProvider(result, "kimi").status).toBe("unavailable");
|
||||
expect(usageFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("fetches MiniMax usage from MINIMAX_API_KEY against the global endpoint", async () => {
|
||||
process.env["MINIMAX_API_KEY"] = "minimax_test_token";
|
||||
let requestedUrl: string | null = null;
|
||||
@@ -1488,3 +1717,145 @@ describe("ClaudeQuotaProvider scoped limit reconciliation", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("KimiQuotaProvider usage windows", () => {
|
||||
afterEach(() => {
|
||||
delete process.env["KIMI_TOKEN"];
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("normalizes weekly and enforced rolling usage windows", async () => {
|
||||
process.env["KIMI_TOKEN"] = "kimi_test_token";
|
||||
const fetchApi = vi.fn(async () =>
|
||||
jsonResponse({
|
||||
limited: true,
|
||||
usage: {
|
||||
limit: "100",
|
||||
used: "61",
|
||||
remaining: "39",
|
||||
resetTime: "2026-08-05T00:01:45Z",
|
||||
},
|
||||
limits: [
|
||||
{
|
||||
window: {
|
||||
duration: 300,
|
||||
timeUnit: "TIME_UNIT_MINUTE",
|
||||
},
|
||||
detail: {
|
||||
limit: "100",
|
||||
used: "100",
|
||||
resetTime: "2026-07-31T17:01:45Z",
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const provider = new KimiQuotaProvider({ logger: createLogger(), fetch: fetchApi });
|
||||
|
||||
const usage = await provider.fetchUsage();
|
||||
|
||||
expect(usage).toMatchObject({
|
||||
status: "available",
|
||||
windows: [
|
||||
{
|
||||
id: "coding_usage",
|
||||
label: "Weekly limit",
|
||||
usedPct: 61,
|
||||
remainingPct: 39,
|
||||
resetsAt: "2026-08-05T00:01:45Z",
|
||||
tone: "ok",
|
||||
},
|
||||
{
|
||||
id: "coding_limit_300_time_unit_minute",
|
||||
label: "5-hour limit",
|
||||
usedPct: 100,
|
||||
remainingPct: 0,
|
||||
resetsAt: "2026-07-31T17:01:45Z",
|
||||
tone: "danger",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps valid windows when another limits entry is malformed", async () => {
|
||||
process.env["KIMI_TOKEN"] = "kimi_test_token";
|
||||
const logger = createLogger() as unknown as { debug: ReturnType<typeof vi.fn> };
|
||||
const fetchApi = vi.fn(async () =>
|
||||
jsonResponse({
|
||||
usage: {
|
||||
limit: "100",
|
||||
remaining: "75",
|
||||
resetTime: "2026-08-05T00:01:45Z",
|
||||
},
|
||||
limits: [
|
||||
{ window: { duration: "invalid" }, detail: {} },
|
||||
{
|
||||
window: { duration: 300, timeUnit: "TIME_UNIT_MINUTE" },
|
||||
detail: { limit: "100", remaining: "50" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const provider = new KimiQuotaProvider({ logger: logger as never, fetch: fetchApi });
|
||||
|
||||
const usage = await provider.fetchUsage();
|
||||
|
||||
expect(usage.windows).toHaveLength(2);
|
||||
expect(usage.windows[1]).toMatchObject({
|
||||
label: "5-hour limit",
|
||||
usedPct: 50,
|
||||
remainingPct: 50,
|
||||
});
|
||||
expect(logger.debug).toHaveBeenCalledWith(
|
||||
{ index: 0 },
|
||||
"Ignoring malformed Kimi usage limit window",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts direct limit fields, alternate reset keys, and provider labels", async () => {
|
||||
process.env["KIMI_TOKEN"] = "kimi_test_token";
|
||||
const fetchApi = vi.fn(async () =>
|
||||
jsonResponse({
|
||||
usage: null,
|
||||
limits: [
|
||||
{
|
||||
name: "Burst quota",
|
||||
limit: "80",
|
||||
remaining: "20",
|
||||
reset_at: "2026-08-01T00:00:00Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const provider = new KimiQuotaProvider({ logger: createLogger(), fetch: fetchApi });
|
||||
|
||||
const usage = await provider.fetchUsage();
|
||||
|
||||
expect(usage.windows).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "coding_limit_burst_quota",
|
||||
label: "Burst quota",
|
||||
usedPct: 75,
|
||||
remainingPct: 25,
|
||||
resetsAt: "2026-08-01T00:00:00Z",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps window ids unique when Kimi returns duplicate limit descriptors", async () => {
|
||||
process.env["KIMI_TOKEN"] = "kimi_test_token";
|
||||
const duplicate = {
|
||||
window: { duration: 300, timeUnit: "TIME_UNIT_MINUTE" },
|
||||
detail: { limit: "100", used: "10" },
|
||||
};
|
||||
const fetchApi = vi.fn(async () => jsonResponse({ limits: [duplicate, duplicate] }));
|
||||
const provider = new KimiQuotaProvider({ logger: createLogger(), fetch: fetchApi });
|
||||
|
||||
const usage = await provider.fetchUsage();
|
||||
|
||||
expect(usage.windows.map((window) => window.id)).toEqual([
|
||||
"coding_limit_300_time_unit_minute",
|
||||
"coding_limit_300_time_unit_minute_2",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user