flexgate 0.12.2__tar.gz → 0.13.0__tar.gz

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.
Files changed (44) hide show
  1. {flexgate-0.12.2 → flexgate-0.13.0}/CLAUDE.md +3 -2
  2. {flexgate-0.12.2 → flexgate-0.13.0}/PKG-INFO +8 -6
  3. {flexgate-0.12.2 → flexgate-0.13.0}/README.md +7 -5
  4. {flexgate-0.12.2 → flexgate-0.13.0}/docs/cli.md +7 -5
  5. {flexgate-0.12.2 → flexgate-0.13.0}/docs/usage.md +19 -9
  6. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/__init__.py +1 -1
  7. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/cli.py +25 -9
  8. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/usage.py +24 -9
  9. flexgate-0.13.0/tests/test_usage.py +104 -0
  10. {flexgate-0.12.2 → flexgate-0.13.0}/.github/workflows/docs.yml +0 -0
  11. {flexgate-0.12.2 → flexgate-0.13.0}/.github/workflows/release.yml +0 -0
  12. {flexgate-0.12.2 → flexgate-0.13.0}/.gitignore +0 -0
  13. {flexgate-0.12.2 → flexgate-0.13.0}/config.yaml.template +0 -0
  14. {flexgate-0.12.2 → flexgate-0.13.0}/docs/Makefile +0 -0
  15. {flexgate-0.12.2 → flexgate-0.13.0}/docs/_static/.gitkeep +0 -0
  16. {flexgate-0.12.2 → flexgate-0.13.0}/docs/api.md +0 -0
  17. {flexgate-0.12.2 → flexgate-0.13.0}/docs/conf.py +0 -0
  18. {flexgate-0.12.2 → flexgate-0.13.0}/docs/configuration.md +0 -0
  19. {flexgate-0.12.2 → flexgate-0.13.0}/docs/development.md +0 -0
  20. {flexgate-0.12.2 → flexgate-0.13.0}/docs/index.md +0 -0
  21. {flexgate-0.12.2 → flexgate-0.13.0}/docs/quickstart.md +0 -0
  22. {flexgate-0.12.2 → flexgate-0.13.0}/docs/requirements.txt +0 -0
  23. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/__main__.py +0 -0
  24. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/config.py +0 -0
  25. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/doctor.py +0 -0
  26. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/fallback.py +0 -0
  27. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/healthcheck.py +0 -0
  28. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/images.py +0 -0
  29. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/main.py +0 -0
  30. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/migrate.py +0 -0
  31. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/proxy.py +0 -0
  32. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/responses.py +0 -0
  33. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/router.py +0 -0
  34. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/server.py +0 -0
  35. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/service.py +0 -0
  36. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/settings.py +0 -0
  37. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/sync.py +0 -0
  38. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/ui.py +0 -0
  39. {flexgate-0.12.2 → flexgate-0.13.0}/flexgate/update.py +0 -0
  40. {flexgate-0.12.2 → flexgate-0.13.0}/pyproject.toml +0 -0
  41. {flexgate-0.12.2 → flexgate-0.13.0}/test.png +0 -0
  42. {flexgate-0.12.2 → flexgate-0.13.0}/test_multimodal.py +0 -0
  43. {flexgate-0.12.2 → flexgate-0.13.0}/test_multimodal_gateway.py +0 -0
  44. {flexgate-0.12.2 → flexgate-0.13.0}/tests/test_dispatch_translation.py +0 -0
@@ -23,6 +23,7 @@ flexgate service {install|start|stop|restart|reload|status|uninstall}
23
23
  flexgate run # foreground/debug only
24
24
  flexgate status # providers, fallback chains, per-key usage summary, active routes
25
25
  flexgate usage [--force] # per-key usage/quota only; --force rechecks cached failures
26
+ flexgate usage --used # window percentages as used quota (default --remain: remaining)
26
27
  flexgate usage --verbose # raw per-adapter usage lines (pre-0.10 default)
27
28
  flexgate usage --time-format hours # countdown units: dhm (default) / hours / minutes
28
29
  flexgate usage --json # structured JSON (most data commands support --json)
@@ -99,12 +100,12 @@ OpenAI-style client → POST /v1/images/generations
99
100
 
100
101
  | File | Role |
101
102
  |------|------|
102
- | `cli.py` | argparse CLI; service lifecycle commands, foreground `run`, config/settings/sync commands, `flexgate log` journal viewer; unified usage-summary rendering (plan + 5h/weekly percent + reset countdown; `--verbose` for raw lines, `--time-format` units) and `--json` output for every data command (mutating service commands are wrapped so their human output lands in a `log` array) |
103
+ | `cli.py` | argparse CLI; service lifecycle commands, foreground `run`, config/settings/sync commands, `flexgate log` journal viewer; unified usage-summary rendering (plan + labeled 5h/weekly remaining-or-used percent + reset countdown; `usage --remain`/`--used` pick the direction, `--verbose` for raw lines, `--time-format` units) and `--json` output for every data command (mutating service commands are wrapped so their human output lands in a `log` array) |
103
104
  | `ui.py` | Shared terminal styling: ANSI helpers (`bold`/`dim`/`red`/...), `ok`/`warn`/`fail`/`err` output helpers, `emit_json`/`json_fail` (`--json` convention `{"ok": ...}`), `FlexgateHelpFormatter` + `FlexgateParser` (colored help on every Python version; all gated by `NO_COLOR` + stdout isatty) |
104
105
  | `config.py` | Pydantic-like dataclasses (`GatewayConfig`, `ProviderConfig`, `RouteConfig`, `ScheduleEntry`), YAML load/save, `TIER_PATTERNS` regex map, `is_placeholder_key`; `ProviderConfig.wire` selects the upstream protocol (`anthropic` → `{base_url}/v1/messages` + x-api-key, `responses` → `{base_url}/responses` + Bearer) |
105
106
  | `router.py` | `resolve(config, model)` — schedule-first then default routes, first regex match wins; model aliases normalized before matching |
106
107
  | `proxy.py` | `handle_request()` — httpx async proxy, per-key fallback retry loop, SSE streaming + JSON pass-through |
107
- | `usage.py` | `flexgate status` usage queries — per-platform adapters (MiniMax coding_plan API, Kimi Code usages API, GLM coding-plan/team quota APIs, LiteLLM `/key/info`, DeepSeek balance API) plus a minimal chat probe fallback; every adapter also fills a normalized `QuotaInfo` (plan + 5h/weekly `WindowQuota`: remaining percent, reset epoch; plus a `balance` text for prepaid credit) used by the unified summary and `--json`; unreported platform data ("?") stays None → displayed as 0% / no countdown; a key listed under several providers is queried once and reported under a single owner (`_owner_plan` / `duplicate_providers`) |
108
+ | `usage.py` | `flexgate status` usage queries — per-platform adapters (MiniMax coding_plan API, Kimi Code usages API, GLM coding-plan/team quota APIs, LiteLLM `/key/info`, DeepSeek balance API) plus a minimal chat probe fallback; every adapter also fills a normalized `QuotaInfo` (plan + 5h/weekly `WindowQuota`: remaining percent, used/total text, reset epoch; plus a `balance` text for prepaid credit) used by the unified summary and `--json` (windows carry both `remaining_percent` and `used_percent = 100 − remaining`); unreported platform data ("?") stays None → displayed as 0% remaining / 100% used, no countdown; a key listed under several providers is queried once and reported under a single owner (`_owner_plan` / `duplicate_providers`) |
108
109
  | `responses.py` | Responses ⇄ Anthropic translation for `POST /v1/responses` on Anthropic-wire providers: `responses_request_to_anthropic` (input items → messages, instructions → system, tools/tool_choice/max_output_tokens, temperature clamp), `anthropic_to_responses` (text/thinking/tool_use → message/reasoning/function_call items, usage incl. cache tokens, `max_tokens` → `incomplete`), `StreamTranslator` (Anthropic SSE → Responses SSE with continuous `sequence_number` and a guaranteed terminal event), `translate_response` (wraps the proxied Starlette response) |
109
110
  | `server.py` | Starlette app creation, `POST /v1/messages` + `POST /v1/responses` (Codex: passthrough for `wire: responses` providers, `responses.py` translation for every other provider) + `POST /v1/images/{generations,edits}` endpoints, `SIGUSR1` lifespan reload |
110
111
  | `images.py` | OpenAI Images API → MiniMax `/v1/image_generation` translation (`image-01`, size→width/height clamped to 512–2048 mult of 8, `data.image_base64[]`→`data[].b64_json`); edits endpoint returns 501; unknown image model names get 501 `model_not_supported` |
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flexgate
3
- Version: 0.12.2
3
+ Version: 0.13.0
4
4
  Summary: Flexible local API gateway for Claude Code — route models to different providers
5
5
  Project-URL: Homepage, https://github.com/Agony5757/flexible-gateway
6
6
  Project-URL: Repository, https://github.com/Agony5757/flexible-gateway
@@ -240,8 +240,9 @@ Trusted Publisher(repo: `Agony5757/flexible-gateway`,workflow: `release.yml`
240
240
  flexgate status # providers + fallback 链 + 每个 key 的用量摘要 + 当前路由
241
241
  flexgate status --no-usage # 跳过用量查询,只看配置
242
242
  flexgate status --usage-timeout 30
243
- flexgate usage # 只看每个 key 的用量/额度(统一摘要)
243
+ flexgate usage # 只看每个 key 的用量/额度(统一摘要,剩余量)
244
244
  flexgate usage --usage-timeout 30
245
+ flexgate usage --used # 窗口百分比显示为已用量(默认 --remain 显示剩余量)
245
246
  flexgate usage --force # 重查上次失败的 key(默认跳过,读缓存)
246
247
  flexgate usage --verbose # 显示各适配器的原始明细(旧行为)
247
248
  flexgate usage --time-format hours # 倒计时格式:dhm(默认)/ hours / minutes
@@ -251,14 +252,15 @@ flexgate usage --time-format hours # 倒计时格式:dhm(默认)/ hours /
251
252
  fallback 链、当前生效的路由,并逐一查询**每个 key** 的用量/额度;
252
253
  `flexgate usage` 只输出其中的用量部分。
253
254
 
254
- 用量默认输出**统一摘要**——每个 key 一行的套餐名、5h 余额百分比、周余额
255
- 百分比、5h 剩余时间、周用量剩余时间:
255
+ 用量默认输出**统一摘要**——每个 key 一行的套餐名、带 `remaining`/`used`
256
+ 标签的 5h 与周窗口百分比、5h 剩余时间、周用量剩余时间(百分比是剩余
257
+ 还是已用不再有歧义;`--used` 与 `--remain` 互斥,切换显示方向):
256
258
 
257
259
  ```text
258
260
  Usage (timeout 15s per key)
259
261
  zai
260
- ✓ #1 cbc4***sL7n [main] plan pro 5h 88% · 4h 36m weekly 81% · 6d 16h 15m
261
- ✓ #2 302b***RLBh [gsj] plan max 5h 100% · — weekly 99% · 6d 17h 46m
262
+ ✓ #1 cbc4***sL7n [main] plan pro 5h remaining 88% · 4h 36m weekly remaining 81% · 6d 16h 15m
263
+ ✓ #2 302b***RLBh [gsj] plan max 5h remaining 100% · — weekly remaining 99% · 6d 17h 46m
262
264
  ```
263
265
 
264
266
  平台未返回的数据(明细里的 `?`)有固定语义:余额 `?` → `0%`;重置
@@ -223,8 +223,9 @@ Trusted Publisher(repo: `Agony5757/flexible-gateway`,workflow: `release.yml`
223
223
  flexgate status # providers + fallback 链 + 每个 key 的用量摘要 + 当前路由
224
224
  flexgate status --no-usage # 跳过用量查询,只看配置
225
225
  flexgate status --usage-timeout 30
226
- flexgate usage # 只看每个 key 的用量/额度(统一摘要)
226
+ flexgate usage # 只看每个 key 的用量/额度(统一摘要,剩余量)
227
227
  flexgate usage --usage-timeout 30
228
+ flexgate usage --used # 窗口百分比显示为已用量(默认 --remain 显示剩余量)
228
229
  flexgate usage --force # 重查上次失败的 key(默认跳过,读缓存)
229
230
  flexgate usage --verbose # 显示各适配器的原始明细(旧行为)
230
231
  flexgate usage --time-format hours # 倒计时格式:dhm(默认)/ hours / minutes
@@ -234,14 +235,15 @@ flexgate usage --time-format hours # 倒计时格式:dhm(默认)/ hours /
234
235
  fallback 链、当前生效的路由,并逐一查询**每个 key** 的用量/额度;
235
236
  `flexgate usage` 只输出其中的用量部分。
236
237
 
237
- 用量默认输出**统一摘要**——每个 key 一行的套餐名、5h 余额百分比、周余额
238
- 百分比、5h 剩余时间、周用量剩余时间:
238
+ 用量默认输出**统一摘要**——每个 key 一行的套餐名、带 `remaining`/`used`
239
+ 标签的 5h 与周窗口百分比、5h 剩余时间、周用量剩余时间(百分比是剩余
240
+ 还是已用不再有歧义;`--used` 与 `--remain` 互斥,切换显示方向):
239
241
 
240
242
  ```text
241
243
  Usage (timeout 15s per key)
242
244
  zai
243
- ✓ #1 cbc4***sL7n [main] plan pro 5h 88% · 4h 36m weekly 81% · 6d 16h 15m
244
- ✓ #2 302b***RLBh [gsj] plan max 5h 100% · — weekly 99% · 6d 17h 46m
245
+ ✓ #1 cbc4***sL7n [main] plan pro 5h remaining 88% · 4h 36m weekly remaining 81% · 6d 16h 15m
246
+ ✓ #2 302b***RLBh [gsj] plan max 5h remaining 100% · — weekly remaining 99% · 6d 17h 46m
245
247
  ```
246
248
 
247
249
  平台未返回的数据(明细里的 `?`)有固定语义:余额 `?` → `0%`;重置
@@ -25,7 +25,7 @@ usage: flexgate [-h] [--config CONFIG] [--version] [--json]
25
25
 
26
26
  | 命令 | 内容 |
27
27
  |------|------|
28
- | `usage --json [--verbose]` | 每个 key 的套餐名、5h/周窗口剩余百分比与重置倒计时(详见[用量查询](usage.md)) |
28
+ | `usage --json [--verbose]` | 每个 key 的套餐名、5h/周窗口剩余与已用百分比、重置倒计时(详见[用量查询](usage.md)) |
29
29
  | `status --json` | 版本、server、providers(掩码 key)、当前路由 + `usage` 字段(`--no-usage` 时缺省) |
30
30
  | `doctor --json` / `check --json` | `findings[]`(status/label/detail)与 `summary{ok,warn,fail,skip}`,退出码语义不变 |
31
31
  | `update --json [--check]` | 包版本/升级动作、配置 schema 迁移状态、服务 reload 结果与执行日志 |
@@ -83,17 +83,19 @@ flexgate service uninstall # 停止、禁用并删除 unit
83
83
  flexgate status # providers + fallback 链 + 每个 key 的用量摘要 + 当前路由
84
84
  flexgate status --no-usage # 跳过用量查询,只看配置
85
85
  flexgate status --usage-timeout 30
86
- flexgate usage # 只看每个 key 的用量/额度(统一摘要)
86
+ flexgate usage # 只看每个 key 的用量/额度(统一摘要,剩余量)
87
87
  flexgate usage --usage-timeout 30
88
+ flexgate usage --used # 窗口百分比显示为已用量(默认 --remain 显示剩余量)
88
89
  flexgate usage --force # 重查上次失败的 key(默认跳过,读缓存)
89
90
  flexgate usage --verbose # 显示各适配器的原始明细(旧行为)
90
91
  flexgate usage --time-format hours # 倒计时以小时计(dhm / hours / minutes)
91
92
  ```
92
93
 
93
94
  `usage`(及 `status` 的用量段)默认输出**统一摘要**:每个 key 一行的
94
- 套餐名、5h 余额百分比、周余额百分比、5h 剩余时间、周用量剩余时间。
95
- 两者的第一行都会显示本地系统时间(`usage` 单独一行;`status` 附在首行
96
- 版本号旁)。
95
+ 套餐名、带 `remaining`/`used` 标签的 5h 与周窗口百分比、5h 剩余时间、
96
+ 周用量剩余时间——百分比是剩余还是已用一目了然,`--used`(与 `--remain`
97
+ 互斥)切换方向。两者的第一行都会显示本地系统时间(`usage` 单独一行;
98
+ `status` 附在首行版本号旁)。
97
99
  平台未返回的 `?` 值按固定语义处理(余额 `?` → `0%`,重置时间 `?` →
98
100
  `—` 无倒计时)。字段、JSON 结构与 `?` 语义详见[用量查询](usage.md)。
99
101
 
@@ -4,8 +4,10 @@
4
4
  两者的第一行都会显示本地系统时间(`usage` 单独一行;`status` 附在首行
5
5
  版本号旁),标注本次快照的生成时刻。
6
6
  默认输出**统一摘要**:每个 key 一行,包含套餐名、5 小时窗口余额百分比、
7
- 周窗口余额百分比、5 小时窗口剩余时间(距重置的倒计时)和周用量剩余时间;
8
- `--verbose` 才显示各适配器的原始明细。
7
+ 周窗口余额百分比、5 小时窗口剩余时间(距重置的倒计时)和周用量剩余时间。
8
+ 窗口百分比一律带 **`remaining` / `used` 标签**,不再需要猜数字是剩余还是
9
+ 已用:默认显示剩余量(`--remain`),`flexgate usage --used` 改为显示已用量
10
+ (= 100 − 剩余)。`--verbose` 才显示各适配器的原始明细。
9
11
 
10
12
  各平台的查询方式差异很大(有的平台根本没有可用的接口),flexgate 按
11
13
  `base_url` 自动选择适配器;GLM 平台(z.ai / bigmodel.cn)还结合 key 条目
@@ -52,8 +54,8 @@
52
54
 
53
55
  Usage (timeout 15s per key)
54
56
  zhipu
55
- ✓ #1 cbc4***sL7n [main] plan pro 5h 88% · 4h 36m weekly 81% · 6d 16h 15m
56
- ✓ #2 302b***RLBh [gsj] plan max 5h 100% · — weekly 99% · 6d 17h 46m
57
+ ✓ #1 cbc4***sL7n [main] plan pro 5h remaining 88% · 4h 36m weekly remaining 81% · 6d 16h 15m
58
+ ✓ #2 302b***RLBh [gsj] plan max 5h remaining 100% · — weekly remaining 99% · 6d 17h 46m
57
59
  deepseek
58
60
  ✓ #1 sk-c***9e13 [official] balance 489.61 CNY
59
61
  ustc
@@ -62,7 +64,10 @@ Usage (timeout 15s per key)
62
64
 
63
65
  - **plan**:套餐名(GLM 个人版的 pro/max、GLM 团队版的套餐名、Kimi 的会员等级);
64
66
  平台不提供时显示 `—`。
65
- - **5h / weekly 百分比**:窗口**剩余**百分比(≤25% 黄色、≤10% 红色)。
67
+ - **5h / weekly 百分比**:带 `remaining`(剩余)标签的窗口百分比;
68
+ `flexgate usage --used` 换成带 `used` 标签的已用百分比(= 100 − 剩余),
69
+ `--remain`(默认)与 `--used` 互斥。颜色始终按**剩余**量警示:
70
+ 剩余 ≤25% 黄色、≤10% 红色(`--used` 视图下即已用 ≥75% / ≥90%)。
66
71
  - **倒计时**:距窗口重置的剩余时间。`--time-format` 控制格式:
67
72
  - `dhm`(默认):`4d 4h 23m` / `2h 47m` / `23m`
68
73
  - `hours`:`52.1h`
@@ -75,7 +80,7 @@ Usage (timeout 15s per key)
75
80
  平台有时不返回某项数据(verbose 明细里显示 `?`)。统一摘要按如下处理:
76
81
 
77
82
  - **余额 `?` → `0%`**:平台没有报余额时按 0 计(如 Kimi 的
78
- `weekly remaining ?/100`)。
83
+ `weekly remaining ?/100`);`--used` 视图下相应显示 `100%`。
79
84
  - **重置时间 `?` → `—`(无倒计时)**:平台没有返回重置时间通常表示
80
85
  窗口未激活、没有正在进行的计数(如 z.ai / 智谱 5h 窗口用量为 0 时)。
81
86
  JSON 输出中对应字段为 `null`。
@@ -128,12 +133,14 @@ Usage (timeout 15s per key)
128
133
  "plan": null,
129
134
  "five_hour": {
130
135
  "remaining_percent": 100.0,
136
+ "used_percent": 0.0,
131
137
  "remaining_seconds": 9241,
132
138
  "reset_at": "2026-10-07T20:00:00+08:00",
133
139
  "window_hours": 5.0
134
140
  },
135
141
  "weekly": {
136
142
  "remaining_percent": 99.0,
143
+ "used_percent": 1.0,
137
144
  "remaining_seconds": 369241,
138
145
  "reset_at": "2026-10-12T00:00:00+08:00"
139
146
  }
@@ -144,11 +151,14 @@ Usage (timeout 15s per key)
144
151
  }
145
152
  ```
146
153
 
147
- - 字段语义与统一摘要一致:余额未知 → `remaining_percent: 0.0`;
148
- 重置时间未知 → `remaining_seconds`/`reset_at` 为 `null`。
154
+ - 字段语义与统一摘要一致:余额未知 → `remaining_percent: 0.0`
155
+ (`used_percent` 相应为 `100.0`);重置时间未知 →
156
+ `remaining_seconds`/`reset_at` 为 `null`。
157
+ - `used_percent` 恒等于 `100 − remaining_percent`,两个方向都不用再猜。
149
158
  - DeepSeek 的余额在顶层 `balance` 字段(如 `"487.77 CNY"`,多币种以
150
159
  ` · ` 连接)。
151
- - 平台额外信息保留在 `window_hours`(如 5.0)和 `used`(原始用量文本)。
160
+ - 平台额外信息保留在 `window_hours`(如 5.0)和 `used`(已用/总量文本,
161
+ 如 `"264/35000 credits"` 或 `"37/100"`)。
152
162
  - key 一律掩码显示,永不输出明文。
153
163
 
154
164
  ## 查询失败缓存与 `--force`
@@ -1,3 +1,3 @@
1
1
  """Flexgate — Flexible API Gateway for Claude Code."""
2
2
 
3
- __version__ = "0.12.2"
3
+ __version__ = "0.13.0"
@@ -270,7 +270,8 @@ def cmd_usage(args: argparse.Namespace) -> None:
270
270
 
271
271
  print(_dim(_now_str()))
272
272
  _print_usage(config, timeout, force=force, verbose=verbose,
273
- time_format=getattr(args, "time_format", "dhm"))
273
+ time_format=getattr(args, "time_format", "dhm"),
274
+ quota_view=getattr(args, "quota_view", None) or "remain")
274
275
 
275
276
 
276
277
  def _usage_section_json(
@@ -300,13 +301,15 @@ def _usage_marker(r) -> str:
300
301
  return _green("✓") if r.ok else _red("✗")
301
302
 
302
303
 
303
- def _pct_col(wq) -> str:
304
- """Remaining percent, colored by urgency; unknown → 0% (platform "?")."""
305
- value = wq.remaining_percent if (wq is not None and wq.remaining_percent is not None) else 0.0
304
+ def _pct_col(wq, quota_view: str = "remain") -> str:
305
+ """Window percent in the requested view ("remain" or "used"), colored by
306
+ how much quota is left; unknown → 0% remaining / 100% used (platform "?")."""
307
+ remaining = wq.remaining_percent if (wq is not None and wq.remaining_percent is not None) else 0.0
308
+ value = remaining if quota_view != "used" else 100.0 - remaining
306
309
  text = f"{value:.0f}%"
307
- if value <= 10:
310
+ if remaining <= 10:
308
311
  return _red(text)
309
- if value <= 25:
312
+ if remaining <= 25:
310
313
  return _yellow(text)
311
314
  return text
312
315
 
@@ -323,9 +326,12 @@ def _print_usage_summary(
323
326
  time_format: str,
324
327
  duplicates: dict | None = None,
325
328
  order: list[str] | None = None,
329
+ quota_view: str = "remain",
326
330
  ) -> None:
327
- """Unified view: plan, 5h %, weekly %, 5h/weekly reset countdown per key."""
331
+ """Unified view: plan, labeled 5h/weekly remaining-or-used percent and
332
+ reset countdown per key. quota_view picks the percent's direction."""
328
333
  now = time.time()
334
+ word = "remaining" if quota_view != "used" else "used"
329
335
  for name in order or list(usage):
330
336
  results = usage.get(name)
331
337
  if not results:
@@ -355,7 +361,7 @@ def _print_usage_summary(
355
361
  if wq is None:
356
362
  line += f" {label} —"
357
363
  else:
358
- line += f" {label} {_pct_col(wq)} · {_dur_col(wq, time_format, now)}"
364
+ line += f" {label} {word} {_pct_col(wq, quota_view)} · {_dur_col(wq, time_format, now)}"
359
365
  print(line)
360
366
  else:
361
367
  print(f" {marker} {key.ljust(key_w)} {_dim(detail)}")
@@ -374,6 +380,7 @@ def _print_usage(
374
380
  force: bool = False,
375
381
  verbose: bool = False,
376
382
  time_format: str = "dhm",
383
+ quota_view: str = "remain",
377
384
  ) -> None:
378
385
  from flexgate.usage import FORCE_HINT, duplicate_providers, run_usage_check
379
386
 
@@ -387,7 +394,7 @@ def _print_usage(
387
394
  if verbose:
388
395
  _print_usage_verbose(usage, duplicates, order)
389
396
  else:
390
- _print_usage_summary(usage, time_format, duplicates, order)
397
+ _print_usage_summary(usage, time_format, duplicates, order, quota_view=quota_view)
391
398
 
392
399
 
393
400
  def _print_usage_verbose(
@@ -1500,6 +1507,15 @@ def main() -> None:
1500
1507
  "--time-format", choices=("dhm", "hours", "minutes"), default="dhm",
1501
1508
  help="Countdown format: dhm='4d 4h 23m', hours='52.1h', minutes='3125m'"
1502
1509
  )
1510
+ usage_view = usage_p.add_mutually_exclusive_group()
1511
+ usage_view.add_argument(
1512
+ "--remain", dest="quota_view", action="store_const", const="remain",
1513
+ help="Show window percentages as remaining quota (default)"
1514
+ )
1515
+ usage_view.add_argument(
1516
+ "--used", dest="quota_view", action="store_const", const="used",
1517
+ help="Show window percentages as used quota instead of remaining"
1518
+ )
1503
1519
  _add_json_flag(usage_p)
1504
1520
 
1505
1521
  # flexgate log ...
@@ -38,9 +38,9 @@ queries it with the provider's own API key:
38
38
 
39
39
  Alongside the human-readable ``lines``, every adapter fills a normalized
40
40
  ``QuotaInfo`` (plan name + 5-hour/weekly ``WindowQuota`` with remaining
41
- percent and reset epoch, plus a ``balance`` text for prepaid credit) so
42
- the CLI can render one unified summary and ``--json`` consumers get
43
- structured fields. Data a platform did not report
41
+ percent, used/total text and reset epoch, plus a ``balance`` text for
42
+ prepaid credit) so the CLI can render one unified summary and ``--json``
43
+ consumers get structured fields. Data a platform did not report
44
44
  (the "?" cases) stays None: an unknown balance is displayed as 0% and an
45
45
  unknown reset time means no countdown is active.
46
46
 
@@ -94,7 +94,7 @@ class WindowQuota:
94
94
  remaining_percent: float | None = None
95
95
  reset_epoch: float | None = None # epoch seconds
96
96
  window_hours: float | None = None # e.g. 5.0 for a 5-hour window
97
- used_text: str | None = None # raw usage text, e.g. "1513/35000 credits"
97
+ used_text: str | None = None # used/total text, e.g. "1513/35000 credits"
98
98
 
99
99
 
100
100
  @dataclass
@@ -245,6 +245,18 @@ def _pct_from_counts(part, total) -> float | None:
245
245
  return max(0.0, min(100.0, part_f / total_f * 100.0))
246
246
 
247
247
 
248
+ def _used_text_from_remaining(remaining, total) -> str | None:
249
+ """used/total text derived from a platform's remaining/total counts."""
250
+ try:
251
+ rem = float(remaining)
252
+ tot = float(total)
253
+ except (TypeError, ValueError):
254
+ return None
255
+ if tot <= 0 or not 0 <= rem <= tot:
256
+ return None
257
+ return f"{tot - rem:g}/{tot:g}"
258
+
259
+
248
260
  def _epoch_ms(value) -> float | None:
249
261
  """Epoch milliseconds → epoch seconds; None when missing/invalid/zero."""
250
262
  if not value:
@@ -298,8 +310,9 @@ def _minimax_window(row: dict, prefix: str, reset: str, hours: float | None = No
298
310
  remaining = float(row[f"{prefix}_usage_count"])
299
311
  except (KeyError, TypeError, ValueError):
300
312
  return quota
301
- if total > 0 and 0 <= remaining <= total:
302
- quota.used_text = f"{total - remaining:g}/{total:g}"
313
+ used_text = _used_text_from_remaining(remaining, total)
314
+ if used_text is not None:
315
+ quota.used_text = used_text
303
316
  if quota.remaining_percent is None:
304
317
  quota.remaining_percent = _pct_from_counts(remaining, total)
305
318
  return quota
@@ -545,7 +558,7 @@ async def _usage_kimi(
545
558
  quota.weekly = WindowQuota(
546
559
  remaining_percent=_pct_from_counts(weekly.get("remaining"), weekly.get("limit")),
547
560
  reset_epoch=_epoch_from_iso(weekly.get("resetTime")),
548
- used_text=f"{weekly.get('remaining', '?')}/{weekly['limit']}",
561
+ used_text=_used_text_from_remaining(weekly.get("remaining"), weekly.get("limit")),
549
562
  )
550
563
  for limit in data.get("limits", []):
551
564
  if not isinstance(limit, dict):
@@ -571,7 +584,7 @@ async def _usage_kimi(
571
584
  remaining_percent=_pct_from_counts(detail.get("remaining"), detail.get("limit")),
572
585
  reset_epoch=_epoch_from_iso(detail.get("resetTime")),
573
586
  window_hours=hours,
574
- used_text=f"{detail.get('remaining', '?')}/{detail.get('limit', '?')}",
587
+ used_text=_used_text_from_remaining(detail.get("remaining"), detail.get("limit")),
575
588
  )
576
589
  parallel = (data.get("parallel") or {}).get("limit")
577
590
  if parallel:
@@ -851,7 +864,8 @@ def result_to_dict(result: UsageResult, *, verbose: bool = False, now: float | N
851
864
  """One UsageResult as a JSON-ready dict.
852
865
 
853
866
  Semantics for missing platform data: an unknown remaining percent is
854
- reported as 0.0; an unknown reset time yields null (no countdown active).
867
+ reported as 0.0 (used_percent mirrors it as 100.0); an unknown reset
868
+ time yields null (no countdown active).
855
869
  """
856
870
  now = time.time() if now is None else now
857
871
 
@@ -861,6 +875,7 @@ def result_to_dict(result: UsageResult, *, verbose: bool = False, now: float | N
861
875
  pct = wq.remaining_percent if wq.remaining_percent is not None else 0.0
862
876
  out: dict = {
863
877
  "remaining_percent": round(pct, 1),
878
+ "used_percent": round(100.0 - pct, 1),
864
879
  "remaining_seconds": (
865
880
  max(0, int(wq.reset_epoch - now)) if wq.reset_epoch is not None else None
866
881
  ),
@@ -0,0 +1,104 @@
1
+ import contextlib
2
+ import io
3
+ import unittest
4
+ from unittest.mock import patch
5
+
6
+ import httpx
7
+
8
+ from flexgate.cli import _pct_col, _print_usage_summary
9
+ from flexgate.config import ApiKey, ProviderConfig
10
+ from flexgate.usage import (
11
+ QuotaInfo,
12
+ UsageResult,
13
+ WindowQuota,
14
+ _usage_kimi,
15
+ result_to_dict,
16
+ )
17
+
18
+
19
+ class KimiAdapterTests(unittest.IsolatedAsyncioTestCase):
20
+ async def test_used_text_is_used_not_remaining(self):
21
+ provider = ProviderConfig("kimi", "https://api.kimi.com/v1", [ApiKey("test")])
22
+ body = {
23
+ "user": {"membership": {"level": "LEVEL_ADVANCED"}},
24
+ "usage": {"remaining": 63, "limit": 100, "resetTime": "2026-12-13T22:17:00+00:00"},
25
+ "limits": [{
26
+ "window": {"timeUnit": "TIME_UNIT_MINUTE", "duration": 300},
27
+ "detail": {"remaining": 74, "limit": 100, "resetTime": "2026-12-06T22:17:00+00:00"},
28
+ }],
29
+ "parallel": {"limit": 30},
30
+ }
31
+ async with httpx.AsyncClient(transport=httpx.MockTransport(
32
+ lambda req: httpx.Response(200, json=body)
33
+ )) as client:
34
+ lines, quota, err = await _usage_kimi(client, provider, provider.api_keys[0], 3)
35
+ self.assertIsNone(err)
36
+ self.assertAlmostEqual(quota.weekly.remaining_percent, 63.0)
37
+ self.assertEqual(quota.weekly.used_text, "37/100")
38
+ self.assertAlmostEqual(quota.five_hour.remaining_percent, 74.0)
39
+ self.assertEqual(quota.five_hour.used_text, "26/100")
40
+
41
+
42
+ class ResultDictTests(unittest.TestCase):
43
+ def test_used_percent_mirrors_remaining(self):
44
+ quota = QuotaInfo(
45
+ plan="pro",
46
+ five_hour=WindowQuota(remaining_percent=88.0, used_text="264/35000 credits"),
47
+ )
48
+ payload = result_to_dict(
49
+ UsageResult("zai", "key #1 (k)", "m", True, quota=quota, index=0, masked_key="k")
50
+ )
51
+ five = payload["five_hour"]
52
+ self.assertEqual(five["remaining_percent"], 88.0)
53
+ self.assertEqual(five["used_percent"], 12.0)
54
+ self.assertEqual(five["used"], "264/35000 credits")
55
+
56
+ def test_unknown_remaining_is_zero_used_is_full(self):
57
+ quota = QuotaInfo(weekly=WindowQuota())
58
+ payload = result_to_dict(UsageResult("x", "k", "m", True, quota=quota))
59
+ self.assertEqual(payload["weekly"]["remaining_percent"], 0.0)
60
+ self.assertEqual(payload["weekly"]["used_percent"], 100.0)
61
+
62
+
63
+ class SummaryViewTests(unittest.TestCase):
64
+ @staticmethod
65
+ def _usage():
66
+ quota = QuotaInfo(
67
+ plan="pro",
68
+ five_hour=WindowQuota(remaining_percent=88.0),
69
+ weekly=WindowQuota(remaining_percent=81.0),
70
+ )
71
+ return {"zai": [UsageResult("zai", "key #1 (k)", "m", True, quota=quota,
72
+ index=0, masked_key="cbc4***sL7n", note="main")]}
73
+
74
+ def _render(self, **kwargs):
75
+ buf = io.StringIO()
76
+ with patch("flexgate.ui._TTY", False), contextlib.redirect_stdout(buf):
77
+ _print_usage_summary(self._usage(), "dhm", order=["zai"], **kwargs)
78
+ return buf.getvalue()
79
+
80
+ def test_percent_columns_labeled_remaining_by_default(self):
81
+ out = self._render()
82
+ self.assertIn("5h remaining 88%", out)
83
+ self.assertIn("weekly remaining 81%", out)
84
+ self.assertNotIn("used", out)
85
+
86
+ def test_used_view_flips_and_labels(self):
87
+ out = self._render(quota_view="used")
88
+ self.assertIn("5h used 12%", out)
89
+ self.assertIn("weekly used 19%", out)
90
+ self.assertNotIn("remaining", out)
91
+
92
+ def test_pct_col_views(self):
93
+ wq = WindowQuota(remaining_percent=88.0)
94
+ with patch("flexgate.ui._TTY", False):
95
+ self.assertEqual(_pct_col(wq), "88%")
96
+ self.assertEqual(_pct_col(wq, "remain"), "88%")
97
+ self.assertEqual(_pct_col(wq, "used"), "12%")
98
+ unknown = WindowQuota()
99
+ self.assertEqual(_pct_col(unknown), "0%")
100
+ self.assertEqual(_pct_col(unknown, "used"), "100%")
101
+
102
+
103
+ if __name__ == "__main__":
104
+ unittest.main()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes