flexgate 0.11.3__tar.gz → 0.12.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.
- {flexgate-0.11.3 → flexgate-0.12.0}/CLAUDE.md +17 -5
- {flexgate-0.11.3 → flexgate-0.12.0}/PKG-INFO +82 -3
- {flexgate-0.11.3 → flexgate-0.12.0}/README.md +81 -2
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/api.md +44 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/cli.md +6 -2
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/configuration.md +1 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/usage.md +21 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/__init__.py +1 -1
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/cli.py +58 -15
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/config.py +24 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/fallback.py +12 -5
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/healthcheck.py +29 -13
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/proxy.py +19 -7
- flexgate-0.12.0/flexgate/responses.py +1060 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/server.py +63 -1
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/sync.py +18 -3
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/usage.py +77 -3
- {flexgate-0.11.3 → flexgate-0.12.0}/.github/workflows/docs.yml +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/.github/workflows/release.yml +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/.gitignore +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/config.yaml.template +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/Makefile +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/_static/.gitkeep +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/conf.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/development.md +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/index.md +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/quickstart.md +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/docs/requirements.txt +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/__main__.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/doctor.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/images.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/main.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/migrate.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/router.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/service.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/settings.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/ui.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/flexgate/update.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/pyproject.toml +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/test.png +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/test_multimodal.py +0 -0
- {flexgate-0.11.3 → flexgate-0.12.0}/test_multimodal_gateway.py +0 -0
|
@@ -42,7 +42,8 @@ flexgate settings apply --dry-run # preview the env diff without writi
|
|
|
42
42
|
# confsync config sync
|
|
43
43
|
flexgate sync # pull: replace local config.yaml with the remote document (backup first)
|
|
44
44
|
flexgate sync push # upload local config.yaml to the server
|
|
45
|
-
flexgate sync --dry-run # preview
|
|
45
|
+
flexgate sync --dry-run # preview pull: reads remote, writes nothing locally
|
|
46
|
+
flexgate sync push --dry-run # preview push: uploads nothing (no new remote version)
|
|
46
47
|
|
|
47
48
|
# Versioning / upgrades
|
|
48
49
|
flexgate --version # print package version
|
|
@@ -77,11 +78,19 @@ without a systemd user instance.
|
|
|
77
78
|
|
|
78
79
|
```
|
|
79
80
|
Claude Code → POST /v1/messages (model="claude-sonnet-4-6")
|
|
80
|
-
→ server.py (Starlette app, /v1/messages + /v1/images/* routes)
|
|
81
|
+
→ server.py (Starlette app, /v1/messages + /v1/responses + /v1/images/* routes)
|
|
81
82
|
→ router.py (resolve(): regex match model, check schedule windows first, then default routes)
|
|
82
83
|
→ proxy.py (rewrite model field if override, swap x-api-key, SSE streaming pass-through)
|
|
83
84
|
→ Upstream provider (z.ai, minimax, xiaomi, etc.)
|
|
84
85
|
|
|
86
|
+
Codex CLI → POST /v1/responses (model="glm-5.3", wire_api="responses")
|
|
87
|
+
→ server.py (same regex routing on the body's model field)
|
|
88
|
+
→ wire: responses provider → proxy.py passthrough to {base_url}/responses with Bearer auth
|
|
89
|
+
→ any other provider → responses.py translates Responses ⇄ Anthropic Messages,
|
|
90
|
+
then proxy.py to {base_url}/v1/messages with x-api-key
|
|
91
|
+
→ Responses-compatible upstream (z.ai /api/v1/responses, kimi.com /coding/v1/responses)
|
|
92
|
+
or an Anthropic-wire upstream (zhipu, MiniMax, Xiaomi MiMo, DeepSeek, ...)
|
|
93
|
+
|
|
85
94
|
OpenAI-style client → POST /v1/images/generations
|
|
86
95
|
→ images.py (translate to MiniMax /v1/image_generation; provider auto-detected by base_url)
|
|
87
96
|
```
|
|
@@ -92,11 +101,12 @@ OpenAI-style client → POST /v1/images/generations
|
|
|
92
101
|
|------|------|
|
|
93
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) |
|
|
94
103
|
| `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) |
|
|
95
|
-
| `config.py` | Pydantic-like dataclasses (`GatewayConfig`, `ProviderConfig`, `RouteConfig`, `ScheduleEntry`), YAML load/save, `TIER_PATTERNS` regex map, `is_placeholder_key` |
|
|
104
|
+
| `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) |
|
|
96
105
|
| `router.py` | `resolve(config, model)` — schedule-first then default routes, first regex match wins; model aliases normalized before matching |
|
|
97
106
|
| `proxy.py` | `handle_request()` — httpx async proxy, per-key fallback retry loop, SSE streaming + JSON pass-through |
|
|
98
|
-
| `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 |
|
|
99
|
-
| `
|
|
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
|
+
| `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
|
+
| `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 |
|
|
100
110
|
| `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` |
|
|
101
111
|
| `fallback.py` | Catch-all route: merged Anthropic/OpenAI-shaped JSON errors for every unserved path — 404 `route_not_found` (lists valid routes), 405 `method_not_allowed`, 501 `endpoint_not_supported` per recognized API family with an actionable reason |
|
|
102
112
|
| `main.py` | Thin bootstrap: load config → create app → run uvicorn |
|
|
@@ -117,6 +127,8 @@ OpenAI-style client → POST /v1/images/generations
|
|
|
117
127
|
- **Key fallback** (`proxy.py`): a provider's `api_keys` list holds one or more keys for the same upstream (entries are key strings or `{key, note}` mappings — plus optional `organization`/`project` on GLM team keys, used only by the usage check; `note` is a free-form label shown by `flexgate status` and in fallback logs). Multiple accounts on one upstream — e.g. several MiniMax subscriptions — belong in ONE provider, not separate ones. GLM coding plans are the documented exception: z.ai (api.z.ai) and zhipu (open.bigmodel.cn) share one account system — the same keys work on both endpoints, so a provider's `base_url` can be swapped freely when one endpoint is unstable (convention: one provider per key set, `zhipu`/`zhipu-team` on bigmodel). Each *route* has an active-key pointer (`active_key` in YAML, 1-based; `RouteConfig.key_index` 0-based, default first key): requests on that route start from the pointed key, and on a retryable failure (HTTP 401/402/403/429/500/502/503/529, connect error, or timeout) the next key is tried and the pointer advances with it (in memory only, wrapping around — it is not written back to the file); every key is tried at most once and a full circle of failures returns the last error. The pointer is set interactively via `flexgate config edit` → "api keys" (pick a route, with live per-key usage) or by editing the route's `active_key` directly. `resolve()` (`router.py`) returns the matched `RouteConfig` so the proxy can read/advance its pointer. Streaming requests can only fall back before the upstream returns 200. `_regular_proxy`/`_stream_proxy` return `(response, retryable)`; `handle_request` owns the loop and returns the last error when all keys fail. The legacy `api_key` + `fallback_keys` schema is still parsed (`config._parse_api_keys`); migration v3 → v4 rewrites it to `api_keys`. `ProviderConfig.api_key` remains as a first-key property (getter/setter) for the settings import code.
|
|
118
128
|
- **Usage inspection** (`usage.py`): `flexgate status` maps `base_url` to a platform adapter (`_ADAPTERS`): MiniMax → `{origin}/v1/api/openplatform/coding_plan/remains` (only the "general" text-model quota entry is used; its counts are usually 0/0, so usage is read from the `*_remaining_percent` fields), Kimi Code → `{base}/v1/usages` (undocumented, same endpoint as the CLI's `/usage`; reports weekly quota, 5-hour window and parallel limit), GLM (z.ai / bigmodel.cn, one account system — same keys on both endpoints) → adapter picked per key entry: without `organization`/`project` it is a personal coding-plan key → `{origin}/api/monitor/usage/quota/limit` (undocumented but used by z.ai's own plugin; both endpoints serve it), with them it is a team key → the same endpoint with `?type=2` plus `bigmodel-organization`/`bigmodel-project` headers and the team subscription detail for plan name/expiry (both endpoints serve it too), USTC/LiteLLM → `{origin}/key/info`, DeepSeek → `{origin}/user/balance` (prepaid total per currency normalized into `QuotaInfo.balance`, shown next to the key in the unified summary). Hosts in `_PROBE_ONLY_MARKERS` (e.g. xiaomimimo.com — no key-based usage API) and unknown platforms get the minimal chat probe: `POST /v1/messages` with input `"hi"`, `max_tokens=128`. A failed adapter call also degrades to the probe. Any key whose usage query errored — a hard failure (adapter AND probe), or an adapter error merely recovered by the probe — is recorded in `~/.flexgate/usage-cache.json` (sha256 fingerprint of `base_url|key`, never key material — scoped by endpoint so the same key under two providers caches independently; entry keeps the `ok` flag and output lines) and skipped by later `status`/`usage` runs, shown as `cached (… ago)` / `cached failure (… ago)` with a hint; `flexgate usage --force` rechecks them and a clean success clears the entry. Placeholder keys are never cached.
|
|
119
129
|
- **Multimodal degradation**: `MULTIMODAL_MODELS` (currently `{"MiniMax-M3", "glm-4.6v"}`) is the allowlist. Requests carrying image blocks aimed at any other model have images stripped and a `[flexgate]` text note injected into both the outgoing request and the returned response, so non-multimodal backends don't 4xx.
|
|
130
|
+
- **Responses translation** (`responses.py`): `/v1/responses` serves every provider, not just `wire: responses` ones. Anthropic-wire providers get a translated request (`instructions` + system/developer items → `system`; input items → role-merged `messages`; `max_output_tokens` → `max_tokens`, default 8192; `function`/`local_shell`/`custom` tools → Anthropic `tools`; `tool_choice: none` drops the tools; `parallel_tool_calls: false` → `disable_parallel_tool_use`; temperature clamped to 0–1) and a re-framed answer (text → `message`, thinking → `reasoning`, `tool_use` → `function_call`/`custom_tool_call`, `stop_reason: max_tokens` → `status: incomplete`, cache tokens folded into `input_tokens`). Streaming is rebuilt as Responses SSE (`response.created` → per-item added/delta/done → `response.completed`/`incomplete`/`failed`) with continuous `sequence_number`s and a terminal event even when the upstream stream is cut; a non-SSE 200 body is framed as a single completed response; upstream non-200 answers keep their status and body. `reasoning.effort`, `include`, `store`, `previous_response_id` are ignored. The translated request goes through the normal proxy path, so key fallback, image stripping and hot reload all apply unchanged.
|
|
131
|
+
- **Usage dedupe** (`usage.py`): a key listed under several providers (e.g. `zai-responses` sharing keys with `zhipu`) is queried once and reported under one owner — adapter-capable beats probe-only, anthropic wire beats responses wire, then config order. Non-owning providers are left out of the usage result and rendered as a dim "same key(s) already shown under …" line; `--json` exposes the mapping as `usage.duplicates`.
|
|
120
132
|
- **Schedule-based overrides**: Optional time windows (e.g. 22:00-06:00) override default routes. Overnight wrap is supported.
|
|
121
133
|
- **Service-first lifecycle**: `flexgate.service` is the sole persistent runtime. systemd owns restart, boot startup, logs, and process state.
|
|
122
134
|
- **Hot config reload**: `flexgate service reload` sends `SIGUSR1` for routing-only changes and restarts when the applied config path or endpoint changed. Same-port host changes require an explicit stop/start.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: flexgate
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.12.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
|
|
@@ -20,7 +20,7 @@ Description-Content-Type: text/markdown
|
|
|
20
20
|
[](https://pypi.org/project/flexgate/)
|
|
21
21
|
[](https://agony5757.github.io/flexible-gateway/)
|
|
22
22
|
|
|
23
|
-
本地 Anthropic API 网关,根据请求中的 model 名称自动路由到不同的 provider。同时提供 Claude Code settings.json
|
|
23
|
+
本地 Anthropic API 网关,根据请求中的 model 名称自动路由到不同的 provider。同时提供 Claude Code settings.json 的自动管理功能,并通过 `/v1/responses` 支持 Codex CLI:Responses 兼容上游(z.ai、Kimi 等)直接透传,其余 anthropic wire 的 provider(智谱、MiniMax、小米、DeepSeek 等)由网关做协议转换。
|
|
24
24
|
|
|
25
25
|
完整文档见 **[agony5757.github.io/flexible-gateway](https://agony5757.github.io/flexible-gateway/)**(Sphinx 构建,源文件在 `docs/`,随 main 分支自动发布)。
|
|
26
26
|
|
|
@@ -32,6 +32,77 @@ Claude Code 只能配置一个 `ANTHROPIC_BASE_URL`,所有 tier(opus/sonnet/
|
|
|
32
32
|
Claude Code → localhost:8765 → opus → z.ai (glm-5.1)
|
|
33
33
|
→ sonnet → minimax (MiniMax-M3)
|
|
34
34
|
→ haiku → minimax (MiniMax-M3)
|
|
35
|
+
|
|
36
|
+
Codex CLI → localhost:8765/v1/responses → glm-5.3 → z.ai (Responses API,原生透传)
|
|
37
|
+
→ k3.1-pro → kimi.com (Responses API,原生透传)
|
|
38
|
+
→ MiniMax-M4 → minimax (协议转换)
|
|
39
|
+
→ mimo-v2.6-pro → xiaomi (协议转换)
|
|
40
|
+
→ deepseek-flash → deepseek (协议转换)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Codex CLI 支持
|
|
44
|
+
|
|
45
|
+
Codex CLI(≥0.84)只说 OpenAI Responses 协议(`wire_api = "chat"` 已被移除)。flexgate 的
|
|
46
|
+
`POST /v1/responses` 端点按同样的 model 正则路由,key 轮换/调度/热重载全部复用:
|
|
47
|
+
|
|
48
|
+
- 路由命中声明了 `wire: responses` 的 provider(z.ai `https://api.z.ai/api/v1`、
|
|
49
|
+
Kimi `https://api.kimi.com/coding/v1` 等)时**原样透传**,不做任何改写;
|
|
50
|
+
- 路由命中 anthropic wire 的 provider(智谱、MiniMax、小米 MiMo、DeepSeek 等只提供
|
|
51
|
+
`{base_url}/v1/messages` 的上游)时,网关做**协议转换**:Responses 请求 → Anthropic
|
|
52
|
+
Messages 请求,Anthropic 回答(JSON 与 SSE)→ Responses 回答。因此 Codex CLI 可以直接
|
|
53
|
+
用这些 provider 的模型,无需它们自己支持 Responses。
|
|
54
|
+
|
|
55
|
+
转换覆盖:`instructions`/system 消息 → `system`;input items(消息、`function_call`、
|
|
56
|
+
`function_call_output`、`input_image`、`input_file`)→ `messages`;`max_output_tokens` →
|
|
57
|
+
`max_tokens`(缺省 8192);`tools`(`function` / `local_shell` / `custom`)→ Anthropic
|
|
58
|
+
`tools`;`tool_choice` / `parallel_tool_calls` → Anthropic `tool_choice`;上游 `text` /
|
|
59
|
+
`thinking` / `tool_use` 块 → `message` / `reasoning` / `function_call`(custom 工具为
|
|
60
|
+
`custom_tool_call`)item;`stop_reason: max_tokens` → `status: incomplete`;usage 含缓存
|
|
61
|
+
token 折算进 `input_tokens` / `input_tokens_details.cached_tokens`。流式按
|
|
62
|
+
`response.created` → 逐 item 的 added/delta/done → `response.completed` 重新成帧,上游
|
|
63
|
+
流被截断时也会发出终止事件。`reasoning.effort`、`include`、`store`、
|
|
64
|
+
`previous_response_id` 等字段被忽略(上游无对应能力)。
|
|
65
|
+
|
|
66
|
+
`~/.codex/config.toml` 接入方式(配合 `~/.codex/models.json` 模型目录):
|
|
67
|
+
|
|
68
|
+
```toml
|
|
69
|
+
model_provider = "flexgate"
|
|
70
|
+
model = "glm-5.3"
|
|
71
|
+
model_catalog_json = "~/.codex/models.json"
|
|
72
|
+
|
|
73
|
+
[model_providers.flexgate]
|
|
74
|
+
name = "Flexgate"
|
|
75
|
+
base_url = "http://127.0.0.1:8765/v1"
|
|
76
|
+
wire_api = "responses"
|
|
77
|
+
experimental_bearer_token = "gateway" # 占位符,网关替换为真实 key
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
对应 `config.yaml` 片段(原生透传 + 协议转换两种 provider 混用):
|
|
81
|
+
|
|
82
|
+
```yaml
|
|
83
|
+
providers:
|
|
84
|
+
zai-responses: # 原生 Responses 上游:透传
|
|
85
|
+
base_url: "https://api.z.ai/api/v1"
|
|
86
|
+
wire: responses
|
|
87
|
+
api_keys:
|
|
88
|
+
- "your-glm-api-key"
|
|
89
|
+
available_models: ["glm-5.3", "glm-5.3-flash"]
|
|
90
|
+
|
|
91
|
+
minimax: # anthropic wire:/v1/responses 走协议转换
|
|
92
|
+
base_url: "https://api.minimaxi.com/anthropic"
|
|
93
|
+
api_keys:
|
|
94
|
+
- "your-minimax-api-key"
|
|
95
|
+
available_models: ["MiniMax-M4"]
|
|
96
|
+
|
|
97
|
+
routes:
|
|
98
|
+
- pattern: "^glm-5\\.3-flash"
|
|
99
|
+
provider: zai-responses
|
|
100
|
+
model: "glm-5.3-flash"
|
|
101
|
+
- pattern: "^glm-"
|
|
102
|
+
provider: zai-responses
|
|
103
|
+
model: "glm-5.3"
|
|
104
|
+
- pattern: "^MiniMax"
|
|
105
|
+
provider: minimax # Codex 里用 MiniMax-M4 即可
|
|
35
106
|
```
|
|
36
107
|
|
|
37
108
|
> **运行原则:持久化只走 service。** Linux 上的持久化 serve 只由 systemd 用户服务
|
|
@@ -194,6 +265,13 @@ Usage (timeout 15s per key)
|
|
|
194
265
|
时间 `?` → `—`(无倒计时,窗口未计数)。`--verbose` 显示原始明细;
|
|
195
266
|
`--json` 输出结构化数据(见下)。
|
|
196
267
|
|
|
268
|
+
**同一个 key 只查一次、只显示一次**:一个 key 同时挂在两个 provider 下时
|
|
269
|
+
(典型场景:原生 Responses 的 `zai-responses` 与 anthropic wire 的 `zhipu`
|
|
270
|
+
共用同一批 key),查询会归到一个「归属」provider(优先有专用用量接口的、
|
|
271
|
+
再优先 anthropic wire 的),另一个 provider 不再重复查询,只显示一行提示
|
|
272
|
+
(如 `zai-responses same key(s) already shown under zhipu`);
|
|
273
|
+
`--json` 里对应 `duplicates` 字段。
|
|
274
|
+
|
|
197
275
|
各平台的用量查询方式差异很大,flexgate 按 `base_url` 自动选择适配器
|
|
198
276
|
(GLM 平台还按 key 条目是否配置 `organization`/`project` 区分个人版/团队版):
|
|
199
277
|
|
|
@@ -219,7 +297,7 @@ Usage (timeout 15s per key)
|
|
|
219
297
|
|
|
220
298
|
### HTTP API(图像生成与结构化错误)
|
|
221
299
|
|
|
222
|
-
除 `POST /v1/messages`
|
|
300
|
+
除 `POST /v1/messages` 和 `POST /v1/responses`(OpenAI Responses,Codex CLI 用;原生透传或协议转换)外,网关还提供 OpenAI 兼容的图像生成端点
|
|
223
301
|
`POST /v1/images/generations`:自动发现配置中的 MiniMax provider,把请求
|
|
224
302
|
翻译为 MiniMax `image-01` 文生图(模型名提示如 `gpt-image`/`dall-e` 均可,
|
|
225
303
|
`size` 钳制到 512–2048 的 8 倍数,响应为 `data[].b64_json`)。
|
|
@@ -411,6 +489,7 @@ routes: # 从上到下匹配,首个命中生效
|
|
|
411
489
|
|------|------|
|
|
412
490
|
| `server.host/port` | 网关监听地址 |
|
|
413
491
|
| `providers.<name>.base_url` | Provider 的 API 地址 |
|
|
492
|
+
| `providers.<name>.wire` | 上游协议:`anthropic`(默认,`{base_url}/v1/messages` + x-api-key)或 `responses`(`{base_url}/responses` + Bearer,原生 Responses 上游)。`/v1/responses` 请求命中 anthropic wire 的 provider 时由网关做协议转换 |
|
|
414
493
|
| `providers.<name>.api_keys` | API key 列表(一个或多个,互为 fallback);每项为 key 字符串或 `{key, note}`(`note` 是备注)。智谱团队版 key 还可加 `organization`/`project`(团队组织/项目 ID),供 `flexgate usage` 查询团队套餐额度 |
|
|
415
494
|
| `providers.<name>.available_models` | 该 provider 的可用模型列表,首个条目作为路由省略 `model` 时的回退模型 |
|
|
416
495
|
| `claude_settings.*` | 写入 settings.json 的模型和超时配置 |
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
[](https://pypi.org/project/flexgate/)
|
|
4
4
|
[](https://agony5757.github.io/flexible-gateway/)
|
|
5
5
|
|
|
6
|
-
本地 Anthropic API 网关,根据请求中的 model 名称自动路由到不同的 provider。同时提供 Claude Code settings.json
|
|
6
|
+
本地 Anthropic API 网关,根据请求中的 model 名称自动路由到不同的 provider。同时提供 Claude Code settings.json 的自动管理功能,并通过 `/v1/responses` 支持 Codex CLI:Responses 兼容上游(z.ai、Kimi 等)直接透传,其余 anthropic wire 的 provider(智谱、MiniMax、小米、DeepSeek 等)由网关做协议转换。
|
|
7
7
|
|
|
8
8
|
完整文档见 **[agony5757.github.io/flexible-gateway](https://agony5757.github.io/flexible-gateway/)**(Sphinx 构建,源文件在 `docs/`,随 main 分支自动发布)。
|
|
9
9
|
|
|
@@ -15,6 +15,77 @@ Claude Code 只能配置一个 `ANTHROPIC_BASE_URL`,所有 tier(opus/sonnet/
|
|
|
15
15
|
Claude Code → localhost:8765 → opus → z.ai (glm-5.1)
|
|
16
16
|
→ sonnet → minimax (MiniMax-M3)
|
|
17
17
|
→ haiku → minimax (MiniMax-M3)
|
|
18
|
+
|
|
19
|
+
Codex CLI → localhost:8765/v1/responses → glm-5.3 → z.ai (Responses API,原生透传)
|
|
20
|
+
→ k3.1-pro → kimi.com (Responses API,原生透传)
|
|
21
|
+
→ MiniMax-M4 → minimax (协议转换)
|
|
22
|
+
→ mimo-v2.6-pro → xiaomi (协议转换)
|
|
23
|
+
→ deepseek-flash → deepseek (协议转换)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
### Codex CLI 支持
|
|
27
|
+
|
|
28
|
+
Codex CLI(≥0.84)只说 OpenAI Responses 协议(`wire_api = "chat"` 已被移除)。flexgate 的
|
|
29
|
+
`POST /v1/responses` 端点按同样的 model 正则路由,key 轮换/调度/热重载全部复用:
|
|
30
|
+
|
|
31
|
+
- 路由命中声明了 `wire: responses` 的 provider(z.ai `https://api.z.ai/api/v1`、
|
|
32
|
+
Kimi `https://api.kimi.com/coding/v1` 等)时**原样透传**,不做任何改写;
|
|
33
|
+
- 路由命中 anthropic wire 的 provider(智谱、MiniMax、小米 MiMo、DeepSeek 等只提供
|
|
34
|
+
`{base_url}/v1/messages` 的上游)时,网关做**协议转换**:Responses 请求 → Anthropic
|
|
35
|
+
Messages 请求,Anthropic 回答(JSON 与 SSE)→ Responses 回答。因此 Codex CLI 可以直接
|
|
36
|
+
用这些 provider 的模型,无需它们自己支持 Responses。
|
|
37
|
+
|
|
38
|
+
转换覆盖:`instructions`/system 消息 → `system`;input items(消息、`function_call`、
|
|
39
|
+
`function_call_output`、`input_image`、`input_file`)→ `messages`;`max_output_tokens` →
|
|
40
|
+
`max_tokens`(缺省 8192);`tools`(`function` / `local_shell` / `custom`)→ Anthropic
|
|
41
|
+
`tools`;`tool_choice` / `parallel_tool_calls` → Anthropic `tool_choice`;上游 `text` /
|
|
42
|
+
`thinking` / `tool_use` 块 → `message` / `reasoning` / `function_call`(custom 工具为
|
|
43
|
+
`custom_tool_call`)item;`stop_reason: max_tokens` → `status: incomplete`;usage 含缓存
|
|
44
|
+
token 折算进 `input_tokens` / `input_tokens_details.cached_tokens`。流式按
|
|
45
|
+
`response.created` → 逐 item 的 added/delta/done → `response.completed` 重新成帧,上游
|
|
46
|
+
流被截断时也会发出终止事件。`reasoning.effort`、`include`、`store`、
|
|
47
|
+
`previous_response_id` 等字段被忽略(上游无对应能力)。
|
|
48
|
+
|
|
49
|
+
`~/.codex/config.toml` 接入方式(配合 `~/.codex/models.json` 模型目录):
|
|
50
|
+
|
|
51
|
+
```toml
|
|
52
|
+
model_provider = "flexgate"
|
|
53
|
+
model = "glm-5.3"
|
|
54
|
+
model_catalog_json = "~/.codex/models.json"
|
|
55
|
+
|
|
56
|
+
[model_providers.flexgate]
|
|
57
|
+
name = "Flexgate"
|
|
58
|
+
base_url = "http://127.0.0.1:8765/v1"
|
|
59
|
+
wire_api = "responses"
|
|
60
|
+
experimental_bearer_token = "gateway" # 占位符,网关替换为真实 key
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
对应 `config.yaml` 片段(原生透传 + 协议转换两种 provider 混用):
|
|
64
|
+
|
|
65
|
+
```yaml
|
|
66
|
+
providers:
|
|
67
|
+
zai-responses: # 原生 Responses 上游:透传
|
|
68
|
+
base_url: "https://api.z.ai/api/v1"
|
|
69
|
+
wire: responses
|
|
70
|
+
api_keys:
|
|
71
|
+
- "your-glm-api-key"
|
|
72
|
+
available_models: ["glm-5.3", "glm-5.3-flash"]
|
|
73
|
+
|
|
74
|
+
minimax: # anthropic wire:/v1/responses 走协议转换
|
|
75
|
+
base_url: "https://api.minimaxi.com/anthropic"
|
|
76
|
+
api_keys:
|
|
77
|
+
- "your-minimax-api-key"
|
|
78
|
+
available_models: ["MiniMax-M4"]
|
|
79
|
+
|
|
80
|
+
routes:
|
|
81
|
+
- pattern: "^glm-5\\.3-flash"
|
|
82
|
+
provider: zai-responses
|
|
83
|
+
model: "glm-5.3-flash"
|
|
84
|
+
- pattern: "^glm-"
|
|
85
|
+
provider: zai-responses
|
|
86
|
+
model: "glm-5.3"
|
|
87
|
+
- pattern: "^MiniMax"
|
|
88
|
+
provider: minimax # Codex 里用 MiniMax-M4 即可
|
|
18
89
|
```
|
|
19
90
|
|
|
20
91
|
> **运行原则:持久化只走 service。** Linux 上的持久化 serve 只由 systemd 用户服务
|
|
@@ -177,6 +248,13 @@ Usage (timeout 15s per key)
|
|
|
177
248
|
时间 `?` → `—`(无倒计时,窗口未计数)。`--verbose` 显示原始明细;
|
|
178
249
|
`--json` 输出结构化数据(见下)。
|
|
179
250
|
|
|
251
|
+
**同一个 key 只查一次、只显示一次**:一个 key 同时挂在两个 provider 下时
|
|
252
|
+
(典型场景:原生 Responses 的 `zai-responses` 与 anthropic wire 的 `zhipu`
|
|
253
|
+
共用同一批 key),查询会归到一个「归属」provider(优先有专用用量接口的、
|
|
254
|
+
再优先 anthropic wire 的),另一个 provider 不再重复查询,只显示一行提示
|
|
255
|
+
(如 `zai-responses same key(s) already shown under zhipu`);
|
|
256
|
+
`--json` 里对应 `duplicates` 字段。
|
|
257
|
+
|
|
180
258
|
各平台的用量查询方式差异很大,flexgate 按 `base_url` 自动选择适配器
|
|
181
259
|
(GLM 平台还按 key 条目是否配置 `organization`/`project` 区分个人版/团队版):
|
|
182
260
|
|
|
@@ -202,7 +280,7 @@ Usage (timeout 15s per key)
|
|
|
202
280
|
|
|
203
281
|
### HTTP API(图像生成与结构化错误)
|
|
204
282
|
|
|
205
|
-
除 `POST /v1/messages`
|
|
283
|
+
除 `POST /v1/messages` 和 `POST /v1/responses`(OpenAI Responses,Codex CLI 用;原生透传或协议转换)外,网关还提供 OpenAI 兼容的图像生成端点
|
|
206
284
|
`POST /v1/images/generations`:自动发现配置中的 MiniMax provider,把请求
|
|
207
285
|
翻译为 MiniMax `image-01` 文生图(模型名提示如 `gpt-image`/`dall-e` 均可,
|
|
208
286
|
`size` 钳制到 512–2048 的 8 倍数,响应为 `data[].b64_json`)。
|
|
@@ -394,6 +472,7 @@ routes: # 从上到下匹配,首个命中生效
|
|
|
394
472
|
|------|------|
|
|
395
473
|
| `server.host/port` | 网关监听地址 |
|
|
396
474
|
| `providers.<name>.base_url` | Provider 的 API 地址 |
|
|
475
|
+
| `providers.<name>.wire` | 上游协议:`anthropic`(默认,`{base_url}/v1/messages` + x-api-key)或 `responses`(`{base_url}/responses` + Bearer,原生 Responses 上游)。`/v1/responses` 请求命中 anthropic wire 的 provider 时由网关做协议转换 |
|
|
397
476
|
| `providers.<name>.api_keys` | API key 列表(一个或多个,互为 fallback);每项为 key 字符串或 `{key, note}`(`note` 是备注)。智谱团队版 key 还可加 `organization`/`project`(团队组织/项目 ID),供 `flexgate usage` 查询团队套餐额度 |
|
|
398
477
|
| `providers.<name>.available_models` | 该 provider 的可用模型列表,首个条目作为路由省略 `model` 时的回退模型 |
|
|
399
478
|
| `claude_settings.*` | 写入 settings.json 的模型和超时配置 |
|
|
@@ -5,6 +5,7 @@ Flexgate 在本地监听(默认 `127.0.0.1:8765`)提供以下端点:
|
|
|
5
5
|
| 端点 | 说明 |
|
|
6
6
|
|------|------|
|
|
7
7
|
| `POST /v1/messages` | Anthropic Messages API 代理(核心端点) |
|
|
8
|
+
| `POST /v1/responses` | OpenAI Responses API(Codex CLI):原生 Responses 上游透传,其余 provider 走协议转换 |
|
|
8
9
|
| `POST /v1/images/generations` | OpenAI 兼容图像生成(转 MiniMax `image-01`) |
|
|
9
10
|
| `POST /v1/images/edits` | 固定返回 501(上游仅支持文生图) |
|
|
10
11
|
| 其他路径 | 结构化 JSON 错误(404 / 405 / 501,见下文) |
|
|
@@ -26,6 +27,49 @@ Flexgate 在本地监听(默认 `127.0.0.1:8765`)提供以下端点:
|
|
|
26
27
|
(`MULTIMODAL_MODELS`,当前为 `MiniMax-M3`、`glm-4.6v`)中时,图片会被
|
|
27
28
|
剥离,并在请求与响应中注入 `[flexgate]` 文本说明,避免非多模态上游报 4xx。
|
|
28
29
|
|
|
30
|
+
## POST /v1/responses
|
|
31
|
+
|
|
32
|
+
OpenAI Responses API 端点,Codex CLI 用的协议。请求体中的 `model` 字段走与
|
|
33
|
+
`/v1/messages` 完全相同的正则路由、key fallback 和热重载:
|
|
34
|
+
|
|
35
|
+
- **原生透传**:路由命中 `wire: responses` 的 provider(z.ai
|
|
36
|
+
`https://api.z.ai/api/v1`、Kimi `https://api.kimi.com/coding/v1` 等)时,
|
|
37
|
+
请求与回答(含 SSE)原样转发。
|
|
38
|
+
- **协议转换**:路由命中 anthropic wire 的 provider(智谱、MiniMax、小米 MiMo、
|
|
39
|
+
DeepSeek 等只有 `{base_url}/v1/messages` 的上游)时,由 `flexgate/responses.py`
|
|
40
|
+
双向转换:
|
|
41
|
+
|
|
42
|
+
| Responses 请求 | Anthropic 请求 |
|
|
43
|
+
|----------------|----------------|
|
|
44
|
+
| `instructions`、system/developer 消息 | `system` |
|
|
45
|
+
| input items(消息 / `function_call` / `function_call_output` / `input_image` / `input_file`) | `messages`(相邻同角色合并,工具结果并入同一条 user 消息) |
|
|
46
|
+
| `max_output_tokens` | `max_tokens`(缺省 8192) |
|
|
47
|
+
| `tools`:`function` / `local_shell` / `custom` | `tools`(`input_schema`) |
|
|
48
|
+
| `tool_choice`(`none` 时整体去掉 tools)、`parallel_tool_calls: false` | `tool_choice`(含 `disable_parallel_tool_use`) |
|
|
49
|
+
| `temperature` / `top_p` | 同名(temperature 钳制到 0–1) |
|
|
50
|
+
|
|
51
|
+
| Anthropic 回答 | Responses 回答 |
|
|
52
|
+
|----------------|----------------|
|
|
53
|
+
| `text` 块 | `message` item(`output_text`) |
|
|
54
|
+
| `thinking` 块 | `reasoning` item(`summary_text`) |
|
|
55
|
+
| `tool_use` 块 | `function_call` item(`custom` 工具为 `custom_tool_call`) |
|
|
56
|
+
| `stop_reason: max_tokens` | `status: incomplete` |
|
|
57
|
+
| usage(含 cache 读写 token) | `usage`(缓存 token 折进 `input_tokens`,命中数进 `input_tokens_details.cached_tokens`) |
|
|
58
|
+
|
|
59
|
+
流式按 `response.created` → `response.in_progress` → 逐 item 的
|
|
60
|
+
`output_item.added` / `content_part.added` / `output_text.delta`(或
|
|
61
|
+
`function_call_arguments.delta` / `reasoning_summary_text.delta`)/ `*.done`
|
|
62
|
+
→ `response.completed`(或 `response.incomplete` / `response.failed`)重新
|
|
63
|
+
成帧,`sequence_number` 连续;上游流被截断或中途报错时也会发出终止事件。
|
|
64
|
+
上游返回非 200 时保留原状态码与错误体(key fallback 行为不变)。
|
|
65
|
+
- **忽略的字段**:`reasoning.effort`、`include`、`store`、`previous_response_id`、
|
|
66
|
+
`metadata`、`truncation`、`text.format` 等(上游无对应能力);`input` 中的
|
|
67
|
+
`reasoning` item 不会回放给上游。
|
|
68
|
+
- **多模态**:`input_image` 会转成 Anthropic image 块,因此
|
|
69
|
+
[多模态降级](configuration.md)规则同样生效(非多模态模型剥离图片并注入
|
|
70
|
+
`[flexgate]` 说明)。
|
|
71
|
+
- 只有 `POST /v1/responses`(create)被代理;检索/取消等子路径返回 501。
|
|
72
|
+
|
|
29
73
|
## POST /v1/images/generations
|
|
30
74
|
|
|
31
75
|
OpenAI Images API 兼容端点,让 OpenAI 风格的客户端无需任何额外配置即可
|
|
@@ -31,7 +31,7 @@ usage: flexgate [-h] [--config CONFIG] [--version] [--json]
|
|
|
31
31
|
| `update --json [--check]` | 包版本/升级动作、配置 schema 迁移状态、服务 reload 结果与执行日志 |
|
|
32
32
|
| `config show/path/init/set --json` | 配置全量(key 掩码)、路径、创建结果、路由变更 |
|
|
33
33
|
| `settings import/apply --json` | 导入/应用结果(token 掩码;`apply --dry-run` 不写文件) |
|
|
34
|
-
| `sync --json [--dry-run]` | 动作、服务器、文档、结果(pushed/bootstrapped/replaced)与备份路径 |
|
|
34
|
+
| `sync --json [--dry-run]` | 动作、服务器、文档、结果(pushed/would-push/bootstrapped/would-bootstrap/replaced/would-replace)与备份路径 |
|
|
35
35
|
| `service status --json` | systemd 状态(installed/active/enabled)、unit、配置、applied endpoint、legacy 进程、当前路由 |
|
|
36
36
|
| `service install/uninstall/start/stop/restart/reload --json` | `{"ok", "action", "exit_code", "log": [原人类输出行]}` |
|
|
37
37
|
| `log --json` | journalctl 原生 NDJSON(每行一个 JSON 对象,`-f` 流式;`--grep`/`-r` 过滤 MESSAGE 字段) |
|
|
@@ -275,9 +275,13 @@ confsync 配置段):
|
|
|
275
275
|
flexgate sync # 默认 pull:用远端文档整体替换本地配置(先备份)
|
|
276
276
|
flexgate sync pull # 同上
|
|
277
277
|
flexgate sync push # 上传本地 config.yaml
|
|
278
|
-
flexgate sync --dry-run #
|
|
278
|
+
flexgate sync --dry-run # 只预览,不写配置(pull)
|
|
279
|
+
flexgate sync push --dry-run # 只预览,不上传任何内容(push)
|
|
279
280
|
```
|
|
280
281
|
|
|
282
|
+
`--dry-run` 对两个方向都生效:pull 只读取远端、不写本地文件;push
|
|
283
|
+
不向服务器上传任何内容(不产生新版本),仅打印将要推送的文档与目标服务器。
|
|
284
|
+
|
|
281
285
|
更多细节见 `flexgate help`。
|
|
282
286
|
|
|
283
287
|
## 版本与升级
|
|
@@ -83,6 +83,7 @@ routes: # 从上到下匹配,首个命中生效
|
|
|
83
83
|
|------|------|
|
|
84
84
|
| `server.host/port` | 网关监听地址 |
|
|
85
85
|
| `providers.<name>.base_url` | Provider 的 API 地址 |
|
|
86
|
+
| `providers.<name>.wire` | 上游协议:`anthropic`(默认,`{base_url}/v1/messages` + x-api-key)或 `responses`(`{base_url}/responses` + Bearer,原生 Responses 上游,Codex CLI 用)。`POST /v1/responses` 命中 anthropic wire 的 provider 时由网关做协议转换,见 [HTTP API](api.md#post-v1responses) |
|
|
86
87
|
| `providers.<name>.api_keys` | API key 列表(一个或多个,互为 fallback);每项为 key 字符串或 `{key, note}`(`note` 是备注)。GLM 团队版 key 还可加 `organization`/`project`(团队组织/项目 ID),供 `flexgate usage` 查询团队套餐额度;未配置时按个人版 coding plan key 处理 |
|
|
87
88
|
| `providers.<name>.available_models` | 该 provider 的可用模型列表,首个条目作为路由省略 `model` 时的回退模型 |
|
|
88
89
|
| `claude_settings.*` | 写入 settings.json 的模型和超时配置 |
|
|
@@ -25,6 +25,27 @@
|
|
|
25
25
|
如果某平台的专用接口调用失败,flexgate 会自动退化为 minimal probe 再试
|
|
26
26
|
一次。
|
|
27
27
|
|
|
28
|
+
## 同一个 key 只查一次
|
|
29
|
+
|
|
30
|
+
一个 key 同时挂在两个 provider 下时(典型场景:原生 Responses 的
|
|
31
|
+
`zai-responses` 与 anthropic wire 的 `zhipu` 共用同一批 key),两个 provider
|
|
32
|
+
查询的是同一个账号,会打印两遍同样的额度。flexgate 因此给每个 key 指定
|
|
33
|
+
唯一「归属」provider,按以下顺序挑选:
|
|
34
|
+
|
|
35
|
+
1. 有专用用量接口的 provider 优先于只能 probe 的;
|
|
36
|
+
2. anthropic wire 的 provider 优先于 `wire: responses` 的;
|
|
37
|
+
3. 配置文件中的先后顺序。
|
|
38
|
+
|
|
39
|
+
未被归属的 provider 不再查询,只显示一行提示:
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
zai-responses same key(s) already shown under zhipu
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`flexgate usage --json` / `status --json` 的 `usage.duplicates` 字段给出
|
|
46
|
+
同样的映射(provider → 已展示这些 key 的 provider 列表)。占位符 key 不参与
|
|
47
|
+
去重(本地状态,不发请求)。
|
|
48
|
+
|
|
28
49
|
:::{caution}
|
|
29
50
|
用量查询接口多为平台内部接口,可能随时变动;查询结果仅供参考。
|
|
30
51
|
:::
|
|
@@ -228,11 +228,15 @@ def _status_json_payload(config: GatewayConfig, config_path: str, args: argparse
|
|
|
228
228
|
"routes": _routes_json(config),
|
|
229
229
|
}
|
|
230
230
|
if not getattr(args, "no_usage", False):
|
|
231
|
-
from flexgate.usage import run_usage_check
|
|
231
|
+
from flexgate.usage import duplicate_providers, run_usage_check
|
|
232
232
|
|
|
233
233
|
timeout = getattr(args, "usage_timeout", 15.0)
|
|
234
234
|
usage = run_usage_check(config, timeout=timeout)
|
|
235
|
-
payload["usage"] = _usage_section_json(
|
|
235
|
+
payload["usage"] = _usage_section_json(
|
|
236
|
+
usage, timeout,
|
|
237
|
+
verbose=getattr(args, "verbose", False),
|
|
238
|
+
duplicates=duplicate_providers(config),
|
|
239
|
+
)
|
|
236
240
|
return payload
|
|
237
241
|
|
|
238
242
|
|
|
@@ -250,14 +254,16 @@ def cmd_usage(args: argparse.Namespace) -> None:
|
|
|
250
254
|
verbose = getattr(args, "verbose", False)
|
|
251
255
|
|
|
252
256
|
if _wants_json(args):
|
|
253
|
-
from flexgate.usage import run_usage_check
|
|
257
|
+
from flexgate.usage import duplicate_providers, run_usage_check
|
|
254
258
|
|
|
255
259
|
usage = run_usage_check(config, timeout=timeout, force=force)
|
|
256
260
|
payload = {
|
|
257
261
|
"ok": True,
|
|
258
262
|
"version": __version__,
|
|
259
263
|
"force": force,
|
|
260
|
-
**_usage_section_json(
|
|
264
|
+
**_usage_section_json(
|
|
265
|
+
usage, timeout, verbose=verbose, duplicates=duplicate_providers(config)
|
|
266
|
+
),
|
|
261
267
|
}
|
|
262
268
|
_emit_json(payload)
|
|
263
269
|
return
|
|
@@ -267,7 +273,9 @@ def cmd_usage(args: argparse.Namespace) -> None:
|
|
|
267
273
|
time_format=getattr(args, "time_format", "dhm"))
|
|
268
274
|
|
|
269
275
|
|
|
270
|
-
def _usage_section_json(
|
|
276
|
+
def _usage_section_json(
|
|
277
|
+
usage: dict, timeout: float, *, verbose: bool = False, duplicates: dict | None = None
|
|
278
|
+
) -> dict:
|
|
271
279
|
"""Shared usage payload for `usage --json` and `status --json`."""
|
|
272
280
|
from flexgate.usage import result_to_dict
|
|
273
281
|
|
|
@@ -275,6 +283,7 @@ def _usage_section_json(usage: dict, timeout: float, *, verbose: bool = False) -
|
|
|
275
283
|
return {
|
|
276
284
|
"timeout": timeout,
|
|
277
285
|
"skipped": sum(1 for results in usage.values() for r in results if r.skipped),
|
|
286
|
+
"duplicates": duplicates or {},
|
|
278
287
|
"providers": [
|
|
279
288
|
{
|
|
280
289
|
"provider": name,
|
|
@@ -309,10 +318,19 @@ def _dur_col(wq, time_format: str, now: float) -> str:
|
|
|
309
318
|
return _format_duration(wq.reset_epoch - now, time_format)
|
|
310
319
|
|
|
311
320
|
|
|
312
|
-
def _print_usage_summary(
|
|
321
|
+
def _print_usage_summary(
|
|
322
|
+
usage: dict,
|
|
323
|
+
time_format: str,
|
|
324
|
+
duplicates: dict | None = None,
|
|
325
|
+
order: list[str] | None = None,
|
|
326
|
+
) -> None:
|
|
313
327
|
"""Unified view: plan, 5h %, weekly %, 5h/weekly reset countdown per key."""
|
|
314
328
|
now = time.time()
|
|
315
|
-
for name
|
|
329
|
+
for name in order or list(usage):
|
|
330
|
+
results = usage.get(name)
|
|
331
|
+
if not results:
|
|
332
|
+
_print_duplicate_note(name, (duplicates or {}).get(name), whole=True)
|
|
333
|
+
continue
|
|
316
334
|
print(f" {_bold(_cyan(name))}")
|
|
317
335
|
rows = [] # (result, key, plan|None, five, weekly, detail|None)
|
|
318
336
|
for r in results:
|
|
@@ -342,6 +360,17 @@ def _print_usage_summary(usage: dict, time_format: str) -> None:
|
|
|
342
360
|
print(line)
|
|
343
361
|
else:
|
|
344
362
|
print(f" {marker} {key.ljust(key_w)} {_dim(detail)}")
|
|
363
|
+
_print_duplicate_note(name, (duplicates or {}).get(name))
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _print_duplicate_note(name: str, owners: list[str] | None, whole: bool = False) -> None:
|
|
367
|
+
"""One dim line for a provider whose keys are reported under another one."""
|
|
368
|
+
if not owners:
|
|
369
|
+
return
|
|
370
|
+
if whole:
|
|
371
|
+
print(f" {_bold(_cyan(name))} {_dim('same key(s) already shown under ' + ', '.join(owners))}")
|
|
372
|
+
else:
|
|
373
|
+
print(f" {_dim('other key(s) also shown under ' + ', '.join(owners))}")
|
|
345
374
|
|
|
346
375
|
|
|
347
376
|
def _print_usage(
|
|
@@ -351,24 +380,32 @@ def _print_usage(
|
|
|
351
380
|
verbose: bool = False,
|
|
352
381
|
time_format: str = "dhm",
|
|
353
382
|
) -> None:
|
|
354
|
-
from flexgate.usage import FORCE_HINT, run_usage_check
|
|
383
|
+
from flexgate.usage import FORCE_HINT, duplicate_providers, run_usage_check
|
|
355
384
|
|
|
356
385
|
print("\n" + _bold("Usage") + _dim(f" (timeout {timeout:g}s per key)"))
|
|
357
386
|
usage = run_usage_check(config, timeout=timeout, force=force)
|
|
387
|
+
duplicates = duplicate_providers(config)
|
|
388
|
+
order = [name for name in config.providers if name in usage or name in duplicates]
|
|
358
389
|
skipped = sum(1 for results in usage.values() for r in results if r.skipped)
|
|
359
390
|
if skipped:
|
|
360
391
|
print(_dim(f" {skipped} key(s) skipped — last check failed ({FORCE_HINT})"))
|
|
361
392
|
if verbose:
|
|
362
|
-
_print_usage_verbose(usage)
|
|
393
|
+
_print_usage_verbose(usage, duplicates, order)
|
|
363
394
|
else:
|
|
364
|
-
_print_usage_summary(usage, time_format)
|
|
395
|
+
_print_usage_summary(usage, time_format, duplicates, order)
|
|
365
396
|
|
|
366
397
|
|
|
367
|
-
def _print_usage_verbose(
|
|
398
|
+
def _print_usage_verbose(
|
|
399
|
+
usage: dict, duplicates: dict | None = None, order: list[str] | None = None
|
|
400
|
+
) -> None:
|
|
368
401
|
"""Original per-adapter detail lines (`--verbose`)."""
|
|
369
402
|
from flexgate.usage import FORCE_HINT
|
|
370
403
|
|
|
371
|
-
for name
|
|
404
|
+
for name in order or list(usage):
|
|
405
|
+
results = usage.get(name)
|
|
406
|
+
if not results:
|
|
407
|
+
_print_duplicate_note(name, (duplicates or {}).get(name), whole=True)
|
|
408
|
+
continue
|
|
372
409
|
print(f" {_bold(_cyan(name))}")
|
|
373
410
|
for r in results:
|
|
374
411
|
marker = _usage_marker(r)
|
|
@@ -378,6 +415,7 @@ def _print_usage_verbose(usage: dict) -> None:
|
|
|
378
415
|
print(f" {_dim(line)}")
|
|
379
416
|
else:
|
|
380
417
|
print(f" {line if r.ok else _red(line)}")
|
|
418
|
+
_print_duplicate_note(name, (duplicates or {}).get(name))
|
|
381
419
|
|
|
382
420
|
|
|
383
421
|
# ── settings subcommands ────────────────────────────────────────────
|
|
@@ -398,7 +436,11 @@ def cmd_sync(args: argparse.Namespace) -> None:
|
|
|
398
436
|
from flexgate.sync import sync_pull, sync_push
|
|
399
437
|
action = getattr(args, "action", None) or "pull"
|
|
400
438
|
if action == "push":
|
|
401
|
-
sync_push(
|
|
439
|
+
sync_push(
|
|
440
|
+
args.config,
|
|
441
|
+
dry_run=getattr(args, "dry_run", False),
|
|
442
|
+
as_json=_wants_json(args),
|
|
443
|
+
)
|
|
402
444
|
else:
|
|
403
445
|
sync_pull(
|
|
404
446
|
args.config,
|
|
@@ -1240,7 +1282,8 @@ def _print_sync_help() -> None:
|
|
|
1240
1282
|
{_dim("is a declared dependency. 'flexgate sync' (pull) replaces the local")}
|
|
1241
1283
|
{_dim("config.yaml with the remote document (a timestamped backup is kept); on a")}
|
|
1242
1284
|
{_dim("machine without config.yaml the pull bootstraps the file. Use")}
|
|
1243
|
-
{_dim("'flexgate sync push' to upload
|
|
1285
|
+
{_dim("'flexgate sync push' to upload; --dry-run previews either direction")}
|
|
1286
|
+
{_dim("(push uploads nothing, pull writes nothing locally). The document")}
|
|
1244
1287
|
{_dim("lives at app 'flexgate', name 'config.yaml'. Changes hot-reload the")}
|
|
1245
1288
|
{_dim("running service automatically.")}
|
|
1246
1289
|
""")
|
|
@@ -1512,7 +1555,7 @@ def main() -> None:
|
|
|
1512
1555
|
)
|
|
1513
1556
|
sy.add_argument(
|
|
1514
1557
|
"--dry-run", action="store_true",
|
|
1515
|
-
help="
|
|
1558
|
+
help="Preview only: push uploads nothing, pull writes nothing locally"
|
|
1516
1559
|
)
|
|
1517
1560
|
_add_json_flag(sy)
|
|
1518
1561
|
|