quotacap 0.0.45 → 0.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,6 +35,13 @@ export declare function refreshKimiOAuthToken(oauthHost: string, refreshToken: s
35
35
  refresh_token?: string;
36
36
  expires_in?: number;
37
37
  }>;
38
+ /** The Kimi account has no active subscription (observed: cancelled plan
39
+ * answers /usages 200 with `{}`, /me `user_level_name` "Free", and the TUI
40
+ * shows "No usage data available"). The TUI reports the same state, so the
41
+ * PTY fallback is skipped: report it, do not mask it with a timeout. */
42
+ export declare class KimiSubscriptionInactiveError extends Error {
43
+ constructor(detail: string);
44
+ }
38
45
  /** A refresh rotated the tokens but the result could not be saved for the Kimi CLI. */
39
46
  export declare class KimiCredentialWriteError extends Error {
40
47
  constructor(credPath: string, cause: unknown);
@@ -153,6 +153,14 @@ function parseKimiApiMonthly(u, legacyUsages) {
153
153
  }
154
154
  return {};
155
155
  }
156
+ function isEmptyUsageBody(u) {
157
+ const usage = u.usage;
158
+ const hasUsage = !!usage && typeof usage === "object" && Object.keys(usage).length > 0;
159
+ const hasLimits = Array.isArray(u.limits) && u.limits.length > 0;
160
+ const usages = u.usages;
161
+ const hasUsages = !!usages && typeof usages === "object" && Object.keys(usages).length > 0;
162
+ return !hasUsage && !hasLimits && !hasUsages;
163
+ }
156
164
  export function parseKimiApiUsage(usagesBody, meBody, now = new Date()) {
157
165
  if (typeof usagesBody !== "object" || usagesBody === null) {
158
166
  throw new Error("kimi: invalid api response");
@@ -212,6 +220,21 @@ export function parseKimiApiUsage(usagesBody, meBody, now = new Date()) {
212
220
  }
213
221
  }
214
222
  }
223
+ // 3. Plan identity (from meBody), before the field throws: an empty
224
+ // usage body on a free plan is a dead subscription, not a parse failure.
225
+ let plan = "unknown";
226
+ if (meBody && typeof meBody === "object") {
227
+ const me = meBody;
228
+ if (typeof me.user_level_name === "string" && me.user_level_name.trim().length > 0) {
229
+ plan = me.user_level_name.trim().toLowerCase();
230
+ }
231
+ }
232
+ if (weeklyPct === null && sessionPct === null && !resetsAt && isEmptyUsageBody(u) && plan === "free") {
233
+ throw new KimiSubscriptionInactiveError("plan free, empty usage response");
234
+ }
235
+ // Any other shape without data stays a parse error: an empty body on a
236
+ // paid or unknown plan falls through to the PTY path, whose transcript
237
+ // decides (usage panel vs "No usage data available").
215
238
  if (weeklyPct === null || weeklyPct < 0 || weeklyPct > 100) {
216
239
  throw new Error("kimi: weekly pct not found in api response");
217
240
  }
@@ -221,14 +244,6 @@ export function parseKimiApiUsage(usagesBody, meBody, now = new Date()) {
221
244
  if (!resetsAt || Number.isNaN(new Date(resetsAt).getTime())) {
222
245
  throw new Error("kimi: weekly reset not found in api response");
223
246
  }
224
- // 3. Plan identity (from meBody)
225
- let plan = "unknown";
226
- if (meBody && typeof meBody === "object") {
227
- const me = meBody;
228
- if (typeof me.user_level_name === "string" && me.user_level_name.trim().length > 0) {
229
- plan = me.user_level_name.trim().toLowerCase();
230
- }
231
- }
232
247
  // 4. Optional monthly quota (from limit_month_total, limits, or subscriptionBalance)
233
248
  const monthly = parseKimiApiMonthly(u, legacyUsages);
234
249
  const periodStart = new Date(new Date(resetsAt).getTime() - 7 * 86400000).toISOString();
@@ -377,6 +392,16 @@ export async function refreshKimiOAuthToken(oauthHost, refreshToken, deviceId, s
377
392
  expires_in: typeof data.expires_in === "number" ? data.expires_in : undefined,
378
393
  };
379
394
  }
395
+ /** The Kimi account has no active subscription (observed: cancelled plan
396
+ * answers /usages 200 with `{}`, /me `user_level_name` "Free", and the TUI
397
+ * shows "No usage data available"). The TUI reports the same state, so the
398
+ * PTY fallback is skipped: report it, do not mask it with a timeout. */
399
+ export class KimiSubscriptionInactiveError extends Error {
400
+ constructor(detail) {
401
+ super(`kimi: subscription inactive (${detail})`);
402
+ this.name = "KimiSubscriptionInactiveError";
403
+ }
404
+ }
380
405
  /** A refresh rotated the tokens but the result could not be saved for the Kimi CLI. */
381
406
  export class KimiCredentialWriteError extends Error {
382
407
  constructor(credPath, cause) {
@@ -463,6 +488,11 @@ export async function pollKimiApi(ctx) {
463
488
  headers.Authorization = `Bearer ${freshToken}`;
464
489
  usagesRes = await fetch(usagesUrl, { headers, signal });
465
490
  }
491
+ // 402/403 on an authenticated /usages call is an entitlement state, not
492
+ // a transport failure: the account has no active subscription.
493
+ if (usagesRes.status === 402 || usagesRes.status === 403) {
494
+ throw new KimiSubscriptionInactiveError(`HTTP ${usagesRes.status}`);
495
+ }
466
496
  if (!usagesRes.ok) {
467
497
  throw new Error(`kimi: usage request failed (HTTP ${usagesRes.status})`);
468
498
  }
@@ -520,9 +550,13 @@ export const kimiAdapter = {
520
550
  return await pollKimiApi(authCtx);
521
551
  }
522
552
  catch (e) {
523
- // A lost rotated token leaves the CLI logged out: report it, do not mask it with the PTY path.
553
+ // A lost rotated token leaves the CLI logged out, and a dead
554
+ // subscription reads the same in the TUI: report either, do not
555
+ // mask them with the PTY path.
524
556
  if (e instanceof KimiCredentialWriteError)
525
557
  throw e;
558
+ if (e instanceof KimiSubscriptionInactiveError)
559
+ throw e;
526
560
  }
527
561
  }
528
562
  return pollKimiPty();
@@ -97,7 +97,10 @@ export function buildSnapshot(db, opts) {
97
97
  providerFailed = true;
98
98
  }
99
99
  }
100
- // Precedence: invalid, reset-passed, provider-failed, stale, not-reporting
100
+ // Precedence: invalid, provider-failed, reset-passed, stale, not-reporting.
101
+ // A fresh failure outranks a passed reset: "poll again to capture the new
102
+ // window" is only actionable when polls succeed, and would otherwise mask
103
+ // the real state (e.g. an inactive subscription) behind a re-poll prompt.
101
104
  let exclusionReason = null;
102
105
  if (quota === null) {
103
106
  exclusionReason = "not-reporting";
@@ -105,12 +108,12 @@ export function buildSnapshot(db, opts) {
105
108
  else if (isInvalid) {
106
109
  exclusionReason = "invalid";
107
110
  }
108
- else if (resetPassed) {
109
- exclusionReason = "reset-passed";
110
- }
111
111
  else if (providerFailed) {
112
112
  exclusionReason = "provider-failed";
113
113
  }
114
+ else if (resetPassed) {
115
+ exclusionReason = "reset-passed";
116
+ }
114
117
  else if (stale) {
115
118
  exclusionReason = "stale";
116
119
  }
@@ -86,6 +86,15 @@ const UNRECOGNIZED_OMITTED = "Unrecognized diagnostic text omitted";
86
86
  // "account is not eligible" is the Antigravity sentence; a bare "not eligible" is not.
87
87
  // The hyphen covers "Sign-in with". "signed in with" does not match.
88
88
  const ACCOUNT_CONFIRMATION = /\b(?:account is not eligible|verify your account|eligibility check failed|device code|sign(?:ing)?[ -]in with)\b/i;
89
+ // Cancelled- or missing-subscription wording. The QuotaCap-authored phrase
90
+ // ("subscription inactive", thrown by adapters that detect it directly) plus
91
+ // Kimi's own sentences for the same state: the /usage panel shows "No usage
92
+ // data available" and prompting fails with "[provider.auth_error] 403 ...
93
+ // does not have access to Kimi Code ... Upgrade your plan". Bare "does not
94
+ // have access" is not enough: it must name Kimi Code, so file-permission
95
+ // errors never match. A bare "Upgrade your plan" is not enough either: it
96
+ // can be upsell banner text on an otherwise healthy screen.
97
+ const SUBSCRIPTION_INACTIVE = /\bsubscription inactive\b|\bno usage data available\b|\bprovider\.auth_error\b|\bdoes not have access to Kimi Code\b/i;
89
98
  function matchPrecedence(evidence, errorName, errorCode, text) {
90
99
  // Order 1: timeout — Structured AbortError or an explicit QuotaCap abort/timeout checkpoint.
91
100
  // A ready or completion timeout whose transcript is an account-confirmation
@@ -93,7 +102,13 @@ function matchPrecedence(evidence, errorName, errorCode, text) {
93
102
  // abort stays a timeout even if that screen is in the transcript.
94
103
  const signInTimeout = ACCOUNT_CONFIRMATION.test(text) &&
95
104
  (evidence?.checkpoint === "ready timeout" || evidence?.checkpoint === "completion timeout");
105
+ // Same fall-through for a dead subscription: a completion timeout whose
106
+ // stable transcript is the empty usage panel reports the subscription
107
+ // state, not the timeout that a missing completion pattern caused.
108
+ const inactiveTimeout = SUBSCRIPTION_INACTIVE.test(text) &&
109
+ (evidence?.checkpoint === "ready timeout" || evidence?.checkpoint === "completion timeout");
96
110
  const isAbort = !signInTimeout &&
111
+ !inactiveTimeout &&
97
112
  (errorName === "AbortError" ||
98
113
  errorCode === "ABORT_ERR" ||
99
114
  evidence?.checkpoint === "abort" ||
@@ -158,6 +173,12 @@ function matchPrecedence(evidence, errorName, errorCode, text) {
158
173
  }
159
174
  // Order 6: auth — login required, not logged in, logged out, unauthorized, unauthorised, forbidden,
160
175
  // run <provider> login to continue, or error indicating missing, invalid, or expired credentials, authentication, or API key
176
+ // A dead subscription sorts as auth (the 403 is an authorization state),
177
+ // first in this order so its summary wins over login wording: the user is
178
+ // logged in, and "login required" would mislead.
179
+ if (SUBSCRIPTION_INACTIVE.test(text)) {
180
+ return { code: "auth", phrase: "subscription inactive" };
181
+ }
161
182
  if (/\brun\s+[a-z0-9_:-]+\s+login\s+to\s+continue\b/i.test(text)) {
162
183
  return { code: "auth", phrase: "run <provider> login to continue" };
163
184
  }
@@ -424,7 +445,8 @@ export function diagnosticError(reason, evidence) {
424
445
  const matchedLines = lines.filter((l) => /\b(error|failed|failure|fatal|unauthorized|unauthorised|denied|forbidden|panic|exception)\b/i.test(l) ||
425
446
  /\btrust\b/i.test(l) ||
426
447
  /\b(stdin is not a terminal|device not configured|not a tty|inappropriate ioctl|node-pty)\b/i.test(l) ||
427
- ACCOUNT_CONFIRMATION.test(l));
448
+ ACCOUNT_CONFIRMATION.test(l) ||
449
+ SUBSCRIPTION_INACTIVE.test(l));
428
450
  safeStdoutText = matchedLines.join(" ");
429
451
  }
430
452
  else {
@@ -497,6 +519,12 @@ function getSummaryAndAction(code, providerName, provider, errorDetail) {
497
519
  action: `Open ${providerName} directly in your terminal to check whether it starts. If it works there, inspect the QuotaCap service log and report the adapter failure. Refresh in the dashboard retries through the same service.`,
498
520
  };
499
521
  case "auth":
522
+ if (/\bsubscription inactive\b/i.test(errorDetail)) {
523
+ return {
524
+ summary: `${providerName} subscription inactive`,
525
+ action: `Open ${providerName} to manage your subscription, or run \`quotacap providers disable ${provider}\` to stop polling it. Then select Refresh in the QuotaCap dashboard.`,
526
+ };
527
+ }
500
528
  if (/\baccount confirmation required\b/i.test(errorDetail)) {
501
529
  return {
502
530
  summary: `${providerName} needs you to confirm the subscription account`,
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // generated by scripts/build-embed.mjs — do not edit
2
- export const VERSION = "0.0.45";
2
+ export const VERSION = "0.0.46";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "quotacap",
3
- "version": "0.0.45",
3
+ "version": "0.0.46",
4
4
  "description": "Local quota tracker for AI coding plans with a dashboard, CLI, MCP server, and next-plan recommendations.",
5
5
  "license": "MIT",
6
6
  "keywords": [