flexgate 0.11.2__tar.gz → 0.11.5__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 (41) hide show
  1. {flexgate-0.11.2 → flexgate-0.11.5}/CLAUDE.md +11 -4
  2. {flexgate-0.11.2 → flexgate-0.11.5}/PKG-INFO +48 -3
  3. {flexgate-0.11.2 → flexgate-0.11.5}/README.md +47 -2
  4. {flexgate-0.11.2 → flexgate-0.11.5}/docs/cli.md +8 -2
  5. {flexgate-0.11.2 → flexgate-0.11.5}/docs/usage.md +8 -0
  6. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/__init__.py +1 -1
  7. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/cli.py +17 -4
  8. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/config.py +21 -0
  9. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/fallback.py +12 -5
  10. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/healthcheck.py +29 -13
  11. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/proxy.py +19 -7
  12. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/server.py +51 -1
  13. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/sync.py +18 -3
  14. {flexgate-0.11.2 → flexgate-0.11.5}/.github/workflows/docs.yml +0 -0
  15. {flexgate-0.11.2 → flexgate-0.11.5}/.github/workflows/release.yml +0 -0
  16. {flexgate-0.11.2 → flexgate-0.11.5}/.gitignore +0 -0
  17. {flexgate-0.11.2 → flexgate-0.11.5}/config.yaml.template +0 -0
  18. {flexgate-0.11.2 → flexgate-0.11.5}/docs/Makefile +0 -0
  19. {flexgate-0.11.2 → flexgate-0.11.5}/docs/_static/.gitkeep +0 -0
  20. {flexgate-0.11.2 → flexgate-0.11.5}/docs/api.md +0 -0
  21. {flexgate-0.11.2 → flexgate-0.11.5}/docs/conf.py +0 -0
  22. {flexgate-0.11.2 → flexgate-0.11.5}/docs/configuration.md +0 -0
  23. {flexgate-0.11.2 → flexgate-0.11.5}/docs/development.md +0 -0
  24. {flexgate-0.11.2 → flexgate-0.11.5}/docs/index.md +0 -0
  25. {flexgate-0.11.2 → flexgate-0.11.5}/docs/quickstart.md +0 -0
  26. {flexgate-0.11.2 → flexgate-0.11.5}/docs/requirements.txt +0 -0
  27. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/__main__.py +0 -0
  28. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/doctor.py +0 -0
  29. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/images.py +0 -0
  30. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/main.py +0 -0
  31. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/migrate.py +0 -0
  32. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/router.py +0 -0
  33. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/service.py +0 -0
  34. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/settings.py +0 -0
  35. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/ui.py +0 -0
  36. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/update.py +0 -0
  37. {flexgate-0.11.2 → flexgate-0.11.5}/flexgate/usage.py +0 -0
  38. {flexgate-0.11.2 → flexgate-0.11.5}/pyproject.toml +0 -0
  39. {flexgate-0.11.2 → flexgate-0.11.5}/test.png +0 -0
  40. {flexgate-0.11.2 → flexgate-0.11.5}/test_multimodal.py +0 -0
  41. {flexgate-0.11.2 → flexgate-0.11.5}/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 changes without writing
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,17 @@ 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
+ → proxy.py (passthrough to {base_url}/responses with Bearer auth — provider must
89
+ declare `wire: responses`; no protocol translation)
90
+ → Responses-compatible upstream (z.ai /api/v1/responses, kimi.com /coding/v1/responses)
91
+
85
92
  OpenAI-style client → POST /v1/images/generations
86
93
  → images.py (translate to MiniMax /v1/image_generation; provider auto-detected by base_url)
87
94
  ```
@@ -92,11 +99,11 @@ OpenAI-style client → POST /v1/images/generations
92
99
  |------|------|
93
100
  | `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
101
  | `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` |
102
+ | `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
103
  | `router.py` | `resolve(config, model)` — schedule-first then default routes, first regex match wins; model aliases normalized before matching |
97
104
  | `proxy.py` | `handle_request()` — httpx async proxy, per-key fallback retry loop, SSE streaming + JSON pass-through |
98
105
  | `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
- | `server.py` | Starlette app creation, `POST /v1/messages` + `POST /v1/images/{generations,edits}` endpoints, `SIGUSR1` lifespan reload |
106
+ | `server.py` | Starlette app creation, `POST /v1/messages` + `POST /v1/responses` (Codex passthrough; non-responses providers get a structured `wire_mismatch` 501) + `POST /v1/images/{generations,edits}` endpoints, `SIGUSR1` lifespan reload |
100
107
  | `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
108
  | `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
109
  | `main.py` | Thin bootstrap: load config → create app → run uvicorn |
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flexgate
3
- Version: 0.11.2
3
+ Version: 0.11.5
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
  [![PyPI](https://img.shields.io/pypi/v/flexgate)](https://pypi.org/project/flexgate/)
21
21
  [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](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(GLM、Kimi 等 Responses 兼容上游)。
24
24
 
25
25
  完整文档见 **[agony5757.github.io/flexible-gateway](https://agony5757.github.io/flexible-gateway/)**(Sphinx 构建,源文件在 `docs/`,随 main 分支自动发布)。
26
26
 
@@ -32,6 +32,50 @@ 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
+ ```
39
+
40
+ ### Codex CLI 支持
41
+
42
+ Codex CLI(≥0.84)只说 OpenAI Responses 协议(`wire_api = "chat"` 已被移除)。flexgate 的
43
+ `POST /v1/responses` 端点按同样的 model 正则路由,透传到声明了 `wire: responses` 的 provider
44
+ (z.ai `https://api.z.ai/api/v1`、Kimi `https://api.kimi.com/coding/v1` 等),key 轮换/调度/
45
+ 热重载全部复用。不做协议转换:路由命中 anthropic wire 的 provider 时返回结构化 `wire_mismatch` 错误。
46
+
47
+ `~/.codex/config.toml` 接入方式(配合 `~/.codex/models.json` 模型目录):
48
+
49
+ ```toml
50
+ model_provider = "flexgate"
51
+ model = "glm-5.3"
52
+ model_catalog_json = "~/.codex/models.json"
53
+
54
+ [model_providers.flexgate]
55
+ name = "Flexgate"
56
+ base_url = "http://127.0.0.1:8765/v1"
57
+ wire_api = "responses"
58
+ experimental_bearer_token = "gateway" # 占位符,网关替换为真实 key
59
+ ```
60
+
61
+ 对应 `config.yaml` 片段:
62
+
63
+ ```yaml
64
+ providers:
65
+ zai-responses:
66
+ base_url: "https://api.z.ai/api/v1"
67
+ wire: responses
68
+ api_keys:
69
+ - "your-glm-api-key"
70
+ available_models: ["glm-5.3", "glm-5.3-flash"]
71
+
72
+ routes:
73
+ - pattern: "^glm-5\\.3-flash"
74
+ provider: zai-responses
75
+ model: "glm-5.3-flash"
76
+ - pattern: "^glm-"
77
+ provider: zai-responses
78
+ model: "glm-5.3"
35
79
  ```
36
80
 
37
81
  > **运行原则:持久化只走 service。** Linux 上的持久化 serve 只由 systemd 用户服务
@@ -219,7 +263,7 @@ Usage (timeout 15s per key)
219
263
 
220
264
  ### HTTP API(图像生成与结构化错误)
221
265
 
222
- 除 `POST /v1/messages` 外,网关还提供 OpenAI 兼容的图像生成端点
266
+ 除 `POST /v1/messages` 和 `POST /v1/responses`(OpenAI Responses 透传,Codex CLI 用)外,网关还提供 OpenAI 兼容的图像生成端点
223
267
  `POST /v1/images/generations`:自动发现配置中的 MiniMax provider,把请求
224
268
  翻译为 MiniMax `image-01` 文生图(模型名提示如 `gpt-image`/`dall-e` 均可,
225
269
  `size` 钳制到 512–2048 的 8 倍数,响应为 `data[].b64_json`)。
@@ -411,6 +455,7 @@ routes: # 从上到下匹配,首个命中生效
411
455
  |------|------|
412
456
  | `server.host/port` | 网关监听地址 |
413
457
  | `providers.<name>.base_url` | Provider 的 API 地址 |
458
+ | `providers.<name>.wire` | 上游协议:`anthropic`(默认,`{base_url}/v1/messages` + x-api-key)或 `responses`(`{base_url}/responses` + Bearer,Codex 用,需 Responses 兼容上游) |
414
459
  | `providers.<name>.api_keys` | API key 列表(一个或多个,互为 fallback);每项为 key 字符串或 `{key, note}`(`note` 是备注)。智谱团队版 key 还可加 `organization`/`project`(团队组织/项目 ID),供 `flexgate usage` 查询团队套餐额度 |
415
460
  | `providers.<name>.available_models` | 该 provider 的可用模型列表,首个条目作为路由省略 `model` 时的回退模型 |
416
461
  | `claude_settings.*` | 写入 settings.json 的模型和超时配置 |
@@ -3,7 +3,7 @@
3
3
  [![PyPI](https://img.shields.io/pypi/v/flexgate)](https://pypi.org/project/flexgate/)
4
4
  [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](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(GLM、Kimi 等 Responses 兼容上游)。
7
7
 
8
8
  完整文档见 **[agony5757.github.io/flexible-gateway](https://agony5757.github.io/flexible-gateway/)**(Sphinx 构建,源文件在 `docs/`,随 main 分支自动发布)。
9
9
 
@@ -15,6 +15,50 @@ 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
+ ```
22
+
23
+ ### Codex CLI 支持
24
+
25
+ Codex CLI(≥0.84)只说 OpenAI Responses 协议(`wire_api = "chat"` 已被移除)。flexgate 的
26
+ `POST /v1/responses` 端点按同样的 model 正则路由,透传到声明了 `wire: responses` 的 provider
27
+ (z.ai `https://api.z.ai/api/v1`、Kimi `https://api.kimi.com/coding/v1` 等),key 轮换/调度/
28
+ 热重载全部复用。不做协议转换:路由命中 anthropic wire 的 provider 时返回结构化 `wire_mismatch` 错误。
29
+
30
+ `~/.codex/config.toml` 接入方式(配合 `~/.codex/models.json` 模型目录):
31
+
32
+ ```toml
33
+ model_provider = "flexgate"
34
+ model = "glm-5.3"
35
+ model_catalog_json = "~/.codex/models.json"
36
+
37
+ [model_providers.flexgate]
38
+ name = "Flexgate"
39
+ base_url = "http://127.0.0.1:8765/v1"
40
+ wire_api = "responses"
41
+ experimental_bearer_token = "gateway" # 占位符,网关替换为真实 key
42
+ ```
43
+
44
+ 对应 `config.yaml` 片段:
45
+
46
+ ```yaml
47
+ providers:
48
+ zai-responses:
49
+ base_url: "https://api.z.ai/api/v1"
50
+ wire: responses
51
+ api_keys:
52
+ - "your-glm-api-key"
53
+ available_models: ["glm-5.3", "glm-5.3-flash"]
54
+
55
+ routes:
56
+ - pattern: "^glm-5\\.3-flash"
57
+ provider: zai-responses
58
+ model: "glm-5.3-flash"
59
+ - pattern: "^glm-"
60
+ provider: zai-responses
61
+ model: "glm-5.3"
18
62
  ```
19
63
 
20
64
  > **运行原则:持久化只走 service。** Linux 上的持久化 serve 只由 systemd 用户服务
@@ -202,7 +246,7 @@ Usage (timeout 15s per key)
202
246
 
203
247
  ### HTTP API(图像生成与结构化错误)
204
248
 
205
- 除 `POST /v1/messages` 外,网关还提供 OpenAI 兼容的图像生成端点
249
+ 除 `POST /v1/messages` 和 `POST /v1/responses`(OpenAI Responses 透传,Codex CLI 用)外,网关还提供 OpenAI 兼容的图像生成端点
206
250
  `POST /v1/images/generations`:自动发现配置中的 MiniMax provider,把请求
207
251
  翻译为 MiniMax `image-01` 文生图(模型名提示如 `gpt-image`/`dall-e` 均可,
208
252
  `size` 钳制到 512–2048 的 8 倍数,响应为 `data[].b64_json`)。
@@ -394,6 +438,7 @@ routes: # 从上到下匹配,首个命中生效
394
438
  |------|------|
395
439
  | `server.host/port` | 网关监听地址 |
396
440
  | `providers.<name>.base_url` | Provider 的 API 地址 |
441
+ | `providers.<name>.wire` | 上游协议:`anthropic`(默认,`{base_url}/v1/messages` + x-api-key)或 `responses`(`{base_url}/responses` + Bearer,Codex 用,需 Responses 兼容上游) |
397
442
  | `providers.<name>.api_keys` | API key 列表(一个或多个,互为 fallback);每项为 key 字符串或 `{key, note}`(`note` 是备注)。智谱团队版 key 还可加 `organization`/`project`(团队组织/项目 ID),供 `flexgate usage` 查询团队套餐额度 |
398
443
  | `providers.<name>.available_models` | 该 provider 的可用模型列表,首个条目作为路由省略 `model` 时的回退模型 |
399
444
  | `claude_settings.*` | 写入 settings.json 的模型和超时配置 |
@@ -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 字段) |
@@ -92,6 +92,8 @@ flexgate usage --time-format hours # 倒计时以小时计(dhm / hours / minu
92
92
 
93
93
  `usage`(及 `status` 的用量段)默认输出**统一摘要**:每个 key 一行的
94
94
  套餐名、5h 余额百分比、周余额百分比、5h 剩余时间、周用量剩余时间。
95
+ 两者的第一行都会显示本地系统时间(`usage` 单独一行;`status` 附在首行
96
+ 版本号旁)。
95
97
  平台未返回的 `?` 值按固定语义处理(余额 `?` → `0%`,重置时间 `?` →
96
98
  `—` 无倒计时)。字段、JSON 结构与 `?` 语义详见[用量查询](usage.md)。
97
99
 
@@ -273,9 +275,13 @@ confsync 配置段):
273
275
  flexgate sync # 默认 pull:用远端文档整体替换本地配置(先备份)
274
276
  flexgate sync pull # 同上
275
277
  flexgate sync push # 上传本地 config.yaml
276
- flexgate sync --dry-run # 只预览,不写配置
278
+ flexgate sync --dry-run # 只预览,不写配置(pull)
279
+ flexgate sync push --dry-run # 只预览,不上传任何内容(push)
277
280
  ```
278
281
 
282
+ `--dry-run` 对两个方向都生效:pull 只读取远端、不写本地文件;push
283
+ 不向服务器上传任何内容(不产生新版本),仅打印将要推送的文档与目标服务器。
284
+
279
285
  更多细节见 `flexgate help`。
280
286
 
281
287
  ## 版本与升级
@@ -1,6 +1,8 @@
1
1
  # 用量查询
2
2
 
3
3
  `flexgate status` 和 `flexgate usage` 会逐一查询**每个 key** 的用量/额度。
4
+ 两者的第一行都会显示本地系统时间(`usage` 单独一行;`status` 附在首行
5
+ 版本号旁),标注本次快照的生成时刻。
4
6
  默认输出**统一摘要**:每个 key 一行,包含套餐名、5 小时窗口余额百分比、
5
7
  周窗口余额百分比、5 小时窗口剩余时间(距重置的倒计时)和周用量剩余时间;
6
8
  `--verbose` 才显示各适配器的原始明细。
@@ -30,6 +32,8 @@
30
32
  ## 统一摘要(默认输出)
31
33
 
32
34
  ```text
35
+ 2026-10-07 19:59:42
36
+
33
37
  Usage (timeout 15s per key)
34
38
  zhipu
35
39
  ✓ #1 cbc4***sL7n [main] plan pro 5h 88% · 4h 36m weekly 81% · 6d 16h 15m
@@ -66,6 +70,8 @@ Usage (timeout 15s per key)
66
70
  的原始逐行信息,与旧版输出一致:
67
71
 
68
72
  ```text
73
+ 2026-10-07 20:01:15
74
+
69
75
  Usage (timeout 15s per key)
70
76
  kimi:
71
77
  ✓ key #1 (sk-k***66N6) [ywj] Kimi Code usages API (unofficial)
@@ -139,6 +145,8 @@ provider 下时缓存互不影响),此后 `flexgate status` / `flexgate usag
139
145
  提示:
140
146
 
141
147
  ```text
148
+ 2026-10-07 20:02:33
149
+
142
150
  Usage (timeout 15s per key)
143
151
  2 key(s) skipped — last check failed (recheck with: flexgate usage --force)
144
152
  zai
@@ -1,3 +1,3 @@
1
1
  """Flexgate — Flexible API Gateway for Claude Code."""
2
2
 
3
- __version__ = "0.11.2"
3
+ __version__ = "0.11.5"
@@ -76,6 +76,13 @@ def _format_duration(seconds: float, style: str) -> str:
76
76
  return f"{hours}h {minutes}m"
77
77
  return f"{minutes}m"
78
78
 
79
+
80
+ def _now_str() -> str:
81
+ """Local system time stamped on the first output line of usage/status."""
82
+ from datetime import datetime
83
+
84
+ return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
85
+
79
86
  # ── run (foreground debugging) ─────────────────────────────────────
80
87
 
81
88
  def _service_config_arg(args: argparse.Namespace) -> str | None:
@@ -174,7 +181,7 @@ def cmd_status(args: argparse.Namespace) -> None:
174
181
  _emit_json(_status_json_payload(config, config_path, args))
175
182
  return
176
183
 
177
- print(_bold(f"flexgate {__version__}"))
184
+ print(_bold(f"flexgate {__version__}") + _dim(f" · {_now_str()}"))
178
185
  print(f" {_dim('config:')} {os.path.abspath(config_path)}")
179
186
  print(f" {_dim('server:')} {_cyan(f'{config.server.host}:{config.server.port}')}")
180
187
 
@@ -255,6 +262,7 @@ def cmd_usage(args: argparse.Namespace) -> None:
255
262
  _emit_json(payload)
256
263
  return
257
264
 
265
+ print(_dim(_now_str()))
258
266
  _print_usage(config, timeout, force=force, verbose=verbose,
259
267
  time_format=getattr(args, "time_format", "dhm"))
260
268
 
@@ -390,7 +398,11 @@ def cmd_sync(args: argparse.Namespace) -> None:
390
398
  from flexgate.sync import sync_pull, sync_push
391
399
  action = getattr(args, "action", None) or "pull"
392
400
  if action == "push":
393
- sync_push(args.config, as_json=_wants_json(args))
401
+ sync_push(
402
+ args.config,
403
+ dry_run=getattr(args, "dry_run", False),
404
+ as_json=_wants_json(args),
405
+ )
394
406
  else:
395
407
  sync_pull(
396
408
  args.config,
@@ -1232,7 +1244,8 @@ def _print_sync_help() -> None:
1232
1244
  {_dim("is a declared dependency. 'flexgate sync' (pull) replaces the local")}
1233
1245
  {_dim("config.yaml with the remote document (a timestamped backup is kept); on a")}
1234
1246
  {_dim("machine without config.yaml the pull bootstraps the file. Use")}
1235
- {_dim("'flexgate sync push' to upload, and --dry-run to preview. The document")}
1247
+ {_dim("'flexgate sync push' to upload; --dry-run previews either direction")}
1248
+ {_dim("(push uploads nothing, pull writes nothing locally). The document")}
1236
1249
  {_dim("lives at app 'flexgate', name 'config.yaml'. Changes hot-reload the")}
1237
1250
  {_dim("running service automatically.")}
1238
1251
  """)
@@ -1504,7 +1517,7 @@ def main() -> None:
1504
1517
  )
1505
1518
  sy.add_argument(
1506
1519
  "--dry-run", action="store_true",
1507
- help="Show what would change without writing the config"
1520
+ help="Preview only: push uploads nothing, pull writes nothing locally"
1508
1521
  )
1509
1522
  _add_json_flag(sy)
1510
1523
 
@@ -48,12 +48,21 @@ class ApiKey:
48
48
  project: str = ""
49
49
 
50
50
 
51
+ # Upstream wire protocols. "anthropic" (default) speaks Anthropic Messages
52
+ # (`{base_url}/v1/messages`, x-api-key auth) — the Claude Code path. "responses"
53
+ # speaks the OpenAI Responses API (`{base_url}/responses`, Bearer auth) —
54
+ # what Codex CLI requires; upstreams such as GLM (api.z.ai/api/v1) and Kimi
55
+ # (api.kimi.com/coding/v1) expose Responses-compatible endpoints.
56
+ WIRES = ("anthropic", "responses")
57
+
58
+
51
59
  @dataclass
52
60
  class ProviderConfig:
53
61
  name: str
54
62
  base_url: str
55
63
  api_keys: list[ApiKey] = field(default_factory=list)
56
64
  available_models: list[str] = field(default_factory=list)
65
+ wire: str = "anthropic"
57
66
 
58
67
  @property
59
68
  def default_model(self) -> str | None:
@@ -239,11 +248,17 @@ def load_config(path: str | None = None) -> GatewayConfig:
239
248
  raise ValueError(
240
249
  f"Provider '{name}': 'available_models' must be a list of model names"
241
250
  )
251
+ wire = prov.get("wire", "anthropic")
252
+ if wire not in WIRES:
253
+ raise ValueError(
254
+ f"Provider '{name}': 'wire' must be one of {WIRES} (got '{wire}')"
255
+ )
242
256
  cfg.providers[name] = ProviderConfig(
243
257
  name=name,
244
258
  base_url=prov["base_url"].rstrip("/"),
245
259
  api_keys=_parse_api_keys(name, prov),
246
260
  available_models=[str(m) for m in available],
261
+ wire=wire,
247
262
  )
248
263
 
249
264
  cfg.routes = _parse_routes(raw.get("routes", []), cfg.providers)
@@ -328,6 +343,8 @@ def save_config(cfg: GatewayConfig, path: str | None = None) -> None:
328
343
  }
329
344
  if prov.available_models:
330
345
  entry["available_models"] = list(prov.available_models)
346
+ if prov.wire != "anthropic":
347
+ entry["wire"] = prov.wire
331
348
  data["providers"][name] = entry
332
349
 
333
350
  if cfg.schedule:
@@ -368,6 +385,10 @@ server:
368
385
  # usage page's request headers; `flexgate usage` needs them to query the
369
386
  # team plan quota, and without them the entry is treated as a personal
370
387
  # coding-plan key.
388
+ # `wire` selects the upstream protocol: "anthropic" (default, /v1/messages,
389
+ # x-api-key) or "responses" (/v1/responses, Bearer) for Codex CLI against
390
+ # Responses-compatible upstreams such as z.ai (https://api.z.ai/api/v1)
391
+ # or Kimi (https://api.kimi.com/coding/v1).
371
392
  # A route's `active_key` (see below)
372
393
  # selects which key its requests start from; when that key fails with a
373
394
  # retryable error (401/402/403/429/5xx/529 or a connection error — e.g.
@@ -26,7 +26,7 @@ import re
26
26
  from starlette.requests import Request
27
27
  from starlette.responses import JSONResponse
28
28
 
29
- SUPPORTED_ROUTES = ("POST /v1/messages", "POST /v1/images/generations")
29
+ SUPPORTED_ROUTES = ("POST /v1/messages", "POST /v1/responses", "POST /v1/images/generations")
30
30
 
31
31
 
32
32
  def error_json(message: str, status: int, error_type: str, code: str) -> JSONResponse:
@@ -46,9 +46,16 @@ _UNSUPPORTED_FAMILIES: list[tuple[re.Pattern[str], str]] = [
46
46
  "Count tokens client-side (e.g. with a tokenizer) instead.",
47
47
  ),
48
48
  (
49
- re.compile(r"^/v1/(chat/completions|responses)(/.*)?$"),
50
- "OpenAI chat is not served: flexgate proxies Anthropic-style POST /v1/messages only. "
51
- "Point an Anthropic-compatible client at this gateway, or call the upstream provider directly.",
49
+ re.compile(r"^/v1/chat/completions(/.*)?$"),
50
+ "OpenAI chat is not served: flexgate proxies Anthropic-style POST /v1/messages "
51
+ "and Responses-style POST /v1/responses only. "
52
+ "Point an Anthropic/Responses-compatible client at this gateway, or call the upstream provider directly.",
53
+ ),
54
+ (
55
+ # POST /v1/responses is served above; this catches retrieval etc.
56
+ re.compile(r"^/v1/responses(/.*)?$"),
57
+ "Only POST /v1/responses (create) is proxied, matching Codex CLI's stateless "
58
+ "store=false traffic; response retrieval/cancellation is not available.",
52
59
  ),
53
60
  (
54
61
  re.compile(r"^/v1/images/edits$"),
@@ -78,7 +85,7 @@ async def fallback(request: Request) -> JSONResponse:
78
85
  """Catch-all handler for every path/method flexgate does not serve."""
79
86
  path = request.url.path.rstrip("/") or "/"
80
87
 
81
- if path in ("/v1/messages", "/v1/images/generations"):
88
+ if path in ("/v1/messages", "/v1/responses", "/v1/images/generations"):
82
89
  return error_json(
83
90
  f"{request.method} is not allowed on {path}; use POST.",
84
91
  405,
@@ -1,8 +1,10 @@
1
1
  """Provider connectivity verification.
2
2
 
3
3
  Tests each unique ``(provider, model)`` combination referenced by the
4
- configured routes (default + schedule) by issuing a minimal
5
- ``POST /v1/messages`` request with ``max_tokens=1``.
4
+ configured routes (default + schedule) by issuing a minimal request:
5
+ ``POST /v1/messages`` with ``max_tokens=1`` for Anthropic-wire providers,
6
+ ``POST /responses`` with ``max_output_tokens=16`` for Responses-wire
7
+ providers (the OpenAI Responses API Codex CLI speaks).
6
8
 
7
9
  This catches the common pre-flight failure modes before the gateway
8
10
  starts accepting traffic:
@@ -92,17 +94,31 @@ async def _check_one(
92
94
  "api_key looks like a placeholder — edit your config.yaml",
93
95
  )
94
96
 
95
- url = f"{provider.base_url}/v1/messages"
96
- headers = {
97
- "content-type": "application/json",
98
- "x-api-key": provider.api_key,
99
- "anthropic-version": "2023-06-01",
100
- }
101
- body = {
102
- "model": model or _FALLBACK_TEST_MODEL,
103
- "max_tokens": 1,
104
- "messages": [{"role": "user", "content": "ping"}],
105
- }
97
+ if provider.wire == "responses":
98
+ url = f"{provider.base_url}/responses"
99
+ headers = {
100
+ "content-type": "application/json",
101
+ "authorization": f"Bearer {provider.api_key}",
102
+ }
103
+ body = {
104
+ "model": model or _FALLBACK_TEST_MODEL,
105
+ "input": "ping",
106
+ "max_output_tokens": 16,
107
+ "store": False,
108
+ "stream": False,
109
+ }
110
+ else:
111
+ url = f"{provider.base_url}/v1/messages"
112
+ headers = {
113
+ "content-type": "application/json",
114
+ "x-api-key": provider.api_key,
115
+ "anthropic-version": "2023-06-01",
116
+ }
117
+ body = {
118
+ "model": model or _FALLBACK_TEST_MODEL,
119
+ "max_tokens": 1,
120
+ "messages": [{"role": "user", "content": "ping"}],
121
+ }
106
122
 
107
123
  try:
108
124
  resp = await client.post(url, headers=headers, json=body, timeout=timeout)
@@ -68,8 +68,13 @@ def _error_json(error_type: str, message: str, status: int) -> JSONResponse:
68
68
 
69
69
 
70
70
  def _build_upstream_headers(
71
- incoming_headers: dict[str, str], api_key: str
71
+ incoming_headers: dict[str, str], api_key: str, wire: str = "anthropic"
72
72
  ) -> dict[str, str]:
73
+ if wire == "responses":
74
+ return {
75
+ "content-type": "application/json",
76
+ "authorization": f"Bearer {api_key}",
77
+ }
73
78
  return {
74
79
  "content-type": "application/json",
75
80
  "x-api-key": api_key,
@@ -91,13 +96,20 @@ async def handle_request(
91
96
  body_json["model"] = model_override
92
97
 
93
98
  model = body_json.get("model", "")
94
- strip_images = not _model_supports_multimodal(model) and _has_image_content(body_json)
95
- if strip_images:
96
- _strip_images_from_request(body_json)
97
- logger.info("Stripped image content for non-multimodal model: %s", model)
99
+ if provider.wire == "responses":
100
+ # Responses wire: passthrough of the OpenAI Responses body; image
101
+ # items (input_image) are left as-is — an honest upstream 4xx beats
102
+ # silent degradation until per-wire multimodal handling is needed.
103
+ url = f"{provider.base_url}/responses"
104
+ strip_images = False
105
+ else:
106
+ url = f"{provider.base_url}/v1/messages"
107
+ strip_images = not _model_supports_multimodal(model) and _has_image_content(body_json)
108
+ if strip_images:
109
+ _strip_images_from_request(body_json)
110
+ logger.info("Stripped image content for non-multimodal model: %s", model)
98
111
 
99
112
  body = json.dumps(body_json, ensure_ascii=False).encode()
100
- url = f"{provider.base_url}/v1/messages"
101
113
  is_stream = body_json.get("stream", False)
102
114
 
103
115
  # Key fallback: try keys starting from the route's active-key pointer.
@@ -120,7 +132,7 @@ async def handle_request(
120
132
  provider.name, index + 1, _mask_key(entry.key),
121
133
  f" [{entry.note}]" if entry.note else "",
122
134
  )
123
- headers = _build_upstream_headers(incoming_headers, entry.key)
135
+ headers = _build_upstream_headers(incoming_headers, entry.key, provider.wire)
124
136
  if is_stream:
125
137
  resp, retryable = await _stream_proxy(client, url, headers, body, provider.name)
126
138
  else:
@@ -15,7 +15,7 @@ from starlette.responses import JSONResponse
15
15
  from starlette.routing import Route
16
16
 
17
17
  from flexgate.config import GatewayConfig, load_config
18
- from flexgate.fallback import fallback
18
+ from flexgate.fallback import error_json, fallback
19
19
  from flexgate.images import images_edits, images_generate
20
20
  from flexgate.proxy import handle_request
21
21
  from flexgate.router import NoRouteMatchError, resolve
@@ -64,6 +64,55 @@ async def messages(request: Request) -> JSONResponse:
64
64
  return resp
65
65
 
66
66
 
67
+ async def responses(request: Request) -> JSONResponse:
68
+ """OpenAI Responses API endpoint (POST /v1/responses) — the wire Codex
69
+ CLI speaks. Pure passthrough: the body's ``model`` field drives the same
70
+ regex routing as /v1/messages, and only Responses-wire providers may serve
71
+ it (protocol translation is out of scope)."""
72
+ t0 = time.monotonic()
73
+ config: GatewayConfig = request.app.state.config
74
+ client: httpx.AsyncClient = request.app.state.client
75
+
76
+ body_bytes = await request.body()
77
+ try:
78
+ body_json = json.loads(body_bytes)
79
+ except json.JSONDecodeError:
80
+ return error_json("Invalid JSON in request body", 400, "invalid_request_error", "invalid_json")
81
+
82
+ model_name = body_json.get("model", "")
83
+
84
+ try:
85
+ provider, model_override, schedule_name, route = resolve(config, model_name)
86
+ except NoRouteMatchError as exc:
87
+ return error_json(str(exc), 503, "not_found_error", "route_not_found")
88
+
89
+ if provider.wire != "responses":
90
+ return error_json(
91
+ f"Route for '{model_name}' matched provider '{provider.name}', which speaks the "
92
+ f"Anthropic wire ({{base_url}}/v1/messages) and cannot serve /v1/responses. "
93
+ f"Add a 'wire: responses' provider (e.g. z.ai 'https://api.z.ai/api/v1' or Kimi "
94
+ f"'https://api.kimi.com/coding/v1') and a route matching this model.",
95
+ 501,
96
+ "not_implemented",
97
+ "wire_mismatch",
98
+ )
99
+
100
+ display_model = model_override or model_name
101
+ logger.info("[%s] %s -> %s (%s) [responses]", schedule_name, model_name, provider.name, display_model)
102
+
103
+ incoming_headers = dict(request.headers)
104
+ resp = await handle_request(
105
+ client, body_bytes, body_json, incoming_headers, provider, model_override, route,
106
+ )
107
+
108
+ elapsed_ms = int((time.monotonic() - t0) * 1000)
109
+ logger.info(
110
+ "[%s] %s -> %s (%s) [responses] | %s | %dms",
111
+ schedule_name, model_name, provider.name, display_model, resp.status_code, elapsed_ms,
112
+ )
113
+ return resp
114
+
115
+
67
116
  def _load_new_config(config_path: str) -> GatewayConfig | None:
68
117
  try:
69
118
  return load_config(config_path)
@@ -121,6 +170,7 @@ def create_app(config: GatewayConfig, config_path: str | None = None) -> Starlet
121
170
 
122
171
  routes = [
123
172
  Route("/v1/messages", messages, methods=["POST"]),
173
+ Route("/v1/responses", responses, methods=["POST"]),
124
174
  Route("/v1/images/generations", images_generate, methods=["POST"]),
125
175
  Route("/v1/images/edits", images_edits, methods=["POST"]),
126
176
  # Catch-all last: structured, reasoned errors for anything unsupported.
@@ -51,7 +51,7 @@ def _get_client(as_json: bool = False):
51
51
  return client, DEFAULT_APP
52
52
 
53
53
 
54
- def sync_push(config_path: str, as_json: bool = False) -> dict | None:
54
+ def sync_push(config_path: str, dry_run: bool = False, as_json: bool = False) -> dict | None:
55
55
  """Upload the local config.yaml to the confsync server."""
56
56
  from flexgate.ui import emit_json, json_fail
57
57
 
@@ -60,11 +60,26 @@ def sync_push(config_path: str, as_json: bool = False) -> dict | None:
60
60
  if as_json:
61
61
  json_fail(message)
62
62
  err(message, 1)
63
- with open(config_path, encoding="utf-8") as f:
64
- content = f.read()
65
63
 
66
64
  client, app = _get_client(as_json)
67
65
  confsync, _ = _import_confsync()
66
+
67
+ if dry_run:
68
+ report = {
69
+ "action": "push",
70
+ "server": client.server_url,
71
+ "document": f"{app}/{DOC_NAME}",
72
+ "result": "would-push",
73
+ }
74
+ if as_json:
75
+ emit_json({"ok": True, **report})
76
+ return None
77
+ print(f"{yellow('Dry run:')} would push {cyan(config_path)} → "
78
+ f"{dim(f'{app}/{DOC_NAME} on {client.server_url}')} (no upload).")
79
+ return report
80
+
81
+ with open(config_path, encoding="utf-8") as f:
82
+ content = f.read()
68
83
  with client:
69
84
  try:
70
85
  version = client.push(app, DOC_NAME, content)
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