Compare commits

...
Author SHA1 Message Date
RCD f0241c3e6b feat(rust): add Claude upstream auth header shaping
- Add provider-specific auth header hook to Provider trait
- Use x-api-key + anthropic-version for Claude upstream requests
- Keep bearer auth for Codex/default provider path
- Strengthen active-Claude routing test to assert Anthropic headers
- Keep Rust suite green (53/53)
2026-04-08 01:47:50 +07:00
RCD d8b1ade0ea test(rust): exercise active Claude provider path
- Add active-Claude proxy/health/runtime test
- Add Claude account/state tests for manual provider path
- Keep Rust suite green at 53/53
2026-04-08 01:46:21 +07:00
RCD 0b04915694 feat(rust): scaffold Claude provider slice
- Add claude config section and ClaudeProvider skeleton
- Register Claude in provider registry without changing default runtime provider
- Add manual Claude account CLI path and provider-generic manual account helper
- Add targeted Claude account/state tests
- Keep Rust suite green (52/52)
2026-04-08 01:41:59 +07:00
RCD 40cb8329e6 refactor(rust): route proxy through provider registry
- Make Provider trait object-safe with boxed future refresh API
- Add ProviderRegistry and active provider resolution
- Refactor proxy runtime, health, upstream routing, and refresh paths
  to use active provider instead of hardcoded Codex wiring
- Preserve Codex refresh metadata through generic refresh flow
- Keep full Rust suite green (49/49)
2026-04-08 01:37:56 +07:00
RCD d88d3a7829 feat(rust): add multi-provider config section and active provider selection
- Add ProvidersConfig with active provider field to AppConfig
- Add active_provider() and active_provider_label() config methods
- Update example TOML with providers section
- Fix all test AppConfig constructions with ..AppConfig::default()
- All 49 tests pass
2026-04-08 01:24:30 +07:00
RCD 646ceef400 feat(rust): introduce provider abstraction and refactor state to be provider-agnostic
- Add provider.rs with Provider trait, ProviderId, AuthResult, RefreshResult
- Implement CodexProvider wrapping existing Codex device/refresh flows
- Refactor state.rs: add provider-generic account methods that legacy
  codex-specific wrappers delegate to
- Simplify remove_account fallback to first remaining account
- All 49 tests pass on the new abstraction layer
2026-04-08 01:19:54 +07:00
RCD b741c439e9 fix(rust): relax expires_at assertion to work with placeholder id_token fixture 2026-04-08 01:15:55 +07:00
RCD a29917297b chore: replace test fixture tokens with placeholders for shield compliance 2026-04-08 00:49:18 +07:00
RCD d3f61fc925 chore: bump UPSTREAM_VERSION to v6.9.16 2026-04-08 00:38:44 +07:00
RCD e3302b694c Merge tag 'v6.9.16' into rust-replatform 2026-04-08 00:38:27 +07:00
Luis Pater c8b7e2b8d6 fix(executor): ensure empty stream completions use output_item.done as fallback
Fixed: #2583
2026-04-07 18:21:12 +08:00
Luis Pater cad45ffa33 Merge pull request #2578 from LemonZuo/feat_socks5h
feat: support socks5h scheme for proxy settings
2026-04-07 09:57:18 +08:00
Luis Pater 6a27bceec0 Merge pull request #2576 from zilianpn/fix/disable-cooling-auth-errors
fix(auth): honor disable-cooling and enrich no-auth errors
2026-04-07 09:56:25 +08:00
Lemon 163d68318f feat: support socks5h scheme for proxy settings 2026-04-07 07:46:11 +08:00
zilianpn 0ea768011b fix(auth): honor disable-cooling and enrich no-auth errors 2026-04-07 01:12:13 +08:00
Luis Pater 9f5bdfaa31 Merge pull request #2531 from jamestut/openai-vertex-token-usage-fix
Fix missing `response.completed.usage` for late-usage OpenAI-compatible streams
2026-04-06 09:30:49 +08:00
Luis Pater 9eabdd09db Merge pull request #2522 from aikins01/fix/strip-tool-use-signature
fix(amp): strip signature from tool_use blocks before forwarding to Claude
2026-04-06 09:30:14 +08:00
Luis Pater c3f8dc362e Merge pull request #2491 from mpfo0106/feature/claude-code-safe-alignment-sentinels
test(claude): add compatibility sentinels and centralize builtin fallback handling
2026-04-06 09:27:08 +08:00
Luis Pater b85120873b Merge pull request #2332 from RaviTharuma/fix/claude-thinking-signature
fix: preserve Claude thinking signatures in Codex translator
2026-04-06 09:25:06 +08:00
Luis Pater 6f58518c69 docs(readme): remove redundant GITSTORE_GIT_BRANCH description in README files 2026-04-06 09:23:04 +08:00
Luis Pater 000fcb15fa Merge pull request #2298 from snoyiatk/feat/add-gitstore-branch
feat(gitstore): add support for specifying git branch (via GITSTORE_G…
2026-04-06 09:21:03 +08:00
Luis Pater ea43361492 Merge pull request #2121 from destinoantagonista-wq/main
Reconcile registry model states on auth changes
2026-04-06 09:13:27 +08:00
Luis Pater c1818f197b Merge pull request #1940 from Blue-B/fix/claude-interleaved-thinking-amp-gzip-budget
fix(claude): enable interleaved-thinking beta, decode AMP error gzip, fix budget 400
2026-04-06 09:08:23 +08:00
RCD a7ea27d047 chore: record terminal operator user testing rerun 2026-04-05 20:41:25 +07:00
RCD 53be957861 fix: allow configurable codex refresh endpoint 2026-04-05 20:24:07 +07:00
RCD e6ec1fd86a chore: record terminal operator user testing 2026-04-05 20:05:54 +07:00
Aikins Laryea b0653cec7b fix(amp): strip signature from tool_use blocks before forwarding to Claude
ensureAmpSignature injects signature:"" into tool_use blocks so the
Amp TUI does not crash on P.signature.length. when Amp sends the
conversation back, Claude rejects the extra field with 400:
  tool_use.signature: Extra inputs are not permitted

strip the proxy-injected signature from tool_use blocks in
SanitizeAmpRequestBody before forwarding to the upstream API.
2026-04-05 12:26:24 +00:00
RCD 08065bd061 chore: record terminal operator scrutiny pass 2026-04-05 19:04:00 +07:00
RCD 159a3b218e fix: keep footer guidance fully visible 2026-04-05 18:55:55 +07:00
RCD 46758c9787 chore: record terminal operator scrutiny rerun 2026-04-05 18:44:03 +07:00
RCD 91fe656204 fix: count runtime-usable Codex accounts 2026-04-05 18:29:09 +07:00
RCD 67c79b9dc5 fix: keep TUI footer visible and passive polling read-only 2026-04-05 18:24:00 +07:00
RCD 53f6f99433 chore: record terminal operator scrutiny 2026-04-05 18:03:57 +07:00
RCD cea7a0f4e3 fix: make TUI runtime refresh truthful 2026-04-05 17:45:13 +07:00
RCD f4ae033c97 fix: tighten auth runtime health refresh state 2026-04-05 17:36:32 +07:00
Luis Pater 22a1a24cf5 feat(executor): add tests for preserving key order in cache control functions
Added comprehensive tests to ensure key order is maintained when modifying payloads in `normalizeCacheControlTTL` and `enforceCacheControlLimit` functions. Removed unused helper functions and refactored implementations for better readability and efficiency.
2026-04-05 17:58:13 +08:00
RCD 1c2396bb52 feat: align rust operator console state copy 2026-04-05 16:55:19 +07:00
RCD 3da810d19a feat: improve rust operator console 2026-04-05 16:39:18 +07:00
RCD 1b3542d77c feat: add runtime stats surface to proxypilot-rs 2026-04-05 16:13:41 +07:00
RCD 1c3edd9f4a feat: share auth runtime domain helpers 2026-04-05 15:56:19 +07:00
RCD c603b98c2b chore: add rust operator mission scaffolding 2026-04-05 15:42:41 +07:00
RCD fbc6545d85 feat: refresh expired codex tokens before proxying 2026-04-05 14:54:27 +07:00
RCD 20fda28fb4 feat: preserve codex plan metadata in rust state 2026-04-05 14:52:33 +07:00
RCD 469fd38420 feat: add account removal to proxypilot-rs 2026-04-05 14:51:34 +07:00
RCD 0b80a392e7 feat: surface token expiry in proxypilot-rs tui 2026-04-05 14:49:59 +07:00
RCD f9da6dcb0a feat: add account controls to proxypilot-rs tui 2026-04-05 14:47:28 +07:00
RCD 16a0799176 feat: refresh codex accounts in proxypilot-rs 2026-04-05 14:45:02 +07:00
RCD ff5fa96583 feat: add codex device login to proxypilot-rs 2026-04-05 14:39:16 +07:00
RCD 3e205f7335 feat: import codex auth files into proxypilot-rs 2026-04-05 14:32:15 +07:00
RCD 056e4d8edf feat: add codex account state to proxypilot-rs 2026-04-05 14:27:50 +07:00
RCD fcdcbfc174 feat: add explicit codex routes to proxypilot-rs 2026-04-05 14:22:48 +07:00
RCD 85687a4ab7 feat: add proxypilot-rs codex proxy shell 2026-04-05 14:19:51 +07:00
RCD 388a7a127d chore: scaffold rust replatform workspace 2026-04-05 14:19:48 +07:00
RCD e040fdb330 chore: merge upstream CLIProxyAPI v6.9.15
# Conflicts:
#	.gitignore
#	README.md
#	README_CN.md
#	README_JA.md
#	cmd/server/main.go
2026-04-05 13:55:36 +07:00
Luis Pater ada8e2905e feat(api): enhance proxy resolution for API key-based auth
Added comprehensive support for resolving proxy URLs from configuration based on API key and provider attributes. Introduced new helper functions and extended the test suite to validate fallback mechanisms and compatibility cases.
2026-04-05 01:56:34 +08:00
Luis Pater 4ba10531da feat(docs): add Poixe AI sponsorship details to README files
Added Poixe AI sponsorship information, including referral bonuses and platform capabilities, to README files in English, Japanese, and Chinese. Updated assets to include Poixe AI logo.
2026-04-05 01:20:50 +08:00
RCD 81929c06da fix(security): remove unverified management asset fallback (#12) 2026-04-04 21:25:56 +07:00
Luis Pater 3774b56e9f feat(misc): add background updater for Antigravity version caching
Introduce `StartAntigravityVersionUpdater` to periodically refresh the cached Antigravity version using a non-blocking background process. Updated main server flow to initialize the updater.
2026-04-04 22:09:11 +08:00
Luis Pater c2d4137fb9 feat(executor): enhance Qwen system message handling with strict injection and merging rules
Closes: #2537
2026-04-04 21:51:02 +08:00
Luis Pater 2ee938acaf Merge pull request #2535 from rensumo/main
feat: 动态获取 Antigravity User-Agent 版本号
2026-04-04 21:00:47 +08:00
rensumo 8d5e470e1f feat: dynamically fetch antigravity UA version from releases API
Fetch the latest version from the antigravity auto-updater releases
endpoint and cache it for 6 hours. Falls back to 1.21.9 if the API
is unreachable or returns unexpected data.
2026-04-04 14:52:59 +08:00
James 65e9e892a4 Fix missing response.completed.usage for late-usage OpenAI-compatible streams 2026-04-04 05:58:04 +00:00
Luis Pater 8430b28cfa Merge pull request #2526 from rensumo/main
feat: 升级反重力 (antigravity) UA 版本为 1.21.9
2026-04-04 11:32:16 +08:00
rensumo f3ab8f4bc5 chore: update antigravity UA version to 1.21.9 2026-04-04 07:35:08 +08:00
Luis Pater 0e4f189c2e Merge pull request #1302 from dinhkarate/feat(vertex)/add-prefix-field
Feat(vertex): add prefix field
2026-04-04 04:17:12 +08:00
Luis Pater 754b126944 fix(executor): remove commented-out code in QwenExecutor 2026-04-04 02:14:48 +08:00
Luis Pater ae37ccffbf Merge pull request #2520 from Arronlong/main
fix:qwen invalid_parameter_error
2026-04-04 02:13:09 +08:00
RCD d548446ce8 docs(readme): document default config bootstrap 2026-04-04 00:32:55 +07:00
RCD 852642d5ee fix(startup): bootstrap packaged default config 2026-04-04 00:32:36 +07:00
RCD 371bfc3528 docs: record upstream v6.9.12 sync 2026-04-04 00:22:10 +07:00
RCD 9cf230cc40 chore: merge upstream CLIProxyAPI v6.9.12 2026-04-04 00:21:26 +07:00
Luis Pater 42c062bb5b Merge pull request #2509 from adamhelfgott/fix-claude-thinking-temperature
Normalize Claude temperature when thinking is enabled
2026-04-03 23:55:50 +08:00
Luis Pater f389667ec3 Merge pull request #2513 from lonr-6/codex/fix-ws-custom-tool-repair-v2
fix: repair responses websocket custom tool call pairing
2026-04-03 23:45:38 +08:00
Arronlong 29dba0399b Comment out system message check in Qwen executor
fix qwen invalid_parameter_error
2026-04-03 23:07:33 +08:00
Luis Pater a824e7cd0b feat(models): add GPT-5.3, GPT-5.4, and GPT-5.4-mini with enhanced "thinking" levels 2026-04-03 23:05:10 +08:00
Luis Pater adb580b344 feat(security): add configuration to toggle Gemini CLI endpoint access
Closes: #2445
2026-04-03 21:46:49 +08:00
Luis Pater 06405f2129 fix(security): enforce stricter localhost validation for GeminiCLIAPIHandler
Closes: #2445
2026-04-03 21:22:03 +08:00
Kai Wang d1fd2c4ad4 fix: repair websocket custom tool calls 2026-04-03 17:11:44 +08:00
Kai Wang b6c6379bfa fix: repair websocket custom tool calls 2026-04-03 17:11:42 +08:00
Kai Wang 8f0e66b72e fix: repair websocket custom tool calls 2026-04-03 17:11:41 +08:00
Adam Helfgott f63cf6ff7a Normalize Claude temperature for thinking 2026-04-03 03:45:51 -04:00
RCD de8d8cc432 chore: restore executor compatibility wrappers 2026-04-03 13:16:37 +07:00
RCD 3d853cb295 chore: merge upstream CLIProxyAPI v6.9.10 2026-04-03 13:13:41 +07:00
Luis Pater d2419ed49d feat(executor): ensure default system message in QwenExecutor payload 2026-04-03 11:18:48 +08:00
mpfo0106 9b5ce8c64f Keep Claude builtin helpers aligned with the shared helper layout
The review asked for the builtin tool registry helper to live with the rest
of executor support utilities. This moves the registry code into the helps
package, exports the minimal surface executor needs, and keeps behavior tests
with the executor while leaving registry-focused checks with the helper.

Constraint: Requested layout keeps executor helper utilities centralized under internal/runtime/executor/helps
Rejected: Keep the files in executor and reply with rationale | conflicts with requested package organization
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep executor behavior tests near applyClaudeToolPrefix and keep pure registry tests in helps
Tested: go test ./internal/runtime/executor/helps ./internal/runtime/executor -run 'Claude|Builtin|Tool'; go test ./test/...; go test ./...
Not-tested: End-to-end Claude Code direct-connect/session runtime behavior
2026-04-03 00:13:02 +09:00
Duong M. CUONG 058793c73a feat(gitstore): honor configured branch and follow live remote default 2026-04-02 14:44:44 +00:00
Luis Pater ab9ebea592 Merge PR #2474
# Conflicts:
#	internal/api/modules/amp/response_rewriter.go
#	internal/api/modules/amp/response_rewriter_test.go
2026-04-02 22:31:12 +08:00
Luis Pater 7ee37ee4b9 feat: add /healthz endpoint and test coverage for health check
Closes: #2493
2026-04-02 21:56:27 +08:00
Luis Pater 3171d524f0 docs: fix duplicated ProxyPal entry in README files 2026-04-02 21:22:40 +08:00
Luis Pater 3e78a8d500 Merge branch 'main' into dev 2026-04-02 21:21:26 +08:00
Luis Pater fcba912cc4 Merge pull request #2492 from davidwushi1145/main
fix(responses): reassemble split SSE event/data frames before streaming
2026-04-02 21:20:31 +08:00
Luis Pater 7170eeea5f Merge pull request #2454 from buddingnewinsights/add-proxypal-to-readme
docs: add ProxyPal to "Who is with us?" section
2026-04-02 21:18:22 +08:00
Luis Pater e3eb048c7a Merge pull request #2489 from Soein/upstream-pr
fix: 增强 Claude 反代检测对抗能力
2026-04-02 21:16:58 +08:00
Luis Pater a59e92435b Merge pull request #2490 from router-for-me/logs
Refactor websocket logging and error handling
2026-04-02 20:47:31 +08:00
davidwushi1145 108895fc04 Harden Responses SSE framing against partial chunk boundaries
Follow-up review found two real framing hazards in the handler-layer
framer: it could flush a partial `data:` payload before the JSON was
complete, and it could inject an extra newline before chunks that
already began with `\n`/`\r\n`. This commit tightens the framer so it
only emits undelimited events when the buffered `data:` payload is
already valid JSON (or `[DONE]`), skips newline injection for chunks
that already start with a line break, and avoids the heavier
`bytes.Split` path while scanning SSE fields.

The regression suite now covers split `data:` payload chunks,
newline-prefixed chunks, and dropping incomplete trailing data on
flush, so the original Responses fix remains intact while the review
concerns are explicitly locked down.

Constraint: Keep the follow-up limited to handler-layer framing and tests
Rejected: Ignore the review and rely on current executor chunk shapes | leaves partial data payload corruption possible
Rejected: Build a fully generic SSE parser | wider change than needed for the identified risks
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Do not emit undelimited Responses SSE events unless buffered `data:` content is already complete and valid
Tested: /tmp/go1.26.1/go/bin/go test ./sdk/api/handlers/openai -count=1
Tested: /tmp/go1.26.1/go/bin/go test ./sdk/api/handlers -count=1
Tested: /tmp/go1.26.1/go/bin/go vet ./sdk/api/handlers/...
Not-tested: Full repository test suite outside sdk/api/handlers packages
2026-04-02 20:39:49 +08:00
davidwushi1145 abc293c642 Prevent malformed Responses SSE frames from breaking stream clients
Line-oriented upstream executors can emit `event:` and `data:` as
separate chunks, but the Responses handler had started terminating
each incoming chunk as a full SSE event. That split `response.created`
into an empty event plus a later data block, which broke downstream
clients like OpenClaw.

This keeps the fix in the handler layer: a small stateful framer now
buffers standalone `event:` lines until the matching `data:` arrives,
preserves already-framed events, and ignores delimiter-only leftovers.
The regression suite now covers split event/data framing, full-event
passthrough, terminal errors, and the bootstrap path that forwards
line-oriented openai-response streams from non-Codex executors too.

Constraint: Keep the fix localized to Responses handler framing instead of patching every executor
Rejected: Revert to v6.9.7 chunk writing | would reintroduce data-only framing regressions
Rejected: Patch each line-oriented executor separately | duplicates fragile SSE assembly logic
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Do not assume incoming Responses stream chunks are already complete SSE events; preserve handler-layer reassembly for split `event:`/`data:` inputs
Tested: /tmp/go1.26.1/go/bin/go test ./sdk/api/handlers/openai -count=1
Tested: /tmp/go1.26.1/go/bin/go test ./sdk/api/handlers -count=1
Tested: /tmp/go1.26.1/go test ./sdk/api/handlers/... -count=1
Tested: /tmp/go1.26.1/go/bin/go vet ./sdk/api/handlers/...
Tested: Temporary patched server on 127.0.0.1:18317 -> /v1/models 200, /v1/responses non-stream 200, /v1/responses stream emitted combined `event:` + `data:` frames
Not-tested: Full repository test suite outside sdk/api/handlers packages
2026-04-02 20:26:42 +08:00
mpfo0106 da3a498a28 Keep Claude Code compatibility work low-risk and reviewable
This change stops short of broader Claude Code runtime alignment and instead
hardens two safe edges: builtin tool prefix handling and source-informed
sentinel coverage for future drift checks.

Constraint: Must preserve existing default behavior for current users
Rejected: Implement control-plane/session alignment now | too much runtime risk for a first slice
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Treat the new fixtures as compatibility sentinels, not a full Claude Code schema contract
Tested: go test ./test/...; go test ./sdk/translator/...; go test ./internal/runtime/executor -run 'Claude|Builtin|Tool'; go test ./...
Not-tested: End-to-end Claude Code direct-connect/session runtime behavior
2026-04-02 20:35:39 +09:00
pzy bb44671845 fix: 修复反代检测对抗的 3 个问题
- computeFingerprint 使用 rune 索引替代字节索引,修复多字节字符指纹不匹配
- utls Chrome TLS 指纹仅对 Anthropic 官方域名生效,自定义 base_url 走标准 transport
- IPv6 地址使用 net.JoinHostPort 正确拼接端口
2026-04-02 19:12:55 +08:00
Luis Pater 09e480036a feat(auth): add support for managing custom headers in auth files
Closes #2457
2026-04-02 19:11:09 +08:00
pzy 249f969110 fix: Claude API 请求使用 utls Chrome TLS 指纹
Claude executor 的 API 请求之前使用 Go 标准库 crypto/tls,JA3 指纹
与真实 Claude Code(Bun/BoringSSL)不匹配,可被 Cloudflare 识别。

- 新增 helps/utls_client.go,封装 utls Chrome 指纹 + HTTP/2 + 代理支持
- Claude executor 的 4 处 NewProxyAwareHTTPClient 替换为 NewUtlsHTTPClient
- 其他 executor(Gemini/Codex/iFlow 等)不受影响,仍用标准 TLS
- 非 HTTPS 请求自动回退到标准 transport
2026-04-02 19:09:56 +08:00
hkfires 4f8acec2d8 refactor(logging): centralize websocket handshake recording 2026-04-02 18:39:32 +08:00
hkfires 34339f61ee Refactor websocket logging and error handling
- Introduced new logging functions for websocket requests, handshakes, errors, and responses in `logging_helpers.go`.
- Updated `CodexWebsocketsExecutor` to utilize the new logging functions for improved clarity and consistency in websocket operations.
- Modified the handling of websocket upgrade rejections to log relevant metadata.
- Changed the request body key to a timeline body key in `openai_responses_websocket.go` to better reflect its purpose.
- Enhanced tests to verify the correct logging of websocket events and responses, including disconnect events and error handling scenarios.
2026-04-02 17:30:51 +08:00
pzy 4045378cb4 fix: 增强 Claude 反代检测对抗能力
基于 Claude Code v2.1.88 源码分析,修复多个可被 Anthropic 检测的差距:

- 实现消息指纹算法(SHA256 盐值 + 字符索引),替代随机 buildHash
- billing header cc_version 从设备 profile 动态取版本号,不再硬编码
- billing header cc_entrypoint 从客户端 UA 解析,支持 cli/vscode/local-agent
- billing header 新增 cc_workload 支持(通过 X-CPA-Claude-Workload 头传入)
- 新增 X-Claude-Code-Session-Id 头(每 apiKey 缓存 UUID,TTL=1h)
- 新增 x-client-request-id 头(仅 api.anthropic.com,每请求 UUID)
- 补全 4 个缺失的 beta flags(structured-outputs/fast-mode/redact-thinking/token-efficient-tools)
- OAuth scope 对齐 Claude Code 2.1.88(移除 org:create_api_key,添加 sessions/mcp/file_upload)
- Anthropic-Dangerous-Direct-Browser-Access 仅在 API key 模式发送
- 响应头网关指纹清洗(剥离 litellm/helicone/portkey/cloudflare/kong/braintrust 前缀头)
2026-04-02 15:55:22 +08:00
Luis Pater 4f99bc54f1 test: update codex header expectations 2026-04-02 11:19:37 +08:00
Luis Pater 913f4a9c5f test: fix executor tests after helpers refactor 2026-04-02 11:12:30 +08:00
Luis Pater 25d1c18a3f fix: scope experimental cch signing to billing header 2026-04-02 11:03:11 +08:00
Luis Pater d09dd4d0b2 Merge commit '15c2f274ea690c9a7c9db22f9f454af869db5375' into dev 2026-04-02 10:59:54 +08:00
Luis Pater 474fb042da Merge pull request #2476 from router-for-me/cherry-pick/pr-2438-to-dev
Cherry-pick PR #2438 onto dev
2026-04-02 10:36:50 +08:00
Michael 8435c3d7be feat(tui): show time in usage details 2026-04-02 10:35:13 +08:00
Luis Pater e783d0a62e Merge pull request #2441 from MonsterQiu/issue-2421-alias-before-suspension
fix(auth): resolve oauth aliases before suspension checks
2026-04-02 10:27:39 +08:00
Luis Pater b05f575e9b Merge pull request #2444 from 0oAstro/fix/codex-nonstream-finish-reason-tool-calls
fix(codex): set finish_reason to "tool_calls" in non-streaming response when tool calls are present
2026-04-02 10:01:25 +08:00
Aikins Laryea f5e9f01811 test(amp): update tests to expect thinking blocks to pass through during streaming 2026-04-01 20:35:23 +00:00
Aikins Laryea ff7dbb5867 test(amp): update tests to expect thinking blocks to pass through during streaming 2026-04-01 20:21:39 +00:00
Aikins Laryea e34b2b4f1d fix(gemini): clean tool schemas and eager_input_streaming
delegate schema sanitization to util.CleanJSONSchemaForGemini and drop the top-level eager_input_streaming key to prevent validation errors when sending claude tools to the gemini api
2026-04-01 19:49:38 +00:00
edlsh 15c2f274ea fix: preserve cloak config defaults when mode omitted 2026-04-01 13:20:11 -04:00
edlsh 37249339ac feat: add opt-in experimental Claude cch signing 2026-04-01 13:03:17 -04:00
Luis Pater c422d16beb Merge pull request #2398 from 7RPH/fix/responses-sse-framing
fix: preserve SSE event boundaries for Responses streams
2026-04-02 00:46:51 +08:00
Luis Pater 66cd50f603 Merge pull request #2468 from router-for-me/ip
fix(openai): improve client IP retrieval in websocket handler
2026-04-02 00:03:35 +08:00
hkfires caa529c282 fix(openai): improve client IP retrieval in websocket handler 2026-04-01 20:16:01 +08:00
hkfires 51a4379bf4 refactor(openai): remove websocket body log truncation limit 2026-04-01 18:11:43 +08:00
Luis Pater acf98ed10e fix(openai): add session reference counter and cache lifecycle management for websocket tools 2026-04-01 17:28:50 +08:00
Luis Pater d1c07a091e fix(openai): add websocket tool call repair with caching and tests to improve transcript consistency 2026-04-01 17:16:49 +08:00
Luis Pater 105a21548f fix(codex): centralize session management with global store and add tests for executor session lifecycle 2026-04-01 13:17:10 +08:00
Luis Pater 1734aa1664 fix(codex): prioritize websocket-enabled credentials across priority tiers in scheduler logic 2026-04-01 12:51:12 +08:00
Luis Pater ca11b236a7 refactor(runtime, openai): simplify header management and remove redundant websocket logging logic 2026-04-01 11:57:31 +08:00
huynhgiabuu 6fdff8227d docs: add ProxyPal to 'Who is with us?' section
Add ProxyPal (https://github.com/buddingnewinsights/proxypal) to the
community projects list in all three README files (EN, CN, JA).
Placed after CCS, restoring its original position.

ProxyPal is a cross-platform desktop app (macOS, Windows, Linux) that
wraps CLIProxyAPI with a native GUI, supporting multiple AI providers,
usage analytics, request monitoring, and auto-configuration for popular
coding tools.

Closes #2420
2026-04-01 10:23:22 +07:00
Luis Pater 330e12d3c2 fix(codex): conditionally set Session_id header for Mac OS user agents and clean up redundant logic 2026-04-01 11:11:45 +08:00
RCD 8fc58e0806 chore: merge upstream CLIProxyAPI v6.9.7 2026-04-01 03:36:56 +07:00
Luis Pater b468ca79c3 Merge branch 'dev' of github.com:router-for-me/CLIProxyAPI into dev 2026-04-01 03:09:03 +08:00
Luis Pater d2c7e4e96a refactor(runtime): move executor utilities to helps package and update references 2026-04-01 03:08:20 +08:00
Luis Pater 1c7003ff68 Merge pull request #2452 from Lucaszmv/fix-qwen-cli-v0.13.2
fix(qwen): update CLI simulation to v0.13.2 and adjust header casing
2026-04-01 02:44:27 +08:00
Lucaszmv 1b44364e78 fix(qwen): update CLI simulation to v0.13.2 2026-03-31 15:19:07 -03:00
0oAstro ec77f4a4f5 fix(codex): set finish_reason to tool_calls in non-streaming response when tool calls are present 2026-03-31 14:12:15 +05:30
MonsterQiu f611dd6e96 refactor(auth): dedupe route-aware model support checks 2026-03-31 15:42:25 +08:00
MonsterQiu 07b7c1a1e0 fix(auth): resolve oauth aliases before suspension checks 2026-03-31 14:27:14 +08:00
Luis Pater 51fd58d74f fix(codex): use normalizeCodexInstructions to set default instructions 2026-03-31 12:16:57 +08:00
Luis Pater faae9c2f7c Merge pull request #2422 from MonsterQiu/fix/codex-compact-instructions
fix(codex): add default instructions for /responses/compact
2026-03-31 12:14:20 +08:00
Luis Pater bc3a6e4646 Merge pull request #2434 from MonsterQiu/fix/codex-responses-null-instructions
fix(codex): normalize null instructions for /responses requests
2026-03-31 12:01:21 +08:00
Luis Pater b09b03e35e Merge pull request #2424 from possible055/fix/websocket-transcript-replacement
fix(openai): handle transcript replacement after websocket v2 compaction
2026-03-31 11:00:33 +08:00
Luis Pater 16231947e7 Merge pull request #2426 from xixiwenxuanhe/feature/antigravity-credits
feat(antigravity): add AI credits quota fallback
2026-03-31 10:51:40 +08:00
MonsterQiu 39b9a38fbc fix(codex): normalize null instructions across responses paths 2026-03-31 10:32:39 +08:00
MonsterQiu bd855abec9 fix(codex): normalize null instructions for responses requests 2026-03-31 10:29:02 +08:00
Luis Pater 7c3c2e9f64 Merge pull request #2417 from CharTyr/fix/amp-streaming-thinking-regression
fix(amp): 修复流式响应中 thinking block 被错误抑制导致的 TUI 空白回复
2026-03-31 10:12:13 +08:00
Luis Pater c10f8ae2e2 Fixed: #2420
docs(readme): remove ProxyPal section from all README translations
2026-03-31 07:23:02 +08:00
xixiwenxuanhe a0bf33eca6 fix(antigravity): preserve fallback and honor config gate 2026-03-31 00:14:05 +08:00
xixiwenxuanhe 88dd9c715d feat(antigravity): add AI credits quota fallback 2026-03-30 23:58:12 +08:00
apparition a3e21df814 fix(openai): avoid developer transcript resets
- Narrow websocket transcript replacement detection to assistant outputs and function calls
- Preserve existing merge behavior for follow-up developer messages without previous_response_id
- Add a regression test covering mid-session developer message updates
2026-03-30 23:33:16 +08:00
MonsterQiu d3b94c9241 fix(codex): normalize null instructions for compact requests 2026-03-30 22:58:05 +08:00
apparition c1d7599829 fix(openai): handle transcript replacement after websocket compaction
- Add shouldReplaceWebsocketTranscript() to detect historical model output in input
- Add normalizeResponseTranscriptReplacement() for full transcript reset handling
- Prevent duplicate stale turn-state when clients replace local history post-compaction
- Avoid orphaned function_call items from incremental append on compact transcripts
- Add unit tests for transcript replacement detection and state reset behavior
2026-03-30 22:44:58 +08:00
MonsterQiu d11936f292 fix(codex): add default instructions for /responses/compact 2026-03-30 22:44:46 +08:00
Luis Pater 17363edf25 fix(auth): skip downtime for request-scoped 404 errors in model state management 2026-03-30 22:22:42 +08:00
CharTyr 279cbbbb8a fix(amp): don't suppress thinking blocks in streaming mode
Reverts the streaming thinking suppression introduced in b15453c.
rewriteStreamEvent should only inject signatures and rewrite model
names — suppressing thinking blocks in streaming mode breaks SSE
index alignment and causes the Amp TUI to render empty responses
on the second message onward (especially with model-mapped
non-Claude providers like GPT-5.4).

Non-streaming responses still suppress thinking when tool_use is
present via rewriteModelInResponse.
2026-03-30 20:09:32 +08:00
Luis Pater 486cd4c343 Merge pull request #2409 from sususu98/fix/tool-use-pairing-break
fix(antigravity): reorder model parts to prevent tool_use↔tool_result pairing breakage
2026-03-30 16:59:46 +08:00
sususu98 25feceb783 fix(antigravity): reorder model parts to prevent tool_use↔tool_result pairing breakage
When a Claude assistant message contains [text, tool_use, text], the
Antigravity API internally splits the model message at functionCall
boundaries, creating an extra assistant turn between tool_use and the
following tool_result. Claude then rejects with:

  tool_use ids were found without tool_result blocks immediately after

Fix: extend the existing 2-way part reordering (thinking-first) to a
3-way partition: thinking → regular → functionCall. This ensures
functionCall parts are always last, so Antigravity's split cannot
insert an extra assistant turn before the user's tool_result.

Fixes #989
2026-03-30 15:09:33 +08:00
Luis Pater d26752250d Merge pull request #2403 from CharTyr/clean-pr
fix(amp): 修复Amp CLI 集成 缺失/无效 signature 导致的 TUI 崩溃与上游 400 问题
2026-03-30 12:54:15 +08:00
CharTyr b15453c369 fix(amp): address PR review - stream thinking suppression, SSE detection, test init
- Call suppressAmpThinking in rewriteStreamEvent for streaming path
- Handle nil return from suppressAmpThinking to skip suppressed events
- Narrow looksLikeSSEChunk to line-prefix detection (HasPrefix vs Contains)
- Initialize suppressedContentBlock map in test
2026-03-30 00:42:04 -04:00
CharTyr 04ba8c8bc3 feat(amp): sanitize signatures and handle stream suppression for Amp compatibility 2026-03-29 22:23:18 -04:00
Luis Pater 6570692291 Merge pull request #2400 from router-for-me/revert-2374-codex-cache-clean
Revert "fix(codex): restore prompt cache continuity for Codex requests"
2026-03-29 22:19:39 +08:00
trph f73d55ddaa fix: simplify responses SSE suffix handling 2026-03-29 22:19:25 +08:00
Luis Pater 13aa5b3375 Revert "fix(codex): restore prompt cache continuity for Codex requests" 2026-03-29 22:18:14 +08:00
trph 0fcc02fbea fix: tighten responses SSE review follow-up 2026-03-29 22:10:28 +08:00
trph c03883ccf0 fix: address responses SSE review feedback 2026-03-29 22:00:46 +08:00
trph 134a9eac9d fix: preserve SSE event boundaries for Responses streams 2026-03-29 17:23:16 +08:00
RCD 1e4ba8f4c7 ci: normalize dev installer version metadata 2026-03-29 15:04:22 +07:00
RCD 950e484af6 ci: allow dev versions in Windows installer builds 2026-03-29 15:01:07 +07:00
RCD 9167f0a416 ci: fix Windows release workflow 2026-03-29 14:57:15 +07:00
RCD 3af8992d23 chore: merge upstream CLIProxyAPI v6.9.5 sync into main 2026-03-29 14:41:08 +07:00
RCD 9332a5eac8 chore: finalize upstream CLIProxyAPI v6.9.5 sync 2026-03-29 14:33:20 +07:00
RCD 9fddf15d2a chore: merge upstream CLIProxyAPI v6.9.5
# Conflicts:
#	README.md
#	README_CN.md
#	README_JA.md
2026-03-29 13:59:33 +07:00
RCD f793af5a12 chore: merge upstream CLIProxyAPI v6.9.4
# Conflicts:
#	README.md
#	README_CN.md
#	README_JA.md
2026-03-29 13:57:29 +07:00
RCD 1436721c3e chore: merge upstream CLIProxyAPI v6.9.3
# Conflicts:
#	README_CN.md
2026-03-29 13:56:38 +07:00
RCD 5f48b13144 chore: merge upstream CLIProxyAPI v6.9.2
# Conflicts:
#	README_JA.md
#	internal/api/handlers/management/auth_files.go
2026-03-29 13:55:37 +07:00
Luis Pater 6d8de0ade4 feat(auth): implement weighted provider rotation for improved scheduling fairness 2026-03-29 13:49:01 +08:00
Luis Pater 1587ff5e74 Merge pull request #2389 from router-for-me/claude
fix(claude): add default max_tokens for models
2026-03-29 13:03:20 +08:00
hkfires f033d3a6df fix(claude): enhance ensureModelMaxTokens to use registered max_completion_tokens and fallback to default 2026-03-29 13:00:43 +08:00
hkfires 145e0e0b5d fix(claude): add default max_tokens for models 2026-03-29 12:46:00 +08:00
Luis Pater 9b7d7021af docs(readme): update LingtrueAPI link in all README translations 2026-03-29 12:30:24 +08:00
Luis Pater e41c22ef44 docs(readme): add LingtrueAPI sponsorship details to all README translations 2026-03-29 12:23:37 +08:00
Ravi Tharuma 5fc2bd393e fix: retain codex thinking signature until item done 2026-03-28 14:41:25 +01:00
Luis Pater 55271403fb Merge pull request #2374 from VooDisss/codex-cache-clean
fix(codex): restore prompt cache continuity for Codex requests
2026-03-28 21:16:51 +08:00
Luis Pater 36fba66619 Merge pull request #2371 from RaviTharuma/docs/provider-specific-routes
docs: clarify provider-specific routing for aliased models
2026-03-28 21:11:29 +08:00
Ravi Tharuma 66eb12294a fix: clear stale thinking signature when no block is open 2026-03-28 14:08:31 +01:00
Ravi Tharuma 73b22ec29b fix: omit empty signature field from thinking blocks
Emit signature only when non-empty in both streaming content_block_start
and non-streaming thinking blocks. Avoids turning 'missing signature'
into 'empty/invalid signature' which Claude clients may reject.
2026-03-28 14:08:31 +01:00
Ravi Tharuma c31ae2f3b5 fix: retain previously captured thinking signature on new summary part 2026-03-28 14:08:31 +01:00
Ravi Tharuma 76b53d6b5b fix: finalize pending thinking block before next summary part 2026-03-28 14:08:31 +01:00
Ravi Tharuma a34dfed378 fix: preserve Claude thinking signatures in Codex translator 2026-03-28 14:08:31 +01:00
Luis Pater b9b127a7ea Merge pull request #2347 from edlsh/fix/codex-strip-stream-options
fix(codex): strip stream_options from Responses API requests
2026-03-28 21:03:01 +08:00
Luis Pater 2741e7b7b3 Merge pull request #2346 from pjpjq/codex/fix-codex-capacity-retry
fix(codex): Treat Codex capacity errors as retryable
2026-03-28 21:00:50 +08:00
Luis Pater 1767a56d4f Merge pull request #2343 from kongkk233/fix/proxy-transport-defaults
Preserve default transport settings for proxy clients
2026-03-28 20:58:24 +08:00
Luis Pater 779e6c2d2f Merge pull request #2231 from 7RPH/fix/responses-stream-multi-tool-calls
fix: preserve separate streamed tool calls in Responses API
2026-03-28 20:53:19 +08:00
Luis Pater 73c831747b Merge pull request #2133 from DragonFSKY/fix/2061-stale-modelstates
fix(auth): prevent stale runtime state inheritance from disabled auth entries
2026-03-28 20:50:57 +08:00
Luis Pater 10b824fcac fix(security): validate auth file names to prevent unsafe input 2026-03-28 04:48:23 +08:00
VooDisss e5d3541b5a refactor(codex): remove stale affinity cleanup leftovers
Drop the last affinity-related executor artifacts so the PR stays focused on the minimal Codex continuity fix set: stable prompt cache identity, stable session_id, and the executor-only behavior that was validated to restore cache reads.
2026-03-27 20:40:26 +02:00
VooDisss 79755e76ea refactor(pr): remove forbidden translator changes
Drop the chat-completions translator edits from this PR so the branch complies with the repository policy that forbids pull-request changes under internal/translator. The remaining PR stays focused on the executor-level Codex continuity fix that was validated to restore cache reuse.
2026-03-27 19:34:13 +02:00
VooDisss 35f158d526 refactor(pr): narrow Codex cache fix scope
Remove the experimental auth-affinity routing changes from this PR so it stays focused on the validated Codex continuity fix. This keeps the prompt-cache repair while avoiding unrelated routing-policy concerns such as provider/model affinity scope, lifecycle cleanup, and hard-pin fallback semantics.
2026-03-27 19:06:34 +02:00
VooDisss 6962e09dd9 fix(auth): scope affinity by provider
Keep sticky auth affinity limited to matching providers and stop persisting execution-session IDs as long-lived affinity keys so provider switching and normal streaming traffic do not create incorrect pins or stale affinity state.
2026-03-27 18:52:58 +02:00
VooDisss 4c4cbd44da fix(auth): avoid leaking or over-persisting affinity keys
Stop using one-shot idempotency keys as long-lived auth-affinity identifiers and remove raw affinity-key values from debug logs so sticky routing keeps its continuity benefits without creating avoidable memory growth or credential exposure risks.
2026-03-27 18:34:51 +02:00
VooDisss 26eca8b6ba fix(codex): preserve continuity and safe affinity fallback
Restore Claude continuity after the continuity refactor, keep auth-affinity keys out of upstream Codex session identifiers, and only persist affinity after successful execution so retries can still rotate to healthy credentials when the first auth fails.
2026-03-27 18:27:33 +02:00
VooDisss 62b17f40a1 refactor(codex): align continuity helpers with review feedback
Align websocket continuity resolution with the HTTP Codex path, make auth-affinity principal keys use a stable string representation, and extract small helpers that remove duplicated continuity and affinity logic without changing the validated cache-hit behavior.
2026-03-27 18:11:57 +02:00
VooDisss 511b8a992e fix(codex): restore prompt cache continuity for Codex requests
Prompt caching on Codex was not reliably reusable through the proxy because repeated chat-completions requests could reach the upstream without the same continuity envelope. In practice this showed up most clearly with OpenCode, where cache reads worked in the reference client but not through CLIProxyAPI, although the root cause is broader than OpenCode itself.

The proxy was breaking continuity in several ways: executor-layer Codex request preparation stripped prompt_cache_retention, chat-completions translation did not preserve that field, continuity headers used a different shape than the working client behavior, and OpenAI-style Codex requests could be sent without a stable prompt_cache_key. When that happened, session_id fell back to a fresh random value per request, so upstream Codex treated repeated requests as unrelated turns instead of as part of the same cacheable context.

This change fixes that by preserving caller-provided prompt_cache_retention on Codex execution paths, preserving prompt_cache_retention when translating OpenAI chat-completions requests to Codex, aligning Codex continuity headers to session_id, and introducing an explicit Codex continuity policy that derives a stable continuity key from the best available signal. The resolution order prefers an explicit prompt_cache_key, then execution session metadata, then an explicit idempotency key, then stable request-affinity metadata, then a stable client-principal hash, and finally a stable auth-ID hash when no better continuity signal exists.

The same continuity key is applied to both prompt_cache_key in the request body and session_id in the request headers so repeated requests reuse the same upstream cache/session identity. The auth manager also keeps auth selection sticky for repeated request sequences, preventing otherwise-equivalent Codex requests from drifting across different upstream auth contexts and accidentally breaking cache reuse.

To keep the implementation maintainable, the continuity resolution and diagnostics are centralized in a dedicated Codex continuity helper instead of being scattered across executor flow code. Regression coverage now verifies retention preservation, continuity-key precedence, stable auth-ID fallback, websocket parity, translator preservation, and auth-affinity behavior. Manual validation confirmed prompt cache reads now occur through CLIProxyAPI when using Codex via OpenCode, and the fix should also benefit other clients that rely on stable repeated Codex request continuity.
2026-03-27 17:49:29 +02:00
Luis Pater 7dccc7ba2f docs(readme): remove redundant whitespace in BmoPlus sponsorship section of Chinese README 2026-03-27 20:52:14 +08:00
Luis Pater 70c90687fd docs(readme): fix formatting in BmoPlus sponsorship section of Chinese README 2026-03-27 20:49:43 +08:00
Luis Pater 8144ffd5c8 Merge pull request #2370 from B3o/add-bmoplus-sponsor
docs: add BmoPlus sponsorship banners to READMEs
2026-03-27 20:48:22 +08:00
Ravi Tharuma 0ab977c236 docs: clarify provider path limitations 2026-03-27 11:13:08 +01:00
Ravi Tharuma 224f0de353 docs: neutralize provider-specific path wording 2026-03-27 11:11:06 +01:00
B3o 6b45d311ec add BmoPlus sponsorship banners to READMEs 2026-03-27 18:01:35 +08:00
Ravi Tharuma d54de441d3 docs: clarify provider-specific routing for aliased models 2026-03-27 10:53:09 +01:00
白金 1821bf7051 docs: add BmoPlus sponsorship banners to READMEs 2026-03-27 17:39:29 +08:00
Luis Pater d42b5d4e78 docs(readme): update QQ group information in Chinese README 2026-03-27 11:46:21 +08:00
edlsh 754f3bcbc3 fix(codex): strip stream_options from Responses API requests
The Codex/OpenAI Responses API does not support the stream_options
parameter. When clients (e.g. Amp CLI) include stream_options in their
requests, CLIProxyAPI forwards it as-is, causing a 400 error:

  {"detail":"Unsupported parameter: stream_options"}

Strip stream_options alongside the other unsupported parameters
(previous_response_id, prompt_cache_retention, safety_identifier)
in Execute, ExecuteStream, and CountTokens.
2026-03-25 11:58:36 -04:00
pjpj 36973d4a6f Handle Codex capacity errors as retryable 2026-03-25 23:25:31 +08:00
kwz c89d19b300 Preserve default transport settings for proxy clients 2026-03-25 15:33:09 +08:00
RCD fc9616026b chore: merge upstream CLIProxyAPI v6.9.2 2026-03-25 09:38:44 +07:00
Luis Pater 1e6bc81cfd refactor(config): replace auto-update-panel with disable-auto-update-panel for clarity 2026-03-25 10:31:44 +08:00
Luis Pater 1a149475e0 Merge pull request #2293 from Xvvln/fix/management-asset-security
fix(security): harden management panel asset updater
2026-03-25 10:22:49 +08:00
Luis Pater e5166841db Merge pull request #2310 from shellus/fix/claude-openai-system-top-level
fix: preserve OpenAI system messages as Claude top-level system
2026-03-25 10:21:18 +08:00
Luis Pater bb9b2d1758 Merge pull request #2320 from cikichen/build/freebsd-support
build: add freebsd support for releases
2026-03-25 10:12:35 +08:00
Luis Pater 76c064c729 Merge pull request #2335 from router-for-me/auth
Support batch upload and delete for auth files
2026-03-25 09:34:44 +08:00
Luis Pater d2f652f436 Merge pull request #2333 from router-for-me/codex
feat(codex): pass through codex client identity headers
2026-03-25 09:34:09 +08:00
Luis Pater 6a452a54d5 Merge pull request #2316 from router-for-me/openai
Add per-model thinking support for OpenAI compatibility
2026-03-25 09:31:28 +08:00
hkfires 9e5693e74f feat(api): support batch auth file upload and delete 2026-03-25 09:20:17 +08:00
hkfires 528b1a2307 feat(codex): pass through codex client identity headers 2026-03-25 08:48:18 +08:00
Luis Pater 0cc978ec1d Merge pull request #2297 from router-for-me/readme
docs(readme): update japanese documentation links
2026-03-25 03:11:24 +08:00
simon d312422ab4 build: add freebsd support to releases 2026-03-24 16:49:04 +08:00
hkfires fee736933b feat(openai-compat): add per-model thinking support 2026-03-24 14:21:12 +08:00
GeJiaXiang 09c92aa0b5 fix: keep a fallback turn for system-only Claude inputs 2026-03-24 13:54:25 +08:00
GeJiaXiang 8c67b3ae64 test: verify remaining user message after system merge 2026-03-24 13:47:52 +08:00
GeJiaXiang 000e4ceb4e fix: map OpenAI system messages to Claude top-level system 2026-03-24 13:42:33 +08:00
RCD a2a4fba626 chore: merge upstream CLIProxyAPI v6.9.1 2026-03-24 09:41:49 +07:00
hkfires 5c99846ecf docs(readme): update japanese documentation links 2026-03-24 09:47:01 +08:00
trph cc32f5ff61 fix: unify Responses output indexes for streamed items 2026-03-24 08:59:09 +08:00
trph fbff68b9e0 fix: preserve choice-aware output indexes for streamed tool calls 2026-03-24 08:54:43 +08:00
trph 7e1a543b79 fix: preserve separate streamed tool calls in Responses API 2026-03-24 08:51:15 +08:00
Luis Pater d475aaba96 Fixed: #2274
fix(translator): omit null content fields in Codex OpenAI tool call responses
2026-03-24 01:00:57 +08:00
Luis Pater 96f55570f7 Merge pull request #2282 from eltociear/add-ja-doc
docs: add Japanese README
2026-03-24 00:40:58 +08:00
Luis Pater 0906aeca87 Merge pull request #2254 from clcc2019/main
refactor: streamline usage reporting by consolidating record publishi…
2026-03-24 00:39:31 +08:00
Xvvln 7333619f15 fix: reject oversized downloads instead of truncating; warn on unverified fallback
- Read maxAssetDownloadSize+1 bytes and error if exceeded, preventing
  silent truncation that could write a broken management.html to disk
- Log explicit warning when fallback URL is used without digest
  verification, so users are aware of the reduced security guarantee
2026-03-24 00:27:44 +08:00
Luis Pater 97c0487add Merge pull request #2223 from cnrpman/fix/codex-responses-web-search-preview-compat
fix: normalize web_search_preview for codex responses
2026-03-24 00:25:37 +08:00
DragonFSKY 74b862d8b8 test(cliproxy): cover delete re-add stale state flow 2026-03-24 00:21:04 +08:00
Xvvln 2db8df8e38 fix(security): harden management panel asset updater
- Abort update when SHA256 digest mismatch is detected instead of
  logging a warning and proceeding (prevents MITM asset replacement)
- Cap asset download size to 10 MB via io.LimitReader (defense-in-depth
  against OOM from oversized responses)
- Add `auto-update-panel` config option (default: false) to make the
  periodic background updater opt-in; the panel is still downloaded
  on first access when missing, but no longer silently auto-updated
  every 3 hours unless explicitly enabled
2026-03-24 00:10:04 +08:00
Luis Pater a576088d5f Merge pull request #2222 from kaitranntt/kai/fix/758-openai-proxy-alternating-model-support
fix: fall back on model support errors during auth rotation
2026-03-24 00:03:28 +08:00
Luis Pater 66ff916838 Merge pull request #2220 from xulongwu4/main
fix: normalize model name in TranslateRequest fallback to prevent prefix leak
2026-03-23 23:56:15 +08:00
Luis Pater 7b0453074e Merge pull request #2219 from beck-8/fix/context-done-race
fix: avoid data race when watching request cancellation
2026-03-23 22:57:21 +08:00
Luis Pater a000eb523d Merge pull request #2213 from TTTPOB/ua-fix
feat(claude): stabilize device fingerprint across mixed Claude Code and cloaked clients
2026-03-23 22:53:51 +08:00
Luis Pater 18a4fedc7f Merge pull request #2126 from ailuntz/fix/watcher-auth-cache-memory
perf(watcher): reduce auth cache memory
2026-03-23 22:47:34 +08:00
Luis Pater 5d6cdccda0 Merge pull request #2268 from sususu98/fix/sanitize-tool-names
fix(translator): sanitize tool names for Gemini function_declarations compatibility
2026-03-23 21:42:22 +08:00
Luis Pater 1b7f4ac3e1 Merge pull request #2252 from sususu98/fix/antigravity-empty-thought-text
fix(antigravity): always include text field in thought parts to prevent Google 500
2026-03-23 21:41:25 +08:00
Luis Pater afc1a5b814 Fixed: #2281
refactor(claude): centralize usage token calculation logic and add tests for cached token handling
2026-03-23 21:30:03 +08:00
Ikko Eltociear Ashimineandgemini-code-assist[bot] 7ed38db54f docs: update README_JA.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-03-23 16:57:43 +09:00
Ikko Eltociear Ashimineandgemini-code-assist[bot] 28c10f4e69 docs: update README_JA.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-03-23 16:57:32 +09:00
Ikko Eltociear Ashimineandgemini-code-assist[bot] 6e12441a3b Update README_JA.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-03-23 16:57:19 +09:00
Ikko Ashimine 65c439c18d docs: add Japanese README 2026-03-23 15:23:18 +09:00
dslife2025 0ed2d16596 Merge branch 'router-for-me:main' into main 2026-03-23 09:50:43 +08:00
Supra4E8C db335ac616 Merge pull request #2269 from router-for-me/auth-fix
fix(auth): ensure absolute paths for auth file handling
2026-03-22 22:53:44 +08:00
sususu98 e8bb350467 fix: extend tool name sanitization to all remaining Gemini-bound translators
Apply SanitizeFunctionName on request and RestoreSanitizedToolName on
response for: gemini/claude, gemini/openai/chat-completions,
gemini/openai/responses, antigravity/openai/chat-completions,
gemini-cli/openai/chat-completions.

Also update SanitizedToolNameMap to handle OpenAI format
(tools[].function.name) in addition to Claude format (tools[].name).
2026-03-22 14:06:46 +08:00
Supra4E8C 5331d51f27 fix(auth): ensure absolute paths for auth file handling 2026-03-22 13:58:16 +08:00
sususu98 755ca75879 fix: address review feedback - init ToolNameMap eagerly, log collisions, add collision test 2026-03-22 13:24:03 +08:00
sususu98 2398ebad55 fix(translator): sanitize tool names for Gemini function_declarations compatibility
Claude Code and MCP clients may send tool names containing characters
invalid for Gemini's function_declarations (e.g. '/', '@', spaces).
Sanitize on request via SanitizeFunctionName and restore original names
on response for both antigravity/claude and gemini-cli/claude translators.
2026-03-22 13:10:53 +08:00
clcc2019 c1bf298216 refactor: streamline usage reporting by consolidating record publishing logic
- Introduced a new method `buildRecord` in `usageReporter` to encapsulate record creation, improving code readability and maintainability.
- Added latency tracking to usage records, ensuring accurate reporting of request latencies.
- Updated tests to validate the inclusion of latency in usage records and ensure proper functionality of the new reporting structure.
2026-03-20 19:44:26 +08:00
sususu e005208d76 fix(antigravity): always include text field in thought parts to prevent Google 500
When Claude sends redacted thinking with empty text, the translator
was omitting the "text" field from thought parts. Google Antigravity
API requires this field, causing 500 "Unknown Error" responses.

Verified: 129/129 error logs with empty thought → 500, 0/97 success
logs had empty thought. After fix: 0 new "Unknown Error" 500s.
2026-03-20 18:59:25 +08:00
Junyi Du d1df70d02f chore: add codex builtin tool normalization logging 2026-03-20 14:08:37 +08:00
Luis Pater f81acd0760 Merge pull request #2243 from router-for-me/oauth
Improve OAuth callback handling with async prompts
2026-03-20 12:35:44 +08:00
hkfires 636da4c932 refactor(auth): replace manual input handling with AsyncPrompt for callback URLs 2026-03-20 12:24:27 +08:00
hkfires cccb77b552 fix(auth): avoid blocking oauth callback wait on prompt 2026-03-20 11:48:30 +08:00
Luis Pater 2bd646ad70 refactor: replace sjson.Set usage with sjson.SetBytes to optimize mutable JSON transformations 2026-03-19 17:58:54 +08:00
tpob 52c1fa025e fix(claude): learn official fingerprints after custom baselines 2026-03-19 13:59:41 +08:00
tpob 680105f84d fix(claude): refresh cached fingerprint after baseline upgrades 2026-03-19 13:28:58 +08:00
tpob f7069e9548 fix(claude): pin stabilized OS arch to baseline 2026-03-19 13:07:16 +08:00
Junyi Du 793840cdb4 fix: cover dated and nested codex web search aliases 2026-03-19 03:41:12 +08:00
Junyi Du 8f421de532 fix: handle sjson errors in codex tool normalization 2026-03-19 03:36:06 +08:00
Junyi Du be2dd60ee7 fix: normalize web_search_preview for codex responses 2026-03-19 03:23:14 +08:00
Tam Nhu Tran ea3e0b713e fix: harden pooled model-support fallback state 2026-03-18 13:19:20 -04:00
tpob 8179d5a8a4 fix(claude): avoid racy fingerprint downgrades 2026-03-19 01:03:41 +08:00
tpob 6fa7abe434 fix(claude): keep configured baseline above older fingerprints 2026-03-19 01:02:04 +08:00
Tam Nhu Tran 5135c22cd6 fix: fall back on model support errors during auth rotation 2026-03-18 12:43:45 -04:00
Longwu Ou 1e27990561 address PR review: log sjson error and add unit tests
- Log a warning instead of silently ignoring sjson.SetBytes errors in the TranslateRequest fallback path
  - Add registry_test.go with tests covering the fallback model normalization and verifying registered transforms take precedence
2026-03-18 12:43:40 -04:00
Longwu Ou e1e9fc43c1 fix: normalize model name in TranslateRequest fallback to prevent prefix leak
When no request translator is registered for a format pair (e.g.
        openai-response → openai-response), TranslateRequest returned the raw
        payload unchanged. This caused client-side model prefixes (e.g.
        "copilot/gpt-5-mini") to leak into upstream requests, resulting in
        "The requested model is not supported" errors from providers.

        The fallback path now updates the "model" field in the payload to
        match the resolved model name before returning.
2026-03-18 12:30:22 -04:00
beck-8 b2921518ac fix: avoid data race when watching request cancellation 2026-03-19 00:15:52 +08:00
tpob dd64adbeeb fix(claude): preserve legacy user agent overrides 2026-03-19 00:03:09 +08:00
tpob 616d41c06a fix(claude): restore legacy runtime OS arch fallback 2026-03-19 00:01:50 +08:00
tpob e0e337aeb9 feat(claude): add switch for device profile stabilization 2026-03-18 19:31:59 +08:00
tpob d52839fced fix: stabilize claude device fingerprint 2026-03-18 18:46:54 +08:00
Luis Pater 56073ded69 Merge pull request #2200 from sususu98/feat/local-model-flag
feat: add -local-model flag to skip remote model catalog fetching
2026-03-18 10:58:07 +08:00
sususu98 9738a53f49 feat: add -local-model flag to skip remote model catalog fetching
When enabled, the server uses only the embedded models.json loaded at
init() and skips registry.StartModelsUpdater(), disabling the initial
remote fetch and 3-hour periodic refresh. The management panel
auto-updater (managementasset.StartAutoUpdater) is unaffected.
2026-03-18 10:48:03 +08:00
Luis Pater be3f8dbf7e Merge pull request #2187 from Darley-Wey/fix/claude-disable-parallel-tool-calls
fix(claude): honor disable_parallel_tool_use
2026-03-17 21:06:08 +08:00
Darley 9c6c3612a8 fix(claude): read disable_parallel_tool_use from tool_choice 2026-03-17 19:35:41 +08:00
Darley 19e1a4447a fix(claude): honor disable_parallel_tool_use 2026-03-17 19:17:41 +08:00
dinhkarateandClaude Opus 4.6 36efcc6e28 fix(vertex): include prefix in auth filename and validate at import
Address two blocking issues from PR review:
- Auth file now named vertex-{prefix}-{project}.json so importing the
  same project with different prefixes no longer overwrites credentials
- Prefix containing "/" is rejected at import time instead of being
  silently ignored at runtime
- Add prefix to in-memory metadata map for consistency

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 15:06:04 +07:00
Pham Quang Dinh a337ecf35c Merge branch 'router-for-me:main' into feat(vertex)/add-prefix-field 2026-03-17 11:48:40 +07:00
RCD 3595d47a9d docs: record v0.3.0-dev-0.43 release 2026-03-17 02:29:57 +07:00
RCD 82a00093b6 chore: merge upstream CLIProxyAPI v6.8.55 2026-03-17 02:25:21 +07:00
Luis Pater fb95813fbf Merge pull request #2142 from Muran-prog/fix/strip-uniqueItems-gemini-2123
fix: strip uniqueItems from Gemini function_declarations (#2123)
2026-03-16 20:34:28 +08:00
Luis Pater db63f9b5d6 Merge pull request #2162 from enieuwy/fix/responses-api-json-valid-check
fix: validate JSON before raw-embedding function call outputs in Responses API
2026-03-16 18:42:31 +08:00
Luis Pater 25f6c4a250 Merge pull request #2158 from sususu98/fix/antigravity-functionresponse-name
fix(antigravity): resolve empty functionResponse.name for toolu_* tool_use_id format
2026-03-16 18:39:40 +08:00
enieuwy b24ae74216 fix: validate JSON before raw-embedding function call outputs in Responses API
gjson.Parse() marks any string starting with { or [ as gjson.JSON type,
even when the content is not valid JSON (e.g. macOS plist format, truncated
tool results). This caused sjson.SetRaw to embed non-JSON content directly
into the Gemini API request payload, producing 400 errors.

Add json.Valid() check before using SetRaw to ensure only actually valid
JSON is embedded raw. Non-JSON content now falls through to sjson.Set
which properly escapes it as a JSON string.

Fixes #2161
2026-03-16 15:29:18 +08:00
Luis Pater 59ad8f40dc Merge pull request #2124 from RGBadmin/feat/auth-list-priority-note
feat(api): expose priority and note in GET /auth-files response
2026-03-16 12:31:11 +08:00
sususu98 ff03dc6a2c fix(antigravity): resolve empty functionResponse.name for toolu_* tool_use_id format
The Claude-to-Gemini translator derived function names by splitting
tool_use_id on "-", which produced empty strings for IDs with exactly
2 segments (e.g. toolu_tool-<uuid>). Replace the string-splitting
heuristic with a lookup map built from tool_use blocks during the
main processing loop, with fallback to the raw ID on miss.
2026-03-16 11:18:29 +08:00
Luis Pater dc7187ca5b fix(websocket): pin only websocket-capable auth IDs and add corresponding test 2026-03-16 09:57:38 +08:00
Luis Pater b1dcff778c Merge pull request #2141 from Muran-prog/fix/tool-calling-translation-2132
fix: skip empty assistant message in tool call translation (#2132)
2026-03-16 01:42:27 +08:00
Luis Pater 198b3f4a40 chore(ci): update build metadata to use GITHUB_REF_NAME in workflows 2026-03-16 00:30:44 +08:00
Luis Pater 9fee7f488e chore(ci): update GoReleaser config and release workflow to skip validation step 2026-03-16 00:16:25 +08:00
RGBadminandClaude Opus 4.6 c1241a98e2 fix(api): restrict fallback note to string-typed JSON values
Only emit note in listAuthFilesFromDisk when the JSON value is actually
a string (gjson.String), matching the synthesizer/buildAuthFileEntry
behavior. Non-string values like numbers or booleans are now ignored
instead of being coerced via gjson.String().

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:00:17 +08:00
RGBadminandClaude Opus 4.6 8d8f5970ee fix(api): fallback to Metadata for priority/note on uploaded auths
buildAuthFileEntry now falls back to reading priority/note from
auth.Metadata when Attributes lacks them. This covers auths registered
via UploadAuthFile which bypass the synthesizer and only populate
Metadata from the raw JSON.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 17:36:11 +08:00
RGBadminandClaude Opus 4.6 f90120f846 fix(api): propagate note to Gemini virtual auths and align priority parsing
- Read note from Attributes (consistent with priority) in buildAuthFileEntry,
  fixing missing note on Gemini multi-project virtual auth cards.
- Propagate note from primary to virtual auths in SynthesizeGeminiVirtualAuths,
  mirroring existing priority propagation.
- Sync note/priority writes to both Metadata and Attributes in PatchAuthFileFields,
  with refactored nil-check to reduce duplication (review feedback).
- Validate priority type in fallback disk-read path instead of coercing all values
  to 0 via gjson.Int(), aligning with the auth-manager code path.
- Add regression tests for note synthesis, virtual-auth note propagation, and
  end-to-end multi-project Gemini note inheritance.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 16:47:01 +08:00
Muran-prog 0b94d36c4a test: use exact match for tool name assertion
Address review feedback - drop function.name fallback and
strings.Contains in favor of direct == comparison.
2026-03-14 21:45:28 +02:00
Muran-prog 152c310bb7 test: add uniqueItems stripping test
Covers the fix from the previous commit — verifies uniqueItems is
removed from the schema and moved to the description hint.
2026-03-14 21:22:14 +02:00
Muran-prog f6bbca35ab fix: strip uniqueItems from Gemini function_declarations (#2123)
Gemini API rejects uniqueItems in tool schemas with 400. Add it to
unsupportedConstraints alongside minItems/maxItems where it belongs.

Same class of fix as #1424 and #1531.
2026-03-14 21:18:06 +02:00
Muran-prog c8cee6a209 fix: skip empty assistant message in tool call translation (#2132)
When assistant has tool_calls but no text content, the translator
emitted an empty message into the Responses API input array before
function_call items. The API then couldn't match function_call_output
to its function_call by call_id, returning:

  No tool output found for function call ...

Only emit assistant messages that have content parts. Tool-call-only
messages now produce function_call items directly.

Added 9 tests for tool calling translation covering single/parallel
calls, multi-turn conversations, name shortening, empty content
edge cases, and call_id integrity.
2026-03-14 21:01:01 +02:00
Luis Pater b5701f416b Fixed: #2102
fix(auth): ensure unique auth index for shared API keys across providers and credential identities
2026-03-15 02:48:54 +08:00
Luis Pater 4b1a404fcb Fixed: #1936
feat(translator): add image type handling in ConvertClaudeRequestToGemini
2026-03-15 02:18:28 +08:00
Luis Pater 67669196ed Merge pull request #2131 from HEUDavid/docs/add-who-is-with-us
docs: Add Shadow AI to 'Who is with us?' section
2026-03-15 01:44:46 +08:00
DragonFSKY 5c817a9b42 fix(auth): prevent stale ModelStates inheritance from disabled auth entries
When an auth file is deleted and re-created with the same path/ID, the
new auth could inherit stale ModelStates (cooldown/backoff) from the
previously disabled entry, preventing it from being routed.

Gate runtime state inheritance (ModelStates, LastRefreshedAt,
NextRefreshAfter) on both existing and incoming auth being non-disabled
in Manager.Update and Service.applyCoreAuthAddOrUpdate.

Closes #2061
2026-03-14 23:46:23 +08:00
destinoantagonista-wq e08f68ed7c chore(auth): drop reconcile test file from pr 2026-03-14 14:41:26 +00:00
destinoantagonista-wq f09ed25fd3 fix(auth): tighten registry model reconciliation 2026-03-14 14:40:06 +00:00
hkfires 58fd9bf964 fix(codex): add 'go' plan_type in registerModelsForAuth 2026-03-14 22:09:14 +08:00
HEUDavid 7b3dfc67bc docs: Add Shadow AI to 'Who is with us?' section 2026-03-14 21:01:07 +08:00
HEUDavid cdd24052d3 docs: Add Shadow AI to 'Who is with us?' section 2026-03-14 20:53:43 +08:00
Luis Pater 733fd8edab Merge pull request #2111 from qzydustin/main
Fix missing streaming usage tracking for OpenAI-compatible providers
2026-03-14 18:17:08 +08:00
Luis Pater af27f2b8bc Merge pull request #2110 from router-for-me/codex
feat(service): extend model registration for team and business types
2026-03-14 18:10:01 +08:00
Luis Pater 2e1925d762 Merge pull request #2108 from sususu98/fix/gemini-cli-tool-schema-and-empty-parts
fix(gemini-cli): sanitize tool schemas and filter empty parts
2026-03-14 18:02:52 +08:00
Luis Pater 77254bd074 Merge pull request #2116 from router-for-me/vertex
fix(config): allow vertex keys without base-url
2026-03-14 17:27:48 +08:00
RGBadminandClaude Opus 4.6 5b6342e6ac feat(api): expose priority and note fields in GET /auth-files list response
The list endpoint previously omitted priority and note, which are stored
inside each auth file's JSON content. This adds them to both the normal
(auth-manager) and fallback (disk-read) code paths, and extends
PATCH /auth-files/fields to support writing the note field.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 14:47:31 +08:00
destinoantagonista-wq e166e56249 Reconcile registry model states on auth changes
Add Manager.ReconcileRegistryModelStates to clear stale per-model runtime failures for models currently registered in the global model registry. The method finds models supported for an auth, resets non-clean ModelState entries, updates aggregated availability, persists changes, and pushes a snapshot to the scheduler. Introduce modelStateIsClean helper to determine when a model state needs resetting. Call ReconcileRegistryModelStates from Service paths that register/refresh models (applyCoreAuthAddOrUpdate and refreshModelRegistrationForAuth) to keep the scheduler and global registry aligned after model re-registration.
2026-03-13 19:41:49 +00:00
hkfires 560c020477 fix(config): allow vertex keys without base-url 2026-03-13 19:09:26 +08:00
Zhenyu Qi aec65e3be3 fix(openai_compat): add stream_options.include_usage for streaming usage tracking 2026-03-13 00:48:17 -07:00
hkfires f44f0702f8 feat(service): extend model registration for team and business types 2026-03-13 14:12:19 +08:00
sususu98 b76b79068f fix(gemini-cli): sanitize tool schemas and filter empty parts
1. Claude translator: add CleanJSONSchemaForGemini() to sanitize tool
   input schemas (removes $schema, anyOf, const, format, etc.) and
   delete eager_input_streaming from tool declarations. Remove fragile
   bytes.Replace for format:"uri" now covered by schema cleaner.

2. Gemini native translator: filter out content entries with empty or
   missing parts arrays to prevent Gemini API 400 error "required
   oneof field 'data' must have one initialized field".

Both fixes align gemini-cli with protections already present in the
antigravity translator.
2026-03-13 12:37:37 +08:00
Luis Pater 1db23979e8 Merge pull request #2106 from router-for-me/model
feat(model_registry): enhance model registration and refresh mechanisms
2026-03-13 11:18:51 +08:00
hkfires c3d5dbe96f feat(model_registry): enhance model registration and refresh mechanisms 2026-03-13 10:56:39 +08:00
RCD 3a828bb14c docs: record maintenance fix rollout 2026-03-12 12:55:04 +07:00
RCD c93f57a02a fix(translator): align tool and gemini semantics 2026-03-12 12:54:50 +07:00
RCD dd0d99e64b fix(management): harden handler state and paths 2026-03-12 12:54:33 +07:00
RCD 96f28fc5d5 fix(auth): harden token persistence and refresh 2026-03-12 12:54:14 +07:00
RCD 85f6a29477 docs: record maintenance review findings 2026-03-12 12:02:21 +07:00
RCD 13a1fbe946 fix(auth): resolve nested filestore deletes 2026-03-12 11:20:51 +07:00
RCD 1f82eedbef chore: switch releases to manual publishing 2026-03-12 11:07:03 +07:00
RCD d9e5506949 docs: track CLIProxyAPI v6.8.51 sync 2026-03-12 11:00:53 +07:00
RCD 6628e20d8c fix(cmd): align model listing with codex tiers 2026-03-12 11:00:16 +07:00
RCD 64e2a43259 chore: merge upstream CLIProxyAPI v6.8.51 2026-03-12 10:58:52 +07:00
RCD febd409cca Merge tag 'v6.8.50' 2026-03-12 10:53:58 +07:00
Luis Pater 5484489406 chore(ci): update model catalog fetch method in workflows 2026-03-12 11:19:24 +08:00
Luis Pater 0ac52da460 chore(ci): update model catalog fetch method in release workflow 2026-03-12 10:50:46 +08:00
Luis Pater 817cebb321 Merge pull request #2082 from router-for-me/antigravity
Refactor Antigravity model handling and improve logging
2026-03-12 10:39:13 +08:00
Luis Pater 683f3709d6 Merge pull request #2076 from aikins01/fix/backfill-empty-function-response-names
fix: backfill empty functionResponse.name from preceding functionCall
2026-03-12 10:35:44 +08:00
hkfires dbd42a42b2 fix(model_updater): clarify log message for model refresh failure 2026-03-12 10:32:04 +08:00
hkfires ec24baf757 feat(fetch_antigravity_models): add command to fetch and save Antigravity model list 2026-03-12 10:21:09 +08:00
hkfires dea3e74d35 feat(antigravity): refactor model handling and remove unused code 2026-03-12 09:24:45 +08:00
Aikins Laryea a6c3042e34 refactor: remove redundant bounds checks per code review 2026-03-12 00:12:43 +00:00
Aikins Laryea 861537c9bd fix: backfill empty functionResponse.name from preceding functionCall
when Amp or Claude Code sends functionResponse with an empty name in Gemini
conversation history, the Gemini API rejects the request with 400
"Name cannot be empty". this fix backfills empty names from the
corresponding preceding functionCall parts using positional matching.

covers all three Gemini translator paths:
- gemini/gemini (direct API key)
- antigravity/gemini (OAuth)
- gemini-cli/gemini (Gemini CLI)

also switches fixCLIToolResponse pending group matching from LIFO to
FIFO to correctly handle multiple sequential tool call groups.

fixes #1903
2026-03-12 00:00:38 +00:00
Luis Pater 8c92cb0883 Merge pull request #2056 from lang-911/codex/custom-useragent-request
feat(config/codex): Add Codex header defaults (`user-agent`: override; `beta-features`: default)
2026-03-11 22:56:36 +08:00
Luis Pater 89d7be9525 Merge branch 'dev' into codex/custom-useragent-request 2026-03-11 22:55:50 +08:00
lang-911 2b79d7f22f fix: restore double quotes style in config.example.yaml for consistency and readability 2026-03-11 06:59:26 -07:00
lang-911 163fe287ce fix: codex header defaults example 2026-03-11 06:55:03 -07:00
lang-911 70988d387b Add Codex websocket header defaults 2026-03-11 00:34:57 -07:00
Luis Pater ddaa9d2436 Fixed: #2034
feat(proxy): centralize proxy handling with `proxyutil` package and enhance test coverage

- Added `proxyutil` package to simplify proxy handling across the codebase.
- Refactored various components (`executor`, `cliproxy`, `auth`, etc.) to use `proxyutil` for consistent and reusable proxy logic.
- Introduced support for "direct" proxy mode to explicitly bypass all proxies.
- Updated tests to validate proxy behavior (e.g., `direct`, HTTP/HTTPS, and SOCKS5).
- Enhanced YAML configuration documentation for proxy options.
2026-03-11 11:08:02 +08:00
Luis Pater 7b7b258c38 Fixed: #2022
test(translator): add tests for handling Claude system messages as string and array
2026-03-11 10:47:33 +08:00
Luis Pater cf74ed2f0c Merge pull request #2013 from router-for-me/model
Fetch model catalog from network
2026-03-10 19:07:23 +08:00
ailuntz c3762328a5 perf(watcher): reduce auth cache memory 2026-03-10 16:27:10 +08:00
hkfires e333fbea3d feat(updater): update StartModelsUpdater to block until models refresh completes 2026-03-10 14:41:58 +08:00
hkfires efbe36d1d4 feat(updater): change models refresh to one-time fetch on startup 2026-03-10 14:18:54 +08:00
hkfires 8553cfa40e feat(workflows): refresh models catalog in workflows 2026-03-10 14:03:31 +08:00
hkfires 30d5c95b26 feat(registry): refresh model catalog from network 2026-03-10 14:02:54 +08:00
hkfires d1e3195e6f feat(codex): register models by plan tier 2026-03-10 11:20:37 +08:00
Luis Pater ce53d3a287 Fixed: #1997
test(auth-scheduler): add benchmarks and priority-based scheduling improvements

- Added `BenchmarkManagerPickNextMixedPriority500` for mixed-priority performance assessment.
- Updated `pickNextMixed` to prioritize highest ready priority tiers.
- Introduced `highestReadyPriorityLocked` and `pickReadyAtPriorityLocked` for better scheduling logic.
- Added unit test to validate selection of highest priority tiers in mixed provider scenarios.
2026-03-09 22:27:15 +08:00
Blue-B 5f58248016 fix(claude): clamp max_tokens to model limit in normalizeClaudeBudget
When adjustedBudget < minBudget, the previous fix blindly set
max_tokens = budgetTokens+1 which could exceed MaxCompletionTokens.

Now: cap max_tokens at MaxCompletionTokens, recalculate budget, and
disable thinking entirely if constraints are unsatisfiable.

Add unit tests covering raise, clamp, disable, and no-op scenarios.
2026-03-09 22:10:30 +09:00
Luis Pater 4cc99e7449 Merge pull request #1992 from dcrdev/main
System prompt silently dropped when sent as a string
2026-03-09 21:03:15 +08:00
Luis Pater 71773fe032 Merge pull request #1996 from router-for-me/codex/fix-unbounded-websocket-log-buffering
fix: cap websocket body log growth in responses handler
2026-03-09 20:50:38 +08:00
Dominic Robinson a1e0fa0f39 test(executor): cover string system prompt handling in checkSystemInstructionsWithMode 2026-03-09 12:40:27 +00:00
Supra4E8C fc2f0b6983 fix: cap websocket body log growth 2026-03-09 17:48:30 +08:00
Dominic Robinson 5c9997cdac fix: Preserve system prompt when sent as a string instead of content block array 2026-03-09 07:38:11 +00:00
Blue-B 07d6689d87 fix(claude): add interleaved-thinking beta header, AMP gzip error decoding, normalizeClaudeBudget max_tokens
1. Always include interleaved-thinking-2025-05-14 beta header so that
   thinking blocks are returned correctly for all Claude models.

2. Remove status-code guard in AMP reverse proxy ModifyResponse so that
   error responses (4xx/5xx) with hidden gzip encoding are decoded
   properly — prevents garbled error messages reaching the client.

3. In normalizeClaudeBudget, when the adjusted budget falls below the
   model minimum, set max_tokens = budgetTokens+1 instead of leaving
   the request unchanged (which causes a 400 from the API).
2026-03-07 21:31:10 +09:00
dinhkarate 14cb2b95c6 feat(vertex): add --vertex-import-prefix flag for model namespacing 2026-01-29 13:32:38 +07:00
dinhkarate fdeef48498 feat(vertex): Add Prefix field to VertexCredentialStorage for per-file model namespacing 2026-01-29 13:32:38 +07:00
356 changed files with 39245 additions and 8568 deletions
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
cargo fetch --manifest-path rust/Cargo.toml
if [ ! -f rust/proxypilot-rs.toml ]; then
cargo run --manifest-path rust/Cargo.toml -p proxypilot-rs -- init --config rust/proxypilot-rs.toml
fi
+86
View File
@@ -0,0 +1,86 @@
# Architecture
High-level system guidance for the Rust terminal operator-console slice.
**What belongs here:** module boundaries, state ownership, data flow, invariants, and where workers should add new behavior.
**What does not belong here:** low-level implementation diffs or line-by-line rewrite plans.
---
## Current Rust Entry Points
- `rust/proxypilot-rs/src/main.rs` wires CLI entrypoints.
- `cli.rs` defines command surfaces.
- `accounts.rs` handles CLI account operations against disk-backed account state.
- `config.rs` loads TOML config and resolves the state-file path.
- `state.rs` owns persisted local account state.
- `codex.rs` owns Codex device login and refresh-token exchange logic.
- `proxy.rs` owns the local HTTP proxy process and current in-memory proxy state.
- `tui.rs` owns the terminal operator console.
## State Layers
There are three distinct state layers in this mission. Workers must keep them separate and truthful:
1. **Config state**
- Loaded from TOML via `config.rs`
- Includes bind address, state-file path, upstream base URL, and fallback API key
2. **Saved local account state**
- Loaded and saved through `state.rs`
- Used by CLI account commands and by the TUI for disk-backed account visibility and local actions
3. **Live runtime state**
- Lives inside the running proxy process
- Includes the adopted active credential, request counters, refresh attempts/results, and any runtime-auth summary shown by `/v0/runtime/stats`
- Must not silently re-read disk on every stats request and pretend disk changes already altered runtime memory
## Desired Shared Domain for This Mission
This milestone should create a small shared auth/runtime domain used by both proxy and TUI-facing logic. It should own:
- RFC3339 parsing / clock helpers
- auth-health classification with the shared vocabulary:
- `valid`
- `expiring_soon`
- `expired`
- `static`
- `unknown`
- refresh outcome/status types
- runtime stats snapshot types for `/v0/runtime/stats`
The goal is to remove duplicated auth/time decision logic currently spread across `proxy.rs` and `tui.rs`.
## Runtime Stats Surface
`GET /v0/runtime/stats` is a read-only local operator endpoint.
It should expose runtime-memory state for:
- bind address
- upstream base URL
- active account name
- account count
- auth-health summary
- request counters
- last runtime refresh status
- last runtime refresh timestamp
This endpoint is the runtime source of truth for the TUI's operator-health panels.
## TUI Composition Model
The TUI should combine two inputs:
- **Disk-backed local state** for account list, selected-account details, and local account actions
- **Runtime stats HTTP data** for live auth/runtime visibility
This split is intentional. The UI must stay truthful if local saved state and running runtime state diverge.
## Mission Invariants
- The branch remains Codex-only for this mission.
- The TUI remains terminal-first and should become more operator-console-like, not more dashboard-like.
- Runtime counters are in-memory only and reset when the proxy process restarts.
- `R` targets the active account runtime action; `f` targets the selected saved account action.
- `r` reloads local/disk and runtime surfaces; `c` clears transient feedback only.
- Empty states and failures must stay readable and operator-meaningful.
+27
View File
@@ -0,0 +1,27 @@
# Environment
Environment variables, external dependencies, and setup notes.
**What belongs here:** required env vars, local setup notes, external dependency expectations, and fixture guidance.
**What does not belong here:** service start/stop commands or fixed ports outside explanatory notes.
---
## External Dependencies
- No external database, cache, or queue is required for this mission.
- No live Codex/OpenAI credentials are required for baseline automated validation.
- Use mocked local HTTP fixtures for upstream proxy and refresh-token flows unless the user explicitly expands scope to live credentials.
## Local Config Notes
- The Rust slice uses a TOML config and a separate state file.
- Run `./.factory/init.sh` to fetch Rust dependencies and create `rust/proxypilot-rs.toml` if it is missing before local smoke validation.
- Workers may generate temporary local configs for smoke validation.
- Relative state-file paths resolve relative to the chosen config file path.
## Local Runtime Notes
- The default Rust bind is `127.0.0.1:8318`.
- Keep runtime observability surfaces on the same local Rust proxy process.
- Avoid unrelated busy ports already present on the machine.
+97
View File
@@ -0,0 +1,97 @@
# User Testing
Validation guidance for the Rust terminal operator-console mission.
**What belongs here:** validation surfaces, tools, setup notes, and concurrency guidance.
**What does not belong here:** service command definitions (use `.factory/services.yaml`).
---
## Validation Surface
### HTTP runtime surface
- Endpoints:
- `GET /healthz`
- `GET /v0/runtime/stats`
- supported local Codex proxy routes touched by runtime tracking
- Primary tools:
- `curl`
- Rust mocked endpoint tests
- Validation focus:
- local health identity
- runtime stats schema and semantics
- request counters
- proactive refresh
- 401 retry refresh
- refresh failure tracking
### TUI surface
- Command:
- `cargo run -p proxypilot-rs -- tui --config <path>`
- Primary tools:
- `tuistory`
- manual local smoke when needed
- Validation focus:
- runtime/auth visibility
- truthful footer/help text
- local account visibility when runtime is down
- reload, clear feedback, selected refresh, active refresh-now
- readable empty/error states
### CLI/account surface
- Commands:
- `init`
- `account add-codex`
- `account list`
- `account activate`
- `account remove`
- `account refresh-codex`
- Primary tools:
- shell
- Validation focus:
- config creation semantics
- disk-backed account lifecycle semantics
- refreshable vs static-account behavior
## Validation Concurrency
- Automated Rust validation activities: max `2` concurrent
- rationale: machine has ample memory/CPU, but Rust tests plus local mocked listener flows should stay conservative
- Manual TUI validation: max `1` at a time
- rationale: interactive terminal verification is not realistically parallel and should not overlap with another heavy manual runtime smoke
## Setup Notes
- Baseline automated validation does not require live external credentials.
- Prefer mocked local upstream and refresh fixtures for HTTP/runtime tests.
- TUI validation requires a local config file and usually a running local Rust proxy for runtime-visible scenarios.
- Proxy-down scenarios are also required: validators should verify local disk-backed account visibility when runtime is unreachable.
## Flow Validator Guidance: shell
- Use only `.factory/validation/terminal-operator-console/user-testing/fixtures/cli-shell/` plus `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/`.
- Use temporary config/state files inside that fixture directory; do not modify repo-root default configs.
- Stay on CLI/account flows only; do not start long-lived proxy services from this fixture.
- Do not use live device-login. Prefer `init`, `account add-codex`, `account list`, `account activate`, `account remove`, and negative-path `account refresh-codex` checks against local fixture state.
- If refresh-success validation cannot be isolated without live OpenAI OAuth, record it as blocked with concrete evidence rather than using private credentials.
## Flow Validator Guidance: curl
- Use only `.factory/validation/terminal-operator-console/user-testing/fixtures/http-runtime/` plus `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/`.
- Own ports `18318-18339` for this validator only. Keep the proxy on `127.0.0.1:18318` unless a collision forces another port in that range.
- Mock the Codex upstream locally; never send `/v1/*` validation traffic to the real OpenAI upstream.
- Auth-refresh success paths may be blocked if the running binary cannot be pointed at a local OAuth token stub. Failure-path validation with intentionally invalid refresh tokens is allowed if it stays within the assigned fixture.
- Capture before/after `curl` output for stats-changing requests so counter deltas are explicit.
## Flow Validator Guidance: tuistory
- Use only `.factory/validation/terminal-operator-console/user-testing/fixtures/tui-console/` plus `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/`.
- Run only one TUI session at a time.
- Own ports `18418-18439` for proxy/mock services used by this validator. Keep runtime-down scenarios fully local by stopping those fixture services instead of touching shared ports.
- Keep disk-backed state isolated to the assigned fixture config/state files so reload, activate, delete, and refresh actions are attributable to this validator alone.
- Capture snapshots before and after each key flow (`r`, `a`, `d`, `f`, `R`, `c`) and note whether feedback came from local disk state or live runtime stats.
## Discovered Validation Quirks
- CLI `account refresh-codex` and runtime-triggered refresh paths now honor `codex.refresh_token_url` when set, so validators can redirect refresh success to a local stub from the real user surface while still relying on the built-in OpenAI OAuth endpoint when the override is unset.
- `tuistory` sessions should be closed explicitly after the TUI exits with `q`; the PTY can remain allocated even after the binary terminates.
- In runtime-down TUI scenarios, selected-account refresh (`f`) still attempts the hardwired OAuth refresh exchange for refreshable saved accounts and surfaces that remote failure text. Treat that as truthful runtime-dependent behavior, not as loss of local disk state.
+16
View File
@@ -0,0 +1,16 @@
commands:
install: cargo fetch --manifest-path rust/Cargo.toml
init: ./.factory/init.sh
fmt: cargo fmt --all --manifest-path rust/Cargo.toml
test: cargo test --manifest-path rust/Cargo.toml
typecheck: cargo check --manifest-path rust/Cargo.toml
lint: cargo clippy --manifest-path rust/Cargo.toml --all-targets -- -D warnings
tui-help: cargo run --manifest-path rust/Cargo.toml -p proxypilot-rs -- tui --help
services:
proxypilot-rs:
start: cargo run --manifest-path rust/Cargo.toml -p proxypilot-rs -- run --config rust/proxypilot-rs.toml
stop: lsof -ti :8318 | xargs -r kill
healthcheck: curl -sf http://127.0.0.1:8318/healthz
port: 8318
depends_on: []
@@ -0,0 +1,89 @@
---
name: rust-operator-worker
description: Implement Rust terminal-operator-console features for proxypilot-rs with test-first discipline and truthful runtime/TUI verification.
---
# Rust Operator Worker
NOTE: Startup and cleanup are handled by `worker-base`. This skill defines the WORK PROCEDURE.
## When to Use This Skill
Use for features in the Rust replatform slice that touch `proxypilot-rs` runtime/auth logic, local HTTP observability, CLI/account coherence, or the terminal operator console.
## Required Skills
- `tdd` — invoke before implementation to drive failing tests first for new runtime/auth/TUI helper behavior.
- `tuistory` — invoke when manually validating terminal operator-console behavior.
- `verification-before-completion` — invoke before claiming the feature is complete so evidence matches the actual commands and outputs.
## Work Procedure
1. Read `mission.md`, `validation-contract.md`, mission `AGENTS.md`, and `.factory/library/*.md` relevant to the feature before editing.
2. Confirm which validation assertions the feature fulfills and restate them in your notes.
3. Write or update failing Rust tests first (red) for the feature's intended behavior before changing implementation.
4. Implement the smallest Rust changes needed to make those tests pass while preserving the mission boundaries:
- keep the work inside the Rust replatform slice unless docs are explicitly part of the feature
- prefer shared auth/runtime helpers over duplicating logic
- keep runtime-memory state distinct from disk-backed saved state
5. Run focused checks during iteration, then the required final validators:
- `cargo fmt --all --manifest-path rust/Cargo.toml`
- `cargo test --manifest-path rust/Cargo.toml`
6. If the feature affects the TUI or runtime observability surface, perform manual verification with `tuistory` or equivalent local smoke and capture what changed on screen or via local HTTP output.
7. Review the changed files for truthfulness of operator-visible wording, especially where runtime state and disk state can diverge.
8. Produce a handoff that cites exact commands, tests added, interactive checks, and any discovered gaps.
## Example Handoff
```json
{
"salientSummary": "Added a shared auth-health/runtime model plus `/v0/runtime/stats`, then wired the TUI runtime panel to the new stats surface. Ran fmt/tests successfully and manually verified runtime counters plus active-account refresh feedback in the terminal UI.",
"whatWasImplemented": "Created a shared runtime/auth module for auth-health classification and refresh status, extended proxy state with in-memory counters and last refresh metadata, added GET /v0/runtime/stats with stable fields, and updated the TUI to render runtime stats while keeping disk-backed account controls separate.",
"whatWasLeftUndone": "",
"verification": {
"commandsRun": [
{
"command": "cargo fmt --all --manifest-path rust/Cargo.toml",
"exitCode": 0,
"observation": "Formatting completed without changes needed after final pass."
},
{
"command": "cargo test --manifest-path rust/Cargo.toml",
"exitCode": 0,
"observation": "Workspace tests passed, including new runtime stats and auth-health cases."
}
],
"interactiveChecks": [
{
"action": "Launched proxypilot-rs TUI against a local fixture config, pressed `r`, `R`, and `c`, and inspected the runtime/auth panel.",
"observed": "Runtime counters and last refresh outcome became visible, active-account refresh targeted the active account even when another row was selected, and clear-feedback only cleared the transient status line."
}
]
},
"tests": {
"added": [
{
"file": "rust/proxypilot-rs/src/proxy.rs",
"cases": [
{
"name": "runtime_stats_reset_after_restart",
"verifies": "In-memory runtime stats start empty on fresh process start and do not persist across restarts."
},
{
"name": "runtime_stats_reports_401_refresh_path_once",
"verifies": "A single client request that triggers 401 and retry increments upstream 401 and refresh counters without double-counting total proxied requests."
}
]
}
]
},
"discoveredIssues": []
}
```
## When to Return to Orchestrator
- The feature requires changing mission boundaries or touching non-Rust product surfaces outside the approved scope.
- The intended behavior cannot be implemented truthfully without clarifying runtime-vs-disk ownership semantics.
- A required local validation path cannot be exercised because config/fixtures/runtime setup is missing or broken.
- The feature reveals a larger refactor is needed than fits a single worker session.
@@ -0,0 +1,28 @@
{
"featureId": "cli-state-runtime-truthfulness-and-docs",
"reviewedAt": "2026-04-05T10:54:50.137470Z",
"commitId": "1c2396bb",
"transcriptSkeletonReviewed": true,
"diffReviewed": true,
"status": "fail",
"codeReview": {
"summary": "Reviewed feature commit 1c2396bb together with the directly relevant follow-up fixes f4ae033c and cea7a0f4. CLI wording, docs alignment, static-account refresh errors, and runtime-vs-disk refresh targeting are much clearer after those changes, but the TUI footer layout still prevents the new explanatory copy from being visible.",
"issues": [
{
"file": "rust/proxypilot-rs/src/tui.rs",
"line": 389,
"severity": "blocking",
"description": "The footer block is still allocated `Constraint::Length(3)` even though it now renders four content lines (feedback, selected-account hint, runtime status hint, and key help) inside a bordered paragraph at lines 523-534. In ratatui that height leaves room for only a single inner text row, so the newly added runtime/disk guidance and keybinding help are clipped off-screen. That means the feature does not actually make the cross-surface behavior explicit to operators, and docs/tests now describe footer copy that users cannot see."
}
]
},
"sharedStateObservations": [
{
"area": "skills",
"observation": "TUI copy changes in this mission need a visibility check, not just string-helper tests. The current worker skill and tests verified footer text helpers, but they did not verify that the fixed-height footer block can actually render the added lines.",
"evidence": "rust/proxypilot-rs/src/tui.rs:389 keeps the footer at `Constraint::Length(3)` while rust/proxypilot-rs/src/tui.rs:523-534 renders four lines; the added tests at rust/proxypilot-rs/src/tui.rs:770-842 assert string content only and do not exercise visible layout fit."
}
],
"addressesFailureFrom": null,
"summary": "Fail: the reviewed feature and its direct follow-up fixes improved CLI/runtime truthfulness, but the TUI footer's fixed height still clips the newly added selected-account/runtime hints and key help, so an operator cannot see the copy intended to explain runtime-vs-disk divergence."
}
@@ -0,0 +1,21 @@
{
"featureId": "fix-runtime-account-count-semantics",
"reviewedAt": "2026-04-05T11:36:06.651055Z",
"commitId": "91fe6562",
"transcriptSkeletonReviewed": true,
"diffReviewed": true,
"status": "pass",
"codeReview": {
"summary": "Reviewed the original runtime-stats feature (`1b3542d7`), the prior scrutiny finding, and the fix commit (`91fe6562`). The fix resolves the remaining non-blocking truthfulness issue: `/v0/runtime/stats.account_count` now counts only runtime-usable Codex accounts, mixed-provider and blank-key entries no longer inflate that value, and the TUI wording matches the runtime semantics.",
"issues": []
},
"sharedStateObservations": [
{
"area": "skills",
"observation": "The worker skipped the rust-operator-worker skill's required manual `tuistory` verification even though the feature touched TUI-visible runtime wording. For this fix the unit-level wording assertion was likely sufficient, but the skill currently leaves that lightweight label-only case undocumented.",
"evidence": "Skill procedure step 6 requires manual verification with `tuistory` when the feature affects the TUI or runtime observability surface (`/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/skills/rust-operator-worker/SKILL.md`). The handoff for session `38bb865f-5bfd-4b20-8a75-281170e69c06` records `followedProcedure: false` and says manual TUI verification was skipped in favor of unit tests because the change was only label alignment."
}
],
"addressesFailureFrom": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/reviews/proxy-runtime-stats-surface.json",
"summary": "Pass. The follow-up fix closes the prior `account_count` truthfulness gap and I found no new code issues in the scoped change."
}
@@ -0,0 +1,15 @@
{
"featureId": "fix-runtime-auth-health-and-date-validation",
"reviewedAt": "2026-04-05T10:53:54.938311Z",
"commitId": "f4ae033c97c0912c03c0a0eaa9b14a2aeb696f8f",
"transcriptSkeletonReviewed": true,
"diffReviewed": true,
"status": "pass",
"codeReview": {
"summary": "Reviewed commit `f4ae033c97c0912c03c0a0eaa9b14a2aeb696f8f` against the feature requirements and worker handoff. The implementation now rejects impossible RFC3339 calendar dates in `auth_runtime::parse_rfc3339_z`, classifies malformed impossible expiry metadata as `unknown`, and recomputes `/v0/runtime/stats` auth health from the live in-memory account state after proactive and 401-triggered refresh mutations. The targeted regressions in `auth_runtime.rs` and `proxy.rs` cover invalid leap-day/month-end inputs plus successful and failed refresh paths, and I found no remaining high-confidence correctness issues in scope.",
"issues": []
},
"sharedStateObservations": [],
"addressesFailureFrom": null,
"summary": "Pass. The reviewed fix closes the two reported blockers: impossible RFC3339 calendar dates no longer parse as valid expiries, and proxy runtime stats now report refreshed auth health truthfully after runtime credential mutations."
}
@@ -0,0 +1,28 @@
{
"featureId": "fix-tui-footer-and-passive-polling",
"reviewedAt": "2026-04-05T11:36:55Z",
"commitId": "67c79b9dc5755305448c33df5cb1d761f150bece",
"transcriptSkeletonReviewed": true,
"diffReviewed": true,
"status": "fail",
"codeReview": {
"summary": "Reviewed the fix commit together with both prior failed reviews (`terminal-tui-operator-console` and `cli-state-runtime-truthfulness-and-docs`). The passive-polling blocker is resolved: idle polling now stays on `/healthz` + `/v0/runtime/stats`, and the new regression test proves it no longer calls `/v1/models`. However, the footer visibility blocker is only partially fixed: the panel now fits the four nominal footer lines, but realistic long feedback still wraps and pushes the help text back out of view.",
"issues": [
{
"file": "rust/proxypilot-rs/src/tui.rs",
"line": 396,
"severity": "blocking",
"description": "The footer still has a fixed height of `Constraint::Length(6)`, which leaves only four inner text rows once the bordered `Keys` block is rendered (`tui.rs:530-543`). That is enough only when the feedback line stays on a single row. But routine operator messages in this same file are much longer\u2014for example the `runtime_refresh_target` failure text at `tui.rs:701-708` is 131 characters before account-name variation, so in the worker's own 120-column verification geometry it wraps to two rows. When that happens, one of the status/help lines is clipped again, so the feature does not fully satisfy the prior blocker of keeping all footer/help guidance visible. The added snapshot test (`tui.rs:943-975`) only exercises a short `Feedback line`, so it misses this realistic wrapped-feedback path."
}
]
},
"sharedStateObservations": [
{
"area": "skills",
"observation": "The shared Rust operator-worker guidance still does not tell workers to exercise long, wrapped operator feedback when validating fixed-height TUI regions. That omission helped this fix reintroduce a footer-visibility edge case even though the worker followed the documented procedure and added a snapshot test.",
"evidence": "`rust-operator-worker` step 6/7 asks for manual TUI verification and truthful operator-visible wording review, but it does not call out wrap/line-budget checks for fixed-height panels (`/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/skills/rust-operator-worker/SKILL.md`). In this fix, the new regression test in `rust/proxypilot-rs/src/tui.rs:943-975` only uses a one-line `Feedback line`, while the production footer can render much longer routine messages such as `runtime_refresh_target` at `tui.rs:701-708`."
}
],
"addressesFailureFrom": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/reviews/terminal-tui-operator-console.json; /home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/reviews/cli-state-runtime-truthfulness-and-docs.json",
"summary": "Fail. The fix successfully stops passive idle polling from contaminating runtime telemetry, but the footer/help blocker is not fully resolved because long, routine feedback messages can still wrap and hide guidance in the fixed-height footer."
}
@@ -0,0 +1,15 @@
{
"featureId": "fix-tui-footer-wrap-visibility",
"reviewedAt": "2026-04-05T12:02:30Z",
"commitId": "159a3b21",
"transcriptSkeletonReviewed": true,
"diffReviewed": true,
"status": "pass",
"codeReview": {
"summary": "Reviewed the prior failed fix (`fix-tui-footer-and-passive-polling`) alongside the rerun fix commit `159a3b21`, the worker handoff, and the transcript skeleton. This rerun fully addresses the remaining footer-wrap blocker: the TUI now sizes the footer from its wrapped content instead of a fixed six-row region, and the regression test was updated to use the same long runtime-active-account failure wording that previously exposed clipping.",
"issues": []
},
"sharedStateObservations": [],
"addressesFailureFrom": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/reviews/fix-tui-footer-and-passive-polling.json",
"summary": "Pass. The rerun replaces the fixed-height footer with content-based sizing and adds realistic long-message regression coverage, so the prior footer-wrap visibility failure is adequately resolved."
}
@@ -0,0 +1,21 @@
{
"featureId": "fix-tui-runtime-truthfulness",
"reviewedAt": "2026-04-05T10:51:50.745826Z",
"commitId": "cea7a0f4",
"transcriptSkeletonReviewed": true,
"diffReviewed": true,
"status": "pass",
"codeReview": {
"summary": "The TUI change now drives `R` from the runtime stats active account, preserves truthful runtime-unavailable and missing-runtime-active feedback, and relabels runtime-memory account counts so they are no longer presented as disk state. The scoped tests cover the new runtime-vs-disk selection logic and wording, and I found no high-confidence correctness issues in the reviewed change.",
"issues": []
},
"sharedStateObservations": [
{
"area": "skills",
"observation": "Mission worker guidance does not explain that mission artifacts may live outside the repo under `/home/fsos/.factory/missions/<id>`. The reviewed worker initially tried repo-relative mission paths and hit ENOENT before switching to the absolute mission directory.",
"evidence": "The transcript skeleton for worker session `da34164d-4575-44bf-b059-608a68652407` shows failed reads of `/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/{mission.md,validation-contract.md,AGENTS.md}` followed by successful reads from `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/...`; `rust-operator-worker` step 1 requires reading mission artifacts but does not document this path fallback."
}
],
"addressesFailureFrom": null,
"summary": "Pass. Commit `cea7a0f4` resolves the reviewed TUI truthfulness blockers: `R` now follows runtime-active state from `/v0/runtime/stats`, runtime-unavailable cases remain explicit without hiding disk-backed state, and the runtime count label no longer claims to be disk-backed."
}
@@ -0,0 +1,33 @@
{
"featureId": "proxy-runtime-stats-surface",
"reviewedAt": "2026-04-05T10:57:26.499831Z",
"commitId": "1b3542d77c125df31d091f052ca872237c5932c6",
"transcriptSkeletonReviewed": true,
"diffReviewed": true,
"status": "pass",
"codeReview": {
"summary": "Reviewed the original runtime-stats implementation commit (`1b3542d7`) plus the directly relevant follow-up fix commit (`f4ae033c`). The feature now satisfies the core HTTP contract: `/v0/runtime/stats` is local-only, counters stay in memory and reset on restart, supported proxied requests are counted once per client request, proactive and 401-triggered refresh outcomes are surfaced, and post-refresh auth health is recomputed truthfully. I found one remaining non-blocking truthfulness gap in mixed-provider saved state.",
"issues": [
{
"file": "rust/proxypilot-rs/src/proxy.rs",
"line": 105,
"severity": "non_blocking",
"description": "`account_count` reports `accounts.accounts.len()`, which counts every saved entry loaded into memory, not just runtime-usable Codex accounts. That becomes untruthful in mixed-provider state because `AccountState` only treats `provider == \"codex\"` entries as active/refreshable (`rust/proxypilot-rs/src/state.rs:153`, `rust/proxypilot-rs/src/state.rs:170`, `rust/proxypilot-rs/src/state.rs:300`), while imported auth preserves arbitrary `provider_type` values from disk (`rust/proxypilot-rs/src/state.rs:232`). A non-Codex imported entry will inflate `/v0/runtime/stats.account_count` even though the runtime cannot actually use it."
}
]
},
"sharedStateObservations": [
{
"area": "conventions",
"observation": "This feature updated `docs/rust-replatform.md` even though the mission guidance says only docs-alignment work should touch that file. The rule exists, but the worker still crossed it in the runtime-stats feature commit.",
"evidence": "Mission AGENTS says `Docs ownership: only features explicitly scoped to docs alignment should update docs/rust-replatform.md or README.md` (`/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/AGENTS.md:59`), while commit `1b3542d7` changes `docs/rust-replatform.md` alongside `rust/proxypilot-rs/src/proxy.rs`."
},
{
"area": "services",
"observation": "Runtime-surface smoke verification depends on setup that is not represented in `.factory/services.yaml`: generating a config file and standing up a local mock upstream/refresh server. Workers had to do this ad hoc in the transcript instead of using shared service metadata.",
"evidence": "`.factory/services.yaml:8-12` only defines `proxypilot-rs` start/stop/healthcheck. The reviewed worker transcript for session `f8120536-90d3-4124-9b6f-a84412e716f4` shows manual `.factory/init.sh`, temporary config creation, and a background mock HTTP server before the `curl` smoke documented in the handoff `2026-04-05T09-14-14-581Z__proxy-runtime-stats-surface__f8120536-90d3-4124-9b6f-a84412e716f4.json`."
}
],
"addressesFailureFrom": null,
"summary": "Pass with one non-blocking issue. The runtime stats surface works as intended after the direct follow-up fix, but `account_count` still overstates runtime-usable accounts when saved state contains non-Codex imported entries."
}
@@ -0,0 +1,26 @@
{
"featureId": "shared-auth-runtime-domain",
"reviewedAt": "2026-04-05T10:52:53.771197Z",
"commitId": "1c3edd9f4a2493a2dcd27931a680c359c14c9f43",
"transcriptSkeletonReviewed": true,
"diffReviewed": true,
"status": "pass",
"codeReview": {
"summary": "The feature successfully extracted shared auth/runtime primitives into `auth_runtime.rs` and both proxy and TUI consumers were moved onto the shared RFC3339 parsing, auth-health classification, and runtime snapshot types. The only blocking correctness gap from the original commit (impossible calendar dates being accepted, plus stale runtime auth-health after refresh) was addressed by the directly relevant follow-up fix `f4ae033c`, so there are no remaining high-confidence issues in this review scope.",
"issues": []
},
"sharedStateObservations": [
{
"area": "skills",
"observation": "The worker had to deviate because the mission/bootstrap path guidance pointed at a repo-relative mission directory that did not exist; the recoverable fallback to `/home/fsos/.factory/missions/...` is not captured in the Rust worker guidance.",
"evidence": "Handoff `2026-04-05T08-56-54-173Z__shared-auth-runtime-domain__132757c8-6967-4cb2-b929-a387c3429b02.json`: lines 100-115 record `followedProcedure: false` and explicitly ask to clarify handling when bootstrap paths point to a repo-relative mission directory that does not exist."
},
{
"area": "services",
"observation": "Local smoke/runtime setup depends on generating `rust/proxypilot-rs.toml` first, but the services manifest only advertises a start command that assumes that file already exists. The canonical setup helper is discoverable only via `.factory/init.sh` rather than the shared service metadata.",
"evidence": "`.factory/services.yaml:9` starts proxypilot-rs with `--config rust/proxypilot-rs.toml`, while `.factory/init.sh:6-7` creates that file on demand before smoke validation."
}
],
"addressesFailureFrom": null,
"summary": "Reviewed the shared auth/runtime domain commit (`1c3edd9f4a2493a2dcd27931a680c359c14c9f43`), its transcript/handoff, and the directly relevant follow-up fix (`f4ae033c`). Result: pass, with no remaining actionable code defects in scope after the follow-up fix, plus two shared-state observations about mission path guidance and init/service discoverability."
}
@@ -0,0 +1,39 @@
{
"featureId": "terminal-tui-operator-console",
"reviewedAt": "2026-04-05T18:06:00Z",
"commitId": "3da810d19a174aa439f079db9b4fb9ad3a15461e",
"transcriptSkeletonReviewed": true,
"diffReviewed": true,
"status": "fail",
"codeReview": {
"summary": "Reviewed the original TUI feature commit `3da810d1` plus the directly relevant follow-up fix `cea7a0f4`. The console now shows runtime stats, handles runtime-unavailable cases more explicitly, and `R` now targets the runtime-reported active account, but two blocking truthfulness issues remain in the live console: the footer/help region is clipped by the fixed layout height, and the TUI's own background model polling mutates the runtime counters and refresh state it is supposed to observe.",
"issues": [
{
"file": "rust/proxypilot-rs/src/tui.rs",
"line": 389,
"severity": "blocking",
"description": "The footer block is still allocated `Constraint::Length(3)` while the `Keys` paragraph renders four separate content lines (`feedback`, selected-account hint, runtime hint, and key help at lines 525-532). With a bordered ratatui block that leaves only one inner text row, so the newly added help/runtime guidance is clipped off-screen. The feature therefore does not actually deliver readable, truthful footer/help text in the running console."
},
{
"file": "rust/proxypilot-rs/src/tui.rs",
"line": 113,
"severity": "blocking",
"description": "The idle poll path still calls `refresh_models()` whenever `/healthz` succeeds (`tui.rs:49-50`, `tui.rs:113-121`, `tui.rs:218-220`). That performs a real `GET /v1/models` through the local proxy, and the proxy counts every supported request and may trigger proactive refresh before forwarding (`proxy.rs:143-145`, `proxy.rs:264-267`). As a result, merely leaving the operator console open inflates `total_proxied_requests`/`successful_upstream_responses` and can change `last_refresh`, so the runtime counters and refresh outcome are not a truthful view of external runtime activity."
}
]
},
"sharedStateObservations": [
{
"area": "conventions",
"observation": "Mission guidance says only docs-scoped features should edit `docs/rust-replatform.md`, but this TUI feature commit changed that file anyway.",
"evidence": "Mission AGENTS `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/AGENTS.md:59` says `Docs ownership: only features explicitly scoped to docs alignment should update docs/rust-replatform.md or README.md`, while commit `3da810d1` changes `docs/rust-replatform.md` alongside `rust/proxypilot-rs/src/tui.rs`."
},
{
"area": "skills",
"observation": "For TUI work, helper-string tests are not enough; shared guidance should explicitly require a layout-fit check for any new multi-line regions.",
"evidence": "`rust/proxypilot-rs/src/tui.rs:743-840` tests helper string content, but no test or skill step verifies that those lines fit inside the fixed-height footer/runtime blocks (`tui.rs:387-389`, `tui.rs:523-534`). The worker handoff for session `b1f2df79-2748-4890-a74a-2cb5e38b416c` reported footer/help validation even though the clipped layout remained."
}
],
"addressesFailureFrom": null,
"summary": "Fail. The feature and direct `cea7a0f4` follow-up improved runtime visibility and `R` targeting, but the live TUI still hides much of the footer/help copy and its own background polling contaminates the runtime counters and refresh status it displays."
}
@@ -0,0 +1,39 @@
{
"milestone": "terminal-operator-console",
"round": 3,
"status": "pass",
"validatorsRun": {
"format": {
"passed": true,
"command": "cargo fmt --all --manifest-path rust/Cargo.toml -- --check",
"exitCode": 0
},
"test": {
"passed": true,
"command": "cargo test --manifest-path rust/Cargo.toml",
"exitCode": 0
},
"typecheck": {
"passed": true,
"command": "cargo check --manifest-path rust/Cargo.toml",
"exitCode": 0
},
"lint": {
"passed": true,
"command": "cargo clippy --manifest-path rust/Cargo.toml --all-targets -- -D warnings",
"exitCode": 0
}
},
"reviewsSummary": {
"total": 1,
"passed": 1,
"failed": 0,
"failedFeatures": []
},
"blockingIssues": [],
"nonBlockingIssues": [],
"appliedUpdates": [],
"suggestedGuidanceUpdates": [],
"rejectedObservations": [],
"previousRound": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/synthesis.round2.json"
}
@@ -0,0 +1,94 @@
{
"milestone": "terminal-operator-console",
"round": 1,
"status": "fail",
"validatorsRun": {
"format": {
"passed": true,
"command": "cargo fmt --all --manifest-path rust/Cargo.toml -- --check",
"exitCode": 0
},
"test": {
"passed": true,
"command": "cargo test --manifest-path rust/Cargo.toml",
"exitCode": 0
},
"typecheck": {
"passed": true,
"command": "cargo check --manifest-path rust/Cargo.toml",
"exitCode": 0
},
"lint": {
"passed": true,
"command": "cargo clippy --manifest-path rust/Cargo.toml --all-targets -- -D warnings",
"exitCode": 0
}
},
"reviewsSummary": {
"total": 6,
"passed": 4,
"failed": 2,
"failedFeatures": [
"terminal-tui-operator-console",
"cli-state-runtime-truthfulness-and-docs"
]
},
"blockingIssues": [
{
"featureId": "terminal-tui-operator-console",
"severity": "blocking",
"description": "The TUI footer/help block still uses Constraint::Length(3) while rendering four content lines inside a bordered block, so the selected-account/runtime divergence copy and key help are clipped off-screen. This makes the console fail both the TUI readability contract and the CLI/runtime-truthfulness feature's operator-facing explanation goals."
},
{
"featureId": "terminal-tui-operator-console",
"severity": "blocking",
"description": "The TUI background polling path still calls GET /v1/models whenever /healthz succeeds, which goes through the proxy and mutates total_proxied_requests, successful_upstream_responses, and potentially last_refresh/auth state. Leaving the console open therefore contaminates the runtime stats it is supposed to observe."
}
],
"nonBlockingIssues": [
{
"featureId": "proxy-runtime-stats-surface",
"severity": "non_blocking",
"description": "runtime_stats.account_count currently reports all saved state entries rather than only runtime-usable Codex accounts, so mixed-provider saved state can overstate runtime-usable account count."
}
],
"appliedUpdates": [
{
"target": "services.yaml",
"description": "Added `init`, `typecheck`, and `lint` commands so scrutiny/user-testing workers can bootstrap the Rust slice and run the full validator suite from shared service metadata.",
"sourceFeature": "scrutiny-validator-terminal-operator-console"
},
{
"target": "library",
"description": "Documented in `.factory/library/environment.md` that `./.factory/init.sh` fetches Rust dependencies and creates `rust/proxypilot-rs.toml` when missing before smoke validation.",
"sourceFeature": "shared-auth-runtime-domain"
}
],
"suggestedGuidanceUpdates": [
{
"target": "rust-operator-worker",
"suggestion": "Clarify that mission artifacts may live under `/home/fsos/.factory/missions/<id>` even when repo-relative `.factory/missions/...` paths are absent, and instruct workers to fall back to the absolute mission directory before treating missing files as blockers.",
"evidence": "Review reports for `shared-auth-runtime-domain` and `fix-tui-runtime-truthfulness` both recorded ENOENT attempts against repo-relative mission paths before successfully reading `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/...`.",
"isSystemic": true
},
{
"target": "rust-operator-worker",
"suggestion": "For TUI features that change visible copy or layout, require a layout-fit visibility check (render/snapshot or terminal smoke) in addition to helper-string assertions so multi-line regions are proven visible.",
"evidence": "Both `terminal-tui-operator-console` and `cli-state-runtime-truthfulness-and-docs` failed review because the footer stayed at `Constraint::Length(3)` while rendering four lines, yet the worker tests only asserted helper-string content.",
"isSystemic": true
},
{
"target": "rust-operator-worker",
"suggestion": "Reinforce the mission boundary that only docs-scoped features may edit `docs/rust-replatform.md` or `README.md`, and direct workers to defer such changes to the explicit docs-alignment feature when possible.",
"evidence": "Review reports for `proxy-runtime-stats-surface` and `terminal-tui-operator-console` both recorded edits to `docs/rust-replatform.md` despite mission AGENTS guidance reserving docs changes for docs-alignment work.",
"isSystemic": true
}
],
"rejectedObservations": [
{
"observation": "Add a dedicated mock upstream/refresh service definition to `.factory/services.yaml` for runtime smoke validation.",
"reason": "ambiguous: the reviewed mock servers were scenario-specific one-off fixtures with ad hoc ports and behavior, so a generic shared service entry would risk encoding the wrong workflow. The concrete bootstrap/config discovery gap was handled instead via additive command/library updates."
}
],
"previousRound": null
}
@@ -0,0 +1,60 @@
{
"milestone": "terminal-operator-console",
"round": 2,
"status": "fail",
"validatorsRun": {
"format": {
"passed": true,
"command": "cargo fmt --all --manifest-path rust/Cargo.toml -- --check",
"exitCode": 0
},
"test": {
"passed": true,
"command": "cargo test --manifest-path rust/Cargo.toml",
"exitCode": 0
},
"typecheck": {
"passed": true,
"command": "cargo check --manifest-path rust/Cargo.toml",
"exitCode": 0
},
"lint": {
"passed": true,
"command": "cargo clippy --manifest-path rust/Cargo.toml --all-targets -- -D warnings",
"exitCode": 0
}
},
"reviewsSummary": {
"total": 2,
"passed": 1,
"failed": 1,
"failedFeatures": [
"fix-tui-footer-and-passive-polling"
]
},
"blockingIssues": [
{
"featureId": "fix-tui-footer-and-passive-polling",
"severity": "blocking",
"description": "The TUI footer still has a fixed six-row outer height, which leaves only four inner text rows inside the bordered keys block. Long routine feedback such as the runtime-active-account failure copy wraps at the validated terminal width, so one of the footer status/help lines becomes clipped again and the operator console still fails the footer-visibility contract."
}
],
"nonBlockingIssues": [],
"appliedUpdates": [],
"suggestedGuidanceUpdates": [
{
"target": "rust-operator-worker",
"suggestion": "When validating fixed-height TUI regions, explicitly exercise long wrapped operator feedback (not just short placeholder strings) so layout-fit checks prove realistic messages remain visible.",
"evidence": "The follow-up review for `fix-tui-footer-and-passive-polling` found the new snapshot test only covered a short `Feedback line`, while real footer messages in `rust/proxypilot-rs/src/tui.rs` are long enough to wrap and clip help text again within the fixed six-row footer.",
"isSystemic": true
},
{
"target": "rust-operator-worker",
"suggestion": "Document when label-only TUI/runtime wording changes may use lightweight non-interactive verification instead of full `tuistory` validation, so narrow observability fixes can follow a clear exception path.",
"evidence": "The pass review for `fix-runtime-account-count-semantics` noted the worker intentionally skipped manual `tuistory` verification because the change only aligned runtime/TUI labels, but the current skill does not describe that small-change exception.",
"isSystemic": false
}
],
"rejectedObservations": [],
"previousRound": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/synthesis.round1.json"
}
@@ -0,0 +1,19 @@
active_account = "refreshable-local"
[[accounts]]
name = "refreshable-local"
provider = "codex"
api_key = "refreshed-access-token"
refresh_token = "refreshed-refresh-token"
id_token = "TEST_ID_TOKEN_PLACEHOLDER"
email = "rerun@example.com"
account_id = "acct_refresh_rerun"
plan_type = "pro"
expires_at = "2030-01-01T00:00:00Z"
source = "import:/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun/refreshable-auth.json"
[[accounts]]
name = "static-local"
provider = "codex"
api_key = "sk-static-local"
source = "manual"
@@ -0,0 +1,11 @@
# isolated CLI refresh rerun config
[server]
bind = "127.0.0.1:8318"
[state]
path = "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun/proxypilot-rs.state.toml"
[codex]
upstream_base_url = "https://api.openai.com"
api_key = ""
refresh_token_url = "http://127.0.0.1:34051/oauth/token"
@@ -0,0 +1,8 @@
{
"access_token": "seed-access-token",
"refresh_token": "seed-refresh-token",
"email": "seed@example.com",
"account_id": "acct_seed",
"expired": "2020-01-01T00:00:00Z",
"type": "codex"
}
@@ -0,0 +1,13 @@
active_account = "preemptive-account"
[[accounts]]
name = "preemptive-account"
provider = "codex"
api_key = "expired-preemptive-token"
refresh_token = "preemptive-refresh-token"
id_token = "header.payload.sig"
email = "refresh@example.com"
account_id = "acct_seed"
plan_type = "seed"
expires_at = "1970-01-01T00:00:00Z"
source = "fixture"
@@ -0,0 +1,10 @@
[server]
bind = "127.0.0.1:18318"
[state]
path = "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/http-refresh-rerun/VAL-HTTP-007.state.toml"
[codex]
upstream_base_url = "http://127.0.0.1:18319"
api_key = ""
refresh_token_url = "http://127.0.0.1:18319/oauth/token"
@@ -0,0 +1,13 @@
active_account = "retry-account"
[[accounts]]
name = "retry-account"
provider = "codex"
api_key = "stale-401-token"
refresh_token = "retry-refresh-token"
id_token = "header.payload.sig"
email = "refresh@example.com"
account_id = "acct_seed"
plan_type = "seed"
expires_at = "2035-01-01T00:00:00Z"
source = "fixture"
@@ -0,0 +1,10 @@
[server]
bind = "127.0.0.1:18318"
[state]
path = "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/http-refresh-rerun/VAL-HTTP-008.state.toml"
[codex]
upstream_base_url = "http://127.0.0.1:18319"
api_key = ""
refresh_token_url = "http://127.0.0.1:18319/oauth/token"
@@ -0,0 +1,142 @@
import argparse
import base64
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
def encode_claims(exp, email, account_id, plan_type):
payload = {
"email": email,
"exp": exp,
"https://api.openai.com/auth": {
"chatgpt_account_id": account_id,
"chatgpt_plan_type": plan_type,
},
}
raw = json.dumps(payload, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
class ReusableServer(ThreadingHTTPServer):
allow_reuse_address = True
class Handler(BaseHTTPRequestHandler):
scenario = "preemptive"
log_path = None
state = {"model_calls": 0}
def log_message(self, format, *args):
return
def _write_json(self, status, payload):
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return body
def _record(self, *, response_status, response_body, request_body=""):
entry = {
"ts": time.time(),
"scenario": self.scenario,
"method": self.command,
"path": self.path,
"headers": {k: v for k, v in self.headers.items()},
"request_body": request_body,
"response_status": response_status,
"response_body": response_body,
"model_call_index": self.state["model_calls"],
}
with open(self.log_path, "a", encoding="utf-8") as fh:
fh.write(json.dumps(entry) + "\n")
def do_GET(self):
if self.path == "/__health":
body = b"ok"
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
if self.path == "/v1/models":
auth = self.headers.get("Authorization", "")
self.state["model_calls"] += 1
if self.scenario == "retry401" and self.state["model_calls"] == 1:
payload = {
"error": "expired token",
"received_authorization": auth,
"attempt": 1,
}
self._record(response_status=401, response_body=payload)
self._write_json(401, payload)
return
payload = {
"object": "list",
"data": [{"id": "gpt-5.2-codex", "object": "model"}],
"received_authorization": auth,
"attempt": self.state["model_calls"],
"scenario": self.scenario,
}
self._record(response_status=200, response_body=payload)
self._write_json(200, payload)
return
payload = {"error": "not found", "path": self.path}
self._record(response_status=404, response_body=payload)
self._write_json(404, payload)
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
raw_body = self.rfile.read(length).decode()
if self.path == "/oauth/token":
form = parse_qs(raw_body)
refresh_token = form.get("refresh_token", [""])[0]
if self.scenario == "preemptive":
payload = {
"access_token": "preemptive-fresh-token",
"refresh_token": "preemptive-fresh-refresh-token",
"id_token": f"header.{encode_claims(1893456000, 'refresh@example.com', 'acct_preemptive', 'team')}.sig",
"expires_in": 3600,
"seen_refresh_token": refresh_token,
}
else:
payload = {
"access_token": "retry-fresh-token",
"refresh_token": "retry-fresh-refresh-token",
"id_token": f"header.{encode_claims(1893456000, 'refresh@example.com', 'acct_retry401', 'pro')}.sig",
"expires_in": 3600,
"seen_refresh_token": refresh_token,
}
self._record(response_status=200, response_body=payload, request_body=raw_body)
self._write_json(200, payload)
return
payload = {"error": "not found", "path": self.path}
self._record(response_status=404, response_body=payload, request_body=raw_body)
self._write_json(404, payload)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--scenario", required=True, choices=["preemptive", "retry401"])
parser.add_argument("--port", required=True, type=int)
parser.add_argument("--log", required=True)
args = parser.parse_args()
Handler.scenario = args.scenario
Handler.log_path = args.log
Handler.state = {"model_calls": 0}
server = ReusableServer(("127.0.0.1", args.port), Handler)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
@@ -0,0 +1,69 @@
{
"groupId": "cli-refresh-rerun",
"testedAt": "2026-04-05T13:32:26Z",
"isolation": {
"surface": "shell",
"fixtureDirectory": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun",
"evidenceDirectory": "/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-refresh-rerun",
"configPath": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun/proxypilot-rs.toml",
"statePath": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun/proxypilot-rs.state.toml",
"refreshTokenUrl": "http://127.0.0.1:34051/oauth/token"
},
"toolsUsed": [
"shell"
],
"assertions": [
{
"id": "VAL-CLI-003",
"title": "Refresh commands handle both refreshable and static accounts clearly",
"status": "pass",
"steps": [
{
"action": "Import a refreshable saved Codex account into isolated state and add a static account",
"expected": "Fixture state contains one active refreshable account and one static account",
"observed": "account list showed `refreshable-local` active with `refresh=refreshable` and `static-local` present with `refresh=static`"
},
{
"action": "Run `account refresh-codex` with no `--name` while the refreshable account is active",
"expected": "Refresh succeeds through the configured local refresh endpoint and updates saved account metadata",
"observed": "Command printed `refreshed saved Codex account `refreshable-local` in local state`; the local stub received one POST to `/oauth/token`; state updated access token, refresh token, email, account id, plan, and expiry"
},
{
"action": "Run `account refresh-codex --name static-local`",
"expected": "Static account refresh is rejected with a clear operator-readable error and no state corruption",
"observed": "Command exited non-zero with `account `static-local` is static and has no refresh token`; follow-up state snapshot matched the post-success state byte-for-byte"
},
{
"action": "Run `account refresh-codex --name missing-local`",
"expected": "Missing account refresh is rejected with a clear operator-readable error and no state corruption",
"observed": "Command exited non-zero with `no saved Codex account named missing-local`; follow-up state snapshot remained unchanged and list output still showed the same active/static accounts"
}
],
"evidence": {
"commandOutputs": [
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-import-refreshable.txt",
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-add-static.txt",
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-list-before-refresh.txt",
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-success.txt",
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-list-after-success.txt",
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-static-fails.txt",
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-missing-fails.txt",
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-list-after-failures.txt"
],
"stateSnapshots": [
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-state-before-refresh.toml",
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-state-after-success.toml",
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-state-after-failures.toml"
],
"network": "terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-stub-requests.json",
"config": "terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-config.toml",
"fixtureImport": "terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-import-auth.json",
"validator": "terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-related-tests.txt"
},
"issues": null
}
],
"frictions": [],
"blockers": [],
"summary": "VAL-CLI-003 passed: refresh succeeded for the active refreshable Codex account through `codex.refresh_token_url`, static and missing account refreshes failed clearly, and saved state stayed coherent after all runs."
}
@@ -0,0 +1,60 @@
{
"groupId": "cli-shell",
"surface": "shell",
"toolsUsed": [
"shell"
],
"assertions": [
{
"id": "VAL-CLI-001",
"status": "pass",
"summary": "init wrote an example config at the requested fixture path and a second run without --force refused to overwrite it with a clear error.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-001-init-success.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-001-init-refused-overwrite.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-001-config.toml"
],
"details": "Used isolated fixture config /home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-shell/20260405T121714Z/proxypilot-rs.toml. Successful init printed the written path. Re-running init returned exit code 1 with \"config already exists ... (pass --force to overwrite)\". The captured config file includes server.bind=127.0.0.1:8318, state.path=proxypilot-rs.state.toml, and codex.upstream_base_url=https://api.openai.com."
},
{
"id": "VAL-CLI-002",
"status": "pass",
"summary": "Add, list, activate, and remove commands kept saved active-account state coherent, including promotion back to the remaining account and explicit empty-state output after removing the final account.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-add-primary.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-add-backup.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-list-after-add.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-activate-backup.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-list-after-activate.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-remove-backup.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-list-after-remove-backup.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-remove-primary.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-list-after-remove-primary.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-state-after-activate-backup.toml",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-state-after-remove-backup.toml",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-state-after-remove-primary.toml"
],
"details": "primary became active when first added; list output marked it with `*`. After activating backup, list output switched the marker to backup and the saved state snapshot shows active_account=\"backup\". Removing backup reported \"local active account is now `primary`\" and the next state snapshot shows active_account=\"primary\". Removing primary reported \"no local active account remains\" and follow-up list output showed \"No local Rust accounts saved yet.\" with an empty accounts snapshot."
},
{
"id": "VAL-CLI-003",
"status": "blocked",
"summary": "Negative refresh paths behaved clearly for static and missing accounts, but the required refresh-success path could not be exercised within the isolated fixture because refresh-codex is hardwired to the live OpenAI OAuth refresh endpoint.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-state-with-static-and-refreshable.toml",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-list-pre-refresh.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-refresh-static-fails.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-refresh-missing-fails.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-list-after-failures.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-state-after-failures.toml",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-refresh-success-blocked.txt"
],
"details": "Imported a refreshable local fixture account and added a static account inside the assigned fixture state. Refreshing the static account failed cleanly with \"account `static-local` is static and has no refresh token\"; refreshing a missing account failed with \"no saved Codex account named missing-local\". Follow-up list/state evidence shows saved state remained unchanged after both failures. The assertion remains blocked because the CLI refresh path uses the built-in OpenAI OAuth refresh endpoint and the supported config surface does not expose a way to redirect refresh-codex to a local mock endpoint without live credentials."
}
],
"frictions": [],
"blockers": [
"VAL-CLI-003 success-path refresh is not isolatable in this shell fixture: refresh-codex uses the built-in live OpenAI OAuth refresh endpoint, and the allowed CLI/config surface provides no local mock override. Live device-login/private credentials were explicitly disallowed, so the refresh-success portion of the assertion was recorded as blocked with evidence."
],
"overallSummary": "Validated 3 CLI shell assertions for terminal-operator-console: VAL-CLI-001 pass, VAL-CLI-002 pass, VAL-CLI-003 blocked due to non-mockable live refresh dependency. Report and evidence were written under the requested flow-report and mission evidence paths."
}
@@ -0,0 +1,84 @@
{
"groupId": "http-refresh-rerun",
"testedAt": "2026-04-05T13:34:49Z",
"isolation": {
"surface": "curl",
"fixtureDirectory": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/http-refresh-rerun",
"evidenceDirectory": "/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-refresh-rerun",
"proxyBind": "127.0.0.1:18318",
"stubBind": "127.0.0.1:18319",
"refreshTokenUrl": "http://127.0.0.1:18319/oauth/token"
},
"toolsUsed": [
"curl"
],
"assertions": [
{
"id": "VAL-HTTP-007",
"title": "Proactive refresh is visible before forwarding expired or near-expiry requests",
"status": "pass",
"steps": [
{
"action": "Start proxypilot-rs with an expired refreshable active account plus a local OAuth/upstream stub",
"expected": "Runtime stats start with expired auth health and zero counters",
"observed": "/v0/runtime/stats reported auth_health.state=expired with total_proxied_requests=0 and auth_refresh_attempts=0"
},
{
"action": "Send GET /v1/models through the proxy",
"expected": "Proxy refreshes before forwarding and the client request succeeds with the refreshed token",
"observed": "Client received 200 JSON showing received_authorization=Bearer preemptive-fresh-token"
},
{
"action": "Inspect runtime stats and stub traffic after the request",
"expected": "Stats show one refresh attempt/success and upstream sees only refreshed-token traffic",
"observed": "Stats showed total_proxied_requests=1, successful_upstream_responses=1, auth_refresh_attempts=1, upstream_401_count=0, last_refresh.kind=success; stub log recorded POST /oauth/token before GET /v1/models with Bearer preemptive-fresh-token"
}
],
"evidence": {
"statsBefore": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-stats-before.json",
"requestHeaders": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-request.headers.txt",
"requestBody": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-request-body.json",
"statsAfter": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-stats-after.json",
"stubLog": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-stub-log.jsonl",
"proxyLog": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-proxy.log",
"stubStdout": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-stub.log"
},
"issues": null
},
{
"id": "VAL-HTTP-008",
"title": "Upstream 401 retry refresh is visible and counted exactly once",
"status": "pass",
"steps": [
{
"action": "Start proxypilot-rs with a refreshable active account and a local stub that returns 401 on the first /v1/models request",
"expected": "Initial stats are zeroed and the first upstream attempt uses the stale token",
"observed": "Stub log recorded the first GET /v1/models with Bearer stale-401-token and response_status=401"
},
{
"action": "Let the proxy handle the 401-triggered refresh-and-retry path for one GET /v1/models client request",
"expected": "Proxy refreshes once, retries once, and the client sees the retried success result",
"observed": "Client received 200 JSON showing received_authorization=Bearer retry-fresh-token on attempt=2"
},
{
"action": "Inspect runtime stats and stub traffic after the request",
"expected": "Stats count one proxied request, one upstream 401, one refresh success, and mock upstream shows 401 then refresh then retry",
"observed": "Stats showed total_proxied_requests=1, successful_upstream_responses=1, auth_refresh_attempts=1, upstream_401_count=1, last_refresh.kind=success; stub log showed GET 401 -> POST /oauth/token -> GET 200 with Bearer retry-fresh-token"
}
],
"evidence": {
"statsBefore": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-stats-before.json",
"requestHeaders": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-request.headers.txt",
"requestBody": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-request-body.json",
"statsAfter": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-stats-after.json",
"stubLog": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-stub-log.jsonl",
"proxyLog": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-proxy.log",
"stubStdout": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-stub.log"
},
"issues": null
}
],
"frictions": [],
"blockers": [],
"summary": "Retested 2 assertions: VAL-HTTP-007 passed with proactive refresh before forwarding, and VAL-HTTP-008 passed with one 401-triggered refresh-and-retry path counted exactly once."
}
@@ -0,0 +1,133 @@
{
"assertions": [
{
"details": "Observed status=ok, provider=codex, listen=127.0.0.1:18318, upstream=http://127.0.0.1:18319 on the reachable fixture and the same local health response with upstream=http://127.0.0.1:18339.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-001-healthz-reachable.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-001-healthz-unreachable.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/fixture-config-fallback.toml",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/fixture-config-unreachable.toml"
],
"id": "VAL-HTTP-001",
"status": "pass",
"summary": "Health checks returned 200 with local proxy identity fields both with the mock upstream and with an unreachable local upstream port."
},
{
"details": "The stats call returned HTTP 200 with a JSON payload and the mock log remained empty (request_count=0), confirming the operator surface is read-only and local.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-002-runtime-stats.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-002-mock-log.json"
],
"id": "VAL-HTTP-002",
"status": "pass",
"summary": "The local /v0/runtime/stats surface returned 200 without auth and did not create any upstream mock traffic."
},
{
"details": "Before and after mutating the state file on disk, /v0/runtime/stats continued to report active_account_name=runtime-valid and auth_health.state=valid for the running process while exposing bind_address, upstream_base_url, account_count, auth_health, request_counters, and last_refresh.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-003-stats-before-disk-mutation.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-003-stats-after-disk-mutation.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-003-state-before.toml",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-003-state-mutated.toml"
],
"id": "VAL-HTTP-003",
"status": "pass",
"summary": "The runtime stats payload exposed the expected stable schema and stayed pinned to runtime-memory state after the disk state file was mutated externally."
},
{
"details": "Observed auth_health.state values: fallback-key -> static with source=config_fallback_key and no active_account_name; static saved account -> static with source=active_account; valid fixture -> valid; expiring fixture -> expiring_soon; expired fixture -> expired; malformed expiry fixture -> unknown with metadata_state=malformed.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-fallback-key.json",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-static-saved.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-valid.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-expiring.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-expired.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-malformed.txt"
],
"id": "VAL-HTTP-004",
"status": "pass",
"summary": "Representative fixtures produced explicit auth-health states for fallback static, saved static, valid, expiring_soon, expired, and malformed unknown cases."
},
{
"details": "Initial stats showed all request counters at 0 and last_refresh.kind=unknown with null timestamps; after two successful requests the counters rose; after restarting the proxy with the same fixture they reset to zero again.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-002-runtime-stats.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-stats-after-success.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-005-stats-after-restart.txt"
],
"id": "VAL-HTTP-005",
"status": "pass",
"summary": "Fresh runtime counters started at zero, last-refresh metadata was null-like before any attempt, and a restart cleared in-memory stats after traffic."
},
{
"details": "Starting from zero, one GET /v1/models and one POST /v1/chat/completions produced total_proxied_requests=2 and successful_upstream_responses=2, with two corresponding mock upstream calls.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-models-success.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-chat-success.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-stats-after-success.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-mock-log.json"
],
"id": "VAL-HTTP-006",
"status": "pass",
"summary": "Successful supported proxy requests incremented both total_proxied_requests and successful_upstream_responses."
},
{
"details": "With an expired refreshable account, the next proxied request returned 502, auth_refresh_attempts/auth_refresh_failures incremented, last_refresh.kind became failure, and the local upstream mock saw zero calls. This confirms the pre-forward refresh attempt, but successful local stubbed refresh remains blocked because the available config surface has no OAuth token endpoint override.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-007-stats-before.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-007-proactive-refresh-attempt.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-007-stats-after.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-007-mock-log.json",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/fixture-config-expired.toml"
],
"id": "VAL-HTTP-007",
"status": "blocked",
"summary": "A proactive refresh attempt was observable before forwarding, but the success path could not be validated because the runtime cannot be redirected from the user surface to a local OAuth token stub."
},
{
"details": "The local mock forced one upstream 401 and the proxy recorded upstream_401_count=1 with a single proxied request, but the refresh attempt failed with a 502 response and the mock saw no /oauth/token call. A successful refresh-and-retry path therefore remains blocked under the current user-surface configuration.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-stats-before.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-401-refresh-attempt.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-stats-after.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-mock-log.json",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/fixture-config-401-retry.toml"
],
"id": "VAL-HTTP-008",
"status": "blocked",
"summary": "The 401-triggered refresh path is visible, but the success retry case cannot be validated locally because the runtime cannot point refresh traffic at a local OAuth token stub from the user surface."
},
{
"details": "The client received HTTP 502 with a local JSON error after the mock upstream returned 401, while /v0/runtime/stats showed total_proxied_requests=1, upstream_401_count=1, auth_refresh_attempts=1, auth_refresh_failures=1, and last_refresh.kind=failure with a failure timestamp/message.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-401-refresh-attempt.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-stats-after.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-mock-log.json"
],
"id": "VAL-HTTP-009",
"status": "pass",
"summary": "A 401-triggered refresh failure remained visible to the operator surface and did not masquerade as success."
},
{
"details": "POST /v1/files returned HTTP 404 with an error naming /v1/files and the supported routes list; successful_upstream_responses and total_proxied_requests stayed unchanged across the before/after stats captures.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-010-stats-before.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-010-unsupported-route.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-010-stats-after.txt"
],
"id": "VAL-HTTP-010",
"status": "pass",
"summary": "Unsupported /v1/* routes returned a clear 404 JSON error and did not change success counters."
}
],
"blockers": [
"VAL-HTTP-007 and VAL-HTTP-008 remain blocked for success-path validation because proxypilot-rs exposes no user-surface config knob to redirect refresh token exchange from the hardwired OAuth endpoint to a local stub."
],
"frictions": [],
"groupId": "http-runtime",
"overallSummary": "Validated 10 HTTP runtime assertions: 8 passed and 2 were blocked (refresh-success paths VAL-HTTP-007 and VAL-HTTP-008).",
"surface": "curl",
"toolsUsed": [
"curl"
]
}
@@ -0,0 +1,188 @@
{
"groupId": "tui-console",
"surface": "tuistory",
"toolsUsed": [
"tuistory",
"shell",
"curl"
],
"assertions": [
{
"id": "VAL-TUI-001",
"status": "pass",
"summary": "The TUI opened as a readable Codex operator console with overview, runtime, runtime-stats, models, accounts, selected-account, feedback, and key-help regions visible.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.png"
],
"details": "Launching `cargo run --manifest-path rust/Cargo.toml -p proxypilot-rs -- tui --config .../config-live.toml` rendered the Codex Operator Console immediately. The initial surface showed readable runtime health, live runtime stats, a disk-backed account list, selected-account details, and footer/help text rather than a blank or cryptic screen."
},
{
"id": "VAL-TUI-002",
"status": "pass",
"summary": "The footer/help text matched the shipped key bindings, and each listed action was exercised through the TUI during validation.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-activate-alpha.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-delete-beta.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-clear-feedback.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-after-q-snapshot.txt"
],
"details": "Visible help text listed `q`, `r`, arrows, `a`, `f`, `R`, `d`, and `c`. Those bindings were exercised across the live, runtime-down, and auth-trouble sessions: reload/poll updated state, arrows changed selection, activate/delete changed local state, selected refresh and active refresh produced targeted feedback, clear removed feedback, and `q` exited the TUI process back to the launcher shell."
},
{
"id": "VAL-TUI-003",
"status": "pass",
"summary": "With no proxy running on the configured port, the TUI explicitly showed runtime unavailability while keeping the local disk-backed account list and selected-account details visible.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-initial.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-initial.png"
],
"details": "Using the isolated runtime-down fixture on 127.0.0.1:18430 without starting a proxy produced `Health: proxy not running yet` and `Runtime unavailable` copy, while still rendering six saved accounts and full selected-account details from the local fixture state file."
},
{
"id": "VAL-TUI-004",
"status": "pass",
"summary": "Pressing `r` refreshed both disk-backed state and runtime-observed data without restarting the TUI.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/cli-activate-beta.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-cli-activate-reload.txt"
],
"details": "After changing the saved active account externally through the CLI and generating runtime traffic through `/v1/models`, pressing `r` in the live TUI updated the disk active account from `alpha` to `beta`, loaded the model list, and refreshed runtime counters to `total=1 success=1` while still truthfully showing the runtime active account as `alpha`."
},
{
"id": "VAL-TUI-005",
"status": "pass",
"summary": "The activate action updated active markers, selected-account details, and feedback coherently.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-before-activate.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-activate-alpha.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-activate-alpha.png"
],
"details": "Before pressing `a`, the selected row was `alpha` while the disk active marker was on `beta`. After `a`, the footer reported `Activated account \\`alpha\\`.` and the active marker moved to `alpha` without corrupting selection or the selected-account panel."
},
{
"id": "VAL-TUI-006",
"status": "pass",
"summary": "The delete action removed the selected account, kept selection in bounds, and updated visible account state coherently.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-clear-feedback.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-delete-beta.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-delete-beta.png"
],
"details": "With `beta` selected, pressing `d` removed that row, reduced the saved-account count from two to one, moved selection to the remaining `alpha` row, and showed `Deleted account \\`beta\\`.` in the footer without leaving stale details on screen."
},
{
"id": "VAL-TUI-007",
"status": "pass",
"summary": "Selected-account refresh targeted the selected row and named that account clearly in feedback.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-select-beta.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-refresh-selected-beta.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-selected-soon.txt"
],
"details": "On the live fixture, `beta` was selected while `alpha` remained active; pressing `f` produced `Failed to refresh account \\`beta\\`: account \\`beta\\` is static and has no refresh token`. In the runtime-down fixture, selecting `soon` and pressing `f` produced feedback naming `soon`, confirming the action targets the selected row rather than the active row."
},
{
"id": "VAL-TUI-008",
"status": "pass",
"summary": "Active-account refresh-now targeted the active account even when another row was selected.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-select-beta.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-refresh-active-alpha.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-select-valid-while-active-soon.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-active-runtime-down.txt"
],
"details": "In the live fixture, `beta` was selected while `alpha` was the active disk/runtime account; pressing `R` produced feedback naming `alpha`, not `beta`. In the runtime-down fixture, `valid` was selected while disk active remained `soon`, and `R` reported `Disk active account remains \\`soon\\``, again proving the action targeted the active account rather than the selected row."
},
{
"id": "VAL-TUI-009",
"status": "pass",
"summary": "Clear-feedback removed transient status text without altering selection or account state.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-refresh-active-alpha.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-clear-feedback.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-clear-feedback.txt"
],
"details": "After visible failure feedback in both live and runtime-down sessions, pressing `c` cleared the footer message back to blank while keeping the selected row, disk active account, runtime panel, and counters unchanged."
},
{
"id": "VAL-TUI-010",
"status": "pass",
"summary": "The TUI used explicit operator-readable auth labels for valid, expiring soon, expired, static, and unknown, with distinct missing-vs-malformed expiry details.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-valid.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-expiring-soon.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-expired.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-static.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-unknown-missing.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-unknown-malformed.txt"
],
"details": "A dedicated auth-label fixture showed `Auth health: valid`, `expiring soon`, `expired`, `static`, and `unknown` in the selected-account panel. The `unknown-missing` account showed `Expiry: expiry metadata missing`, while `unknown-malformed` showed `Expiry: malformed expiry metadata (not-a-timestamp)`, which truthfully distinguishes the two unknown states."
},
{
"id": "VAL-TUI-011",
"status": "pass",
"summary": "When runtime stats were available, the TUI surfaced request counters and the last refresh outcome/timestamp in the runtime panel.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-cli-activate-reload.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-after-reload.txt"
],
"details": "The idle live fixture showed zeroed counters and `Last refresh: unknown`. After proxied traffic, the live runtime panel updated to `total=1 success=1`. After a proxy-triggered refresh failure, the auth-trouble TUI showed `refresh_attempts=1 refresh_failures=1` and `Last refresh: failure for \\`refresh-fail\\` at ...`, making runtime refresh outcome visible without reading files or logs."
},
{
"id": "VAL-TUI-012",
"status": "pass",
"summary": "When runtime was down, local disk-backed actions still worked where feasible and runtime-dependent refresh paths failed with readable copy while local state stayed visible.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-activate-soon.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-selected-soon.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-active-runtime-down.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-delete-valid.txt"
],
"details": "With runtime unavailable, pressing `a` still updated the local disk active account from `valid` to `soon`; `f` failed with readable refresh-token-exchange copy naming the selected account; `R` failed with explicit `runtime stats unavailable` copy while preserving the disk active account label; and `d` still deleted a locally saved account without hiding the local account list."
},
{
"id": "VAL-CROSS-001",
"status": "pass",
"summary": "CLI active-account changes became visible in the TUI after reload while runtime state remained truthfully separate.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/cli-activate-beta.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-cli-activate-reload.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/cli-remove-alpha.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-cli-remove-alpha-reload.txt"
],
"details": "After CLI activation changed the saved active account to `beta`, TUI reload showed `Local disk active account: beta` while still showing `Runtime active account: alpha`. After CLI removal of `alpha`, reload again showed the saved state change (`beta` on disk, one saved account left) while runtime stats still truthfully reported the still-running proxy's runtime state as `alpha`."
},
{
"id": "VAL-CROSS-002",
"status": "pass",
"summary": "A proxy-triggered refresh attempt became visible across runtime surfaces without reading the state file manually.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-proxy-request.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-stats-after.json",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-after-reload.txt"
],
"details": "A proxied `GET /v1/models` against the auth-trouble fixture triggered an expired-account refresh attempt and returned a local 502. `/v0/runtime/stats` then showed `auth_refresh_attempts=1`, `auth_refresh_failures=1`, and a failed `last_refresh`, and the auth-trouble TUI showed the same failed refresh outcome in its runtime panel after reload."
},
{
"id": "VAL-CROSS-003",
"status": "pass",
"summary": "When runtime was down, reload and feedback clearing preserved local state while keeping runtime failures separate from local actions.",
"evidence": [
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-active-runtime-down.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-clear-feedback.txt",
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-reload.txt"
],
"details": "In the runtime-down fixture, local actions changed disk state, `R` surfaced runtime unavailability separately from that local state, `c` cleared only the transient footer message, and `r` reloaded the current disk-backed account list without hiding local accounts or collapsing the separate `Runtime unavailable` messaging."
}
],
"frictions": [
"tuistory keeps the PTY session alive after `q` exits the TUI binary, so explicit `tuistory close` cleanup was still required even though the application quit successfully.",
"With runtime down, `f` still attempts the hardwired Codex OAuth refresh exchange and surfaces the resulting OAuth 401 text instead of a pure local runtime-unavailable message; this was truthful but not called out in user-testing guidance."
],
"blockers": [],
"overallSummary": "Validated 15 assigned TUI/cross-surface assertions for terminal-operator-console: 15 passed, 0 failed, 0 blocked. Evidence and the flow report were written under the requested mission and validation paths."
}
@@ -0,0 +1,20 @@
{
"milestone": "terminal-operator-console",
"round": 2,
"status": "pass",
"assertionsSummary": {
"total": 3,
"passed": 3,
"failed": 0,
"blocked": 0
},
"passedAssertions": [
"VAL-CLI-003",
"VAL-HTTP-007",
"VAL-HTTP-008"
],
"failedAssertions": [],
"blockedAssertions": [],
"appliedUpdates": [],
"previousRound": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/synthesis.round1.json"
}
@@ -0,0 +1,66 @@
{
"milestone": "terminal-operator-console",
"round": 1,
"status": "fail",
"assertionsSummary": {
"total": 28,
"passed": 25,
"failed": 0,
"blocked": 3
},
"passedAssertions": [
"VAL-CLI-001",
"VAL-CLI-002",
"VAL-HTTP-001",
"VAL-HTTP-002",
"VAL-HTTP-003",
"VAL-HTTP-004",
"VAL-HTTP-005",
"VAL-HTTP-006",
"VAL-HTTP-009",
"VAL-HTTP-010",
"VAL-TUI-001",
"VAL-TUI-002",
"VAL-TUI-003",
"VAL-TUI-004",
"VAL-TUI-005",
"VAL-TUI-006",
"VAL-TUI-007",
"VAL-TUI-008",
"VAL-TUI-009",
"VAL-TUI-010",
"VAL-TUI-011",
"VAL-TUI-012",
"VAL-CROSS-001",
"VAL-CROSS-002",
"VAL-CROSS-003"
],
"failedAssertions": [],
"blockedAssertions": [
{
"id": "VAL-CLI-003",
"blockedBy": "Negative refresh paths behaved clearly for static and missing accounts, but the required refresh-success path could not be exercised within the isolated fixture because refresh-codex is hardwired to the live OpenAI OAuth refresh endpoint."
},
{
"id": "VAL-HTTP-007",
"blockedBy": "A proactive refresh attempt was observable before forwarding, but the success path could not be validated because the runtime cannot be redirected from the user surface to a local OAuth token stub."
},
{
"id": "VAL-HTTP-008",
"blockedBy": "The 401-triggered refresh path is visible, but the success retry case cannot be validated locally because the runtime cannot point refresh traffic at a local OAuth token stub from the user surface."
}
],
"appliedUpdates": [
{
"target": "user-testing.md",
"description": "Added flow validator guidance for shell, curl, and tuistory surfaces plus isolated fixture/evidence boundaries for terminal-operator-console validation.",
"source": "setup"
},
{
"target": "user-testing.md",
"description": "Documented discovered validation quirks: hardwired OAuth refresh paths block local success-path refresh testing, tuistory PTYs need explicit close, and runtime-down selected refresh still surfaces remote OAuth failure text.",
"source": "flow-report"
}
],
"previousRound": null
}
@@ -0,0 +1,20 @@
{
"milestone": "terminal-operator-console",
"round": 2,
"status": "pass",
"assertionsSummary": {
"total": 3,
"passed": 3,
"failed": 0,
"blocked": 0
},
"passedAssertions": [
"VAL-CLI-003",
"VAL-HTTP-007",
"VAL-HTTP-008"
],
"failedAssertions": [],
"blockedAssertions": [],
"appliedUpdates": [],
"previousRound": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/synthesis.round1.json"
}
+4 -3
View File
@@ -1,9 +1,7 @@
name: docker-image
on:
push:
tags:
- v*
workflow_dispatch:
env:
APP_NAME: ProxyPilot
@@ -28,6 +26,9 @@ jobs:
- name: Checkout
if: steps.check-secrets.outputs.skip != 'true'
uses: actions/checkout@v4
- name: Refresh models catalog
if: steps.check-secrets.outputs.skip != 'true'
run: curl -fsSL https://raw.githubusercontent.com/router-for-me/models/refs/heads/main/models.json -o internal/registry/models/models.json
- name: Set up QEMU
if: steps.check-secrets.outputs.skip != 'true'
uses: docker/setup-qemu-action@v3
+2
View File
@@ -12,6 +12,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Refresh models catalog
run: curl -fsSL https://raw.githubusercontent.com/router-for-me/models/refs/heads/main/models.json -o internal/registry/models/models.json
- name: Set up Go
uses: actions/setup-go@v5
with:
+1 -3
View File
@@ -1,9 +1,7 @@
name: ProxyPilot Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
permissions:
contents: write
+2
View File
@@ -16,6 +16,8 @@ jobs:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Refresh models catalog
run: curl -fsSL https://raw.githubusercontent.com/router-for-me/models/refs/heads/main/models.json -o internal/registry/models/models.json
- run: git fetch --force --tags
- uses: actions/setup-go@v4
with:
+5 -35
View File
@@ -40,35 +40,6 @@ jobs:
# Build tray app (includes embedded dashboard)
go build -ldflags="-s -w -H=windowsgui" -o dist/ProxyPilot.exe ./cmd/proxypilot-tray
- name: Build Installer UI
run: |
cd installer-ui
npm ci
npm run build
- name: Copy Installer UI to cmd/installer
run: |
# Ensure target directory exists
New-Item -ItemType Directory -Force -Path cmd/installer/ui | Out-Null
# Copy built UI files
Copy-Item -Path installer-ui/dist/* -Destination cmd/installer/ui/ -Recurse -Force
shell: pwsh
- name: Create bundle for installer
run: |
# Create bundle directory
New-Item -ItemType Directory -Force -Path cmd/installer/bundle | Out-Null
# Copy files for embedding
Copy-Item -Path dist/ProxyPilot.exe -Destination cmd/installer/bundle/
Copy-Item -Path config.example.yaml -Destination cmd/installer/bundle/
Copy-Item -Path static/icon.ico -Destination cmd/installer/bundle/
Copy-Item -Path static/icon.png -Destination cmd/installer/bundle/
shell: pwsh
- name: Build Custom Installer
run: |
go build -ldflags="-s -w -H=windowsgui" -o dist/ProxyPilot-Installer.exe ./cmd/installer
- name: Install Inno Setup
run: |
choco install innosetup -y
@@ -82,16 +53,18 @@ jobs:
id: version
run: |
if ("${{ github.event.inputs.version }}" -ne "") {
echo "VERSION=${{ github.event.inputs.version }}" >> $env:GITHUB_OUTPUT
$version = "${{ github.event.inputs.version }}"
} else {
$tag = "${{ github.ref_name }}"
$version = $tag -replace '^v', ''
echo "VERSION=$version" >> $env:GITHUB_OUTPUT
}
$versionInfo = $version -replace '^v', '' -replace '-dev-0\.', '.' -replace '-dev-', '.'
echo "VERSION=$version" >> $env:GITHUB_OUTPUT
echo "VERSION_INFO=$versionInfo" >> $env:GITHUB_OUTPUT
- name: Build Inno Setup Installer
run: |
& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" /DAppVersion="${{ steps.version.outputs.VERSION }}" installer\proxypilot.iss
& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" /DAppVersion="${{ steps.version.outputs.VERSION }}" /DVersionInfoVersion="${{ steps.version.outputs.VERSION_INFO }}" installer\proxypilot.iss
- name: Upload artifacts
uses: actions/upload-artifact@v4
@@ -99,7 +72,6 @@ jobs:
name: windows-release
path: |
dist/ProxyPilot.exe
dist/ProxyPilot-Installer.exe
dist/ProxyPilot-*-Setup.exe
- name: Upload to Release
@@ -108,6 +80,4 @@ jobs:
with:
files: |
dist/ProxyPilot.exe
dist/ProxyPilot-Installer.exe
dist/ProxyPilot-${{ steps.version.outputs.VERSION }}-Setup.exe
config.example.yaml
+9
View File
@@ -49,12 +49,14 @@ docs/*
!docs/long-context-features.md
!docs/desktop-app-build-process.md
!docs/cli.md
!docs/rust-replatform.md
AGENTS.md
CLAUDE.md
GEMINI.md
# Tooling metadata
.vscode/*
.worktrees/
.codex/*
.claude/*
.gemini/*
@@ -74,6 +76,7 @@ claude-progress.txt
feature_list.json
tui-snapshot*.txt
tui-ttyd.png
rust/target/
# Local settings (user-specific)
*.local.json
@@ -118,3 +121,9 @@ config-debug.yaml
test_results.txt
test_results_full.txt
tmpclaude-*
# Opencode
.beads/
.opencode/
.cli-proxy-api/
.venv/
+1
View File
@@ -12,6 +12,7 @@ builds:
- linux
- windows
- darwin
- freebsd
goarch:
- amd64
- arm64
+9 -4
View File
@@ -19,6 +19,10 @@
Built in Go, it handles OAuth authentication, token management, and API translation automatically. One server to route them all.
</p>
<p align="center">
An experimental Rust replatform now lives on the <code>rust-replatform</code> branch with a terminal-first <code>proxypilot-rs</code> binary under <code>rust/</code>.
</p>
---
> [!TIP]
@@ -92,10 +96,11 @@ go build -o proxypilot ./cmd/server
### First Launch
1. Copy config: `cp config.example.yaml config.yaml`
2. Run: `./proxypilot`
3. Server starts on `http://localhost:8317`
4. Open dashboard: `http://localhost:8317/management.html`
1. Packaged installs create `config.yaml` automatically on first start when `config.example.yaml` is bundled next to the executable.
2. If you're running from source, copy config: `cp config.example.yaml config.yaml`
3. Run: `./proxypilot`
4. Server starts on `http://localhost:8317`
5. Open dashboard: `http://localhost:8317/management.html`
### Authentication
+1 -1
View File
@@ -1 +1 @@
v6.8.49
v6.9.16
+276
View File
@@ -0,0 +1,276 @@
// Command fetch_antigravity_models connects to the Antigravity API using the
// stored auth credentials and saves the dynamically fetched model list to a
// JSON file for inspection or offline use.
//
// Usage:
//
// go run ./cmd/fetch_antigravity_models [flags]
//
// Flags:
//
// --auths-dir <path> Directory containing auth JSON files (default: "auths")
// --output <path> Output JSON file path (default: "antigravity_models.json")
// --pretty Pretty-print the output JSON (default: true)
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
sdkauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/proxyutil"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
)
const (
antigravityBaseURLDaily = "https://daily-cloudcode-pa.googleapis.com"
antigravitySandboxBaseURLDaily = "https://daily-cloudcode-pa.sandbox.googleapis.com"
antigravityBaseURLProd = "https://cloudcode-pa.googleapis.com"
antigravityModelsPath = "/v1internal:fetchAvailableModels"
)
func init() {
logging.SetupBaseLogger()
log.SetLevel(log.InfoLevel)
}
// modelOutput wraps the fetched model list with fetch metadata.
type modelOutput struct {
Models []modelEntry `json:"models"`
}
// modelEntry contains only the fields we want to keep for static model definitions.
type modelEntry struct {
ID string `json:"id"`
Object string `json:"object"`
OwnedBy string `json:"owned_by"`
Type string `json:"type"`
DisplayName string `json:"display_name"`
Name string `json:"name"`
Description string `json:"description"`
ContextLength int `json:"context_length,omitempty"`
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
}
func main() {
var authsDir string
var outputPath string
var pretty bool
flag.StringVar(&authsDir, "auths-dir", "auths", "Directory containing auth JSON files")
flag.StringVar(&outputPath, "output", "antigravity_models.json", "Output JSON file path")
flag.BoolVar(&pretty, "pretty", true, "Pretty-print the output JSON")
flag.Parse()
// Resolve relative paths against the working directory.
wd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "error: cannot get working directory: %v\n", err)
os.Exit(1)
}
if !filepath.IsAbs(authsDir) {
authsDir = filepath.Join(wd, authsDir)
}
if !filepath.IsAbs(outputPath) {
outputPath = filepath.Join(wd, outputPath)
}
fmt.Printf("Scanning auth files in: %s\n", authsDir)
// Load all auth records from the directory.
fileStore := sdkauth.NewFileTokenStore()
fileStore.SetBaseDir(authsDir)
ctx := context.Background()
auths, err := fileStore.List(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to list auth files: %v\n", err)
os.Exit(1)
}
if len(auths) == 0 {
fmt.Fprintf(os.Stderr, "error: no auth files found in %s\n", authsDir)
os.Exit(1)
}
// Find the first enabled antigravity auth.
var chosen *coreauth.Auth
for _, a := range auths {
if a == nil || a.Disabled {
continue
}
if strings.EqualFold(strings.TrimSpace(a.Provider), "antigravity") {
chosen = a
break
}
}
if chosen == nil {
fmt.Fprintf(os.Stderr, "error: no enabled antigravity auth found in %s\n", authsDir)
os.Exit(1)
}
fmt.Printf("Using auth: id=%s label=%s\n", chosen.ID, chosen.Label)
// Fetch models from the upstream Antigravity API.
fmt.Println("Fetching Antigravity model list from upstream...")
fetchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
models := fetchModels(fetchCtx, chosen)
if len(models) == 0 {
fmt.Fprintln(os.Stderr, "warning: no models returned (API may be unavailable or token expired)")
} else {
fmt.Printf("Fetched %d models.\n", len(models))
}
// Build the output payload.
out := modelOutput{
Models: models,
}
// Marshal to JSON.
var raw []byte
if pretty {
raw, err = json.MarshalIndent(out, "", " ")
} else {
raw, err = json.Marshal(out)
}
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to marshal JSON: %v\n", err)
os.Exit(1)
}
if err = os.WriteFile(outputPath, raw, 0o644); err != nil {
fmt.Fprintf(os.Stderr, "error: failed to write output file %s: %v\n", outputPath, err)
os.Exit(1)
}
fmt.Printf("Model list saved to: %s\n", outputPath)
}
func fetchModels(ctx context.Context, auth *coreauth.Auth) []modelEntry {
accessToken := metaStringValue(auth.Metadata, "access_token")
if accessToken == "" {
fmt.Fprintln(os.Stderr, "error: no access token found in auth")
return nil
}
baseURLs := []string{antigravityBaseURLProd, antigravityBaseURLDaily, antigravitySandboxBaseURLDaily}
for _, baseURL := range baseURLs {
modelsURL := baseURL + antigravityModelsPath
var payload []byte
if auth != nil && auth.Metadata != nil {
if pid, ok := auth.Metadata["project_id"].(string); ok && strings.TrimSpace(pid) != "" {
payload = []byte(fmt.Sprintf(`{"project": "%s"}`, strings.TrimSpace(pid)))
}
}
if len(payload) == 0 {
payload = []byte(`{}`)
}
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodPost, modelsURL, strings.NewReader(string(payload)))
if errReq != nil {
continue
}
httpReq.Close = true
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
httpReq.Header.Set("User-Agent", misc.AntigravityUserAgent())
httpClient := &http.Client{Timeout: 30 * time.Second}
if transport, _, errProxy := proxyutil.BuildHTTPTransport(auth.ProxyURL); errProxy == nil && transport != nil {
httpClient.Transport = transport
}
httpResp, errDo := httpClient.Do(httpReq)
if errDo != nil {
continue
}
bodyBytes, errRead := io.ReadAll(httpResp.Body)
httpResp.Body.Close()
if errRead != nil {
continue
}
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
continue
}
result := gjson.GetBytes(bodyBytes, "models")
if !result.Exists() {
continue
}
var models []modelEntry
for originalName, modelData := range result.Map() {
modelID := strings.TrimSpace(originalName)
if modelID == "" {
continue
}
// Skip internal/experimental models
switch modelID {
case "chat_20706", "chat_23310", "tab_flash_lite_preview", "tab_jump_flash_lite_preview", "gemini-2.5-flash-thinking", "gemini-2.5-pro":
continue
}
displayName := modelData.Get("displayName").String()
if displayName == "" {
displayName = modelID
}
entry := modelEntry{
ID: modelID,
Object: "model",
OwnedBy: "antigravity",
Type: "antigravity",
DisplayName: displayName,
Name: modelID,
Description: displayName,
}
if maxTok := modelData.Get("maxTokens").Int(); maxTok > 0 {
entry.ContextLength = int(maxTok)
}
if maxOut := modelData.Get("maxOutputTokens").Int(); maxOut > 0 {
entry.MaxCompletionTokens = int(maxOut)
}
models = append(models, entry)
}
return models
}
return nil
}
func metaStringValue(m map[string]interface{}, key string) string {
if m == nil {
return ""
}
v, ok := m[key]
if !ok {
return ""
}
switch val := v.(type) {
case string:
return val
default:
return ""
}
}
File diff suppressed because one or more lines are too long
+115 -16
View File
@@ -8,6 +8,7 @@ import (
"errors"
"flag"
"fmt"
"io"
"io/fs"
"net/url"
"os"
@@ -24,6 +25,8 @@ import (
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v6/internal/managementasset"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v6/internal/startupconfig"
"github.com/router-for-me/CLIProxyAPI/v6/internal/store"
_ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator"
"github.com/router-for-me/CLIProxyAPI/v6/internal/tui"
@@ -103,6 +106,7 @@ func main() {
var switchMode string
var projectID string
var vertexImport string
var vertexImportPrefix string
var configPath string
var password string
var noIncognito bool
@@ -138,6 +142,7 @@ func main() {
// TUI flag
var launchTUI bool
var standalone bool
var localModel bool
// Define command-line flags for different operation modes.
flag.BoolVar(&login, "login", false, "Login Google Account")
@@ -177,9 +182,11 @@ func main() {
flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)")
flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path")
flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file")
flag.StringVar(&vertexImportPrefix, "vertex-import-prefix", "", "Prefix for Vertex model namespacing (use with -vertex-import)")
flag.StringVar(&password, "password", "", "")
flag.BoolVar(&launchTUI, "tui", false, "Start with terminal management UI")
flag.BoolVar(&standalone, "standalone", false, "In TUI mode, start an embedded local server")
flag.BoolVar(&localModel, "local-model", false, "Use embedded model catalog only, skip remote model fetching")
flag.BoolVar(&showVersion, "version", false, "Show ProxyPilot version and exit")
flag.BoolVar(&showStatus, "status", false, "Show ProxyPilot status and exit")
@@ -305,6 +312,7 @@ func main() {
gitStoreRemoteURL string
gitStoreUser string
gitStorePassword string
gitStoreBranch string
gitStoreLocalPath string
gitStoreInst *store.GitTokenStore
gitStoreRoot string
@@ -374,6 +382,9 @@ func main() {
if value, ok := lookupEnv("GITSTORE_LOCAL_PATH", "gitstore_local_path"); ok {
gitStoreLocalPath = value
}
if value, ok := lookupEnv("GITSTORE_GIT_BRANCH", "gitstore_git_branch"); ok {
gitStoreBranch = value
}
if value, ok := lookupEnv("OBJECTSTORE_ENDPOINT", "objectstore_endpoint"); ok {
useObjectStore = true
objectStoreEndpoint = value
@@ -508,7 +519,7 @@ func main() {
}
gitStoreRoot = filepath.Join(gitStoreLocalPath, "gitstore")
authDir := filepath.Join(gitStoreRoot, "auths")
gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword)
gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword, gitStoreBranch)
gitStoreInst.SetBaseDir(authDir)
if errRepo := gitStoreInst.EnsureRepository(); errRepo != nil {
log.Errorf("failed to prepare git token store: %v", errRepo)
@@ -546,12 +557,18 @@ func main() {
configFilePath = configPath
cfg, err = config.LoadConfigOptional(configPath, isCloudDeploy)
} else {
wd, err = os.Getwd()
if err != nil {
log.Errorf("failed to get working directory: %v", err)
return
exePath, errExe := os.Executable()
if errExe != nil {
log.WithError(errExe).Debug("failed to resolve executable path for default config lookup")
}
configFilePath = filepath.Join(wd, "config.yaml")
resolution := startupconfig.ResolveConfigPath("", wd, exePath)
if created, errPrepare := startupconfig.EnsureDefaultConfig(resolution); errPrepare != nil {
log.Errorf("failed to prepare default config: %v", errPrepare)
return
} else if created {
log.Infof("default config initialized from template: %s", resolution.ConfigPath)
}
configFilePath = resolution.ConfigPath
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
}
if err != nil {
@@ -651,7 +668,7 @@ func main() {
if vertexImport != "" {
// Handle Vertex service account import
cmd.DoVertexImport(cfg, vertexImport)
cmd.DoVertexImport(cfg, vertexImport, vertexImportPrefix)
} else if showVersion {
// Version already printed at startup, just exit
return
@@ -812,9 +829,13 @@ func main() {
cmd.WaitForCloudDeploy()
return
}
// Start the main proxy service
// Auto-generate management password if not provided
// This enables browser-based webui access without requiring the -password flag
if localModel && (!launchTUI || standalone) {
log.Info("Local model mode: using embedded model catalog, remote model updates disabled")
}
// Auto-generate management password if not provided.
// This enables browser-based webui access without requiring the -password flag.
autoGenPassword := false
if password == "" {
if pw, err := desktopctl.GetManagementPassword(); err == nil {
@@ -825,13 +846,91 @@ func main() {
log.Warnf("failed to get management password: %v (webui may require manual authentication)", err)
}
}
// Use standalone mode (no keep-alive shutdown) when password was auto-generated
// Keep-alive shutdown is only needed when the tray app spawns the server as subprocess
managementasset.StartAutoUpdater(context.Background(), configFilePath)
if autoGenPassword {
cmd.StartServiceStandalone(cfg, configFilePath, password)
if launchTUI {
proxyURL := fmt.Sprintf("http://127.0.0.1:%d", cfg.Port)
if standalone {
// Standalone mode: start an embedded local server and connect TUI client to it.
managementasset.StartAutoUpdater(context.Background(), configFilePath)
misc.StartAntigravityVersionUpdater(context.Background())
if !localModel {
registry.StartModelsUpdater(context.Background())
}
origStdout := os.Stdout
origStderr := os.Stderr
origLogOutput := log.StandardLogger().Out
log.SetOutput(io.Discard)
devNull, errOpenDevNull := os.Open(os.DevNull)
if errOpenDevNull == nil {
os.Stdout = devNull
os.Stderr = devNull
}
restoreIO := func() {
os.Stdout = origStdout
os.Stderr = origStderr
log.SetOutput(origLogOutput)
if devNull != nil {
_ = devNull.Close()
}
}
if password == "" {
password = fmt.Sprintf("tui-%d-%d", os.Getpid(), time.Now().UnixNano())
}
cancel, done := cmd.StartServiceBackground(cfg, configFilePath, password)
client := tui.NewClient(proxyURL, password)
ready := false
backoff := 100 * time.Millisecond
for i := 0; i < 30; i++ {
if _, errFetchStatus := client.FetchStatus(); errFetchStatus == nil {
ready = true
break
}
time.Sleep(backoff)
if backoff < time.Second {
backoff = time.Duration(float64(backoff) * 1.5)
}
}
if !ready {
restoreIO()
cancel()
<-done
fmt.Fprintf(os.Stderr, "TUI error: embedded server is not ready\n")
return
}
if errRun := tui.RunWithStdio(proxyURL, password, os.Stdin, origStdout); errRun != nil {
restoreIO()
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
} else {
restoreIO()
}
cancel()
<-done
} else {
// Default TUI mode: pure management client.
// The proxy server must already be running.
if errRun := tui.Run(proxyURL, password); errRun != nil {
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
}
}
} else {
cmd.StartService(cfg, configFilePath, password)
managementasset.StartAutoUpdater(context.Background(), configFilePath)
misc.StartAntigravityVersionUpdater(context.Background())
if !localModel {
registry.StartModelsUpdater(context.Background())
}
if autoGenPassword {
cmd.StartServiceStandalone(cfg, configFilePath, password)
} else {
cmd.StartService(cfg, configFilePath, password)
}
}
}
}
+45 -4
View File
@@ -25,6 +25,10 @@ remote-management:
# Disable the bundled management control panel asset download and HTTP route when true.
disable-control-panel: false
# Disable automatic periodic background updates of the management panel from GitHub (default: false).
# When enabled, the panel is only downloaded on first access if missing, and never auto-updated afterward.
# disable-auto-update-panel: false
# GitHub repository for the management control panel. Accepts a repository URL or releases API URL.
panel-github-repository: "https://github.com/router-for-me/Cli-Proxy-API-Management-Center"
@@ -63,6 +67,7 @@ error-logs-max-files: 10
usage-statistics-enabled: false
# Proxy URL. Supports socks5/http/https protocols. Example: socks5://user:pass@192.168.1.1:1080/
# Per-entry proxy-url also supports "direct" or "none" to bypass both the global proxy-url and environment proxies explicitly.
proxy-url: ""
# When true, unprefixed model requests only use credentials without a prefix (except when prefix == model name).
@@ -82,10 +87,14 @@ max-retry-credentials: 0
# Maximum wait time in seconds for a cooled-down credential before triggering a retry.
max-retry-interval: 30
# When true, disable auth/model cooldown scheduling globally (prevents blackout windows after failure states).
disable-cooling: false
# Quota exceeded behavior
quota-exceeded:
switch-project: true # Whether to automatically switch to another project when a quota is exceeded
switch-preview-model: true # Whether to automatically switch to a preview model when a quota is exceeded
antigravity-credits: true # Whether to retry Antigravity quota_exhausted 429s once with enabledCreditTypes=["GOOGLE_ONE_AI"]
# Routing strategy for selecting credentials when multiple match.
routing:
@@ -94,6 +103,10 @@ routing:
# When true, enable authentication for the WebSocket API (/v1/ws).
ws-auth: false
# When true, enable Gemini CLI internal endpoints (/v1internal:*).
# Default is false for safety.
enable-gemini-cli-endpoint: false
# When > 0, emit blank lines every N seconds for non-streaming responses to prevent idle timeouts.
nonstream-keepalive-interval: 0
@@ -110,6 +123,7 @@ nonstream-keepalive-interval: 0
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080"
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# models:
# - name: "gemini-2.5-flash" # upstream model name
# alias: "gemini-flash" # client alias mapped to the upstream model
@@ -128,6 +142,7 @@ nonstream-keepalive-interval: 0
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# models:
# - name: "gpt-5-codex" # upstream model name
# alias: "codex-latest" # client alias mapped to the upstream model
@@ -146,6 +161,7 @@ nonstream-keepalive-interval: 0
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# models:
# - name: "claude-3-5-sonnet-20241022" # upstream model name
# alias: "claude-sonnet-latest" # client alias mapped to the upstream model
@@ -164,14 +180,31 @@ nonstream-keepalive-interval: 0
# - "API"
# - "proxy"
# cache-user-id: true # optional: default is false; set true to reuse cached user_id per API key instead of generating a random one each request
# experimental-cch-signing: false # optional: default is false; when true, sign the final /v1/messages body using the current Claude Code cch algorithm
# # keep this disabled unless you explicitly need the behavior, so upstream seed changes fall back to legacy proxy behavior
# Default headers for Claude API requests. Update when Claude Code releases new versions.
# These are used as fallbacks when the client does not send its own headers.
# In legacy mode, user-agent/package-version/runtime-version/timeout are used as fallbacks
# when the client omits them, while OS/arch remain runtime-derived. When
# stabilize-device-profile is enabled, OS/arch stay pinned to the baseline values below,
# while user-agent/package-version/runtime-version seed a software fingerprint that can
# still upgrade to newer official Claude client versions.
# claude-header-defaults:
# user-agent: "claude-cli/2.1.44 (external, sdk-cli)"
# package-version: "0.74.0"
# runtime-version: "v24.3.0"
# os: "MacOS"
# arch: "arm64"
# timeout: "600"
# stabilize-device-profile: false # optional, default false; set true to enable per-auth/API-key fingerprint pinning
# Default headers for Codex OAuth model requests.
# These are used only for file-backed/OAuth Codex requests when the client
# does not send the header. `user-agent` applies to HTTP and websocket requests;
# `beta-features` only applies to websocket requests. They do not apply to codex-api-key entries.
# codex-header-defaults:
# user-agent: "codex_cli_rs/0.114.0 (Mac OS 14.2.0; x86_64) vscode/1.111.0"
# beta-features: "multi_agent"
# OpenAI compatibility providers
# openai-compatibility:
@@ -183,10 +216,13 @@ nonstream-keepalive-interval: 0
# api-key-entries:
# - api-key: "sk-or-v1-...b780"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# - api-key: "sk-or-v1-...b781" # without proxy-url
# models: # The models supported by the provider.
# - name: "moonshotai/kimi-k2:free" # The actual model name.
# alias: "kimi-k2" # The alias used in the API.
# alias: "kimi-k2" # The alias used in the API.
# thinking: # optional: omit to default to levels ["low","medium","high"]
# levels: ["low", "medium", "high"]
# # You may repeat the same alias to build an internal model pool.
# # The client still sees only one alias in the model list.
# # Requests to that alias will round-robin across the upstream names below,
@@ -199,12 +235,13 @@ nonstream-keepalive-interval: 0
# - name: "kimi-k2.5"
# alias: "claude-opus-4.66"
# Vertex API keys (Vertex-compatible endpoints, use API key + base URL)
# Vertex API keys (Vertex-compatible endpoints, base-url is optional)
# vertex-api-key:
# - api-key: "vk-123..." # x-goog-api-key header
# prefix: "test" # optional: require calls like "test/vertex-pro" to target this credential
# base-url: "https://example.com/api" # e.g. https://zenmux.ai/api
# base-url: "https://example.com/api" # optional, e.g. https://zenmux.ai/api; falls back to Google Vertex when omitted
# proxy-url: "socks5://proxy.example.com:1080" # optional per-key proxy override
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# headers:
# X-Custom-Header: "custom-value"
# models: # optional: map aliases to upstream model names
@@ -254,6 +291,10 @@ nonstream-keepalive-interval: 0
# These aliases rename model IDs for both model listing and request routing.
# Supported channels: gemini-cli, vertex, aistudio, antigravity, claude, codex, qwen, iflow, kimi.
# NOTE: Aliases do not apply to gemini-api-key, codex-api-key, claude-api-key, openai-compatibility, vertex-api-key, or ampcode.
# NOTE: Because aliases affect the merged /v1 model list and merged request routing, overlapping
# client-visible names can become ambiguous across providers. /api/provider/{provider}/... helps
# you select the protocol surface, but inference backend selection can still follow the resolved
# model/alias. For strict backend pinning, use unique aliases/prefixes or avoid overlapping names.
# You can repeat the same name with different aliases to expose multiple client model names.
# oauth-model-alias:
# gemini-cli:
+54
View File
@@ -0,0 +1,54 @@
# ProxyPilot Rust Replatform
This branch carries the Rust rewrite line for ProxyPilot.
## Branch contract
- Go `main` remains the shipping line while Rust grows.
- Rust lives under [`rust/`](/home/fsos/code-lean/ai-tools/ProxyPilot/rust).
- The Rust line is terminal-first and does not treat the browser dashboard as a required early target.
- The first real milestone is a working Rust executable that can proxy a Codex-compatible request end-to-end.
## Current milestone
`proxypilot-rs` is the first Rust binary in the repo. It currently provides:
- a `run` command that starts a local proxy server
- a `tui` command that opens a minimal terminal operator view
- a TOML config model plus a separate local state file for saved accounts
- explicit Codex-facing routes for `/v1/models`, `/v1/chat/completions`, and `/v1/responses`
- a local `/v0/runtime/stats` operator surface for runtime-memory counters, auth-health, and last refresh status
- CLI account commands for adding, importing, device-login, refresh, listing, activating, and removing Codex accounts; these manage saved disk state only and do not pretend a running proxy has already adopted the change
- optional `codex.refresh_token_url` config support for redirecting Codex refresh exchanges to a local stub during validation, while preserving the live OpenAI default when unset
- a TUI operator console that shows live runtime stats, runtime-unavailable copy, local accounts, selected-account details, token state labels, terminal actions for activate/refresh/delete, separate selected-account vs active-account refresh handling, and the `r` / `c` reload-clear controls
- runtime credential resolution that prefers the active saved account over the config fallback key
- proactive Codex token refresh when the active saved account is already expired or within the refresh window, plus the existing 401-retry refresh fallback
- end-to-end tests against a mocked upstream server
## Design defaults
- Go is the behavioral reference, not a line-by-line port target.
- The Rust branch is allowed to redesign config and management surfaces.
- The product identity does not change: ProxyPilot still exists to be a local proxy for coding tools.
## Local workflow
From the repo root:
```bash
cd rust
cargo run -p proxypilot-rs -- init
cargo run -p proxypilot-rs -- account add-codex --name primary --api-key sk-...
cargo run -p proxypilot-rs -- account import-codex --file ../auths/codex-example.json --activate
cargo run -p proxypilot-rs -- account login-codex-device --activate
cargo run -p proxypilot-rs -- account refresh-codex
cargo run -p proxypilot-rs -- account remove --name old-account
cargo run -p proxypilot-rs -- run --config proxypilot-rs.toml
```
Open the TUI with:
```bash
cd rust
cargo run -p proxypilot-rs -- tui --config proxypilot-rs.toml
```
+84
View File
@@ -0,0 +1,84 @@
# Session Progress - 2026-03-12
## Summary
Merged upstream CLIProxyAPI releases `v6.8.50` and `v6.8.51` directly into ProxyPilot `main`, resolved fork-specific conflicts in startup and Docker publishing paths, prepared the next dev release tag `v0.3.0-dev-0.42`, then switched release publishing to a local/manual flow and uploaded the release assets outside GitHub Actions.
## Upstream Releases Included
- `v6.8.50` - preserve string-form system prompts, cap websocket body log growth, and extend scheduler / executor coverage
- `v6.8.51` - refresh model catalog from network on startup, register Codex models by plan tier, and refresh release / workflow paths
## Conflict Resolution Notes
- Kept ProxyPilot Docker publishing identity in `.github/workflows/docker-image.yml` and added the upstream models catalog refresh step before image builds.
- Kept ProxyPilot's management-password startup flow in `cmd/server/main.go` and added `registry.StartModelsUpdater(...)` before service startup.
- Accepted the upstream move from generated static registry data to embedded `internal/registry/models/models.json`, including deletion of `internal/registry/model_definitions_static_data.go`.
## Fork-Specific Follow-Ups
- Updated `internal/cmd/list_models.go` to use the new Codex plan-tier model getters instead of the removed `registry.GetOpenAIModels`.
- Fixed `sdk/auth/filestore.go` delete-path resolution so nested relative auth IDs delete under the configured base dir, absolute paths still work for the management API, and traversal outside the base dir is rejected.
- Updated `UPSTREAM_VERSION` to `v6.8.51`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.8.51`.
- Changed `.github/workflows/proxypilot-release.yml` and `.github/workflows/docker-image.yml` from tag-triggered runs to manual dispatch so releases can be built locally and uploaded manually instead of consuming GitHub Actions minutes.
- Built the `v0.3.0-dev-0.42` release assets locally from the tag snapshot and uploaded:
- `proxypilot-darwin-amd64`
- `proxypilot-darwin-arm64`
- `proxypilot-linux-amd64`
- `proxypilot-linux-arm64`
- `proxypilot-windows-amd64.exe`
- `checksums.txt`
## Verification
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
- `go vet ./...` - PASS
- `go test ./internal/runtime/executor/...` - PASS
- `go test ./internal/registry/...` - PASS
- `go test ./sdk/api/handlers/openai/...` - PASS
- `go test ./sdk/cliproxy/auth -run 'TestFileStore_Delete_(RemovesFile|NotFound|AbsolutePath|RejectsTraversalOutsideBaseDir)' -v` - PASS
- `go test ./sdk/cliproxy/auth` - PASS
- `go test ./sdk/cliproxy/...` - PASS
- `go test ./...` - PASS
## Release Notes
- Next dev tag: `v0.3.0-dev-0.42`
- Latest upstream target at merge time: `CLIProxyAPI v6.8.51`
## Maintenance Review
- Completed parallel findings-first review of `internal/auth/*`, `internal/translator/*`, and `internal/api/handlers/*` on 2026-03-12 12:01:40 +07.
- Auth review findings:
- `internal/auth/kiro/token_repository.go` only queues `auth_method` values `idc` and `builder-id` for background refresh even though `internal/auth/kiro/oauth.go` persists social logins as `auth_method: "social"` and the refresher has a default OAuth refresh path for non-SSO methods. Result: Google/GitHub Kiro tokens are skipped by auto-refresh.
- `internal/auth/kiro/token_repository.go` walks nested token files but rewrites refreshed tokens back to `filepath.Join(baseDir, token.ID)` after truncating IDs to `filepath.Base(path)`. Result: nested Kiro token files would be rewritten into the auth root instead of their original directory.
- Translator review findings:
- `internal/translator/kiro/openai` can emit streamed tool-call argument deltas with the wrong OpenAI tool index.
- `internal/translator/kiro/openai` does not actually enforce `tool_choice`; it still forwards tools when callers request `none` or pin a specific function.
- `internal/translator/openai/openai/responses` downgrades `developer` messages to `user`.
- `internal/translator/gemini/openai/chat-completions` reads/mapping finish reasons incorrectly for some response shapes.
- `internal/translator/gemini/openai/responses` can send `functionResponse.name = "unknown"` on follow-up tool-output requests.
- API handler review findings:
- `internal/api/handlers/management/memory.go` uses raw `session` query values to build filesystem paths for delete/export/import instead of the memory store's sanitized session path helper, allowing traversal outside the memory store root.
- `internal/api/handlers/management/generic_import.go` derives auth filenames from the first characters of imported API keys, exposing secret prefixes in filenames and management responses.
- `internal/api/handlers/management/auth_files.go` writes uploaded auth files to disk before validation and leaves invalid files behind on registration failure.
- `internal/api/handlers/management/config_basic.go` returns a zero-value config from `GetConfig` because it serializes `new(*h.cfg)` instead of the current config.
- `internal/api/handlers/management/auth_priority.go` and `internal/api/handlers/management/auth_files.go` update priority in places the runtime selector does not read, so management-set auth priority does not affect routing and does not persist reliably for file-backed auths.
- Config mutation helpers in `internal/api/handlers/management/handler.go` mutate `h.cfg` before persistence succeeds, so failed writes can leave runtime config diverged from disk until restart.
- Review validation:
- `go test ./internal/auth/... ./internal/translator/... ./internal/api/handlers/...` - PASS
## Maintenance Fixes
- Hardened management memory delete/export/import so session names are validated before resolving filesystem paths, blocking traversal attempts outside the memory store root.
- Changed bulk API-key import filenames to opaque `provider-import-...` names so credential prefixes are no longer exposed in filenames or management responses.
- Changed auth upload handling to validate uploaded JSON before committing it to disk and to roll back failed registrations instead of leaving broken auth files behind.
- Fixed `GetConfig` to return the live in-memory config and changed the simple config mutation helpers to persist cloned config state instead of mutating runtime config before the file write succeeds.
- Fixed file-backed auth persistence so `priority`, `prefix`, and `proxy_url` survive saves, reloads, and management edits, and so runtime selection prefers `Auth.Priority` with a legacy attribute fallback.
- Changed token writers across codex, claude, gemini, kimi, qwen, iflow, copilot, and vertex to use atomic `0600` JSON writes.
- Fixed Kiro background refresh so blank refresh responses do not erase the existing refresh token, nested token paths refresh in place, and social auth token files participate in the refresh scan.
- Fixed Kiro OAuth callback servers so shutdown waits on a dedicated completion signal instead of racing the login flow for the only callback result.
- Fixed Kiro/OpenAI tool streaming to keep a stable mapping from content-block indexes to OpenAI tool ordinals.
- Fixed Kiro/OpenAI request translation so `tool_choice=none|required|function` is enforced instead of treated as a prompt-only hint.
- Fixed OpenAI Responses to Chat Completions conversion to preserve `developer` role messages.
- Fixed Gemini/OpenAI finish-reason mapping so OpenAI receives valid enums while the original Gemini reason is preserved in `native_finish_reason`.
- Added a bounded Gemini function-call name cache so `previous_response_id` follow-up tool outputs resolve the original function name and fail closed when they cannot.
## Maintenance Fix Verification
- `go test ./internal/auth/... ./sdk/auth ./sdk/cliproxy/auth ./internal/translator/... ./internal/api/handlers/...` - PASS
- `go test ./internal/api/handlers/management` - PASS
- `go test ./...` - PASS
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
+28
View File
@@ -0,0 +1,28 @@
# Session Progress - 2026-03-17
## Summary
Merged upstream CLIProxyAPI release `v6.8.55` into ProxyPilot `main`, carrying forward the fork's workflow and branding decisions while absorbing upstream changes from `v6.8.52` through `v6.8.55`.
Built the release assets locally and published `v0.3.0-dev-0.43` on GitHub as the latest ProxyPilot release.
## Upstream Releases Included
- `v6.8.52` - Codex websocket header defaults and related compatibility updates
- `v6.8.53` - Antigravity model refresh and proxy helper improvements
- `v6.8.54` - auth file metadata exposure and management API test coverage
- `v6.8.55` - auth list priority/note support, Gemini responses tool-output fixes, and proxy utility additions
## Conflict Resolution Notes
- Kept the fork versions of `.github/workflows/docker-image.yml`, `.github/workflows/release.yaml`, `.github/workflows/pr-test-build.yml`, and `.goreleaser.yml` so this sync does not alter CI or release automation.
- Kept ProxyPilot README branding and deleted the upstream `README_CN.md` revival because this fork intentionally does not ship that file.
- Merged `internal/api/handlers/management/auth_files.go` semantically so ProxyPilot keeps its `Auth.Priority` persistence while also adding upstream `note` support and priority/note exposure in the auth-file API.
- Kept the stricter Gemini Responses JSON validation in `internal/translator/gemini/openai/responses/gemini_openai-responses_request.go` so partial JSON strings are not embedded as structured results.
## Repo State Updates
- Updated `UPSTREAM_VERSION` to `v6.8.55`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.8.55`.
- Published dev release: `v0.3.0-dev-0.43`.
## Verification
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
- `mise exec go@1.26.0 -- go vet ./...` - PASS
- `mise exec go@1.26.0 -- go test ./...` - PASS
- `gh release list -R Finesssee/ProxyPilot --limit 5` - PASS (`v0.3.0-dev-0.43` is `Latest`)
+26
View File
@@ -0,0 +1,26 @@
# Session Progress - 2026-04-01
## Summary
Merged upstream CLIProxyAPI release `v6.9.7` into ProxyPilot on a dedicated sync branch, carrying forward ProxyPilot branding and local-manual release workflow choices while absorbing the upstream changes from `v6.9.6` and `v6.9.7`.
Re-established a fully local Windows installer build path on Linux using a repo-scoped Wine prefix plus Inno Setup so the `Setup.exe` can be built without CI/CD.
## Upstream Releases Included
- `v6.9.6` - intermediate upstream changes now included through the `v6.9.7` merge
- `v6.9.7` - Codex executor/cache behavior updates, Amp response rewriting improvements, scheduler/auth updates, and related tests
## Conflict Resolution Notes
- Kept the ProxyPilot README and removed upstream `README_CN.md` and `README_JA.md` revivals because this fork intentionally does not ship those translation files.
- Followed upstream on the Codex continuity revert by deleting `internal/runtime/executor/codex_continuity.go` and aligning the Codex cache tests with `v6.9.7`, since upstream explicitly reverted that helper rather than evolving it.
- Preserved the existing fork policy of local/manual releases instead of changing CI or workflow behavior as part of this sync.
## Repo State Updates
- Updated `UPSTREAM_VERSION` to `v6.9.7`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.7`.
- Prepared a local Windows installer toolchain using Wine + Inno Setup for the upcoming `v0.3.0-dev-0.47` release build.
## Pending Verification
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
- `mise exec go@1.26.0 -- go vet ./...`
- `mise exec go@1.26.0 -- go test ./...`
- full local release asset build for `v0.3.0-dev-0.47`
- `gh release list -R Finesssee/ProxyPilot --limit 5`
+28
View File
@@ -0,0 +1,28 @@
# Session Progress - 2026-04-03
## Summary
Merged upstream CLIProxyAPI release `v6.9.10` into ProxyPilot on a dedicated sync branch and preserved the fork's local/manual release workflow.
Reconciled upstream's executor helper-package move with ProxyPilot's existing executor call sites by keeping the new `internal/runtime/executor/helps/` layout while restoring compatibility entrypoints in `internal/runtime/executor/`.
## Upstream Releases Included
- `v6.9.8` - intermediate upstream changes now included through the `v6.9.10` merge
- `v6.9.9` - intermediate upstream changes now included through the `v6.9.10` merge
- `v6.9.10` - latest upstream sync target for this release cycle
## Conflict Resolution Notes
- Kept the ProxyPilot README and continued to omit upstream `README_CN.md` and `README_JA.md` revivals because this fork does not ship those translation files.
- Preserved ProxyPilot's auth-file persistence behavior, including `prefix`, `proxy_url`, `priority`, and last-refresh handling, while also bringing in upstream custom-header hydration and patch support.
- Kept upstream's `internal/runtime/executor/helps/` reorganization, but restored executor-package compatibility wrappers/files so existing fork-specific executors still compile without a larger refactor in the same release pass.
- Continued to omit the upstream TUI translation/usage-tab files because ProxyPilot's current TUI surface does not carry those forked files.
## Repo State Updates
- Updated `UPSTREAM_VERSION` to `v6.9.10`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.10`.
- Recorded the merge commit `chore: merge upstream CLIProxyAPI v6.9.10` before starting validation and release assembly.
## Pending Verification
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
- `mise exec go@1.26.0 -- go vet ./...`
- `mise exec go@1.26.0 -- go test ./...`
- full local release asset build for `v0.3.0-dev-0.48`
- `gh release list -R Finesssee/ProxyPilot --limit 5`
+26
View File
@@ -0,0 +1,26 @@
# Session Progress - 2026-04-04
## Summary
Merged upstream CLIProxyAPI release `v6.9.12` into ProxyPilot on a dedicated sync branch and kept the existing local/manual release workflow unchanged.
This catch-up pull included the upstream delta from `v6.9.11` through `v6.9.12` and merged cleanly without any fork-specific conflict resolution work.
## Upstream Releases Included
- `v6.9.11` - intermediate upstream changes now included through the `v6.9.12` merge
- `v6.9.12` - latest upstream sync target for this release cycle
## Merge Notes
- The merge applied cleanly with upstream changes concentrated in `config.example.yaml`, `internal/config/sdk_config.go`, `internal/runtime/executor/qwen_executor.go`, and `sdk/api/handlers/gemini/gemini-cli_handlers.go`.
- No additional ProxyPilot compatibility shims were needed beyond the executor-wrapper structure restored in the prior sync.
- ProxyPilot branding, release routing, and local-build release flow remain unchanged.
## Repo State Updates
- Updated `UPSTREAM_VERSION` to `v6.9.12`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.12`.
- Prepared the repo for the next local/manual release: `v0.3.0-dev-0.49`.
## Pending Verification
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
- `mise exec go@1.26.0 -- go vet ./...`
- `mise exec go@1.26.0 -- go test ./...`
- full local release asset build for `v0.3.0-dev-0.49`
- `gh release list -R Finesssee/ProxyPilot --limit 5`
+28
View File
@@ -0,0 +1,28 @@
# Session Progress - 2026-04-05
## Summary
Merged upstream CLIProxyAPI release `v6.9.15` into ProxyPilot on a dedicated sync branch based on the latest `origin/main`.
Kept the local management-asset security fix from `origin/main`, preserved ProxyPilot branding and local/manual release workflow choices, and absorbed the upstream delta from `v6.9.13` through `v6.9.15`.
## Upstream Releases Included
- `v6.9.13` - vertex credential namespacing support, websocket custom tool-call repair, and model catalog refreshes
- `v6.9.14` - antigravity version refresh updates and additional upstream maintenance changes
- `v6.9.15` - API-key proxy resolution improvements and stricter Qwen system-message handling
## Conflict Resolution Notes
- Kept the ProxyPilot README branding and continued to omit upstream `README_CN.md` and `README_JA.md` revivals because this fork does not ship those translated files.
- Kept the existing local/manual release workflow and combined the fork's broader `.gitignore` with upstream's additional local-tool entries.
- Preserved the local `internal/managementasset/updater.go` security behavior that removes the unverified fallback download path while accepting the rest of the upstream sync.
- Merged `cmd/server/main.go` semantically so ProxyPilot keeps its wider CLI surface while also adding upstream `--vertex-import-prefix` support.
## Repo State Updates
- Updated `UPSTREAM_VERSION` to `v6.9.15`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.15`.
- Prepared the repo for the next clean release tag: `v0.3.0-dev-0.51`.
## Pending Verification
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
- `go vet ./...`
- `go test ./...`
- clean-tree packaging and release asset assembly for `v0.3.0-dev-0.51`
- `gh release list -R Finesssee/ProxyPilot --limit 5`
+4 -4
View File
@@ -52,11 +52,11 @@ func init() {
sdktr.Register(fOpenAI, fMyProv,
func(model string, raw []byte, stream bool) []byte { return raw },
sdktr.ResponseTransform{
Stream: func(ctx context.Context, model string, originalReq, translatedReq, raw []byte, param *any) []string {
return []string{string(raw)}
Stream: func(ctx context.Context, model string, originalReq, translatedReq, raw []byte, param *any) [][]byte {
return [][]byte{raw}
},
NonStream: func(ctx context.Context, model string, originalReq, translatedReq, raw []byte, param *any) string {
return string(raw)
NonStream: func(ctx context.Context, model string, originalReq, translatedReq, raw []byte, param *any) []byte {
return raw
},
},
)
+6 -6
View File
@@ -1,7 +1,7 @@
{
"project": "ProxyPilot",
"version": "0.3.0",
"upstream": "CLIProxyAPI v6.8.49",
"upstream": "CLIProxyAPI v6.9.15",
"features": [
{
"id": 1,
@@ -103,24 +103,24 @@
"id": 17,
"name": "Auth packages code review",
"description": "Codex review of internal/auth/* packages",
"passes": false
"passes": true
},
{
"id": 18,
"name": "Translator packages code review",
"description": "Codex review of internal/translator/* packages",
"passes": false
"passes": true
},
{
"id": 19,
"name": "API handlers code review",
"description": "Codex review of internal/api/handlers/* packages",
"passes": false
"passes": true
}
],
"summary": {
"total": 19,
"passing": 16,
"failing": 3
"passing": 19,
"failing": 0
}
}
+1
View File
@@ -96,6 +96,7 @@ require (
github.com/muesli/termenv v0.16.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
github.com/pierrec/xxHash v0.1.5
github.com/pjbgf/sha1cd v0.5.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
+2
View File
@@ -180,6 +180,8 @@ github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgF
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pierrec/xxHash v0.1.5 h1:n/jBpwTHiER4xYvK3/CdPVnLDPchj8eTJFFLUb4QHBo=
github.com/pierrec/xxHash v0.1.5/go.mod h1:w2waW5Zoa/Wc4Yqe0wgrIYAGKqRMf7czn2HNKXmuL+I=
github.com/pjbgf/sha1cd v0.5.0 h1:a+UkboSi1znleCDUNT3M5YxjOnN1fz2FhN48FlwCxs0=
github.com/pjbgf/sha1cd v0.5.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
+5 -2
View File
@@ -2,6 +2,9 @@
#ifndef AppVersion
#define AppVersion "0.1.0"
#endif
#ifndef VersionInfoVersion
#define VersionInfoVersion AppVersion
#endif
#ifndef RepoRoot
#define RepoRoot ".."
#endif
@@ -56,13 +59,13 @@ OutputBaseFilename=ProxyPilot-{#AppVersion}-Setup
AppCopyright=MIT License - ProxyPilot Contributors
; --- Version Info Embedded in Installer ---
VersionInfoVersion={#AppVersion}
VersionInfoVersion={#VersionInfoVersion}
VersionInfoCompany=ProxyPilot
VersionInfoDescription=ProxyPilot Installer - Local AI Proxy
VersionInfoTextVersion={#AppVersion}
VersionInfoCopyright=MIT License
VersionInfoProductName=ProxyPilot
VersionInfoProductVersion={#AppVersion}
VersionInfoProductVersion={#VersionInfoVersion}
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
+122 -35
View File
@@ -5,17 +5,17 @@ import (
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/runtime/geminicli"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/proxyutil"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
@@ -637,6 +637,11 @@ func (h *Handler) apiCallTransport(auth *coreauth.Auth) http.RoundTripper {
if proxyStr := strings.TrimSpace(auth.ProxyURL); proxyStr != "" {
proxyCandidates = append(proxyCandidates, proxyStr)
}
if h != nil && h.cfg != nil {
if proxyStr := strings.TrimSpace(proxyURLFromAPIKeyConfig(h.cfg, auth)); proxyStr != "" {
proxyCandidates = append(proxyCandidates, proxyStr)
}
}
}
if h != nil && h.cfg != nil {
if proxyStr := strings.TrimSpace(h.cfg.ProxyURL); proxyStr != "" {
@@ -659,46 +664,128 @@ func (h *Handler) apiCallTransport(auth *coreauth.Auth) http.RoundTripper {
return clone
}
func buildProxyTransport(proxyStr string) *http.Transport {
proxyStr = strings.TrimSpace(proxyStr)
if proxyStr == "" {
type apiKeyConfigEntry interface {
GetAPIKey() string
GetBaseURL() string
}
func resolveAPIKeyConfig[T apiKeyConfigEntry](entries []T, auth *coreauth.Auth) *T {
if auth == nil || len(entries) == 0 {
return nil
}
proxyURL, errParse := url.Parse(proxyStr)
if errParse != nil {
log.WithError(errParse).Debug("parse proxy URL failed")
return nil
attrKey, attrBase := "", ""
if auth.Attributes != nil {
attrKey = strings.TrimSpace(auth.Attributes["api_key"])
attrBase = strings.TrimSpace(auth.Attributes["base_url"])
}
if proxyURL.Scheme == "" || proxyURL.Host == "" {
log.Debug("proxy URL missing scheme/host")
return nil
}
if proxyURL.Scheme == "socks5" {
var proxyAuth *proxy.Auth
if proxyURL.User != nil {
username := proxyURL.User.Username()
password, _ := proxyURL.User.Password()
proxyAuth = &proxy.Auth{User: username, Password: password}
for i := range entries {
entry := &entries[i]
cfgKey := strings.TrimSpace((*entry).GetAPIKey())
cfgBase := strings.TrimSpace((*entry).GetBaseURL())
if attrKey != "" && attrBase != "" {
if strings.EqualFold(cfgKey, attrKey) && strings.EqualFold(cfgBase, attrBase) {
return entry
}
continue
}
dialer, errSOCKS5 := proxy.SOCKS5("tcp", proxyURL.Host, proxyAuth, proxy.Direct)
if errSOCKS5 != nil {
log.WithError(errSOCKS5).Debug("create SOCKS5 dialer failed")
return nil
if attrKey != "" && strings.EqualFold(cfgKey, attrKey) {
if cfgBase == "" || strings.EqualFold(cfgBase, attrBase) {
return entry
}
}
return &http.Transport{
Proxy: nil,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.Dial(network, addr)
},
if attrKey == "" && attrBase != "" && strings.EqualFold(cfgBase, attrBase) {
return entry
}
}
if proxyURL.Scheme == "http" || proxyURL.Scheme == "https" {
return &http.Transport{Proxy: http.ProxyURL(proxyURL)}
if attrKey != "" {
for i := range entries {
entry := &entries[i]
if strings.EqualFold(strings.TrimSpace((*entry).GetAPIKey()), attrKey) {
return entry
}
}
}
log.Debugf("unsupported proxy scheme: %s", proxyURL.Scheme)
return nil
}
func proxyURLFromAPIKeyConfig(cfg *config.Config, auth *coreauth.Auth) string {
if cfg == nil || auth == nil {
return ""
}
authKind, authAccount := auth.AccountInfo()
if !strings.EqualFold(strings.TrimSpace(authKind), "api_key") {
return ""
}
attrs := auth.Attributes
compatName := ""
providerKey := ""
if len(attrs) > 0 {
compatName = strings.TrimSpace(attrs["compat_name"])
providerKey = strings.TrimSpace(attrs["provider_key"])
}
if compatName != "" || strings.EqualFold(strings.TrimSpace(auth.Provider), "openai-compatibility") {
return resolveOpenAICompatAPIKeyProxyURL(cfg, auth, strings.TrimSpace(authAccount), providerKey, compatName)
}
switch strings.ToLower(strings.TrimSpace(auth.Provider)) {
case "gemini":
if entry := resolveAPIKeyConfig(cfg.GeminiKey, auth); entry != nil {
return strings.TrimSpace(entry.ProxyURL)
}
case "claude":
if entry := resolveAPIKeyConfig(cfg.ClaudeKey, auth); entry != nil {
return strings.TrimSpace(entry.ProxyURL)
}
case "codex":
if entry := resolveAPIKeyConfig(cfg.CodexKey, auth); entry != nil {
return strings.TrimSpace(entry.ProxyURL)
}
}
return ""
}
func resolveOpenAICompatAPIKeyProxyURL(cfg *config.Config, auth *coreauth.Auth, apiKey, providerKey, compatName string) string {
if cfg == nil || auth == nil {
return ""
}
apiKey = strings.TrimSpace(apiKey)
if apiKey == "" {
return ""
}
candidates := make([]string, 0, 3)
if v := strings.TrimSpace(compatName); v != "" {
candidates = append(candidates, v)
}
if v := strings.TrimSpace(providerKey); v != "" {
candidates = append(candidates, v)
}
if v := strings.TrimSpace(auth.Provider); v != "" {
candidates = append(candidates, v)
}
for i := range cfg.OpenAICompatibility {
compat := &cfg.OpenAICompatibility[i]
for _, candidate := range candidates {
if candidate != "" && strings.EqualFold(strings.TrimSpace(candidate), compat.Name) {
for j := range compat.APIKeyEntries {
entry := &compat.APIKeyEntries[j]
if strings.EqualFold(strings.TrimSpace(entry.APIKey), apiKey) {
return strings.TrimSpace(entry.ProxyURL)
}
}
return ""
}
}
}
return ""
}
func buildProxyTransport(proxyStr string) *http.Transport {
transport, _, errBuild := proxyutil.BuildHTTPTransport(proxyStr)
if errBuild != nil {
log.WithError(errBuild).Debug("build proxy transport failed")
return nil
}
return transport
}
+190 -151
View File
@@ -2,172 +2,211 @@ package management
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
)
type memoryAuthStore struct {
mu sync.Mutex
items map[string]*coreauth.Auth
}
func TestAPICallTransportDirectBypassesGlobalProxy(t *testing.T) {
t.Parallel()
func (s *memoryAuthStore) List(ctx context.Context) ([]*coreauth.Auth, error) {
_ = ctx
s.mu.Lock()
defer s.mu.Unlock()
out := make([]*coreauth.Auth, 0, len(s.items))
for _, a := range s.items {
out = append(out, a.Clone())
}
return out, nil
}
func (s *memoryAuthStore) Save(ctx context.Context, auth *coreauth.Auth) (string, error) {
_ = ctx
if auth == nil {
return "", nil
}
s.mu.Lock()
if s.items == nil {
s.items = make(map[string]*coreauth.Auth)
}
s.items[auth.ID] = auth.Clone()
s.mu.Unlock()
return auth.ID, nil
}
func (s *memoryAuthStore) Delete(ctx context.Context, id string) error {
_ = ctx
s.mu.Lock()
delete(s.items, id)
s.mu.Unlock()
return nil
}
func TestResolveTokenForAuth_Antigravity_RefreshesExpiredToken(t *testing.T) {
var callCount int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
if r.Method != http.MethodPost {
t.Fatalf("expected POST, got %s", r.Method)
}
if ct := r.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/x-www-form-urlencoded") {
t.Fatalf("unexpected content-type: %s", ct)
}
bodyBytes, _ := io.ReadAll(r.Body)
_ = r.Body.Close()
values, err := url.ParseQuery(string(bodyBytes))
if err != nil {
t.Fatalf("parse form: %v", err)
}
if values.Get("grant_type") != "refresh_token" {
t.Fatalf("unexpected grant_type: %s", values.Get("grant_type"))
}
if values.Get("refresh_token") != "rt" {
t.Fatalf("unexpected refresh_token: %s", values.Get("refresh_token"))
}
if values.Get("client_id") != antigravityOAuthClientID {
t.Fatalf("unexpected client_id: %s", values.Get("client_id"))
}
if values.Get("client_secret") != antigravityOAuthClientSecret {
t.Fatalf("unexpected client_secret")
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": "new-token",
"refresh_token": "rt2",
"expires_in": int64(3600),
"token_type": "Bearer",
})
}))
t.Cleanup(srv.Close)
originalURL := antigravityOAuthTokenURL
antigravityOAuthTokenURL = srv.URL
t.Cleanup(func() { antigravityOAuthTokenURL = originalURL })
store := &memoryAuthStore{}
manager := coreauth.NewManager(store, nil, nil)
auth := &coreauth.Auth{
ID: "antigravity-test.json",
FileName: "antigravity-test.json",
Provider: "antigravity",
Metadata: map[string]any{
"type": "antigravity",
"access_token": "old-token",
"refresh_token": "rt",
"expires_in": int64(3600),
"timestamp": time.Now().Add(-2 * time.Hour).UnixMilli(),
"expired": time.Now().Add(-1 * time.Hour).Format(time.RFC3339),
h := &Handler{
cfg: &config.Config{
SDKConfig: sdkconfig.SDKConfig{ProxyURL: "http://global-proxy.example.com:8080"},
},
}
if _, err := manager.Register(context.Background(), auth); err != nil {
t.Fatalf("register auth: %v", err)
transport := h.apiCallTransport(&coreauth.Auth{ProxyURL: "direct"})
httpTransport, ok := transport.(*http.Transport)
if !ok {
t.Fatalf("transport type = %T, want *http.Transport", transport)
}
if httpTransport.Proxy != nil {
t.Fatal("expected direct transport to disable proxy function")
}
}
func TestAPICallTransportInvalidAuthFallsBackToGlobalProxy(t *testing.T) {
t.Parallel()
h := &Handler{
cfg: &config.Config{
SDKConfig: sdkconfig.SDKConfig{ProxyURL: "http://global-proxy.example.com:8080"},
},
}
transport := h.apiCallTransport(&coreauth.Auth{ProxyURL: "bad-value"})
httpTransport, ok := transport.(*http.Transport)
if !ok {
t.Fatalf("transport type = %T, want *http.Transport", transport)
}
req, errRequest := http.NewRequest(http.MethodGet, "https://example.com", nil)
if errRequest != nil {
t.Fatalf("http.NewRequest returned error: %v", errRequest)
}
proxyURL, errProxy := httpTransport.Proxy(req)
if errProxy != nil {
t.Fatalf("httpTransport.Proxy returned error: %v", errProxy)
}
if proxyURL == nil || proxyURL.String() != "http://global-proxy.example.com:8080" {
t.Fatalf("proxy URL = %v, want http://global-proxy.example.com:8080", proxyURL)
}
}
func TestAPICallTransportAPIKeyAuthFallsBackToConfigProxyURL(t *testing.T) {
t.Parallel()
h := &Handler{
cfg: &config.Config{
SDKConfig: sdkconfig.SDKConfig{ProxyURL: "http://global-proxy.example.com:8080"},
GeminiKey: []config.GeminiKey{{
APIKey: "gemini-key",
ProxyURL: "http://gemini-proxy.example.com:8080",
}},
ClaudeKey: []config.ClaudeKey{{
APIKey: "claude-key",
ProxyURL: "http://claude-proxy.example.com:8080",
}},
CodexKey: []config.CodexKey{{
APIKey: "codex-key",
ProxyURL: "http://codex-proxy.example.com:8080",
}},
OpenAICompatibility: []config.OpenAICompatibility{{
Name: "bohe",
BaseURL: "https://bohe.example.com",
APIKeyEntries: []config.OpenAICompatibilityAPIKey{{
APIKey: "compat-key",
ProxyURL: "http://compat-proxy.example.com:8080",
}},
}},
},
}
cases := []struct {
name string
auth *coreauth.Auth
wantProxy string
}{
{
name: "gemini",
auth: &coreauth.Auth{
Provider: "gemini",
Attributes: map[string]string{"api_key": "gemini-key"},
},
wantProxy: "http://gemini-proxy.example.com:8080",
},
{
name: "claude",
auth: &coreauth.Auth{
Provider: "claude",
Attributes: map[string]string{"api_key": "claude-key"},
},
wantProxy: "http://claude-proxy.example.com:8080",
},
{
name: "codex",
auth: &coreauth.Auth{
Provider: "codex",
Attributes: map[string]string{"api_key": "codex-key"},
},
wantProxy: "http://codex-proxy.example.com:8080",
},
{
name: "openai-compatibility",
auth: &coreauth.Auth{
Provider: "bohe",
Attributes: map[string]string{
"api_key": "compat-key",
"compat_name": "bohe",
"provider_key": "bohe",
},
},
wantProxy: "http://compat-proxy.example.com:8080",
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
transport := h.apiCallTransport(tc.auth)
httpTransport, ok := transport.(*http.Transport)
if !ok {
t.Fatalf("transport type = %T, want *http.Transport", transport)
}
req, errRequest := http.NewRequest(http.MethodGet, "https://example.com", nil)
if errRequest != nil {
t.Fatalf("http.NewRequest returned error: %v", errRequest)
}
proxyURL, errProxy := httpTransport.Proxy(req)
if errProxy != nil {
t.Fatalf("httpTransport.Proxy returned error: %v", errProxy)
}
if proxyURL == nil || proxyURL.String() != tc.wantProxy {
t.Fatalf("proxy URL = %v, want %s", proxyURL, tc.wantProxy)
}
})
}
}
func TestAuthByIndexDistinguishesSharedAPIKeysAcrossProviders(t *testing.T) {
t.Parallel()
manager := coreauth.NewManager(nil, nil, nil)
geminiAuth := &coreauth.Auth{
ID: "gemini:apikey:123",
Provider: "gemini",
Attributes: map[string]string{
"api_key": "shared-key",
},
}
compatAuth := &coreauth.Auth{
ID: "openai-compatibility:bohe:456",
Provider: "bohe",
Label: "bohe",
Attributes: map[string]string{
"api_key": "shared-key",
"compat_name": "bohe",
"provider_key": "bohe",
},
}
if _, errRegister := manager.Register(context.Background(), geminiAuth); errRegister != nil {
t.Fatalf("register gemini auth: %v", errRegister)
}
if _, errRegister := manager.Register(context.Background(), compatAuth); errRegister != nil {
t.Fatalf("register compat auth: %v", errRegister)
}
geminiIndex := geminiAuth.EnsureIndex()
compatIndex := compatAuth.EnsureIndex()
if geminiIndex == compatIndex {
t.Fatalf("shared api key produced duplicate auth_index %q", geminiIndex)
}
h := &Handler{authManager: manager}
token, err := h.resolveTokenForAuth(context.Background(), auth)
if err != nil {
t.Fatalf("resolveTokenForAuth: %v", err)
gotGemini := h.authByIndex(geminiIndex)
if gotGemini == nil {
t.Fatal("expected gemini auth by index")
}
if token != "new-token" {
t.Fatalf("expected refreshed token, got %q", token)
}
if callCount != 1 {
t.Fatalf("expected 1 refresh call, got %d", callCount)
if gotGemini.ID != geminiAuth.ID {
t.Fatalf("authByIndex(gemini) returned %q, want %q", gotGemini.ID, geminiAuth.ID)
}
updated, ok := manager.GetByID(auth.ID)
if !ok || updated == nil {
t.Fatalf("expected auth in manager after update")
gotCompat := h.authByIndex(compatIndex)
if gotCompat == nil {
t.Fatal("expected compat auth by index")
}
if got := tokenValueFromMetadata(updated.Metadata); got != "new-token" {
t.Fatalf("expected manager metadata updated, got %q", got)
}
}
func TestResolveTokenForAuth_Antigravity_SkipsRefreshWhenTokenValid(t *testing.T) {
var callCount int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
w.WriteHeader(http.StatusInternalServerError)
}))
t.Cleanup(srv.Close)
originalURL := antigravityOAuthTokenURL
antigravityOAuthTokenURL = srv.URL
t.Cleanup(func() { antigravityOAuthTokenURL = originalURL })
auth := &coreauth.Auth{
ID: "antigravity-valid.json",
FileName: "antigravity-valid.json",
Provider: "antigravity",
Metadata: map[string]any{
"type": "antigravity",
"access_token": "ok-token",
"expired": time.Now().Add(30 * time.Minute).Format(time.RFC3339),
},
}
h := &Handler{}
token, err := h.resolveTokenForAuth(context.Background(), auth)
if err != nil {
t.Fatalf("resolveTokenForAuth: %v", err)
}
if token != "ok-token" {
t.Fatalf("expected existing token, got %q", token)
}
if callCount != 0 {
t.Fatalf("expected no refresh calls, got %d", callCount)
if gotCompat.ID != compatAuth.ID {
t.Fatalf("authByIndex(compat) returned %q, want %q", gotCompat.ID, compatAuth.ID)
}
}
+540 -73
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io"
"mime/multipart"
"net"
"net/http"
"os"
@@ -57,8 +58,10 @@ type callbackForwarder struct {
}
var (
callbackForwardersMu sync.Mutex
callbackForwarders = make(map[int]*callbackForwarder)
callbackForwardersMu sync.Mutex
callbackForwarders = make(map[int]*callbackForwarder)
errAuthFileMustBeJSON = errors.New("auth file must be .json")
errAuthFileNotFound = errors.New("auth file not found")
)
func extractLastRefreshTimestamp(meta map[string]any) (time.Time, bool) {
@@ -332,6 +335,21 @@ func (h *Handler) listAuthFilesFromDisk(c *gin.Context) {
emailValue := gjson.GetBytes(data, "email").String()
fileData["type"] = typeValue
fileData["email"] = emailValue
if pv := gjson.GetBytes(data, "priority"); pv.Exists() {
switch pv.Type {
case gjson.Number:
fileData["priority"] = int(pv.Int())
case gjson.String:
if parsed, errAtoi := strconv.Atoi(strings.TrimSpace(pv.String())); errAtoi == nil {
fileData["priority"] = parsed
}
}
}
if nv := gjson.GetBytes(data, "note"); nv.Exists() && nv.Type == gjson.String {
if trimmed := strings.TrimSpace(nv.String()); trimmed != "" {
fileData["note"] = trimmed
}
}
}
files = append(files, fileData)
@@ -415,6 +433,37 @@ func (h *Handler) buildAuthFileEntry(auth *coreauth.Auth) gin.H {
if claims := extractCodexIDTokenClaims(auth); claims != nil {
entry["id_token"] = claims
}
// Expose priority from Attributes (set by synthesizer from JSON "priority" field).
// Fall back to Metadata for auths registered via UploadAuthFile (no synthesizer).
if p := strings.TrimSpace(authAttribute(auth, "priority")); p != "" {
if parsed, err := strconv.Atoi(p); err == nil {
entry["priority"] = parsed
}
} else if auth.Metadata != nil {
if rawPriority, ok := auth.Metadata["priority"]; ok {
switch v := rawPriority.(type) {
case float64:
entry["priority"] = int(v)
case int:
entry["priority"] = v
case string:
if parsed, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
entry["priority"] = parsed
}
}
}
}
// Expose note from Attributes (set by synthesizer from JSON "note" field).
// Fall back to Metadata for auths registered via UploadAuthFile (no synthesizer).
if note := strings.TrimSpace(authAttribute(auth, "note")); note != "" {
entry["note"] = note
} else if auth.Metadata != nil {
if rawNote, ok := auth.Metadata["note"].(string); ok {
if trimmed := strings.TrimSpace(rawNote); trimmed != "" {
entry["note"] = trimmed
}
}
}
return entry
}
@@ -492,10 +541,23 @@ func isRuntimeOnlyAuth(auth *coreauth.Auth) bool {
return strings.EqualFold(strings.TrimSpace(auth.Attributes["runtime_only"]), "true")
}
func isUnsafeAuthFileName(name string) bool {
if strings.TrimSpace(name) == "" {
return true
}
if strings.ContainsAny(name, "/\\") {
return true
}
if filepath.VolumeName(name) != "" {
return true
}
return false
}
// Download single auth file by name
func (h *Handler) DownloadAuthFile(c *gin.Context) {
name := c.Query("name")
if name == "" || strings.Contains(name, string(os.PathSeparator)) {
name := strings.TrimSpace(c.Query("name"))
if isUnsafeAuthFileName(name) {
c.JSON(400, gin.H{"error": "invalid name"})
return
}
@@ -524,36 +586,61 @@ func (h *Handler) UploadAuthFile(c *gin.Context) {
return
}
ctx := c.Request.Context()
if file, err := c.FormFile("file"); err == nil && file != nil {
name := filepath.Base(file.Filename)
if !strings.HasSuffix(strings.ToLower(name), ".json") {
c.JSON(400, gin.H{"error": "file must be .json"})
return
}
dst := filepath.Join(h.cfg.AuthDir, name)
if !filepath.IsAbs(dst) {
if abs, errAbs := filepath.Abs(dst); errAbs == nil {
dst = abs
}
}
if errSave := c.SaveUploadedFile(file, dst); errSave != nil {
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to save file: %v", errSave)})
return
}
data, errRead := os.ReadFile(dst)
if errRead != nil {
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to read saved file: %v", errRead)})
return
}
if errReg := h.registerAuthFromFile(ctx, dst, data); errReg != nil {
c.JSON(500, gin.H{"error": errReg.Error()})
return
}
c.JSON(200, gin.H{"status": "ok"})
fileHeaders, errMultipart := h.multipartAuthFileHeaders(c)
if errMultipart != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid multipart form: %v", errMultipart)})
return
}
name := c.Query("name")
if name == "" || strings.Contains(name, string(os.PathSeparator)) {
if len(fileHeaders) == 1 {
if _, errUpload := h.storeUploadedAuthFile(ctx, fileHeaders[0]); errUpload != nil {
if errors.Is(errUpload, errAuthFileMustBeJSON) {
c.JSON(http.StatusBadRequest, gin.H{"error": "file must be .json"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": errUpload.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
if len(fileHeaders) > 1 {
uploaded := make([]string, 0, len(fileHeaders))
failed := make([]gin.H, 0)
for _, file := range fileHeaders {
name, errUpload := h.storeUploadedAuthFile(ctx, file)
if errUpload != nil {
failureName := ""
if file != nil {
failureName = filepath.Base(file.Filename)
}
msg := errUpload.Error()
if errors.Is(errUpload, errAuthFileMustBeJSON) {
msg = "file must be .json"
}
failed = append(failed, gin.H{"name": failureName, "error": msg})
continue
}
uploaded = append(uploaded, name)
}
if len(failed) > 0 {
c.JSON(http.StatusMultiStatus, gin.H{
"status": "partial",
"uploaded": len(uploaded),
"files": uploaded,
"failed": failed,
})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok", "uploaded": len(uploaded), "files": uploaded})
return
}
if c.ContentType() == "multipart/form-data" {
c.JSON(http.StatusBadRequest, gin.H{"error": "no files uploaded"})
return
}
name := strings.TrimSpace(c.Query("name"))
if isUnsafeAuthFileName(name) {
c.JSON(400, gin.H{"error": "invalid name"})
return
}
@@ -566,17 +653,7 @@ func (h *Handler) UploadAuthFile(c *gin.Context) {
c.JSON(400, gin.H{"error": "failed to read body"})
return
}
dst := filepath.Join(h.cfg.AuthDir, filepath.Base(name))
if !filepath.IsAbs(dst) {
if abs, errAbs := filepath.Abs(dst); errAbs == nil {
dst = abs
}
}
if errWrite := os.WriteFile(dst, data, 0o600); errWrite != nil {
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to write file: %v", errWrite)})
return
}
if err = h.registerAuthFromFile(ctx, dst, data); err != nil {
if err = h.writeAuthFile(ctx, filepath.Base(name), data); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
@@ -623,11 +700,172 @@ func (h *Handler) DeleteAuthFile(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok", "deleted": deleted})
return
}
name := c.Query("name")
if name == "" || strings.Contains(name, string(os.PathSeparator)) {
names, errNames := requestedAuthFileNamesForDelete(c)
if errNames != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": errNames.Error()})
return
}
if len(names) == 0 {
c.JSON(400, gin.H{"error": "invalid name"})
return
}
if len(names) == 1 {
if _, status, errDelete := h.deleteAuthFileByName(ctx, names[0]); errDelete != nil {
c.JSON(status, gin.H{"error": errDelete.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
deletedFiles := make([]string, 0, len(names))
failed := make([]gin.H, 0)
for _, name := range names {
deletedName, _, errDelete := h.deleteAuthFileByName(ctx, name)
if errDelete != nil {
failed = append(failed, gin.H{"name": name, "error": errDelete.Error()})
continue
}
deletedFiles = append(deletedFiles, deletedName)
}
if len(failed) > 0 {
c.JSON(http.StatusMultiStatus, gin.H{
"status": "partial",
"deleted": len(deletedFiles),
"files": deletedFiles,
"failed": failed,
})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok", "deleted": len(deletedFiles), "files": deletedFiles})
}
func (h *Handler) multipartAuthFileHeaders(c *gin.Context) ([]*multipart.FileHeader, error) {
if h == nil || c == nil || c.ContentType() != "multipart/form-data" {
return nil, nil
}
form, err := c.MultipartForm()
if err != nil {
return nil, err
}
if form == nil || len(form.File) == 0 {
return nil, nil
}
keys := make([]string, 0, len(form.File))
for key := range form.File {
keys = append(keys, key)
}
sort.Strings(keys)
headers := make([]*multipart.FileHeader, 0)
for _, key := range keys {
headers = append(headers, form.File[key]...)
}
return headers, nil
}
func (h *Handler) storeUploadedAuthFile(ctx context.Context, file *multipart.FileHeader) (string, error) {
if file == nil {
return "", fmt.Errorf("no file uploaded")
}
name := filepath.Base(strings.TrimSpace(file.Filename))
if !strings.HasSuffix(strings.ToLower(name), ".json") {
return "", errAuthFileMustBeJSON
}
src, err := file.Open()
if err != nil {
return "", fmt.Errorf("failed to open uploaded file: %w", err)
}
defer src.Close()
data, err := io.ReadAll(src)
if err != nil {
return "", fmt.Errorf("failed to read uploaded file: %w", err)
}
if err := h.writeAuthFile(ctx, name, data); err != nil {
return "", err
}
return name, nil
}
func (h *Handler) writeAuthFile(ctx context.Context, name string, data []byte) error {
dst := filepath.Join(h.cfg.AuthDir, filepath.Base(name))
if !filepath.IsAbs(dst) {
if abs, errAbs := filepath.Abs(dst); errAbs == nil {
dst = abs
}
}
return h.commitUploadedAuthFile(ctx, dst, data)
}
func requestedAuthFileNamesForDelete(c *gin.Context) ([]string, error) {
if c == nil {
return nil, nil
}
names := uniqueAuthFileNames(c.QueryArray("name"))
if len(names) > 0 {
return names, nil
}
body, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body")
}
body = bytes.TrimSpace(body)
if len(body) == 0 {
return nil, nil
}
var objectBody struct {
Name string `json:"name"`
Names []string `json:"names"`
}
if body[0] == '[' {
var arrayBody []string
if err := json.Unmarshal(body, &arrayBody); err != nil {
return nil, fmt.Errorf("invalid request body")
}
return uniqueAuthFileNames(arrayBody), nil
}
if err := json.Unmarshal(body, &objectBody); err != nil {
return nil, fmt.Errorf("invalid request body")
}
out := make([]string, 0, len(objectBody.Names)+1)
if strings.TrimSpace(objectBody.Name) != "" {
out = append(out, objectBody.Name)
}
out = append(out, objectBody.Names...)
return uniqueAuthFileNames(out), nil
}
func uniqueAuthFileNames(names []string) []string {
if len(names) == 0 {
return nil
}
seen := make(map[string]struct{}, len(names))
out := make([]string, 0, len(names))
for _, name := range names {
name = strings.TrimSpace(name)
if name == "" {
continue
}
if _, ok := seen[name]; ok {
continue
}
seen[name] = struct{}{}
out = append(out, name)
}
return out
}
func (h *Handler) deleteAuthFileByName(ctx context.Context, name string) (string, int, error) {
name = strings.TrimSpace(name)
if isUnsafeAuthFileName(name) {
return "", http.StatusBadRequest, fmt.Errorf("invalid name")
}
targetPath := filepath.Join(h.cfg.AuthDir, filepath.Base(name))
targetID := ""
@@ -644,22 +882,19 @@ func (h *Handler) DeleteAuthFile(c *gin.Context) {
}
if errRemove := os.Remove(targetPath); errRemove != nil {
if os.IsNotExist(errRemove) {
c.JSON(404, gin.H{"error": "file not found"})
} else {
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to remove file: %v", errRemove)})
return filepath.Base(name), http.StatusNotFound, errAuthFileNotFound
}
return
return filepath.Base(name), http.StatusInternalServerError, fmt.Errorf("failed to remove file: %w", errRemove)
}
if errDeleteRecord := h.deleteTokenRecord(ctx, targetPath); errDeleteRecord != nil {
c.JSON(500, gin.H{"error": errDeleteRecord.Error()})
return
return filepath.Base(name), http.StatusInternalServerError, errDeleteRecord
}
if targetID != "" {
h.disableAuth(ctx, targetID)
} else {
h.disableAuth(ctx, targetPath)
}
c.JSON(200, gin.H{"status": "ok"})
return filepath.Base(name), http.StatusOK, nil
}
func (h *Handler) findAuthForDelete(name string) *coreauth.Auth {
@@ -693,10 +928,25 @@ func (h *Handler) authIDForPath(path string) string {
if path == "" {
return ""
}
path = filepath.Clean(path)
if !filepath.IsAbs(path) {
if abs, errAbs := filepath.Abs(path); errAbs == nil {
path = abs
}
}
id := path
if h != nil && h.cfg != nil {
authDir := strings.TrimSpace(h.cfg.AuthDir)
if resolvedAuthDir, errResolve := util.ResolveAuthDir(authDir); errResolve == nil && resolvedAuthDir != "" {
authDir = resolvedAuthDir
}
if authDir != "" {
authDir = filepath.Clean(authDir)
if !filepath.IsAbs(authDir) {
if abs, errAbs := filepath.Abs(authDir); errAbs == nil {
authDir = abs
}
}
if rel, errRel := filepath.Rel(authDir, path); errRel == nil && rel != "" {
id = rel
}
@@ -713,19 +963,53 @@ func (h *Handler) registerAuthFromFile(ctx context.Context, path string, data []
if h.authManager == nil {
return nil
}
if path == "" {
return fmt.Errorf("auth path is empty")
auth, hasLastRefresh, err := h.buildAuthFromFileData(path, data)
if err != nil {
return err
}
return h.registerManagedAuth(ctx, auth, hasLastRefresh)
}
func (h *Handler) commitUploadedAuthFile(ctx context.Context, path string, data []byte) error {
if _, _, err := h.buildAuthFromFileData(path, data); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return fmt.Errorf("failed to prepare auth dir: %w", err)
}
previousData, errRead := os.ReadFile(path)
hadPrevious := errRead == nil
if errRead != nil && !os.IsNotExist(errRead) {
return fmt.Errorf("failed to read existing auth file: %w", errRead)
}
if err := os.WriteFile(path, data, 0o600); err != nil {
return fmt.Errorf("failed to write file: %w", err)
}
if err := h.registerAuthFromFile(ctx, path, data); err != nil {
if hadPrevious {
_ = os.WriteFile(path, previousData, 0o600)
} else {
_ = os.Remove(path)
}
return err
}
return nil
}
func (h *Handler) buildAuthFromFileData(path string, data []byte) (*coreauth.Auth, bool, error) {
if strings.TrimSpace(path) == "" {
return nil, false, fmt.Errorf("auth path is empty")
}
if data == nil {
var err error
data, err = os.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read auth file: %w", err)
return nil, false, fmt.Errorf("failed to read auth file: %w", err)
}
}
metadata := make(map[string]any)
if err := json.Unmarshal(data, &metadata); err != nil {
return fmt.Errorf("invalid auth file: %w", err)
return nil, false, fmt.Errorf("invalid auth file: %w", err)
}
provider, _ := metadata["type"].(string)
if provider == "" {
@@ -756,10 +1040,40 @@ func (h *Handler) registerAuthFromFile(ctx context.Context, path string, data []
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if prefix, ok := authStringMetadata(metadata["prefix"]); ok {
auth.Prefix = prefix
auth.Attributes["prefix"] = prefix
}
if proxyURL, ok := authStringMetadata(metadata["proxy_url"]); ok {
auth.ProxyURL = proxyURL
auth.Attributes["proxy_url"] = proxyURL
}
if priority, ok := authIntMetadata(metadata["priority"]); ok {
auth.Priority = priority
auth.Attributes["priority"] = strconv.Itoa(priority)
}
if hasLastRefresh {
auth.LastRefreshedAt = lastRefresh
}
if existing, ok := h.authManager.GetByID(authID); ok {
if h != nil && h.authManager != nil {
if existing, ok := h.authManager.GetByID(authID); ok {
auth.CreatedAt = existing.CreatedAt
if !hasLastRefresh {
auth.LastRefreshedAt = existing.LastRefreshedAt
}
auth.NextRefreshAfter = existing.NextRefreshAfter
auth.Runtime = existing.Runtime
}
}
coreauth.ApplyCustomHeadersFromMetadata(auth)
return auth, hasLastRefresh, nil
}
func (h *Handler) registerManagedAuth(ctx context.Context, auth *coreauth.Auth, hasLastRefresh bool) error {
if h.authManager == nil {
return nil
}
if existing, ok := h.authManager.GetByID(auth.ID); ok {
auth.CreatedAt = existing.CreatedAt
if !hasLastRefresh {
auth.LastRefreshedAt = existing.LastRefreshedAt
@@ -839,7 +1153,7 @@ func (h *Handler) PatchAuthFileStatus(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok", "disabled": *req.Disabled})
}
// PatchAuthFileFields updates editable fields (prefix, proxy_url, priority) of an auth file.
// PatchAuthFileFields updates editable fields (prefix, proxy_url, headers, priority, note) of an auth file.
func (h *Handler) PatchAuthFileFields(c *gin.Context) {
if h.authManager == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
@@ -847,10 +1161,12 @@ func (h *Handler) PatchAuthFileFields(c *gin.Context) {
}
var req struct {
Name string `json:"name"`
Prefix *string `json:"prefix"`
ProxyURL *string `json:"proxy_url"`
Priority *int `json:"priority"`
Name string `json:"name"`
Prefix *string `json:"prefix"`
ProxyURL *string `json:"proxy_url"`
Headers map[string]string `json:"headers"`
Priority *int `json:"priority"`
Note *string `json:"note"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
@@ -886,21 +1202,143 @@ func (h *Handler) PatchAuthFileFields(c *gin.Context) {
changed := false
if req.Prefix != nil {
targetAuth.Prefix = *req.Prefix
changed = true
}
if req.ProxyURL != nil {
targetAuth.ProxyURL = *req.ProxyURL
changed = true
}
if req.Priority != nil {
prefix := strings.TrimSpace(*req.Prefix)
targetAuth.Prefix = prefix
if targetAuth.Metadata == nil {
targetAuth.Metadata = make(map[string]any)
}
if *req.Priority == 0 {
delete(targetAuth.Metadata, "priority")
if targetAuth.Attributes == nil {
targetAuth.Attributes = make(map[string]string)
}
if prefix == "" {
delete(targetAuth.Metadata, "prefix")
delete(targetAuth.Attributes, "prefix")
} else {
targetAuth.Metadata["priority"] = *req.Priority
targetAuth.Metadata["prefix"] = prefix
targetAuth.Attributes["prefix"] = prefix
}
changed = true
}
if req.ProxyURL != nil {
proxyURL := strings.TrimSpace(*req.ProxyURL)
targetAuth.ProxyURL = proxyURL
if targetAuth.Metadata == nil {
targetAuth.Metadata = make(map[string]any)
}
if targetAuth.Attributes == nil {
targetAuth.Attributes = make(map[string]string)
}
if proxyURL == "" {
delete(targetAuth.Metadata, "proxy_url")
delete(targetAuth.Attributes, "proxy_url")
} else {
targetAuth.Metadata["proxy_url"] = proxyURL
targetAuth.Attributes["proxy_url"] = proxyURL
}
changed = true
}
if len(req.Headers) > 0 {
existingHeaders := coreauth.ExtractCustomHeadersFromMetadata(targetAuth.Metadata)
nextHeaders := make(map[string]string, len(existingHeaders))
for k, v := range existingHeaders {
nextHeaders[k] = v
}
headerChanged := false
for key, value := range req.Headers {
name := strings.TrimSpace(key)
if name == "" {
continue
}
val := strings.TrimSpace(value)
attrKey := "header:" + name
if val == "" {
if _, ok := nextHeaders[name]; ok {
delete(nextHeaders, name)
headerChanged = true
}
if targetAuth.Attributes != nil {
if _, ok := targetAuth.Attributes[attrKey]; ok {
headerChanged = true
}
}
continue
}
if prev, ok := nextHeaders[name]; !ok || prev != val {
headerChanged = true
}
nextHeaders[name] = val
if targetAuth.Attributes != nil {
if prev, ok := targetAuth.Attributes[attrKey]; !ok || prev != val {
headerChanged = true
}
} else {
headerChanged = true
}
}
if headerChanged {
if targetAuth.Metadata == nil {
targetAuth.Metadata = make(map[string]any)
}
if targetAuth.Attributes == nil {
targetAuth.Attributes = make(map[string]string)
}
for key, value := range req.Headers {
name := strings.TrimSpace(key)
if name == "" {
continue
}
val := strings.TrimSpace(value)
attrKey := "header:" + name
if val == "" {
delete(nextHeaders, name)
delete(targetAuth.Attributes, attrKey)
continue
}
nextHeaders[name] = val
targetAuth.Attributes[attrKey] = val
}
if len(nextHeaders) == 0 {
delete(targetAuth.Metadata, "headers")
} else {
metaHeaders := make(map[string]any, len(nextHeaders))
for k, v := range nextHeaders {
metaHeaders[k] = v
}
targetAuth.Metadata["headers"] = metaHeaders
}
changed = true
}
}
if req.Priority != nil || req.Note != nil {
if targetAuth.Metadata == nil {
targetAuth.Metadata = make(map[string]any)
}
if targetAuth.Attributes == nil {
targetAuth.Attributes = make(map[string]string)
}
if req.Priority != nil {
targetAuth.Priority = *req.Priority
if *req.Priority == 0 {
delete(targetAuth.Metadata, "priority")
delete(targetAuth.Attributes, "priority")
} else {
targetAuth.Metadata["priority"] = *req.Priority
targetAuth.Attributes["priority"] = strconv.Itoa(*req.Priority)
}
}
if req.Note != nil {
trimmedNote := strings.TrimSpace(*req.Note)
if trimmedNote == "" {
delete(targetAuth.Metadata, "note")
delete(targetAuth.Attributes, "note")
} else {
targetAuth.Metadata["note"] = trimmedNote
targetAuth.Attributes["note"] = trimmedNote
}
}
changed = true
}
@@ -920,6 +1358,35 @@ func (h *Handler) PatchAuthFileFields(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func authStringMetadata(value any) (string, bool) {
s, ok := value.(string)
if !ok {
return "", false
}
return strings.TrimSpace(s), true
}
func authIntMetadata(value any) (int, bool) {
switch v := value.(type) {
case int:
return v, true
case int32:
return int(v), true
case int64:
return int(v), true
case float64:
return int(v), true
case json.Number:
n, err := v.Int64()
if err != nil {
return 0, false
}
return int(n), true
default:
return 0, false
}
}
func (h *Handler) disableAuth(ctx context.Context, id string) {
if h == nil || h.authManager == nil {
return
@@ -0,0 +1,197 @@
package management
import (
"bytes"
"encoding/json"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
func TestUploadAuthFile_BatchMultipart(t *testing.T) {
t.Setenv("MANAGEMENT_PASSWORD", "")
gin.SetMode(gin.TestMode)
authDir := t.TempDir()
manager := coreauth.NewManager(nil, nil, nil)
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
files := []struct {
name string
content string
}{
{name: "alpha.json", content: `{"type":"codex","email":"alpha@example.com"}`},
{name: "beta.json", content: `{"type":"claude","email":"beta@example.com"}`},
}
var body bytes.Buffer
writer := multipart.NewWriter(&body)
for _, file := range files {
part, err := writer.CreateFormFile("file", file.name)
if err != nil {
t.Fatalf("failed to create multipart file: %v", err)
}
if _, err = part.Write([]byte(file.content)); err != nil {
t.Fatalf("failed to write multipart content: %v", err)
}
}
if err := writer.Close(); err != nil {
t.Fatalf("failed to close multipart writer: %v", err)
}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
req := httptest.NewRequest(http.MethodPost, "/v0/management/auth-files", &body)
req.Header.Set("Content-Type", writer.FormDataContentType())
ctx.Request = req
h.UploadAuthFile(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("expected upload status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
}
var payload map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if got, ok := payload["uploaded"].(float64); !ok || int(got) != len(files) {
t.Fatalf("expected uploaded=%d, got %#v", len(files), payload["uploaded"])
}
for _, file := range files {
fullPath := filepath.Join(authDir, file.name)
data, err := os.ReadFile(fullPath)
if err != nil {
t.Fatalf("expected uploaded file %s to exist: %v", file.name, err)
}
if string(data) != file.content {
t.Fatalf("expected file %s content %q, got %q", file.name, file.content, string(data))
}
}
auths := manager.List()
if len(auths) != len(files) {
t.Fatalf("expected %d auth entries, got %d", len(files), len(auths))
}
}
func TestUploadAuthFile_BatchMultipart_InvalidJSONDoesNotOverwriteExistingFile(t *testing.T) {
t.Setenv("MANAGEMENT_PASSWORD", "")
gin.SetMode(gin.TestMode)
authDir := t.TempDir()
manager := coreauth.NewManager(nil, nil, nil)
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
existingName := "alpha.json"
existingContent := `{"type":"codex","email":"alpha@example.com"}`
if err := os.WriteFile(filepath.Join(authDir, existingName), []byte(existingContent), 0o600); err != nil {
t.Fatalf("failed to seed existing auth file: %v", err)
}
files := []struct {
name string
content string
}{
{name: existingName, content: `{"type":"codex"`},
{name: "beta.json", content: `{"type":"claude","email":"beta@example.com"}`},
}
var body bytes.Buffer
writer := multipart.NewWriter(&body)
for _, file := range files {
part, err := writer.CreateFormFile("file", file.name)
if err != nil {
t.Fatalf("failed to create multipart file: %v", err)
}
if _, err = part.Write([]byte(file.content)); err != nil {
t.Fatalf("failed to write multipart content: %v", err)
}
}
if err := writer.Close(); err != nil {
t.Fatalf("failed to close multipart writer: %v", err)
}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
req := httptest.NewRequest(http.MethodPost, "/v0/management/auth-files", &body)
req.Header.Set("Content-Type", writer.FormDataContentType())
ctx.Request = req
h.UploadAuthFile(ctx)
if rec.Code != http.StatusMultiStatus {
t.Fatalf("expected upload status %d, got %d with body %s", http.StatusMultiStatus, rec.Code, rec.Body.String())
}
data, err := os.ReadFile(filepath.Join(authDir, existingName))
if err != nil {
t.Fatalf("expected existing auth file to remain readable: %v", err)
}
if string(data) != existingContent {
t.Fatalf("expected existing auth file to remain %q, got %q", existingContent, string(data))
}
betaData, err := os.ReadFile(filepath.Join(authDir, "beta.json"))
if err != nil {
t.Fatalf("expected valid auth file to be created: %v", err)
}
if string(betaData) != files[1].content {
t.Fatalf("expected beta auth file content %q, got %q", files[1].content, string(betaData))
}
}
func TestDeleteAuthFile_BatchQuery(t *testing.T) {
t.Setenv("MANAGEMENT_PASSWORD", "")
gin.SetMode(gin.TestMode)
authDir := t.TempDir()
files := []string{"alpha.json", "beta.json"}
for _, name := range files {
if err := os.WriteFile(filepath.Join(authDir, name), []byte(`{"type":"codex"}`), 0o600); err != nil {
t.Fatalf("failed to write auth file %s: %v", name, err)
}
}
manager := coreauth.NewManager(nil, nil, nil)
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
h.tokenStore = &memoryAuthStore{}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
req := httptest.NewRequest(
http.MethodDelete,
"/v0/management/auth-files?name="+url.QueryEscape(files[0])+"&name="+url.QueryEscape(files[1]),
nil,
)
ctx.Request = req
h.DeleteAuthFile(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("expected delete status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
}
var payload map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if got, ok := payload["deleted"].(float64); !ok || int(got) != len(files) {
t.Fatalf("expected deleted=%d, got %#v", len(files), payload["deleted"])
}
for _, name := range files {
if _, err := os.Stat(filepath.Join(authDir, name)); !os.IsNotExist(err) {
t.Fatalf("expected auth file %s to be removed, stat err: %v", name, err)
}
}
}
@@ -0,0 +1,62 @@
package management
import (
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
)
func TestDownloadAuthFile_ReturnsFile(t *testing.T) {
t.Setenv("MANAGEMENT_PASSWORD", "")
gin.SetMode(gin.TestMode)
authDir := t.TempDir()
fileName := "download-user.json"
expected := []byte(`{"type":"codex"}`)
if err := os.WriteFile(filepath.Join(authDir, fileName), expected, 0o600); err != nil {
t.Fatalf("failed to write auth file: %v", err)
}
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/auth-files/download?name="+url.QueryEscape(fileName), nil)
h.DownloadAuthFile(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("expected download status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
}
if got := rec.Body.Bytes(); string(got) != string(expected) {
t.Fatalf("unexpected download content: %q", string(got))
}
}
func TestDownloadAuthFile_RejectsPathSeparators(t *testing.T) {
t.Setenv("MANAGEMENT_PASSWORD", "")
gin.SetMode(gin.TestMode)
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, nil)
for _, name := range []string{
"../external/secret.json",
`..\\external\\secret.json`,
"nested/secret.json",
`nested\\secret.json`,
} {
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/auth-files/download?name="+url.QueryEscape(name), nil)
h.DownloadAuthFile(ctx)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected %d for name %q, got %d with body %s", http.StatusBadRequest, name, rec.Code, rec.Body.String())
}
}
}
@@ -0,0 +1,51 @@
//go:build windows
package management
import (
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
)
func TestDownloadAuthFile_PreventsWindowsSlashTraversal(t *testing.T) {
t.Setenv("MANAGEMENT_PASSWORD", "")
gin.SetMode(gin.TestMode)
tempDir := t.TempDir()
authDir := filepath.Join(tempDir, "auth")
externalDir := filepath.Join(tempDir, "external")
if err := os.MkdirAll(authDir, 0o700); err != nil {
t.Fatalf("failed to create auth dir: %v", err)
}
if err := os.MkdirAll(externalDir, 0o700); err != nil {
t.Fatalf("failed to create external dir: %v", err)
}
secretName := "secret.json"
secretPath := filepath.Join(externalDir, secretName)
if err := os.WriteFile(secretPath, []byte(`{"secret":true}`), 0o600); err != nil {
t.Fatalf("failed to write external file: %v", err)
}
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Request = httptest.NewRequest(
http.MethodGet,
"/v0/management/auth-files/download?name="+url.QueryEscape("../external/"+secretName),
nil,
)
h.DownloadAuthFile(ctx)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d with body %s", http.StatusBadRequest, rec.Code, rec.Body.String())
}
}
@@ -0,0 +1,164 @@
package management
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
func TestPatchAuthFileFields_MergeHeadersAndDeleteEmptyValues(t *testing.T) {
t.Setenv("MANAGEMENT_PASSWORD", "")
gin.SetMode(gin.TestMode)
store := &memoryAuthStore{}
manager := coreauth.NewManager(store, nil, nil)
record := &coreauth.Auth{
ID: "test.json",
FileName: "test.json",
Provider: "claude",
Attributes: map[string]string{
"path": "/tmp/test.json",
"header:X-Old": "old",
"header:X-Remove": "gone",
},
Metadata: map[string]any{
"type": "claude",
"headers": map[string]any{
"X-Old": "old",
"X-Remove": "gone",
},
},
}
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
t.Fatalf("failed to register auth record: %v", errRegister)
}
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
body := `{"name":"test.json","prefix":"p1","proxy_url":"http://proxy.local","headers":{"X-Old":"new","X-New":"v","X-Remove":" ","X-Nope":""}}`
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
ctx.Request = req
h.PatchAuthFileFields(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
}
updated, ok := manager.GetByID("test.json")
if !ok || updated == nil {
t.Fatalf("expected auth record to exist after patch")
}
if updated.Prefix != "p1" {
t.Fatalf("prefix = %q, want %q", updated.Prefix, "p1")
}
if updated.ProxyURL != "http://proxy.local" {
t.Fatalf("proxy_url = %q, want %q", updated.ProxyURL, "http://proxy.local")
}
if updated.Metadata == nil {
t.Fatalf("expected metadata to be non-nil")
}
if got, _ := updated.Metadata["prefix"].(string); got != "p1" {
t.Fatalf("metadata.prefix = %q, want %q", got, "p1")
}
if got, _ := updated.Metadata["proxy_url"].(string); got != "http://proxy.local" {
t.Fatalf("metadata.proxy_url = %q, want %q", got, "http://proxy.local")
}
headersMeta, ok := updated.Metadata["headers"].(map[string]any)
if !ok {
raw, _ := json.Marshal(updated.Metadata["headers"])
t.Fatalf("metadata.headers = %T (%s), want map[string]any", updated.Metadata["headers"], string(raw))
}
if got := headersMeta["X-Old"]; got != "new" {
t.Fatalf("metadata.headers.X-Old = %#v, want %q", got, "new")
}
if got := headersMeta["X-New"]; got != "v" {
t.Fatalf("metadata.headers.X-New = %#v, want %q", got, "v")
}
if _, ok := headersMeta["X-Remove"]; ok {
t.Fatalf("expected metadata.headers.X-Remove to be deleted")
}
if _, ok := headersMeta["X-Nope"]; ok {
t.Fatalf("expected metadata.headers.X-Nope to be absent")
}
if got := updated.Attributes["header:X-Old"]; got != "new" {
t.Fatalf("attrs header:X-Old = %q, want %q", got, "new")
}
if got := updated.Attributes["header:X-New"]; got != "v" {
t.Fatalf("attrs header:X-New = %q, want %q", got, "v")
}
if _, ok := updated.Attributes["header:X-Remove"]; ok {
t.Fatalf("expected attrs header:X-Remove to be deleted")
}
if _, ok := updated.Attributes["header:X-Nope"]; ok {
t.Fatalf("expected attrs header:X-Nope to be absent")
}
}
func TestPatchAuthFileFields_HeadersEmptyMapIsNoop(t *testing.T) {
t.Setenv("MANAGEMENT_PASSWORD", "")
gin.SetMode(gin.TestMode)
store := &memoryAuthStore{}
manager := coreauth.NewManager(store, nil, nil)
record := &coreauth.Auth{
ID: "noop.json",
FileName: "noop.json",
Provider: "claude",
Attributes: map[string]string{
"path": "/tmp/noop.json",
"header:X-Kee": "1",
},
Metadata: map[string]any{
"type": "claude",
"headers": map[string]any{
"X-Kee": "1",
},
},
}
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
t.Fatalf("failed to register auth record: %v", errRegister)
}
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
body := `{"name":"noop.json","note":"hello","headers":{}}`
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
ctx.Request = req
h.PatchAuthFileFields(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
}
updated, ok := manager.GetByID("noop.json")
if !ok || updated == nil {
t.Fatalf("expected auth record to exist after patch")
}
if got := updated.Attributes["header:X-Kee"]; got != "1" {
t.Fatalf("attrs header:X-Kee = %q, want %q", got, "1")
}
headersMeta, ok := updated.Metadata["headers"].(map[string]any)
if !ok {
t.Fatalf("expected metadata.headers to remain a map, got %T", updated.Metadata["headers"])
}
if got := headersMeta["X-Kee"]; got != "1" {
t.Fatalf("metadata.headers.X-Kee = %#v, want %q", got, "1")
}
}
@@ -2,6 +2,7 @@ package management
import (
"net/http"
"strconv"
"strings"
"time"
@@ -38,6 +39,19 @@ func (h *Handler) SetAuthPriority(c *gin.Context) {
}
auth.Priority = *req.Priority
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
if auth.Attributes == nil {
auth.Attributes = make(map[string]string)
}
if *req.Priority == 0 {
delete(auth.Metadata, "priority")
delete(auth.Attributes, "priority")
} else {
auth.Metadata["priority"] = *req.Priority
auth.Attributes["priority"] = strconv.Itoa(*req.Priority)
}
auth.UpdatedAt = time.Now()
updated, err := h.authManager.Update(c.Request.Context(), auth)
@@ -28,7 +28,7 @@ func (h *Handler) GetConfig(c *gin.Context) {
c.JSON(200, gin.H{})
return
}
c.JSON(200, new(*h.cfg))
c.JSON(200, h.cfg)
}
type releaseInfo struct {
@@ -158,7 +158,8 @@ func (h *Handler) PutConfigYAML(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "reload_failed", "message": err.Error()})
return
}
h.cfg = newCfg
h.cfg = cloneConfig(newCfg)
h.committedCfg = cloneConfig(h.cfg)
c.JSON(http.StatusOK, gin.H{"ok": true, "changed": []string{"config"}})
}
@@ -183,14 +184,16 @@ func (h *Handler) GetConfigYAML(c *gin.Context) {
// Debug
func (h *Handler) GetDebug(c *gin.Context) { c.JSON(200, gin.H{"debug": h.cfg.Debug}) }
func (h *Handler) PutDebug(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.Debug = v }) }
func (h *Handler) PutDebug(c *gin.Context) {
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.Debug = v })
}
// UsageStatisticsEnabled
func (h *Handler) GetUsageStatisticsEnabled(c *gin.Context) {
c.JSON(200, gin.H{"usage-statistics-enabled": h.cfg.UsageStatisticsEnabled})
}
func (h *Handler) PutUsageStatisticsEnabled(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.UsageStatisticsEnabled = v })
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.UsageStatisticsEnabled = v })
}
// UsageStatisticsEnabled
@@ -198,7 +201,7 @@ func (h *Handler) GetLoggingToFile(c *gin.Context) {
c.JSON(200, gin.H{"logging-to-file": h.cfg.LoggingToFile})
}
func (h *Handler) PutLoggingToFile(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.LoggingToFile = v })
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.LoggingToFile = v })
}
// LogsMaxTotalSizeMB
@@ -217,8 +220,9 @@ func (h *Handler) PutLogsMaxTotalSizeMB(c *gin.Context) {
if value < 0 {
value = 0
}
h.cfg.LogsMaxTotalSizeMB = value
h.persist(c)
h.mutateConfig(c, func(cfg *config.Config) {
cfg.LogsMaxTotalSizeMB = value
})
}
// ErrorLogsMaxFiles
@@ -237,14 +241,15 @@ func (h *Handler) PutErrorLogsMaxFiles(c *gin.Context) {
if value < 0 {
value = 10
}
h.cfg.ErrorLogsMaxFiles = value
h.persist(c)
h.mutateConfig(c, func(cfg *config.Config) {
cfg.ErrorLogsMaxFiles = value
})
}
// Request log
func (h *Handler) GetRequestLog(c *gin.Context) { c.JSON(200, gin.H{"request-log": h.cfg.RequestLog}) }
func (h *Handler) PutRequestLog(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.RequestLog = v })
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.RequestLog = v })
}
// Websocket auth
@@ -252,7 +257,7 @@ func (h *Handler) GetWebsocketAuth(c *gin.Context) {
c.JSON(200, gin.H{"ws-auth": h.cfg.WebsocketAuth})
}
func (h *Handler) PutWebsocketAuth(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.WebsocketAuth = v })
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.WebsocketAuth = v })
}
// Request retry
@@ -260,7 +265,7 @@ func (h *Handler) GetRequestRetry(c *gin.Context) {
c.JSON(200, gin.H{"request-retry": h.cfg.RequestRetry})
}
func (h *Handler) PutRequestRetry(c *gin.Context) {
h.updateIntField(c, func(v int) { h.cfg.RequestRetry = v })
h.updateIntField(c, func(cfg *config.Config, v int) { cfg.RequestRetry = v })
}
// Max retry interval
@@ -268,7 +273,7 @@ func (h *Handler) GetMaxRetryInterval(c *gin.Context) {
c.JSON(200, gin.H{"max-retry-interval": h.cfg.MaxRetryInterval})
}
func (h *Handler) PutMaxRetryInterval(c *gin.Context) {
h.updateIntField(c, func(v int) { h.cfg.MaxRetryInterval = v })
h.updateIntField(c, func(cfg *config.Config, v int) { cfg.MaxRetryInterval = v })
}
// ForceModelPrefix
@@ -276,7 +281,7 @@ func (h *Handler) GetForceModelPrefix(c *gin.Context) {
c.JSON(200, gin.H{"force-model-prefix": h.cfg.ForceModelPrefix})
}
func (h *Handler) PutForceModelPrefix(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.ForceModelPrefix = v })
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.ForceModelPrefix = v })
}
func normalizeRoutingStrategy(strategy string) (string, bool) {
@@ -313,16 +318,18 @@ func (h *Handler) PutRoutingStrategy(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid strategy"})
return
}
h.cfg.Routing.Strategy = normalized
h.persist(c)
h.mutateConfig(c, func(cfg *config.Config) {
cfg.Routing.Strategy = normalized
})
}
// Proxy URL
func (h *Handler) GetProxyURL(c *gin.Context) { c.JSON(200, gin.H{"proxy-url": h.cfg.ProxyURL}) }
func (h *Handler) PutProxyURL(c *gin.Context) {
h.updateStringField(c, func(v string) { h.cfg.ProxyURL = v })
h.updateStringField(c, func(cfg *config.Config, v string) { cfg.ProxyURL = v })
}
func (h *Handler) DeleteProxyURL(c *gin.Context) {
h.cfg.ProxyURL = ""
h.persist(c)
h.mutateConfig(c, func(cfg *config.Config) {
cfg.ProxyURL = ""
})
}
@@ -509,8 +509,12 @@ func (h *Handler) PutVertexCompatKeys(c *gin.Context) {
}
for i := range arr {
normalizeVertexCompatKey(&arr[i])
if arr[i].APIKey == "" {
c.JSON(400, gin.H{"error": fmt.Sprintf("vertex-api-key[%d].api-key is required", i)})
return
}
}
h.cfg.VertexCompatAPIKey = arr
h.cfg.VertexCompatAPIKey = append([]config.VertexCompatKey(nil), arr...)
h.cfg.SanitizeVertexCompatKeys()
h.persist(c)
}
@@ -1088,7 +1092,7 @@ func (h *Handler) GetAmpUpstreamURL(c *gin.Context) {
// PutAmpUpstreamURL updates the ampcode upstream URL.
func (h *Handler) PutAmpUpstreamURL(c *gin.Context) {
h.updateStringField(c, func(v string) { h.cfg.AmpCode.UpstreamURL = strings.TrimSpace(v) })
h.updateStringField(c, func(cfg *config.Config, v string) { cfg.AmpCode.UpstreamURL = strings.TrimSpace(v) })
}
// DeleteAmpUpstreamURL clears the ampcode upstream URL.
@@ -1108,7 +1112,7 @@ func (h *Handler) GetAmpUpstreamAPIKey(c *gin.Context) {
// PutAmpUpstreamAPIKey updates the ampcode upstream API key.
func (h *Handler) PutAmpUpstreamAPIKey(c *gin.Context) {
h.updateStringField(c, func(v string) { h.cfg.AmpCode.UpstreamAPIKey = strings.TrimSpace(v) })
h.updateStringField(c, func(cfg *config.Config, v string) { cfg.AmpCode.UpstreamAPIKey = strings.TrimSpace(v) })
}
// DeleteAmpUpstreamAPIKey clears the ampcode upstream API key.
@@ -1128,7 +1132,7 @@ func (h *Handler) GetAmpRestrictManagementToLocalhost(c *gin.Context) {
// PutAmpRestrictManagementToLocalhost updates the localhost restriction setting.
func (h *Handler) PutAmpRestrictManagementToLocalhost(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.AmpCode.RestrictManagementToLocalhost = v })
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.AmpCode.RestrictManagementToLocalhost = v })
}
// GetAmpModelMappings returns the ampcode model mappings.
@@ -1217,7 +1221,7 @@ func (h *Handler) GetAmpForceModelMappings(c *gin.Context) {
// PutAmpForceModelMappings updates the force model mappings setting.
func (h *Handler) PutAmpForceModelMappings(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.AmpCode.ForceModelMappings = v })
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.AmpCode.ForceModelMappings = v })
}
// GetAmpUpstreamAPIKeys returns the ampcode upstream API keys mapping.
@@ -3,6 +3,8 @@ package management
import (
"bufio"
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"net/http"
@@ -117,9 +119,7 @@ func (h *Handler) processAPIKey(ctx context.Context, provider, key string, lineN
// Basic duplicate check could be added here if needed
timestamp := time.Now().Unix()
// Use a shortened key hash or prefix for filename to avoid leaking credentials in filenames
safeName := fmt.Sprintf("%s-%s", provider, key[:min(8, len(key))])
fileName := fmt.Sprintf("%s-%d.json", safeName, timestamp)
fileName := newImportedCredentialFileName(provider, timestamp)
record := &coreauth.Auth{
ID: fileName,
@@ -161,9 +161,10 @@ func parseLines(r io.Reader) ([]string, error) {
return lines, nil
}
func min(a, b int) int {
if a < b {
return a
func newImportedCredentialFileName(provider string, timestamp int64) string {
suffix := make([]byte, 6)
if _, err := rand.Read(suffix); err != nil {
return fmt.Sprintf("%s-import-%d.json", provider, timestamp)
}
return b
return fmt.Sprintf("%s-import-%d-%s.json", provider, timestamp, hex.EncodeToString(suffix))
}
+103 -13
View File
@@ -20,6 +20,7 @@ import (
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
"golang.org/x/crypto/bcrypt"
"gopkg.in/yaml.v3"
)
type attemptInfo struct {
@@ -37,6 +38,7 @@ const attemptMaxIdleTime = 2 * time.Hour
// Handler aggregates config reference, persistence path and helpers.
type Handler struct {
cfg *config.Config
committedCfg *config.Config
configFilePath string
mu sync.Mutex
attemptsMu sync.Mutex
@@ -56,9 +58,11 @@ type Handler struct {
func NewHandler(cfg *config.Config, configFilePath string, manager *coreauth.Manager) *Handler {
envSecret, _ := os.LookupEnv("MANAGEMENT_PASSWORD")
envSecret = strings.TrimSpace(envSecret)
clonedCfg := cloneConfig(cfg)
h := &Handler{
cfg: cfg,
cfg: clonedCfg,
committedCfg: cloneConfig(clonedCfg),
configFilePath: configFilePath,
failedAttempts: make(map[string]*attemptInfo),
authManager: manager,
@@ -107,7 +111,13 @@ func NewHandlerWithoutConfigFilePath(cfg *config.Config, manager *coreauth.Manag
}
// SetConfig updates the in-memory config reference when the server hot-reloads.
func (h *Handler) SetConfig(cfg *config.Config) { h.cfg = cfg }
func (h *Handler) SetConfig(cfg *config.Config) {
clonedCfg := cloneConfig(cfg)
h.mu.Lock()
h.cfg = clonedCfg
h.committedCfg = cloneConfig(clonedCfg)
h.mu.Unlock()
}
// SetAuthManager updates the auth manager reference used by management endpoints.
func (h *Handler) SetAuthManager(manager *coreauth.Manager) { h.authManager = manager }
@@ -276,19 +286,45 @@ func (h *Handler) Middleware() gin.HandlerFunc {
// persist saves the current in-memory config to disk.
func (h *Handler) persist(c *gin.Context) bool {
h.mu.Lock()
current := cloneConfig(h.cfg)
h.mu.Unlock()
return h.persistConfig(c, current)
}
func (h *Handler) persistConfig(c *gin.Context, next *config.Config) bool {
if next == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "config unavailable"})
return false
}
next = cloneConfig(next)
h.mu.Lock()
defer h.mu.Unlock()
// Preserve comments when writing
if err := config.SaveConfigPreserveComments(h.configFilePath, h.cfg); err != nil {
if err := saveConfigAtomically(h.configFilePath, next); err != nil {
h.cfg = cloneConfig(h.committedCfg)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to save config: %v", err)})
return false
}
h.cfg = next
h.committedCfg = cloneConfig(next)
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return true
}
func (h *Handler) mutateConfig(c *gin.Context, mutate func(*config.Config)) bool {
h.mu.Lock()
next := cloneConfig(h.cfg)
h.mu.Unlock()
if next == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "config unavailable"})
return false
}
mutate(next)
return h.persistConfig(c, next)
}
// Helper methods for simple types
func (h *Handler) updateBoolField(c *gin.Context, set func(bool)) {
func (h *Handler) updateBoolField(c *gin.Context, set func(*config.Config, bool)) {
var body struct {
Value *bool `json:"value"`
}
@@ -296,11 +332,12 @@ func (h *Handler) updateBoolField(c *gin.Context, set func(bool)) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
set(*body.Value)
h.persist(c)
h.mutateConfig(c, func(cfg *config.Config) {
set(cfg, *body.Value)
})
}
func (h *Handler) updateIntField(c *gin.Context, set func(int)) {
func (h *Handler) updateIntField(c *gin.Context, set func(*config.Config, int)) {
var body struct {
Value *int `json:"value"`
}
@@ -308,11 +345,12 @@ func (h *Handler) updateIntField(c *gin.Context, set func(int)) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
set(*body.Value)
h.persist(c)
h.mutateConfig(c, func(cfg *config.Config) {
set(cfg, *body.Value)
})
}
func (h *Handler) updateStringField(c *gin.Context, set func(string)) {
func (h *Handler) updateStringField(c *gin.Context, set func(*config.Config, string)) {
var body struct {
Value *string `json:"value"`
}
@@ -320,6 +358,58 @@ func (h *Handler) updateStringField(c *gin.Context, set func(string)) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
set(*body.Value)
h.persist(c)
h.mutateConfig(c, func(cfg *config.Config) {
set(cfg, *body.Value)
})
}
func cloneConfig(cfg *config.Config) *config.Config {
if cfg == nil {
return nil
}
raw, err := yaml.Marshal(cfg)
if err != nil {
cloned := *cfg
return &cloned
}
var cloned config.Config
if err = yaml.Unmarshal(raw, &cloned); err != nil {
fallback := *cfg
return &fallback
}
return &cloned
}
func saveConfigAtomically(path string, cfg *config.Config) error {
path = strings.TrimSpace(path)
if path == "" {
return fmt.Errorf("config file path not configured")
}
info, err := os.Stat(path)
if err != nil {
return err
}
original, err := os.ReadFile(path)
if err != nil {
return err
}
tmpFile, err := os.CreateTemp(filepath.Dir(path), ".config-save-*.yaml")
if err != nil {
return err
}
tmpPath := tmpFile.Name()
if errClose := tmpFile.Close(); errClose != nil {
_ = os.Remove(tmpPath)
return errClose
}
defer func() {
_ = os.Remove(tmpPath)
}()
if err = os.WriteFile(tmpPath, original, info.Mode().Perm()); err != nil {
return err
}
if err = config.SaveConfigPreserveComments(tmpPath, cfg); err != nil {
return err
}
return os.Rename(tmpPath, path)
}
@@ -0,0 +1,111 @@
package management
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
)
func TestDeleteMemorySession_RejectsTraversal(t *testing.T) {
t.Setenv("CLIPROXY_MEMORY_DIR", t.TempDir())
gin.SetMode(gin.TestMode)
outsidePath := filepath.Join(t.TempDir(), "outside")
if err := os.WriteFile(outsidePath, []byte("keep"), 0o600); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/memory/session?session="+url.QueryEscape("../outside"), nil)
h := &Handler{}
h.DeleteMemorySession(ctx)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d body=%s", recorder.Code, http.StatusBadRequest, recorder.Body.String())
}
if _, err := os.Stat(outsidePath); err != nil {
t.Fatalf("outside path should remain untouched: %v", err)
}
}
func TestProcessAPIKey_DoesNotLeakSecretPrefixInSavedPath(t *testing.T) {
gin.SetMode(gin.TestMode)
authDir := t.TempDir()
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
key := "sk-secret-prefix-1234567890"
result := h.processAPIKey(context.Background(), "openai", key, 1)
if !result.Success {
t.Fatalf("processAPIKey() failed: %+v", result)
}
if strings.Contains(result.SavedPath, "sk-secret") {
t.Fatalf("saved path leaked key prefix: %q", result.SavedPath)
}
if !strings.HasPrefix(filepath.Base(result.SavedPath), "openai-import-") {
t.Fatalf("saved path = %q, want generated import prefix", result.SavedPath)
}
}
func TestCommitUploadedAuthFile_InvalidDataDoesNotWriteFile(t *testing.T) {
gin.SetMode(gin.TestMode)
authDir := t.TempDir()
path := filepath.Join(authDir, "broken.json")
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
err := h.commitUploadedAuthFile(context.Background(), path, []byte(`{"type":`))
if err == nil {
t.Fatal("commitUploadedAuthFile() unexpectedly succeeded")
}
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
t.Fatalf("invalid upload should not leave a file behind, stat err=%v", statErr)
}
}
func TestGetConfig_ReturnsLiveConfig(t *testing.T) {
gin.SetMode(gin.TestMode)
h := NewHandlerWithoutConfigFilePath(&config.Config{
SDKConfig: config.SDKConfig{
ProxyURL: "http://127.0.0.1:8080",
},
Debug: true,
UsageStatisticsEnabled: true,
}, nil)
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/config", nil)
h.GetConfig(ctx)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, want %d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
}
var got config.Config
if err := json.Unmarshal(recorder.Body.Bytes(), &got); err != nil {
t.Fatalf("Unmarshal() error = %v body=%s", err, recorder.Body.String())
}
if !got.Debug {
t.Fatalf("Debug = %v, want true", got.Debug)
}
if got.ProxyURL != "http://127.0.0.1:8080" {
t.Fatalf("ProxyURL = %q", got.ProxyURL)
}
if !got.UsageStatisticsEnabled {
t.Fatalf("UsageStatisticsEnabled = %v, want true", got.UsageStatisticsEnabled)
}
}
+27 -12
View File
@@ -210,12 +210,11 @@ func (h *Handler) DeleteMemorySession(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
store := memory.NewFileStore(base)
_, path, ok := resolveManagedMemorySession(c, store, c.Query("session"))
if !ok {
return
}
path := filepath.Join(base, "sessions", session)
if err := os.RemoveAll(path); err != nil && !os.IsNotExist(err) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
@@ -289,12 +288,11 @@ func (h *Handler) ExportMemorySession(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
store := memory.NewFileStore(base)
session, dir, ok := resolveManagedMemorySession(c, store, c.Query("session"))
if !ok {
return
}
dir := filepath.Join(base, "sessions", session)
if _, err := os.Stat(dir); err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
return
@@ -357,9 +355,9 @@ func (h *Handler) ImportMemorySession(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "multipart form required"})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
store := memory.NewFileStore(base)
_, dest, ok := resolveManagedMemorySession(c, store, c.Query("session"))
if !ok {
return
}
replace := strings.EqualFold(strings.TrimSpace(c.Query("replace")), "true")
@@ -388,7 +386,6 @@ func (h *Handler) ImportMemorySession(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid zip"})
return
}
dest := filepath.Join(base, "sessions", session)
if replace {
_ = os.RemoveAll(dest)
}
@@ -460,3 +457,21 @@ func anchorAppendOnlyEnabled() bool {
}
return true
}
func resolveManagedMemorySession(c *gin.Context, store *memory.FileStore, rawSession string) (string, string, bool) {
session := strings.TrimSpace(rawSession)
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return "", "", false
}
if strings.Contains(session, "..") || strings.ContainsAny(session, `/\`) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session"})
return "", "", false
}
dir := store.SessionDir(session)
if dir == "" {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to resolve session path"})
return "", "", false
}
return filepath.Base(dir), dir, true
}
+6 -3
View File
@@ -1,18 +1,21 @@
package management
import "github.com/gin-gonic/gin"
import (
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
)
// Quota exceeded toggles
func (h *Handler) GetSwitchProject(c *gin.Context) {
c.JSON(200, gin.H{"switch-project": h.cfg.QuotaExceeded.SwitchProject})
}
func (h *Handler) PutSwitchProject(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.QuotaExceeded.SwitchProject = v })
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.QuotaExceeded.SwitchProject = v })
}
func (h *Handler) GetSwitchPreviewModel(c *gin.Context) {
c.JSON(200, gin.H{"switch-preview-model": h.cfg.QuotaExceeded.SwitchPreviewModel})
}
func (h *Handler) PutSwitchPreviewModel(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.QuotaExceeded.SwitchPreviewModel = v })
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.QuotaExceeded.SwitchPreviewModel = v })
}
@@ -0,0 +1,49 @@
package management
import (
"context"
"sync"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
type memoryAuthStore struct {
mu sync.Mutex
items map[string]*coreauth.Auth
}
func (s *memoryAuthStore) List(_ context.Context) ([]*coreauth.Auth, error) {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]*coreauth.Auth, 0, len(s.items))
for _, item := range s.items {
out = append(out, item)
}
return out, nil
}
func (s *memoryAuthStore) Save(_ context.Context, auth *coreauth.Auth) (string, error) {
if auth == nil {
return "", nil
}
s.mu.Lock()
defer s.mu.Unlock()
if s.items == nil {
s.items = make(map[string]*coreauth.Auth)
}
s.items[auth.ID] = auth
return auth.ID, nil
}
func (s *memoryAuthStore) Delete(_ context.Context, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.items, id)
return nil
}
func (s *memoryAuthStore) SetBaseDir(string) {}
+62 -16
View File
@@ -15,6 +15,8 @@ import (
)
const requestBodyOverrideContextKey = "REQUEST_BODY_OVERRIDE"
const responseBodyOverrideContextKey = "RESPONSE_BODY_OVERRIDE"
const websocketTimelineOverrideContextKey = "WEBSOCKET_TIMELINE_OVERRIDE"
// RequestInfo holds essential details of an incoming HTTP request for logging purposes.
type RequestInfo struct {
@@ -304,6 +306,10 @@ func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error {
if len(apiResponse) > 0 {
_ = w.streamWriter.WriteAPIResponse(apiResponse)
}
apiWebsocketTimeline := w.extractAPIWebsocketTimeline(c)
if len(apiWebsocketTimeline) > 0 {
_ = w.streamWriter.WriteAPIWebsocketTimeline(apiWebsocketTimeline)
}
if err := w.streamWriter.Close(); err != nil {
w.streamWriter = nil
return err
@@ -312,7 +318,7 @@ func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error {
return nil
}
return w.logRequest(w.extractRequestBody(c), finalStatusCode, w.cloneHeaders(), w.body.Bytes(), w.extractAPIRequest(c), w.extractAPIResponse(c), w.extractAPIResponseTimestamp(c), slicesAPIResponseError, forceLog)
return w.logRequest(w.extractRequestBody(c), finalStatusCode, w.cloneHeaders(), w.extractResponseBody(c), w.extractWebsocketTimeline(c), w.extractAPIRequest(c), w.extractAPIResponse(c), w.extractAPIWebsocketTimeline(c), w.extractAPIResponseTimestamp(c), slicesAPIResponseError, forceLog)
}
func (w *ResponseWriterWrapper) cloneHeaders() map[string][]string {
@@ -352,6 +358,18 @@ func (w *ResponseWriterWrapper) extractAPIResponse(c *gin.Context) []byte {
return data
}
func (w *ResponseWriterWrapper) extractAPIWebsocketTimeline(c *gin.Context) []byte {
apiTimeline, isExist := c.Get("API_WEBSOCKET_TIMELINE")
if !isExist {
return nil
}
data, ok := apiTimeline.([]byte)
if !ok || len(data) == 0 {
return nil
}
return bytes.Clone(data)
}
func (w *ResponseWriterWrapper) extractAPIResponseTimestamp(c *gin.Context) time.Time {
ts, isExist := c.Get("API_RESPONSE_TIMESTAMP")
if !isExist {
@@ -364,19 +382,8 @@ func (w *ResponseWriterWrapper) extractAPIResponseTimestamp(c *gin.Context) time
}
func (w *ResponseWriterWrapper) extractRequestBody(c *gin.Context) []byte {
if c != nil {
if bodyOverride, isExist := c.Get(requestBodyOverrideContextKey); isExist {
switch value := bodyOverride.(type) {
case []byte:
if len(value) > 0 {
return bytes.Clone(value)
}
case string:
if strings.TrimSpace(value) != "" {
return []byte(value)
}
}
}
if body := extractBodyOverride(c, requestBodyOverrideContextKey); len(body) > 0 {
return body
}
if w.requestInfo != nil && len(w.requestInfo.Body) > 0 {
return w.requestInfo.Body
@@ -384,13 +391,48 @@ func (w *ResponseWriterWrapper) extractRequestBody(c *gin.Context) []byte {
return nil
}
func (w *ResponseWriterWrapper) logRequest(requestBody []byte, statusCode int, headers map[string][]string, body []byte, apiRequestBody, apiResponseBody []byte, apiResponseTimestamp time.Time, apiResponseErrors []*interfaces.ErrorMessage, forceLog bool) error {
func (w *ResponseWriterWrapper) extractResponseBody(c *gin.Context) []byte {
if body := extractBodyOverride(c, responseBodyOverrideContextKey); len(body) > 0 {
return body
}
if w.body == nil || w.body.Len() == 0 {
return nil
}
return bytes.Clone(w.body.Bytes())
}
func (w *ResponseWriterWrapper) extractWebsocketTimeline(c *gin.Context) []byte {
return extractBodyOverride(c, websocketTimelineOverrideContextKey)
}
func extractBodyOverride(c *gin.Context, key string) []byte {
if c == nil {
return nil
}
bodyOverride, isExist := c.Get(key)
if !isExist {
return nil
}
switch value := bodyOverride.(type) {
case []byte:
if len(value) > 0 {
return bytes.Clone(value)
}
case string:
if strings.TrimSpace(value) != "" {
return []byte(value)
}
}
return nil
}
func (w *ResponseWriterWrapper) logRequest(requestBody []byte, statusCode int, headers map[string][]string, body, websocketTimeline, apiRequestBody, apiResponseBody, apiWebsocketTimeline []byte, apiResponseTimestamp time.Time, apiResponseErrors []*interfaces.ErrorMessage, forceLog bool) error {
if w.requestInfo == nil {
return nil
}
if loggerWithOptions, ok := w.logger.(interface {
LogRequestWithOptions(string, string, map[string][]string, []byte, int, map[string][]string, []byte, []byte, []byte, []*interfaces.ErrorMessage, bool, string, time.Time, time.Time) error
LogRequestWithOptions(string, string, map[string][]string, []byte, int, map[string][]string, []byte, []byte, []byte, []byte, []byte, []*interfaces.ErrorMessage, bool, string, time.Time, time.Time) error
}); ok {
return loggerWithOptions.LogRequestWithOptions(
w.requestInfo.URL,
@@ -400,8 +442,10 @@ func (w *ResponseWriterWrapper) logRequest(requestBody []byte, statusCode int, h
statusCode,
headers,
body,
websocketTimeline,
apiRequestBody,
apiResponseBody,
apiWebsocketTimeline,
apiResponseErrors,
forceLog,
w.requestInfo.RequestID,
@@ -418,8 +462,10 @@ func (w *ResponseWriterWrapper) logRequest(requestBody []byte, statusCode int, h
statusCode,
headers,
body,
websocketTimeline,
apiRequestBody,
apiResponseBody,
apiWebsocketTimeline,
apiResponseErrors,
w.requestInfo.RequestID,
w.requestInfo.Timestamp,
+160 -1
View File
@@ -1,10 +1,14 @@
package middleware
import (
"bytes"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
)
func TestExtractRequestBodyPrefersOverride(t *testing.T) {
@@ -33,7 +37,7 @@ func TestExtractRequestBodySupportsStringOverride(t *testing.T) {
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
wrapper := &ResponseWriterWrapper{}
wrapper := &ResponseWriterWrapper{body: &bytes.Buffer{}}
c.Set(requestBodyOverrideContextKey, "override-as-string")
body := wrapper.extractRequestBody(c)
@@ -41,3 +45,158 @@ func TestExtractRequestBodySupportsStringOverride(t *testing.T) {
t.Fatalf("request body = %q, want %q", string(body), "override-as-string")
}
}
func TestExtractResponseBodyPrefersOverride(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
wrapper := &ResponseWriterWrapper{body: &bytes.Buffer{}}
wrapper.body.WriteString("original-response")
body := wrapper.extractResponseBody(c)
if string(body) != "original-response" {
t.Fatalf("response body = %q, want %q", string(body), "original-response")
}
c.Set(responseBodyOverrideContextKey, []byte("override-response"))
body = wrapper.extractResponseBody(c)
if string(body) != "override-response" {
t.Fatalf("response body = %q, want %q", string(body), "override-response")
}
body[0] = 'X'
if got := wrapper.extractResponseBody(c); string(got) != "override-response" {
t.Fatalf("response override should be cloned, got %q", string(got))
}
}
func TestExtractResponseBodySupportsStringOverride(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
wrapper := &ResponseWriterWrapper{}
c.Set(responseBodyOverrideContextKey, "override-response-as-string")
body := wrapper.extractResponseBody(c)
if string(body) != "override-response-as-string" {
t.Fatalf("response body = %q, want %q", string(body), "override-response-as-string")
}
}
func TestExtractBodyOverrideClonesBytes(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
override := []byte("body-override")
c.Set(requestBodyOverrideContextKey, override)
body := extractBodyOverride(c, requestBodyOverrideContextKey)
if !bytes.Equal(body, override) {
t.Fatalf("body override = %q, want %q", string(body), string(override))
}
body[0] = 'X'
if !bytes.Equal(override, []byte("body-override")) {
t.Fatalf("override mutated: %q", string(override))
}
}
func TestExtractWebsocketTimelineUsesOverride(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
wrapper := &ResponseWriterWrapper{}
if got := wrapper.extractWebsocketTimeline(c); got != nil {
t.Fatalf("expected nil websocket timeline, got %q", string(got))
}
c.Set(websocketTimelineOverrideContextKey, []byte("timeline"))
body := wrapper.extractWebsocketTimeline(c)
if string(body) != "timeline" {
t.Fatalf("websocket timeline = %q, want %q", string(body), "timeline")
}
}
func TestFinalizeStreamingWritesAPIWebsocketTimeline(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
streamWriter := &testStreamingLogWriter{}
wrapper := &ResponseWriterWrapper{
ResponseWriter: c.Writer,
logger: &testRequestLogger{enabled: true},
requestInfo: &RequestInfo{
URL: "/v1/responses",
Method: "POST",
Headers: map[string][]string{"Content-Type": {"application/json"}},
RequestID: "req-1",
Timestamp: time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC),
},
isStreaming: true,
streamWriter: streamWriter,
}
c.Set("API_WEBSOCKET_TIMELINE", []byte("Timestamp: 2026-04-01T12:00:00Z\nEvent: api.websocket.request\n{}"))
if err := wrapper.Finalize(c); err != nil {
t.Fatalf("Finalize error: %v", err)
}
if string(streamWriter.apiWebsocketTimeline) != "Timestamp: 2026-04-01T12:00:00Z\nEvent: api.websocket.request\n{}" {
t.Fatalf("stream writer websocket timeline = %q", string(streamWriter.apiWebsocketTimeline))
}
if !streamWriter.closed {
t.Fatal("expected stream writer to be closed")
}
}
type testRequestLogger struct {
enabled bool
}
func (l *testRequestLogger) LogRequest(string, string, map[string][]string, []byte, int, map[string][]string, []byte, []byte, []byte, []byte, []byte, []*interfaces.ErrorMessage, string, time.Time, time.Time) error {
return nil
}
func (l *testRequestLogger) LogStreamingRequest(string, string, map[string][]string, []byte, string) (logging.StreamingLogWriter, error) {
return &testStreamingLogWriter{}, nil
}
func (l *testRequestLogger) IsEnabled() bool {
return l.enabled
}
type testStreamingLogWriter struct {
apiWebsocketTimeline []byte
closed bool
}
func (w *testStreamingLogWriter) WriteChunkAsync([]byte) {}
func (w *testStreamingLogWriter) WriteStatus(int, map[string][]string) error {
return nil
}
func (w *testStreamingLogWriter) WriteAPIRequest([]byte) error {
return nil
}
func (w *testStreamingLogWriter) WriteAPIResponse([]byte) error {
return nil
}
func (w *testStreamingLogWriter) WriteAPIWebsocketTimeline(apiWebsocketTimeline []byte) error {
w.apiWebsocketTimeline = bytes.Clone(apiWebsocketTimeline)
return nil
}
func (w *testStreamingLogWriter) SetFirstChunkTimestamp(time.Time) {}
func (w *testStreamingLogWriter) Close() error {
w.closed = true
return nil
}
@@ -123,6 +123,10 @@ func (fh *FallbackHandler) WrapHandler(handler gin.HandlerFunc) gin.HandlerFunc
return
}
// Sanitize request body: remove thinking blocks with invalid signatures
// to prevent upstream API 400 errors
bodyBytes = SanitizeAmpRequestBody(bodyBytes)
// Restore the body for the handler to read
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
@@ -249,6 +253,7 @@ func (fh *FallbackHandler) WrapHandler(handler gin.HandlerFunc) gin.HandlerFunc
log.Debugf("amp model mapping: request %s -> %s", normalizedModel, resolvedModel)
logAmpRouting(RouteTypeModelMapping, modelName, resolvedModel, providerName, requestPath)
rewriter := NewResponseRewriter(c.Writer, modelName)
rewriter.suppressThinking = true
c.Writer = rewriter
// Filter Anthropic-Beta header only for local handling paths
filterAntropicBetaHeader(c)
@@ -259,10 +264,17 @@ func (fh *FallbackHandler) WrapHandler(handler gin.HandlerFunc) gin.HandlerFunc
} else if len(providers) > 0 {
// Log: Using local provider (free)
logAmpRouting(RouteTypeLocalProvider, modelName, resolvedModel, providerName, requestPath)
// Wrap with ResponseRewriter for local providers too, because upstream
// proxies (e.g. NewAPI) may return a different model name and lack
// Amp-required fields like thinking.signature.
rewriter := NewResponseRewriter(c.Writer, modelName)
rewriter.suppressThinking = providerName != "claude"
c.Writer = rewriter
// Filter Anthropic-Beta header only for local handling paths
filterAntropicBetaHeader(c)
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
handler(c)
rewriter.Flush()
} else {
// No provider, no mapping, no proxy: fall back to the wrapped handler so it can return an error response
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
-5
View File
@@ -108,11 +108,6 @@ func createReverseProxy(upstreamURL string, secretSource SecretSource) (*httputi
// Modify incoming responses to handle gzip without Content-Encoding
// This addresses the same issue as inline handler gzip handling, but at the proxy level
proxy.ModifyResponse = func(resp *http.Response) error {
// Only process successful responses
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil
}
// Skip if already marked as gzip (Content-Encoding set)
if resp.Header.Get("Content-Encoding") != "" {
return nil
+266 -35
View File
@@ -2,6 +2,8 @@ package amp
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
@@ -12,15 +14,17 @@ import (
)
// ResponseRewriter wraps a gin.ResponseWriter to intercept and modify the response body
// It's used to rewrite model names in responses when model mapping is used
// It is used to rewrite model names in responses when model mapping is used
// and to keep Amp-compatible response shapes.
type ResponseRewriter struct {
gin.ResponseWriter
body *bytes.Buffer
originalModel string
isStreaming bool
body *bytes.Buffer
originalModel string
isStreaming bool
suppressThinking bool
}
// NewResponseRewriter creates a new response rewriter for model name substitution
// NewResponseRewriter creates a new response rewriter for model name substitution.
func NewResponseRewriter(w gin.ResponseWriter, originalModel string) *ResponseRewriter {
return &ResponseRewriter{
ResponseWriter: w,
@@ -29,17 +33,66 @@ func NewResponseRewriter(w gin.ResponseWriter, originalModel string) *ResponseRe
}
}
// Write intercepts response writes and buffers them for model name replacement
const maxBufferedResponseBytes = 2 * 1024 * 1024 // 2MB safety cap
func looksLikeSSEChunk(data []byte) bool {
for _, line := range bytes.Split(data, []byte("\n")) {
trimmed := bytes.TrimSpace(line)
if bytes.HasPrefix(trimmed, []byte("data:")) ||
bytes.HasPrefix(trimmed, []byte("event:")) {
return true
}
}
return false
}
func (rw *ResponseRewriter) enableStreaming(reason string) error {
if rw.isStreaming {
return nil
}
rw.isStreaming = true
if rw.body != nil && rw.body.Len() > 0 {
buf := rw.body.Bytes()
toFlush := make([]byte, len(buf))
copy(toFlush, buf)
rw.body.Reset()
if _, err := rw.ResponseWriter.Write(rw.rewriteStreamChunk(toFlush)); err != nil {
return err
}
if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
log.Debugf("amp response rewriter: switched to streaming (%s)", reason)
return nil
}
func (rw *ResponseRewriter) Write(data []byte) (int, error) {
// Detect streaming on first write
if rw.body.Len() == 0 && !rw.isStreaming {
if !rw.isStreaming && rw.body.Len() == 0 {
contentType := rw.Header().Get("Content-Type")
rw.isStreaming = strings.Contains(contentType, "text/event-stream") ||
strings.Contains(contentType, "stream")
}
if !rw.isStreaming {
if looksLikeSSEChunk(data) {
if err := rw.enableStreaming("sse heuristic"); err != nil {
return 0, err
}
} else if rw.body.Len()+len(data) > maxBufferedResponseBytes {
log.Warnf("amp response rewriter: buffer exceeded %d bytes, switching to streaming", maxBufferedResponseBytes)
if err := rw.enableStreaming("buffer limit"); err != nil {
return 0, err
}
}
}
if rw.isStreaming {
n, err := rw.ResponseWriter.Write(rw.rewriteStreamChunk(data))
rewritten := rw.rewriteStreamChunk(data)
n, err := rw.ResponseWriter.Write(rewritten)
if err == nil {
if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
@@ -50,7 +103,6 @@ func (rw *ResponseRewriter) Write(data []byte) (int, error) {
return rw.body.Write(data)
}
// Flush writes the buffered response with model names rewritten
func (rw *ResponseRewriter) Flush() {
if rw.isStreaming {
if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
@@ -59,40 +111,79 @@ func (rw *ResponseRewriter) Flush() {
return
}
if rw.body.Len() > 0 {
if _, err := rw.ResponseWriter.Write(rw.rewriteModelInResponse(rw.body.Bytes())); err != nil {
rewritten := rw.rewriteModelInResponse(rw.body.Bytes())
// Update Content-Length to match the rewritten body size, since
// signature injection and model name changes alter the payload length.
rw.ResponseWriter.Header().Set("Content-Length", fmt.Sprintf("%d", len(rewritten)))
if _, err := rw.ResponseWriter.Write(rewritten); err != nil {
log.Warnf("amp response rewriter: failed to write rewritten response: %v", err)
}
}
}
// modelFieldPaths lists all JSON paths where model name may appear
var modelFieldPaths = []string{"message.model", "model", "modelVersion", "response.model", "response.modelVersion"}
// rewriteModelInResponse replaces all occurrences of the mapped model with the original model in JSON
// It also suppresses "thinking" blocks if "tool_use" is present to ensure Amp client compatibility
func (rw *ResponseRewriter) rewriteModelInResponse(data []byte) []byte {
// 1. Amp Compatibility: Suppress thinking blocks if tool use is detected
// The Amp client struggles when both thinking and tool_use blocks are present
// ensureAmpSignature injects empty signature fields into tool_use/thinking blocks
// in API responses so that the Amp TUI does not crash on P.signature.length.
func ensureAmpSignature(data []byte) []byte {
for index, block := range gjson.GetBytes(data, "content").Array() {
blockType := block.Get("type").String()
if blockType != "tool_use" && blockType != "thinking" {
continue
}
signaturePath := fmt.Sprintf("content.%d.signature", index)
if gjson.GetBytes(data, signaturePath).Exists() {
continue
}
var err error
data, err = sjson.SetBytes(data, signaturePath, "")
if err != nil {
log.Warnf("Amp ResponseRewriter: failed to add empty signature to %s block: %v", blockType, err)
break
}
}
contentBlockType := gjson.GetBytes(data, "content_block.type").String()
if (contentBlockType == "tool_use" || contentBlockType == "thinking") && !gjson.GetBytes(data, "content_block.signature").Exists() {
var err error
data, err = sjson.SetBytes(data, "content_block.signature", "")
if err != nil {
log.Warnf("Amp ResponseRewriter: failed to add empty signature to streaming %s block: %v", contentBlockType, err)
}
}
return data
}
func (rw *ResponseRewriter) suppressAmpThinking(data []byte) []byte {
if !rw.suppressThinking {
return data
}
if gjson.GetBytes(data, `content.#(type=="tool_use")`).Exists() {
filtered := gjson.GetBytes(data, `content.#(type!="thinking")#`)
if filtered.Exists() {
originalCount := gjson.GetBytes(data, "content.#").Int()
filteredCount := filtered.Get("#").Int()
if originalCount > filteredCount {
var err error
data, err = sjson.SetBytes(data, "content", filtered.Value())
if err != nil {
log.Warnf("Amp ResponseRewriter: failed to suppress thinking blocks: %v", err)
} else {
log.Debugf("Amp ResponseRewriter: Suppressed %d thinking blocks due to tool usage", originalCount-filteredCount)
// Log the result for verification
log.Debugf("Amp ResponseRewriter: Resulting content: %s", gjson.GetBytes(data, "content").String())
}
}
}
}
return data
}
func (rw *ResponseRewriter) rewriteModelInResponse(data []byte) []byte {
data = ensureAmpSignature(data)
data = rw.suppressAmpThinking(data)
if len(data) == 0 {
return data
}
if rw.originalModel == "" {
return data
}
@@ -104,24 +195,164 @@ func (rw *ResponseRewriter) rewriteModelInResponse(data []byte) []byte {
return data
}
// rewriteStreamChunk rewrites model names in SSE stream chunks
func (rw *ResponseRewriter) rewriteStreamChunk(chunk []byte) []byte {
if rw.originalModel == "" {
return chunk
lines := bytes.Split(chunk, []byte("\n"))
var out [][]byte
i := 0
for i < len(lines) {
line := lines[i]
trimmed := bytes.TrimSpace(line)
// Case 1: "event:" line - look ahead for its "data:" line
if bytes.HasPrefix(trimmed, []byte("event: ")) {
// Scan forward past blank lines to find the data: line
dataIdx := -1
for j := i + 1; j < len(lines); j++ {
t := bytes.TrimSpace(lines[j])
if len(t) == 0 {
continue
}
if bytes.HasPrefix(t, []byte("data: ")) {
dataIdx = j
}
break
}
if dataIdx >= 0 {
// Found event+data pair - process through rewriter
jsonData := bytes.TrimPrefix(bytes.TrimSpace(lines[dataIdx]), []byte("data: "))
if len(jsonData) > 0 && jsonData[0] == '{' {
rewritten := rw.rewriteStreamEvent(jsonData)
if rewritten == nil {
i = dataIdx + 1
continue
}
// Emit event line
out = append(out, line)
// Emit blank lines between event and data
for k := i + 1; k < dataIdx; k++ {
out = append(out, lines[k])
}
// Emit rewritten data
out = append(out, append([]byte("data: "), rewritten...))
i = dataIdx + 1
continue
}
}
// No data line found (orphan event from cross-chunk split)
// Pass it through as-is - the data will arrive in the next chunk
out = append(out, line)
i++
continue
}
// Case 2: standalone "data:" line (no preceding event: in this chunk)
if bytes.HasPrefix(trimmed, []byte("data: ")) {
jsonData := bytes.TrimPrefix(trimmed, []byte("data: "))
if len(jsonData) > 0 && jsonData[0] == '{' {
rewritten := rw.rewriteStreamEvent(jsonData)
if rewritten != nil {
out = append(out, append([]byte("data: "), rewritten...))
}
i++
continue
}
}
// Case 3: everything else
out = append(out, line)
i++
}
// SSE format: "data: {json}\n\n"
lines := bytes.Split(chunk, []byte("\n"))
for i, line := range lines {
if bytes.HasPrefix(line, []byte("data: ")) {
jsonData := bytes.TrimPrefix(line, []byte("data: "))
if len(jsonData) > 0 && jsonData[0] == '{' {
// Rewrite JSON in the data line
rewritten := rw.rewriteModelInResponse(jsonData)
lines[i] = append([]byte("data: "), rewritten...)
return bytes.Join(out, []byte("\n"))
}
// rewriteStreamEvent processes a single JSON event in the SSE stream.
// It rewrites model names and ensures signature fields exist.
// NOTE: streaming mode does NOT suppress thinking blocks - they are
// passed through with signature injection to avoid breaking SSE index
// alignment and TUI rendering.
func (rw *ResponseRewriter) rewriteStreamEvent(data []byte) []byte {
// Inject empty signature where needed
data = ensureAmpSignature(data)
// Rewrite model name
if rw.originalModel != "" {
for _, path := range modelFieldPaths {
if gjson.GetBytes(data, path).Exists() {
data, _ = sjson.SetBytes(data, path, rw.originalModel)
}
}
}
return bytes.Join(lines, []byte("\n"))
return data
}
// SanitizeAmpRequestBody removes thinking blocks with empty/missing/invalid signatures
// and strips the proxy-injected "signature" field from tool_use blocks in the messages
// array before forwarding to the upstream API.
// This prevents 400 errors from the API which requires valid signatures on thinking
// blocks and does not accept a signature field on tool_use blocks.
func SanitizeAmpRequestBody(body []byte) []byte {
messages := gjson.GetBytes(body, "messages")
if !messages.Exists() || !messages.IsArray() {
return body
}
modified := false
for msgIdx, msg := range messages.Array() {
if msg.Get("role").String() != "assistant" {
continue
}
content := msg.Get("content")
if !content.Exists() || !content.IsArray() {
continue
}
var keepBlocks []interface{}
contentModified := false
for _, block := range content.Array() {
blockType := block.Get("type").String()
if blockType == "thinking" {
sig := block.Get("signature")
if !sig.Exists() || sig.Type != gjson.String || strings.TrimSpace(sig.String()) == "" {
contentModified = true
continue
}
}
// Use raw JSON to prevent float64 rounding of large integers in tool_use inputs
blockRaw := []byte(block.Raw)
if blockType == "tool_use" && block.Get("signature").Exists() {
blockRaw, _ = sjson.DeleteBytes(blockRaw, "signature")
contentModified = true
}
// sjson.SetBytes supports raw JSON strings if wrapped in gjson.Raw
keepBlocks = append(keepBlocks, json.RawMessage(blockRaw))
}
if contentModified {
contentPath := fmt.Sprintf("messages.%d.content", msgIdx)
var err error
if len(keepBlocks) == 0 {
body, err = sjson.SetBytes(body, contentPath, []interface{}{})
} else {
body, err = sjson.SetBytes(body, contentPath, keepBlocks)
}
if err != nil {
log.Warnf("Amp RequestSanitizer: failed to sanitize message %d: %v", msgIdx, err)
continue
}
modified = true
}
}
if modified {
log.Debugf("Amp RequestSanitizer: sanitized request body")
}
return body
}
@@ -1,6 +1,7 @@
package amp
import (
"strings"
"testing"
)
@@ -100,6 +101,80 @@ func TestRewriteStreamChunk_MessageModel(t *testing.T) {
}
}
func TestRewriteStreamChunk_PreservesThinkingWithSignatureInjection(t *testing.T) {
rw := &ResponseRewriter{}
chunk := []byte("event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"abc\"}}\n\nevent: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"tool_use\",\"name\":\"bash\",\"input\":{}}}\n\n")
result := rw.rewriteStreamChunk(chunk)
// Streaming mode preserves thinking blocks (does NOT suppress them)
// to avoid breaking SSE index alignment and TUI rendering
if !contains(result, []byte(`"content_block":{"type":"thinking"`)) {
t.Fatalf("expected thinking content_block_start to be preserved, got %s", string(result))
}
if !contains(result, []byte(`"delta":{"type":"thinking_delta"`)) {
t.Fatalf("expected thinking_delta to be preserved, got %s", string(result))
}
if !contains(result, []byte(`"type":"content_block_stop","index":0`)) {
t.Fatalf("expected content_block_stop for thinking block to be preserved, got %s", string(result))
}
if !contains(result, []byte(`"content_block":{"type":"tool_use"`)) {
t.Fatalf("expected tool_use content_block frame to remain, got %s", string(result))
}
// Signature should be injected into both thinking and tool_use blocks
if count := strings.Count(string(result), `"signature":""`); count != 2 {
t.Fatalf("expected 2 signature injections, but got %d in %s", count, string(result))
}
}
func TestSanitizeAmpRequestBody_RemovesWhitespaceAndNonStringSignatures(t *testing.T) {
input := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"drop-whitespace","signature":" "},{"type":"thinking","thinking":"drop-number","signature":123},{"type":"thinking","thinking":"keep-valid","signature":"valid-signature"},{"type":"text","text":"keep-text"}]}]}`)
result := SanitizeAmpRequestBody(input)
if contains(result, []byte("drop-whitespace")) {
t.Fatalf("expected whitespace-only signature block to be removed, got %s", string(result))
}
if contains(result, []byte("drop-number")) {
t.Fatalf("expected non-string signature block to be removed, got %s", string(result))
}
if !contains(result, []byte("keep-valid")) {
t.Fatalf("expected valid thinking block to remain, got %s", string(result))
}
if !contains(result, []byte("keep-text")) {
t.Fatalf("expected non-thinking content to remain, got %s", string(result))
}
}
func TestSanitizeAmpRequestBody_StripsSignatureFromToolUseBlocks(t *testing.T) {
input := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"thought","signature":"valid-sig"},{"type":"tool_use","id":"toolu_01","name":"Bash","input":{"cmd":"ls"},"signature":""}]}]}`)
result := SanitizeAmpRequestBody(input)
if contains(result, []byte(`"signature":""`)) {
t.Fatalf("expected signature to be stripped from tool_use block, got %s", string(result))
}
if !contains(result, []byte(`"valid-sig"`)) {
t.Fatalf("expected thinking signature to remain, got %s", string(result))
}
if !contains(result, []byte(`"tool_use"`)) {
t.Fatalf("expected tool_use block to remain, got %s", string(result))
}
}
func TestSanitizeAmpRequestBody_MixedInvalidThinkingAndToolUseSignature(t *testing.T) {
input := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"drop-me","signature":""},{"type":"tool_use","id":"toolu_01","name":"Bash","input":{"cmd":"ls"},"signature":""}]}]}`)
result := SanitizeAmpRequestBody(input)
if contains(result, []byte("drop-me")) {
t.Fatalf("expected invalid thinking block to be removed, got %s", string(result))
}
if contains(result, []byte(`"signature"`)) {
t.Fatalf("expected signature to be stripped from tool_use block, got %s", string(result))
}
if !contains(result, []byte(`"tool_use"`)) {
t.Fatalf("expected tool_use block to remain, got %s", string(result))
}
}
func contains(data, substr []byte) bool {
for i := 0; i <= len(data)-len(substr); i++ {
if string(data[i:i+len(substr)]) == string(substr) {
+4
View File
@@ -317,6 +317,10 @@ func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdk
// setupRoutes configures the API routes for the server.
// It defines the endpoints and associates them with their respective handlers.
func (s *Server) setupRoutes() {
s.engine.GET("/healthz", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
s.engine.GET("/management.html", s.serveManagementControlPanel)
openaiHandlers := openai.NewOpenAIAPIHandler(s.handlers)
geminiHandlers := gemini.NewGeminiAPIHandler(s.handlers)
+25
View File
@@ -1,6 +1,7 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
@@ -46,6 +47,28 @@ func newTestServer(t *testing.T) *Server {
return NewServer(cfg, authManager, accessManager, configPath)
}
func TestHealthz(t *testing.T) {
server := newTestServer(t)
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
rr := httptest.NewRecorder()
server.engine.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("unexpected status code: got %d want %d; body=%s", rr.Code, http.StatusOK, rr.Body.String())
}
var resp struct {
Status string `json:"status"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to parse response JSON: %v; body=%s", err, rr.Body.String())
}
if resp.Status != "ok" {
t.Fatalf("unexpected response status: got %q want %q", resp.Status, "ok")
}
}
func TestAmpProviderModelRoutes(t *testing.T) {
testCases := []struct {
name string
@@ -172,6 +195,8 @@ func TestDefaultRequestLoggerFactory_UsesResolvedLogDirectory(t *testing.T) {
nil,
nil,
nil,
nil,
nil,
true,
"issue-1711",
time.Now(),
+1 -1
View File
@@ -88,7 +88,7 @@ func (o *ClaudeAuth) GenerateAuthURL(state string, pkceCodes *PKCECodes) (string
"client_id": {ClientID},
"response_type": {"code"},
"redirect_uri": {RedirectURI},
"scope": {"org:create_api_key user:profile user:inference"},
"scope": {"user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload"},
"code_challenge": {pkceCodes.CodeChallenge},
"code_challenge_method": {"S256"},
"state": {state},
+1 -19
View File
@@ -4,10 +4,7 @@
package claude
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
)
@@ -61,28 +58,13 @@ func (ts *ClaudeTokenStorage) SaveTokenToFile(authFilePath string) error {
misc.LogSavingCredentials(authFilePath)
ts.Type = "claude"
// Create directory structure if it doesn't exist
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
// Create the token file
f, err := os.Create(authFilePath)
if err != nil {
return fmt.Errorf("failed to create token file: %w", err)
}
defer func() {
_ = f.Close()
}()
// Merge metadata using helper
data, errMerge := misc.MergeMetadata(ts, ts.Metadata)
if errMerge != nil {
return fmt.Errorf("failed to merge metadata: %w", errMerge)
}
// Encode and write the token data as JSON
if err = json.NewEncoder(f).Encode(data); err != nil {
if err := misc.WriteJSONFileSecure(authFilePath, data, false); err != nil {
return fmt.Errorf("failed to write token to file: %w", err)
}
return nil
+9 -1
View File
@@ -378,10 +378,18 @@ func TestToken_SaveTokenToFile(t *testing.T) {
if !tt.wantErr {
// Verify file was created
if _, err := os.Stat(filePath); os.IsNotExist(err) {
info, err := os.Stat(filePath)
if os.IsNotExist(err) {
t.Error("Token file was not created")
return
}
if err != nil {
t.Errorf("Stat() error = %v", err)
return
}
if got := info.Mode().Perm(); got != 0o600 {
t.Errorf("file mode = %v, want %v", got, os.FileMode(0o600))
}
// Verify file contents can be parsed back
data, err := os.ReadFile(filePath)
+7 -12
View File
@@ -4,12 +4,12 @@ package claude
import (
"net/http"
"net/url"
"strings"
"sync"
tls "github.com/refraction-networking/utls"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/proxyutil"
log "github.com/sirupsen/logrus"
"golang.org/x/net/http2"
"golang.org/x/net/proxy"
@@ -31,17 +31,12 @@ type utlsRoundTripper struct {
// newUtlsRoundTripper creates a new utls-based round tripper with optional proxy support
func newUtlsRoundTripper(cfg *config.SDKConfig) *utlsRoundTripper {
var dialer proxy.Dialer = proxy.Direct
if cfg != nil && cfg.ProxyURL != "" {
proxyURL, err := url.Parse(cfg.ProxyURL)
if err != nil {
log.Errorf("failed to parse proxy URL %q: %v", cfg.ProxyURL, err)
} else {
pDialer, err := proxy.FromURL(proxyURL, proxy.Direct)
if err != nil {
log.Errorf("failed to create proxy dialer for %q: %v", cfg.ProxyURL, err)
} else {
dialer = pDialer
}
if cfg != nil {
proxyDialer, mode, errBuild := proxyutil.BuildDialer(cfg.ProxyURL)
if errBuild != nil {
log.Errorf("failed to configure proxy dialer for %q: %v", cfg.ProxyURL, errBuild)
} else if mode != proxyutil.ModeInherit && proxyDialer != nil {
dialer = proxyDialer
}
}
+1 -15
View File
@@ -4,10 +4,7 @@
package codex
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
)
@@ -56,17 +53,6 @@ func (ts *CodexTokenStorage) SetMetadata(meta map[string]any) {
func (ts *CodexTokenStorage) SaveTokenToFile(authFilePath string) error {
misc.LogSavingCredentials(authFilePath)
ts.Type = "codex"
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
f, err := os.Create(authFilePath)
if err != nil {
return fmt.Errorf("failed to create token file: %w", err)
}
defer func() {
_ = f.Close()
}()
// Merge metadata using helper
data, errMerge := misc.MergeMetadata(ts, ts.Metadata)
@@ -74,7 +60,7 @@ func (ts *CodexTokenStorage) SaveTokenToFile(authFilePath string) error {
return fmt.Errorf("failed to merge metadata: %w", errMerge)
}
if err = json.NewEncoder(f).Encode(data); err != nil {
if err := misc.WriteJSONFileSecure(authFilePath, data, false); err != nil {
return fmt.Errorf("failed to write token to file: %w", err)
}
return nil
+9 -1
View File
@@ -304,10 +304,18 @@ func TestCodexTokenStorage_SaveTokenToFile(t *testing.T) {
if !tt.wantErr {
// Verify the file was created
if _, err := os.Stat(filePath); os.IsNotExist(err) {
info, err := os.Stat(filePath)
if os.IsNotExist(err) {
t.Errorf("SaveTokenToFile() file was not created at %s", filePath)
return
}
if err != nil {
t.Errorf("Stat() error = %v", err)
return
}
if got := info.Mode().Perm(); got != 0o600 {
t.Errorf("file mode = %v, want %v", got, os.FileMode(0o600))
}
// Read and verify content
data, err := os.ReadFile(filePath)
+1 -16
View File
@@ -4,10 +4,7 @@
package copilot
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
)
@@ -74,19 +71,7 @@ type DeviceCodeResponse struct {
func (ts *CopilotTokenStorage) SaveTokenToFile(authFilePath string) error {
misc.LogSavingCredentials(authFilePath)
ts.Type = "github-copilot"
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
f, err := os.Create(authFilePath)
if err != nil {
return fmt.Errorf("failed to create token file: %w", err)
}
defer func() {
_ = f.Close()
}()
if err = json.NewEncoder(f).Encode(ts); err != nil {
if err := misc.WriteJSONFileSecure(authFilePath, ts, false); err != nil {
return fmt.Errorf("failed to write token to file: %w", err)
}
return nil
+22 -38
View File
@@ -10,9 +10,7 @@ import (
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/codex"
@@ -20,9 +18,9 @@ import (
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/proxyutil"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"golang.org/x/net/proxy"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
@@ -80,36 +78,16 @@ func (g *GeminiAuth) GetAuthenticatedClient(ctx context.Context, ts *GeminiToken
}
callbackURL := fmt.Sprintf("http://localhost:%d/oauth2callback", callbackPort)
// Configure proxy settings for the HTTP client if a proxy URL is provided.
proxyURL, err := url.Parse(cfg.ProxyURL)
if err == nil {
var transport *http.Transport
if proxyURL.Scheme == "socks5" {
// Handle SOCKS5 proxy.
username := proxyURL.User.Username()
password, _ := proxyURL.User.Password()
auth := &proxy.Auth{User: username, Password: password}
dialer, errSOCKS5 := proxy.SOCKS5("tcp", proxyURL.Host, auth, proxy.Direct)
if errSOCKS5 != nil {
log.Errorf("create SOCKS5 dialer failed: %v", errSOCKS5)
return nil, fmt.Errorf("create SOCKS5 dialer failed: %w", errSOCKS5)
}
transport = &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.Dial(network, addr)
},
}
} else if proxyURL.Scheme == "http" || proxyURL.Scheme == "https" {
// Handle HTTP/HTTPS proxy.
transport = &http.Transport{Proxy: http.ProxyURL(proxyURL)}
}
if transport != nil {
proxyClient := &http.Client{Transport: transport}
ctx = context.WithValue(ctx, oauth2.HTTPClient, proxyClient)
}
transport, _, errBuild := proxyutil.BuildHTTPTransport(cfg.ProxyURL)
if errBuild != nil {
log.Errorf("%v", errBuild)
} else if transport != nil {
proxyClient := &http.Client{Transport: transport}
ctx = context.WithValue(ctx, oauth2.HTTPClient, proxyClient)
}
var err error
// Configure the OAuth2 client.
conf := &oauth2.Config{
ClientID: ClientID,
@@ -327,6 +305,9 @@ func (g *GeminiAuth) getTokenFromWeb(ctx context.Context, config *oauth2.Config,
defer manualPromptTimer.Stop()
}
var manualInputCh <-chan string
var manualInputErrCh <-chan error
waitForCallback:
for {
select {
@@ -348,13 +329,14 @@ waitForCallback:
return nil, err
default:
}
input, err := opts.Prompt("Paste the Gemini callback URL (or press Enter to keep waiting): ")
if err != nil {
return nil, err
}
parsed, err := misc.ParseOAuthCallback(input)
if err != nil {
return nil, err
manualInputCh, manualInputErrCh = misc.AsyncPrompt(opts.Prompt, "Paste the Gemini callback URL (or press Enter to keep waiting): ")
continue
case input := <-manualInputCh:
manualInputCh = nil
manualInputErrCh = nil
parsed, errParse := misc.ParseOAuthCallback(input)
if errParse != nil {
return nil, errParse
}
if parsed == nil {
continue
@@ -367,6 +349,8 @@ waitForCallback:
}
authCode = parsed.Code
break waitForCallback
case errManual := <-manualInputErrCh:
return nil, errManual
case <-timeoutTimer.C:
return nil, fmt.Errorf("oauth flow timed out")
}
+1 -21
View File
@@ -4,14 +4,10 @@
package gemini
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
log "github.com/sirupsen/logrus"
)
// GeminiTokenStorage stores OAuth2 token information for Google Gemini API authentication.
@@ -64,23 +60,7 @@ func (ts *GeminiTokenStorage) SaveTokenToFile(authFilePath string) error {
if errMerge != nil {
return fmt.Errorf("failed to merge metadata: %w", errMerge)
}
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
f, err := os.Create(authFilePath)
if err != nil {
return fmt.Errorf("failed to create token file: %w", err)
}
defer func() {
if errClose := f.Close(); errClose != nil {
log.Errorf("failed to close file: %v", errClose)
}
}()
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
if err := enc.Encode(data); err != nil {
if err := misc.WriteJSONFileSecure(authFilePath, data, true); err != nil {
return fmt.Errorf("failed to write token to file: %w", err)
}
return nil
+8 -1
View File
@@ -86,9 +86,16 @@ func TestGeminiTokenStorage_SaveTokenToFile(t *testing.T) {
}
// Verify file exists
if _, err := os.Stat(authPath); os.IsNotExist(err) {
info, err := os.Stat(authPath)
if os.IsNotExist(err) {
t.Fatal("token file was not created")
}
if err != nil {
t.Fatalf("Stat() error = %v", err)
}
if got := info.Mode().Perm(); got != 0o600 {
t.Fatalf("file mode = %v, want %v", got, os.FileMode(0o600))
}
// Verify type was set
if ts.Type != "gemini" {
+1 -13
View File
@@ -1,10 +1,7 @@
package iflow
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
)
@@ -36,15 +33,6 @@ func (ts *IFlowTokenStorage) SetMetadata(meta map[string]any) {
func (ts *IFlowTokenStorage) SaveTokenToFile(authFilePath string) error {
misc.LogSavingCredentials(authFilePath)
ts.Type = "iflow"
if err := os.MkdirAll(filepath.Dir(authFilePath), 0o700); err != nil {
return fmt.Errorf("iflow token: create directory failed: %w", err)
}
f, err := os.Create(authFilePath)
if err != nil {
return fmt.Errorf("iflow token: create file failed: %w", err)
}
defer func() { _ = f.Close() }()
// Merge metadata using helper
data, errMerge := misc.MergeMetadata(ts, ts.Metadata)
@@ -52,7 +40,7 @@ func (ts *IFlowTokenStorage) SaveTokenToFile(authFilePath string) error {
return fmt.Errorf("failed to merge metadata: %w", errMerge)
}
if err = json.NewEncoder(f).Encode(data); err != nil {
if err := misc.WriteJSONFileSecure(authFilePath, data, false); err != nil {
return fmt.Errorf("iflow token: encode token failed: %w", err)
}
return nil
+1 -18
View File
@@ -4,10 +4,7 @@
package kimi
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
@@ -83,27 +80,13 @@ func (ts *KimiTokenStorage) SaveTokenToFile(authFilePath string) error {
misc.LogSavingCredentials(authFilePath)
ts.Type = "kimi"
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
f, err := os.Create(authFilePath)
if err != nil {
return fmt.Errorf("failed to create token file: %w", err)
}
defer func() {
_ = f.Close()
}()
// Merge metadata using helper
data, errMerge := misc.MergeMetadata(ts, ts.Metadata)
if errMerge != nil {
return fmt.Errorf("failed to merge metadata: %w", errMerge)
}
encoder := json.NewEncoder(f)
encoder.SetIndent("", " ")
if err = encoder.Encode(data); err != nil {
if err := misc.WriteJSONFileSecure(authFilePath, data, true); err != nil {
return fmt.Errorf("failed to write token to file: %w", err)
}
return nil
+1 -2
View File
@@ -433,8 +433,7 @@ func GenerateTokenFileName(tokenData *KiroTokenData) string {
// Priority 1: Use email if available
if tokenData.Email != "" {
// Sanitize email for filename (replace @ and . with -)
sanitizedEmail := tokenData.Email
sanitizedEmail := SanitizeEmailForFilename(tokenData.Email)
sanitizedEmail = strings.ReplaceAll(sanitizedEmail, "@", "-")
sanitizedEmail = strings.ReplaceAll(sanitizedEmail, ".", "-")
return fmt.Sprintf("kiro-%s-%s.json", authMethod, sanitizedEmail)
+3 -1
View File
@@ -194,7 +194,9 @@ func (r *BackgroundRefresher) refreshSingle(ctx context.Context, token *Token) {
}
token.AccessToken = newTokenData.AccessToken
token.RefreshToken = newTokenData.RefreshToken
if newRefreshToken := strings.TrimSpace(newTokenData.RefreshToken); newRefreshToken != "" {
token.RefreshToken = newRefreshToken
}
token.LastVerified = time.Now()
if newTokenData.ExpiresAt != "" {
+11 -4
View File
@@ -13,6 +13,7 @@ import (
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
@@ -105,6 +106,12 @@ func (o *KiroOAuth) startCallbackServer(ctx context.Context, expectedState strin
// Use http scheme for local callback server
redirectURI := fmt.Sprintf("http://localhost:%d/oauth/callback", port)
resultChan := make(chan AuthResult, 1)
callbackReceived := make(chan struct{})
var callbackOnce sync.Once
sendResult := func(result AuthResult) {
resultChan <- result
callbackOnce.Do(func() { close(callbackReceived) })
}
server := &http.Server{
ReadHeaderTimeout: 10 * time.Second,
@@ -120,7 +127,7 @@ func (o *KiroOAuth) startCallbackServer(ctx context.Context, expectedState strin
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `<html><body><h1>Login Failed</h1><p>%s</p><p>You can close this window.</p></body></html>`, html.EscapeString(errParam))
resultChan <- AuthResult{Error: errParam}
sendResult(AuthResult{Error: errParam})
return
}
@@ -128,13 +135,13 @@ func (o *KiroOAuth) startCallbackServer(ctx context.Context, expectedState strin
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `<html><body><h1>Login Failed</h1><p>Invalid state parameter</p><p>You can close this window.</p></body></html>`)
resultChan <- AuthResult{Error: "state mismatch"}
sendResult(AuthResult{Error: "state mismatch"})
return
}
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<html><body><h1>Login Successful!</h1><p>You can close this window and return to the terminal.</p></body></html>`)
resultChan <- AuthResult{Code: code, State: state}
sendResult(AuthResult{Code: code, State: state})
})
server.Handler = mux
@@ -149,7 +156,7 @@ func (o *KiroOAuth) startCallbackServer(ctx context.Context, expectedState strin
select {
case <-ctx.Done():
case <-time.After(authTimeout):
case <-resultChan:
case <-callbackReceived:
}
_ = server.Shutdown(context.Background())
}()
+11 -4
View File
@@ -18,6 +18,7 @@ import (
"os/exec"
"runtime"
"strings"
"sync"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/browser"
@@ -117,6 +118,12 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
// Use http scheme for local callback server
redirectURI := fmt.Sprintf("http://localhost:%d/oauth/callback", port)
resultChan := make(chan WebCallbackResult, 1)
callbackReceived := make(chan struct{})
var callbackOnce sync.Once
sendResult := func(result WebCallbackResult) {
resultChan <- result
callbackOnce.Do(func() { close(callbackReceived) })
}
server := &http.Server{
ReadHeaderTimeout: 10 * time.Second,
@@ -134,7 +141,7 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
fmt.Fprintf(w, `<!DOCTYPE html>
<html><head><title>Login Failed</title></head>
<body><h1>Login Failed</h1><p>%s</p><p>You can close this window.</p></body></html>`, html.EscapeString(errParam))
resultChan <- WebCallbackResult{Error: errParam}
sendResult(WebCallbackResult{Error: errParam})
return
}
@@ -144,7 +151,7 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
fmt.Fprint(w, `<!DOCTYPE html>
<html><head><title>Login Failed</title></head>
<body><h1>Login Failed</h1><p>Invalid state parameter</p><p>You can close this window.</p></body></html>`)
resultChan <- WebCallbackResult{Error: "state mismatch"}
sendResult(WebCallbackResult{Error: "state mismatch"})
return
}
@@ -153,7 +160,7 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
<html><head><title>Login Successful</title></head>
<body><h1>Login Successful!</h1><p>You can close this window and return to the terminal.</p>
<script>window.close();</script></body></html>`)
resultChan <- WebCallbackResult{Code: code, State: state}
sendResult(WebCallbackResult{Code: code, State: state})
})
server.Handler = mux
@@ -168,7 +175,7 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
select {
case <-ctx.Done():
case <-time.After(socialAuthTimeout):
case <-resultChan:
case <-callbackReceived:
}
_ = server.Shutdown(context.Background())
}()
+11 -4
View File
@@ -16,6 +16,7 @@ import (
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/browser"
@@ -1116,6 +1117,12 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
port := listener.Addr().(*net.TCPAddr).Port
redirectURI := fmt.Sprintf("http://127.0.0.1:%d%s", port, authCodeCallbackPath)
resultChan := make(chan AuthCodeCallbackResult, 1)
callbackReceived := make(chan struct{})
var callbackOnce sync.Once
sendResult := func(result AuthCodeCallbackResult) {
resultChan <- result
callbackOnce.Do(func() { close(callbackReceived) })
}
server := &http.Server{
ReadHeaderTimeout: 10 * time.Second,
@@ -1134,7 +1141,7 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
fmt.Fprintf(w, `<!DOCTYPE html>
<html><head><title>Login Failed</title></head>
<body><h1>Login Failed</h1><p>Error: %s</p><p>You can close this window.</p></body></html>`, html.EscapeString(errParam))
resultChan <- AuthCodeCallbackResult{Error: errParam}
sendResult(AuthCodeCallbackResult{Error: errParam})
return
}
@@ -1143,7 +1150,7 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
fmt.Fprint(w, `<!DOCTYPE html>
<html><head><title>Login Failed</title></head>
<body><h1>Login Failed</h1><p>Invalid state parameter</p><p>You can close this window.</p></body></html>`)
resultChan <- AuthCodeCallbackResult{Error: "state mismatch"}
sendResult(AuthCodeCallbackResult{Error: "state mismatch"})
return
}
@@ -1151,7 +1158,7 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
<html><head><title>Login Successful</title></head>
<body><h1>Login Successful!</h1><p>You can close this window and return to the terminal.</p>
<script>window.close();</script></body></html>`)
resultChan <- AuthCodeCallbackResult{Code: code, State: state}
sendResult(AuthCodeCallbackResult{Code: code, State: state})
})
server.Handler = mux
@@ -1166,7 +1173,7 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
select {
case <-ctx.Done():
case <-time.After(10 * time.Minute):
case <-resultChan:
case <-callbackReceived:
}
_ = server.Shutdown(context.Background())
}()

Some files were not shown because too many files have changed in this diff Show More