${esc(row.message)}
${esc(row.action)}
')}
From c03c314b632ba1199574b7e22bcea3a59419ea5e Mon Sep 17 00:00:00 2001 From: Gaoshou101 <188431084+Gaoshou101@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:09:13 +0800 Subject: [PATCH 1/4] Complete diagnostics, model evidence and runtime recovery for v0.2.10 --- .github/workflows/build.yml | 59 ++++- CHANGELOG.md | 20 +- FEASIBILITY.md | 14 +- README.md | 8 + docs/DEPLOYMENT.md | 49 ++++ docs/NEXT_STEPS.md | 192 +++++++++----- docs/RELEASE_NOTES.md | 24 +- docs/VALIDATION.md | 90 +++++++ integrations/cpamp/README.md | 13 + integrations/cpamp/apply.py | 17 +- .../cpamp/commandcode_health_test.go.fragment | 21 ++ .../cpamp/commandcode_quota_test.go.fragment | 9 + internal/bridge/affinity.go | 17 +- internal/bridge/compatibility.go | 130 ++++++++++ internal/bridge/compatibility.json | 13 + internal/bridge/compatibility_test.go | 70 +++++ internal/bridge/cpamp_panel.go | 19 +- internal/bridge/diagnostics.go | 153 +++++++++++ internal/bridge/diagnostics_test.go | 125 +++++++++ internal/bridge/executor.go | 6 +- internal/bridge/management.go | 37 ++- internal/bridge/model_evidence.go | 92 +++++++ internal/bridge/model_evidence_test.go | 75 ++++++ internal/bridge/observability.go | 74 ++++-- internal/bridge/persistence.go | 113 +++++++-- internal/bridge/persistence_test.go | 4 +- internal/bridge/runtime_recovery.go | 168 ++++++++++++ internal/bridge/runtime_recovery_test.go | 204 +++++++++++++++ internal/bridge/runtime_scale_test.go | 62 +++++ internal/bridge/service.go | 92 ++++--- internal/bridge/statistics_retention.go | 71 ++++++ internal/bridge/types.go | 31 ++- internal/bridge/ui/console.css | 8 + internal/bridge/ui/console.js | 81 ++++-- internal/bridge/ui/index.html | 12 +- internal/bridge/usage.go | 13 +- scripts/checksums.py | 7 + scripts/embed_cpamp_panel.py | 2 + scripts/package.py | 1 + scripts/package_cpamp.py | 5 + tests/commandcode_live.py | 240 ++++++++++++------ tests/console-diagnostics.test.cjs | 64 +++++ tests/console-evidence.test.cjs | 43 ++++ tests/cpa_diagnostics.py | 64 +++++ tests/cpa_round2.py | 113 +++++++++ 45 files changed, 2423 insertions(+), 302 deletions(-) create mode 100644 integrations/cpamp/commandcode_health_test.go.fragment create mode 100644 internal/bridge/compatibility.go create mode 100644 internal/bridge/compatibility.json create mode 100644 internal/bridge/compatibility_test.go create mode 100644 internal/bridge/diagnostics.go create mode 100644 internal/bridge/diagnostics_test.go create mode 100644 internal/bridge/model_evidence.go create mode 100644 internal/bridge/model_evidence_test.go create mode 100644 internal/bridge/runtime_recovery.go create mode 100644 internal/bridge/runtime_recovery_test.go create mode 100644 internal/bridge/runtime_scale_test.go create mode 100644 internal/bridge/statistics_retention.go create mode 100644 tests/console-diagnostics.test.cjs create mode 100644 tests/console-evidence.test.cjs create mode 100644 tests/cpa_diagnostics.py create mode 100644 tests/cpa_round2.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c6b487c..2f17e1f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -29,7 +29,7 @@ jobs: run: python3 scripts/embed_cpamp_panel.py dist/cpamp-web/*_cpamp-web.zip - run: go test -race ./... - run: go vet ./... - - run: node --test tests/cpa-auth.test.cjs + - run: node --test tests/*.test.cjs - name: Native host integration (CPA v8.0.23) env: GH_TOKEN: ${{ github.token }} @@ -45,6 +45,8 @@ jobs: CPA_BINARY=/tmp/cpa-test/cli-proxy-api python3 tests/cpa_e2e.py CPA_BINARY=/tmp/cpa-test/cli-proxy-api python3 tests/cpa_native_management.py CPA_BINARY=/tmp/cpa-test/cli-proxy-api python3 tests/cpa_reliability.py + CPA_BINARY=/tmp/cpa-test/cli-proxy-api python3 tests/cpa_diagnostics.py + CPA_BINARY=/tmp/cpa-test/cli-proxy-api python3 tests/cpa_round2.py gh release download v0.2.8 --repo Gaoshou101/CommandCodeBridge --pattern commandcodebridge_0.2.8_linux_amd64.zip --pattern checksums.txt --dir /tmp/bridge-previous cd /tmp/bridge-previous sha256sum --check --ignore-missing checksums.txt @@ -128,6 +130,10 @@ jobs: if ($LASTEXITCODE -ne 0) { throw 'Windows native management integration failed' } python tests/cpa_reliability.py if ($LASTEXITCODE -ne 0) { throw 'Windows reliability integration failed' } + python tests/cpa_diagnostics.py + if ($LASTEXITCODE -ne 0) { throw 'Windows diagnostics integration failed' } + python tests/cpa_round2.py + if ($LASTEXITCODE -ne 0) { throw 'Windows round two integration failed' } python tests/cpa_hot_reload.py if ($LASTEXITCODE -ne 0) { throw 'Windows live configuration integration failed' } - name: ARM64 native host integration @@ -193,7 +199,7 @@ jobs: npm --workspace apps/web run type-check npm --workspace apps/web run test -- src/features/accounts/components/CommandCodeQuotaCard.test.tsx src/features/accounts/components/commandCodeQuotaStore.test.ts src/features/accounts/model/commandCodeQuotaWindows.test.ts src/features/accounts/model/accountHealthEvidence.test.ts src/features/accounts/model/accountQuotaWindowDefinitions.test.ts src/features/accounts/components/QuotaWindowCard.test.tsx src/services/api/CommandCodeOAuth.test.ts src/services/api/oauth.test.ts src/features/oauth/OAuthPage.test.tsx src/features/accounts/components/accountDetail/AccountQuotaTab.test.tsx npm --workspace apps/web run build - (cd apps/manager-server && go test ./internal/service/quotasnapshot -run TestCommandCode -count=1) + (cd apps/manager-server && go test ./internal/service/quotasnapshot ./internal/http/controller/health -run TestCommandCode -count=1) cd "$GITHUB_WORKSPACE" python scripts/package_cpamp.py "$cpamp_source" python - "$cpamp_source" <<'PY' @@ -212,6 +218,55 @@ jobs: dist/*_cpamp-web.zip dist/*_cpamp-web.zip.sha256 + upstream-compatibility: + needs: cpamp-web + runs-on: ubuntu-24.04 + # Report candidate compatibility without changing the pinned release gate. + continue-on-error: true + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.26.x' + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: actions/download-artifact@v4 + with: + name: commandcodebridge-cpamp-web + path: dist/cpamp-web + - name: Test the latest CPA release as a candidate + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + mkdir -p dist/upstream-compatibility + candidate="$(gh release view --repo router-for-me/CLIProxyAPI --json tagName --jq .tagName)" + printf 'Pinned baseline: v8.0.23\nCandidate: %s\n' "$candidate" > dist/upstream-compatibility/result.txt + archive="CLIProxyAPI_${candidate#v}_linux_amd64.tar.gz" + gh release download "$candidate" --repo router-for-me/CLIProxyAPI --pattern "$archive" --pattern checksums.txt --dir dist/upstream-compatibility + (cd dist/upstream-compatibility && sha256sum --check --ignore-missing checksums.txt && tar -xzf "$archive") + python scripts/embed_cpamp_panel.py dist/cpamp-web/*_cpamp-web.zip + go build -trimpath -buildvcs=false -buildmode=c-shared -o dist/upstream-compatibility/commandcodebridge.so ./cmd/commandcodebridge + export CPA_BINARY="$PWD/dist/upstream-compatibility/cli-proxy-api" + export BRIDGE_LIBRARY="$PWD/dist/upstream-compatibility/commandcodebridge.so" + python tests/cpa_e2e.py 2>&1 | tee -a dist/upstream-compatibility/result.txt + python tests/cpa_reliability.py 2>&1 | tee -a dist/upstream-compatibility/result.txt + python tests/cpa_diagnostics.py 2>&1 | tee -a dist/upstream-compatibility/result.txt + - name: Record candidate result + if: always() + shell: bash + run: | + echo '## CPA candidate compatibility' >> "$GITHUB_STEP_SUMMARY" + if [ -f dist/upstream-compatibility/result.txt ]; then cat dist/upstream-compatibility/result.txt >> "$GITHUB_STEP_SUMMARY"; fi + echo 'The candidate result does not change the pinned supported baseline.' >> "$GITHUB_STEP_SUMMARY" + - uses: actions/upload-artifact@v4 + if: always() + with: + name: upstream-cpa-compatibility-report + path: dist/upstream-compatibility/result.txt + release-checksums: needs: [build, cpamp-web] runs-on: ubuntu-24.04 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4013284..a4e987a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,24 @@ # Changelog -## Unreleased +## Unreleased — 0.2.10 源码 + +### Added + +- 凭证运行登记诊断:对照 CPA 运行登记,区分缺失、重复、旧路由、启停未同步、等待加载与未知状态;账户查询、插件直测和 CPA 请求分别保留来源和时间。提供脱敏摘要,不触发模型生成。 +- 设置页升级兼容检查:分别核验插件接口、实际服务页面、额度/最近请求/周期历史标识和快照后端。旧后端未报告能力时显示未知;只读 loopback 健康检查不写入快照。 +- 共享兼容基线写入安装包清单,CI 增加凭证登记回归及较新 CPA 候选版本兼容报告,固定 v8.0.23 发布门槛保留。 + +- 第二轮模型证据接口与凭据选择器,按凭证版本、账户、映射和时间隔离,分开显示插件直测与 CPA 请求。明确套餐拒绝、未知权限、临时限流、过期证据不混用。 +- 运行数据格式元数据、损坏隔离、每分钟检查点、恢复警告与统计迁移原件;支持分钟/日分层汇总和可选过期,默认保留全部日总量。 +- 有请求数和 token 上限的真实验收脚本,新增无网络预览、Claude 工具/图片/thinking 签名重放和 ZDR 脱敏报告。本轮仅在模拟端验收,真实验收待验证。 + +### Changed + +- 请求、统计和额度独立标脏落盘;状态返回待写时长、最后成功时间及分类写入次数。采样增加正抖动,保留逐凭证缓存与 3 并发。 +- 插件直测的模型 401/403 不再被控制台误判为管理登录失效;切换身份后丢弃模型证据与存储旧响应。 +- 凭证保存与宿主加载分别反馈,重复保存相同内容保留已有确认;会话重新分配显示宿主确认。管理登录失效或切换时清除旧诊断并丢弃过期响应。 +- 原生面板安装前显示目标、备份和重启条件;CPAMP 适配脚本增加快照健康能力声明与 HTTP 回归,版本插入点不匹配时给出基线信息。 +- 第一、二轮本地交付与验证记录同步;第三轮明确继续参照 CommandCode 官网控制台的美术风格与页面设计。此版本尚未发布或部署。 ## [0.2.9] - 2026-10-13 diff --git a/FEASIBILITY.md b/FEASIBILITY.md index 032aeb2..461c47a 100644 --- a/FEASIBILITY.md +++ b/FEASIBILITY.md @@ -1,6 +1,6 @@ # CommandCodeBridge:可行性与实现结论 -更新:2026-10-11。 +更新:2026-10-18。 ## 结论 @@ -18,6 +18,14 @@ - 通用 HTTP RPC 只支持全局代理,凭据代理明确拒绝,避免意外绕过。 - 管理页检查了登录、备注编辑、模型测试、设置、主题和响应式布局;登录单测含子路径和端点隔离。 +### 第一轮补充 + +v0.2.10 本地源码新增凭证运行登记诊断和升级兼容检查,分别报告保存、加载、页面与快照后端的证据。固定兼容基线仍为 CPA v8.0.23;较新上游候选任务尚无本轮远端结果。第三轮视觉优化已列入 [NEXT_STEPS.md](docs/NEXT_STEPS.md)。 + +### 第二轮补充 + +v0.2.10 未发布源码已加入按凭据版本/账户/映射隔离的模型证据、独立历史文件落盘、检查点与损坏恢复,以及分钟/日统计分层。90 天合成数据保留总量、JSON 体积缩减约 91.6%;真实宿主连接模拟端的 13 次扩展协议验收通过。真实 Claude/图片语义/thinking/ZDR 和账户共享按用户要求仍为待验证,详见 [VALIDATION.md](docs/VALIDATION.md)。没有跨 key 合并采样,没有发布部署。 + ## 架构 ```text @@ -36,7 +44,9 @@ ## 待真实环境核实 -没有真实 CommandCode key,未发付费请求。套餐 JSON、模型权限、零数据保留和 CPAMP 部署需实账号验证。高吞吐性能未测。安装与协议边界见 [README](README.md)。 +仓库已有真实账户查询、套餐字段与免费 Ling 模型 Chat/Responses/工具往返的验证记录;已有短时模拟并发基线,不能代表真实上游速度或长期生产容量。详见 [VALIDATION.md](docs/VALIDATION.md),本轮未重复使用真实账户。 + +Claude 原生 Messages、图片、thinking signature 和 ZDR 仍缺真实权限/行为验证;个人/组织身份、同账号多 key 的共享边界及长期运行容量仍需核实。CPAMP 已有隔离二进制及历史部署页面验证,本轮未连接或修改目标部署。安装与协议边界见 [README](README.md)。 ## 参考 diff --git a/README.md b/README.md index af81ff4..886abff 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,14 @@ 当前版本 **v0.2.9**。插件调用官方 Provider API;Go 订阅的 `/alpha/generate` 路径和固定上游 provider 模式不在支持范围内。账户用量通过官方 `/alpha/...` 查询接口读取,模型权限以实际套餐为准。 +### 开发中:v0.2.10 第一轮 + +当前源码新增凭证运行登记诊断、脱敏摘要和升级兼容检查。在「凭据与用量」查看登记与三类证据,在「设置」核对插件、页面和快照后端。保存成功与宿主加载分别显示;只读诊断不发模型生成请求。此源码尚未发布,插件商店与安装说明继续对应已发布基线 v0.2.9。 + +详见[下一步规划](./docs/NEXT_STEPS.md)和[验证记录](./docs/VALIDATION.md)。第三轮将继续参照 CommandCode 官网控制台优化美术风格与页面设计。 + +第二轮本地实现已加入同一未发布源码:模型页按凭证显示实测证据和 24 小时有效期;运行历史支持损坏隔离与检查点恢复;统计自动转为近期分钟级、历史日级,默认不删除日总量。真实 Claude/图片/thinking/ZDR 和账户身份共享按用户选择标为**待验证**。详见[验证记录](docs/VALIDATION.md)与[数据恢复说明](docs/DEPLOYMENT.md#第二轮运行数据恢复与统计迁移未发布源码)。 + ## 快速安装 需要启用插件的 [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)。四个平台的原生宿主联测基线为 **CPA v8.0.23**;名称含 `no-plugin` 的宿主构建不能加载本插件。 diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index be5da94..bdf15a7 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -180,3 +180,52 @@ Windows 使用 `Get-FileHash -Algorithm SHA256`,macOS 使用 `shasum -a 256` | 日志写入失败 | 检查 data_dir 的磁盘空间、权限及 `storage_error` | | 重启后设置未按 YAML 改变 | 已存 settings.json 优先;采用明确的迁移方案 | | CPAMP 登录失败 | 确认使用 Manager Server 管理员密钥;它不同于 CPA Management Key | + +## v0.2.10 源码:登记诊断与升级检查 + +本节适用于开发中的 v0.2.10,尚未发布或部署。 + +- 「凭据与用量 → 运行登记诊断」核对本地凭证与 CPA 运行登记。保存响应中的 `saved: true` 仅表示写入成功,`registration` 单独表示宿主确认;等待、缺失或未知时可重试诊断并查 CPA watcher/插件加载日志。 +- 账户查询证明查询结果,插件直测证明执行器结果,CPA 请求记录证明请求曾进入插件;它们分别显示时间和来源。旧日志没有来源时保持未知。宿主在调度前拒绝的请求不会新增插件日志。 +- 「复制脱敏摘要」读取 `GET /v0/management/commandcodebridge/diagnostics/summary`。它排除凭证 ID/备注、文件路径、模型名、key、认证结果及请求正文;仍包含版本、数量、状态和检查时间。完整诊断为同路径下 `/diagnostics`,均使用现有管理鉴权。 +- 「设置 → 升级兼容检查」对应 `/compatibility`,分别显示插件、实际 HTTP 页面、额度、最近请求、周期历史和快照后端。页面摘要相同只证明服务器页面一致,浏览器缓存仍需强刷核对。 +- 快照后端仅在同机 loopback `GET /health` 明确返回布尔能力 `capabilities.commandcode_quota_snapshots_v1` 时判定。旧健康响应、异机/容器不可探测、超时和未知版本均显示未确认,不据此写入试探快照,也不推断不兼容。 +- 页面安装预览列出目标与备份规则,并按最终检查显示重启条件。HTML 热替换不会重建或重启 Manager Server;新增健康声明和快照名单需要匹配源码补丁、重建并重启该服务。 + +兼容清单固定 CPA v8.0.23、ABI 1/RPC 6、CPAMP `dbf61dd`、Manager 1.13.1/1.14.0 基线。较新 CPA 的 CI 候选任务只报告结果,不能替代已验证基线;其本轮远端执行结果尚未取得。 + + +## 第二轮:运行数据恢复与统计迁移(未发布源码) + +源码仍标记 v0.2.10,商店已发布版本保持 v0.2.9。本节适用于自行构建的第二轮源码。 + +### 文件与写入 + +`settings.json`、凭证仍走原配置/宿主流程。`requests.json`、`statistics.json`、`usage.json` 保留原数组/字典结构,分别标脏、250ms 批量刷盘;只有变更的文件写入。`runtime-format.json` 记录格式版本及最近 20 条恢复警告。未知格式、设置损坏或不可读均明确报错,保留原文件。 + +每个运行文件的 `.last-good` 检查点最多每分钟随变更刷新一次。恢复可能丢失检查点之后的数据,独立文件不构成跨文件事务,也不承诺断电 fsync 耐久性。状态/设置页显示最近成功刷盘、待写文件与起始时间,恢复警告重启后仍保留。无有效检查点时,仅重建损坏的观察文件,并提示该历史范围未知;配置与其他有效历史保留。 + +### 损坏与恢复 + +1. 停止写入前先查看设置中的恢复记录及 CPA 日志;运行文件损坏会隔离为 `*.corrupt-<随机值>`,有有效 `.last-good` 时自动恢复。 +2. 隔离原件、检查点和恢复/迁移备份可能包含凭据标签、用量及错误记录,按私有运行数据保管,不提交仓库。插件不会向这些运行文件写入 API key、请求正文或 thinking 签名。 +3. 手工恢复需先停 CPA、备份整个 `data_dir`,再选择可信文件恢复到对应原名;保留警告与隔离原件供核对。不要用其他凭据/上游的额度缓存覆盖当前数据。 +4. 清空统计会保存 `statistics-backup-*.json`,并移走清空前检查点;随后主统计先置空、新检查点再生成,避免清空后从旧检查点回流。清空统计不清请求日志。 + +### 历史统计精度与回滚 + +- 最近 7 个完整 UTC 日加当天保留分钟桶,更早汇总到 UTC 日,保留请求/成功/失败/tokens/延迟和速率累计值。 +- `statistics_retention_days: 0` 默认永久保留日总量;1–3650 表示自动过期更早统计。设置页保存非零值需确认,过期后延长保留时间无法找回。日志条数保留仍独立生效。 +- 跨历史日的查询按相交整日计入;API 返回 `bucket_seconds` 与 `range_note`,页面提示范围可能扩展到整日,不伪造分钟精度。 +- 首次加载已有统计时保存 `statistics-before-daily-v1.json`,该副本只保留一次,不自动轮换。迁移/清空备份与隔离原件需管理员按需归档,以免长期累积。 +- 降级旧版仍可读取相同 JSON 外形和全量总计,但旧版不理解日桶的区间边界。若需恢复旧分钟精度,停服务、保全新历史后,从迁移副本恢复;该副本之后的新请求不会自动合并。不能将这一手工回退描述为无损降级。 + +### 协议真实验收(待验证) + +本轮没有真实账号调用。可先运行无网络预览: + +```sh +python tests/commandcode_live.py --dry-run --generate --chat-model YOUR_CHAT_MODEL --messages-model YOUR_CLAUDE_MODEL --tools --image --thinking --thinking-mode adaptive --zdr --max-requests 13 --max-tokens 2048 +``` + +实际执行需要仓库外 JSON 凭据文件(`api_key`)、CPA/动态库环境变量及明确允许的模型和请求预算,再去掉 `--dry-run` 并添加 `--credential-file`、`--report`。可分组降低预算;所有组合最多 13 次,本脚本硬限制最多 20 次、每次至多 8192 输出 tokens。实际收费规则以上游为准;ZDR 请求被接受也不能证明服务端保留策略。个人/组织与多 key 的共享身份仍待真实验收,因此采样保持逐凭据隔离。 diff --git a/docs/NEXT_STEPS.md b/docs/NEXT_STEPS.md index 860f00e..f33ae56 100644 --- a/docs/NEXT_STEPS.md +++ b/docs/NEXT_STEPS.md @@ -1,96 +1,160 @@ -# CommandCodeBridge 下一步开发待办 +# CommandCodeBridge 下一步优化规划 -更新:2026-10-11。根据当前代码、README、FEASIBILITY 和上一轮开发记录恢复。 +更新:2026-10-18。第一轮已进入 v0.2.10 源码,验证证据见[验证记录](VALIDATION.md)。第二轮本地实现已完成,真实验收按用户要求待验证;第三轮为后续排期,正式发布状态以 Release 为准。 -## 当前基线 +## 结论 -- 版本:0.2.1;CPA 原生 C ABI 1 / RPC schema 6。 -- 已实现多凭据、优先级、会话重分配、模型目录/别名/思考映射、三种客户端协议、工具/图片、套餐用量、日志统计及中文控制台。 -- 当前验证:Go 回归与竞态检查、10 个登录适配测试;CPA v8.0.23 在 Linux amd64/arm64、Windows amd64 和 macOS arm64 各通过模拟集成及异常恢复场景。 -- 四个平台均已完成实际宿主加载与调用,ZIP / SHA256 与构建来源已核验;两个 Linux 包要求 glibc ≥2.34。 -- 真实 CommandCode 账户查询及免费 Ling 模型的 6 次 Chat/Responses、流/非流、工具往返已验证,共 864 tokens,插件与 CPA 记账一致。 -- 用户自行安装;当前交付 GitHub 源码、四平台安装包和部署说明,未修改目标服务。 -- 已建立源码基线和仓库 `Gaoshou101/CommandCodeBridge`,按用户要求改为公开并提供 GitHub 安装源;没有 `.planning` 状态文件。 -- 已继续实施,最新证据见 [VALIDATION.md](VALIDATION.md)。 +下一阶段优先降低故障定位和升级成本,再补真实协议验收与长期运行能力。 -## P0:建立可追踪基线与真实账号验证 +| 优先级 | 方向 | 主要交付 | 粗估工作量 | +| --- | --- | --- | --- | +| P0 | 凭证与宿主运行登记一致性 | 只读诊断、保存与加载确认、脱敏诊断摘要 | 2–3 个开发日 | +| P0 | 插件与 CPAMP 升级兼容性 | 插件/页面/快照后端能力检查、兼容矩阵 | 2–3 个开发日 | +| P1 | 真实协议与模型可用状态 | Claude 关键路径验收、按凭证隔离的模型证据 | 2–4 个开发日,账号等待另计 | +| P1 | 数据恢复与长期运行成本 | 损坏隔离、分类落盘、统计保留与采样优化 | 3–5 个开发日,先测量 | +| P2 | 上游变更与维护效率 | 目录变化预览、契约检查、CI 与文档同步 | 逐项估算 | -### 1. 固化源码基线 +## 当前基线与证据边界 -- [x] 检查源码、示例配置及包内容,确保不包含真实凭据或本机临时路径。 -- [x] 创建首个源码提交;记录版本、CPA 宿主版本和测试命令。 -- [x] 创建私有仓库、配置远端,并将插件元数据改为真实仓库地址。 +- 核心功能已覆盖多凭证、模型映射、三种客户端协议、工具和图片、原生额度窗口、请求统计。 +- v0.2.9 已实现最近请求同步、额度落盘、重启恢复和密钥变更隔离;旧待办中的这些事项已经完成。 +- 仓库记录已有四平台 CPA v8.0.23 宿主联测、异常恢复、热升级和前端回归,以及真实免费 Ling 模型 Chat/Responses/工具往返验证。 +- Claude 原生 Messages、图片、thinking signature、ZDR,以及真实个人/组织身份和同账号多 key 的共享行为,仍有真实验证缺口。 +- CPAMP 页面固定基于源码 dbf61dd;完整周期快照另需 Manager Server 接受 commandcode。 +- 第一轮使用项目内 Go 1.26 工具链与隔离 CPA 进行回归,结果见 VALIDATION.md;此前 PATH 缺少 Go 已不构成验证限制。 +- Hindsight 已只读查询;GitHub Issue、PR、Release 和 CI 实时查询因网络 EOF 未取得结果。本文不声称生产部署或 GitHub 当前状态已核实。 -验收:代码可从提交恢复,版本和构建来源可追踪;远端地址不得用占位值冒充。 +历史记忆记录过“凭证文件存在但 CPA 运行时没有加载,最终报 auth_not_found”的现场问题。本轮在隔离 CPA 复现了插件仍持有凭证、宿主缺失登记、请求进入插件前被拒绝及恢复的链路;没有连接目标部署,不能据此认定历史现场的具体根因。 -### 2. 验证真实 CommandCode 账户接口 +## P0-1(第一轮已实现):凭证与宿主运行状态诊断 -依赖:具有官方 Provider API 权限的 Studio API key。 +**收益:缩短“有 key、有模型,却没有可用账号”的定位过程。** -- [x] 调用只读身份、余额、套餐、窗口和请求数接口,确认真实字段解析。窗口未开始时 `resetAt=0` 保持未知。 -- [ ] 核实个人/组织账户身份及同账号多 key 的额度共享行为,补充脱敏响应样本作为回归夹具。 -- [x] 修正真实汇总 `totalCount` 字段;缺失字段继续显示未知或过期值,不推算余额。 -- [x] 用少量短请求核实免费 Ling 模型的 Chat 流/非流、工具往返及 usage。 -- [x] 核实 Responses 经 CPA 转换后的流/非流结果和实际记账。 -- [ ] 取得具备对应权限的模型后,验证 Claude 原生 Messages、图片、思考签名及 ZDR 参数。 +### 实现前依据 -验收:真实响应与控制台、请求日志、CPA 记账一致;记录实际支持和限制,不以模拟测试代替真实结果。 +- GET /status 只返回插件版本、本地凭证数、模型数及持久化状态。 +- GET /credentials 的健康度来自账户查询和插件已收到的请求,不能说明 CPA 是否已将凭证纳入可调度状态。 +- affinity.go 中已有 runtimeAuths(),封装 host.auth.list,供删除和会话重新分配后的确认使用。 +- 现有 POST /models/test 直接进入插件执行器,成功不能证明客户端经 CPA 调度同样成功。 -## P1:补足运行可靠性与部署验收 +### 第一轮已交付 -### 3. 扩展真实 CPA 宿主的异常场景 +1. 增加只读诊断入口,核对插件凭证、CPA 运行登记、启停状态、routing ID、模型映射和冷却状态。 +2. 展示尚未登记、登记重复、路由 ID 不一致、已停用、模型未映射、已知冷却、宿主不可查询等明确结果。 +3. 新增/编辑/会话重新分配后,分别反馈“保存成功”和“宿主确认”;未确认时提供可重试的结果。 +4. 分开标注账户查询、插件直测、客户端经 CPA 调用三种检查;证据带来源和时间。 +5. 提供脱敏诊断摘要,包含版本、数量、状态和错误类别,排除密钥、认证结果、请求正文与私人账户信息。 -- [x] 新增 `tests/cpa_reliability.py`,覆盖 429 / Retry-After、503、超时、SSE 中断和客户端取消。 -- [x] 核实多 key、同账号多 key、不同模型别名下的冷却、恢复及账号切换。 -- [x] 核实失败/重试时的日志与 usage,避免重复记账;取消后及时释放上游连接。 -- [x] 增加 CPA 重启后凭据、模型映射、统计和会话重分配恢复验收。 +### 验收 -验收:在 Linux/Windows 宿主均有可重复的异常与恢复证据;复用现有单测,不重复新增已覆盖的场景。 +- 隔离 CPA 复现遗漏登记、重复/旧 routing ID、停用未同步,以及热升级后的登记状态。 +- 默认诊断不发模型生成请求;不能检查的项目显示“未知”。 +- 宿主在请求进入插件前拒绝调用时,仍能从诊断定位到缺失环节。 +- 恢复操作有明确动作和结果;自动恢复在宿主能力确认后另行设计。 -### 4. 验证并发与持久化性能 +## P0-2(第一轮已实现):升级兼容性与功能生效检查 -- [x] 对模拟上游做 1/8/32 并发测量,记录吞吐、首字延迟、CPU/内存和磁盘写入量。 -- [x] 测量并确认 `Service.record` 在全局锁内同步写入 JSON 的开销。 -- [x] 实现 250ms 批量写入,明确退出刷盘、失败重试与强制退出的数据损失边界。 -- [x] 验证清空统计、同时查询管理页、关机/重启期间的计数和持久化一致性。 +**收益:减少“安装成功但界面或历史功能没有生效”。** -验收:形成实测基线;优化必须有前后对比,并保持既有日志与统计语义。 +### 实现前依据 -### 5. CPA / CPAMP 部署联测 +面板检查已有进程、路径、HTTP 页面标识和摘要。升级涉及插件动态库、外部页面和 Manager Server 快照名单,单个页面摘要无法说明全部后端能力。 -用户自行安装,目标 `https://cpa.gdp.pw/` 已确认;现场 CPA 版本、实际目录和代理配置由安装时核实。 +### 第一轮已交付 -- [ ] 验证 CPAMP 完整代理、子目录路径、两种管理鉴权头及登录失效后的交互。 -- [ ] 核实 CPA 全局代理在目标环境生效,并验证数据卷权限与重启持久化。 -- [ ] 验收凭据编辑/停用/删除、模型导入/测试、主题及手机布局。 -- [x] 补充安装、升级、备份、回滚和常见错误说明,见 [DEPLOYMENT.md](DEPLOYMENT.md)。 +1. 扩展现有检查为能力清单:插件运行版本、实际页面版本/摘要、额度接口、最近请求接口、快照后端能力和检查时间。 +2. 发布清单记录已验证的 CPA、CPAMP 源码和 Manager Server 基线,以及新增能力的最低要求。 +3. 升级前显示差异、备份位置及重启要求;升级后通过实际 HTTP 页面和接口检查生效。 +4. 区分页面存在、页面已对外服务、快照后端可用。无法只读确认的后端能力显示未确认,避免为检测写入用户快照。 +5. CI 保留 pinned 基线,增加一个经选择的较新上游版本兼容任务;验证后再决定是否更新默认基线。 +6. 保留 apply.py --check 先校验全部插入点、拒绝歧义、重复应用安全的现有约束,补充版本不匹配说明。 -验收:从安装到客户端调用完成一条真实部署链路,重启后数据与账号登记正常。 +### 验收 -## P2:多平台与发布准备 +覆盖仅更新插件、仅更新页面、未打快照后端补丁、浏览器缓存旧版,以及异机/容器无法自动探测等组合。检查结果准确指出下一步操作,并保留已验证的热更新和回滚行为。 -### 6. 补齐平台证据 +## P1-1(第二轮本地已实现):真实协议验收与模型可用状态 -- [x] Linux ARM64:在实际 ARM64 CPA 宿主加载并运行现有集成测试。 -- [x] macOS ARM64:跑通 CI 构建并完成实际宿主加载与调用验证。 -- [x] 核实 CI 产物的 Linux glibc 最低要求,与 README 和各包说明一致。 +**收益:让支持范围和模型选择有可追踪证据。** -验收:区分“已编译”和“已运行验证”,逐平台记录宿主及运行库要求。 +### 交付范围 -### 7. 完成发布准备 +- 扩展 tests/commandcode_live.py,按模型、套餐、客户端协议、上游协议和测试时间记录脱敏结果。 +- 优先补 Claude Messages 流/非流、工具往返、图片,以及 thinking signature 返回与重放。 +- ZDR 分开记录“参数/请求头正确发送”和“上游接受”;保留策略需官方依据,不能由一次请求成功推断。 +- 核实真实个人/组织身份、同账号不同 key 的额度和冷却归属,补必要的脱敏字段夹具。 +- 模型页区分目录可见、套餐权限未知、明确不在套餐、最近实测成功、临时限流或故障;结论按凭证版本、账号和测试时间隔离。 +- 插件直测与客户端经 CPA 测试分别展示;生成检查由用户主动触发,展示 token 上限和请求范围。 -- [x] 在真实仓库跑通测试、四平台宿主联测和四平台构建工作流。 -- [x] 校验 ZIP / SHA256、版本、仓库元数据及授权说明。 -- [x] 整理首版 v0.1.0 发布说明、兼容矩阵和已知限制。 -- [x] 提供自定义 `registry.json`、CPA 命名安装包和统一校验文件,并完成匿名 GitHub 安装及重启加载验证。 -- [ ] 若需要出现在默认官方商店,再向官方 registry 提交登记;当前可通过自定义源安装。 +### 验收 -验收:得到来源可追踪、校验通过的安装包和完整发布说明。 +关键路径有真实客户端响应、插件日志与 CPA usage 对照;单模型权限不足不将整张凭证判失效,临时 429 不成为永久不可用标记。无法取得权限的组合明确记为待验收;真实凭证位于仓库外,真实生成不进入 CI。 -## 安装后的下一步 +## P1-2(第二轮已实现):数据恢复、统计增长与采样效率 -1. 用户按部署说明安装并验证 CPAMP 完整代理、数据卷权限和重启持久化。 -2. 核实同一真实账号多 key 的额度共享行为与个人/组织身份。 -3. 使用具备对应权限的模型完成 Claude Messages、图片、思考签名和 ZDR 的真实验收。 +**收益:控制运行时间增长带来的成本,降低局部存储故障影响。** -范围继续沿用既有决定:生成走官方 Provider API;Go 订阅 `/alpha/generate` 与固定上游 provider 不在当前开发范围。 +### 第二轮实现前依据 + +- 请求日志有 10–10,000 条保留限制;统计按“分钟 × 模型”累计,当时未见按时间淘汰策略。 +- 请求、统计和额度共用 persistDirty,每次分别写三个 JSON;单文件原子替换不提供跨文件事务或断电耐久保证。 +- 启动时任一已读取的运行数据 JSON 无法解析会返回错误。 +- 采样已有最多 3 个并发、每凭证请求合并、缓存和错误退避,可进一步测量同账号多 key 的重复查询成本。 + +### 交付范围 + +1. 测量长时间、多模型、多凭证下的统计条目、磁盘写入、恢复时间、内存和管理查询 P95;复用已有并发测试。 +2. 请求、统计、额度设置独立变更标记,减少无关写入;展示最近成功刷盘时间和持续待写时长。 +3. 设计统计保留与分层聚合,例如近期分钟级、较早小时/日级;明确查询精度、迁移和备份语义后实施。 +4. 运行数据增加格式版本、损坏隔离和最后有效快照恢复;设置/凭证错误继续明确报告,恢复后展示缺失范围。 +5. 真实账户身份验证后,评估按账号合并采样和增加调度抖动;身份未知时保持凭证隔离。 + +### 验收 + +- 故障注入覆盖单文件损坏、部分写入失败、强制中止和恢复;历史观察损坏不静默清空有效配置。 +- 保留统计清空 epoch、关闭前刷盘、换 key 隔离、失败保留原采集时间及本地冷却跳过语义。 +- 对照写入量、查询延迟和恢复耗时。是否采用 SQLite/WAL 由测量和一致性要求决定。 + +## P2:上游变更与维护效率 + +- **目录变化预览**:显示新增、移除、协议变化和别名冲突,保留用户别名与思考映射。 +- **套餐规则来源**:集中记录 cap 的依据、版本与核实时间;真实上游 cap 优先,未知套餐显示未知。 +- **前后端契约**:为额度、最近请求和诊断响应建立共享 JSON 样本与契约检查。 +- **模块边界**:在修改相应功能时拆分凭证管理、面板安装和诊断,保持现有 RPC 与管理 API 兼容。 +- **CI 反馈速度**:评估基础 Go/登录测试与 CPAMP 构建的依赖,仅让需要内嵌页面的任务等待页面构建。 +- **文档同步**:第一轮已修正 FEASIBILITY.md 的旧结论,后续继续以 VALIDATION.md 标注真实与模拟边界。 + +## 建议迭代安排 + +| 迭代 | 范围 | 完成标准 | 粗估 | +| --- | --- | --- | --- | +| 第一轮,v0.2.10 源码 | 两项 P0,补齐当前文档 | 已实现凭证登记诊断、保存/加载区分、兼容检查与隔离宿主回归 | 见验证记录 | +| 第二轮,v0.2.10 未发布源码 | 两项 P1 的本地实现 | 模型证据、数据恢复、统计压缩与模拟协议已验证;真实 Claude/图片/thinking/ZDR 和身份共享待验证 | 本地完成,真实验收待条件 | +| 第三轮 | 继续参照 CommandCode 官网控制台进行视觉与页面设计优化 | 官网参照、设计细节对照、桌面/手机及明暗主题验收 | 3–5 个开发日,页面访问条件另计 | +| 后续小迭代 | P2 | 按实际变更成本选取,有兼容验证后交付 | 逐项估算 | + +## 第三轮:继续参照 CommandCode 官网控制台优化 + +这是用户明确指定的第三轮方向。先取得官网控制台可访问页面或用户提供的截图,记录来源与采集时间,再逐项实现。 + +- 对照官网的字体、字阶、配色、留白、边框、图标、侧栏和页头,建立一致的界面样式变量。 +- 优化概览、凭证与用量、模型映射、日志、设置页面的信息层级、卡片、表格、筛选和详情布局。 +- 完善加载、空状态、错误、过期额度、升级差异和诊断结果的视觉表达。 +- 保留现有业务能力与明确的鉴权/数据状态;适应长模型名、长错误信息和大量凭证。 +- 官网页面不可访问时标明参照缺口,依据用户截图或已核实公开样式进行设计,避免凭空声称已对照。 + +验收:提供逐页面前后截图,桌面与 375/390px 手机宽度、明暗主题无横向溢出;关键按钮、表格、对话框、键盘操作可用;浏览器无运行错误。 + +## 本轮范围 + +本次完成第一、二轮本地源码、测试和文档。按用户明确选择,真实 Claude/图片/thinking/ZDR、个人/组织及同账号多 key 验收标为待验证;第三轮视觉优化尚未执行,部署状态仍需后续核验。沿用既有产品范围:生成走官方 Provider API;Go 订阅 /alpha/generate 和固定上游 provider 模式继续排除在当前范围之外。 + + +## 第二轮实际交付与边界(2026-10-18) + +- 模型页按所选凭据展示插件直测和 CPA 请求证据;只读 `GET /models/evidence?credential_id=...` 不生成。证据绑定密钥版本、代理、上游、ZDR、账户与完整模型配置,保留日志丢失/截断或 24 小时过期后显示未知/过期。只认明确 `MODEL_NOT_IN_PLAN`;普通 403 为权限原因未知,429 为临时限流。 +- `commandcode_live.py` 提供无网络 `--dry-run`、请求数与输出 token 上限、脱敏报告;覆盖 Chat/Responses/Messages 流和非流、双协议工具往返、Messages 图片与 thinking 签名重放。ZDR 分开记录请求参数/模拟端实际请求头和上游接受,保留策略仍需官方依据。 +- 三类运行数据分别标脏、批量落盘,检查点最多每分钟更新一次;新增格式元数据、单文件损坏隔离、有效检查点恢复和持久恢复提示。设置/格式元数据错误仍阻止加载。统计清空防止旧检查点恢复;保留原统计副本。 +- 最近 7 个完整 UTC 日加当天保留分钟级,更早按日汇总,默认永久保留日总量;自定义区间重叠日按整日纳入并提示精度。可选 1–3650 天过期;首次迁移保留旧精度副本,降级需人工选择恢复边界。 +- 采样间隔增加 0–20% 正抖动,保留 3 并发、缓存、失败退避及逐凭据隔离;未启用跨 key 查询合并。 +- 90 天 × 2 模型 × 每分钟一条的本地合成测量保留 259,200 个请求:统计桶 259,200 → 21,768,序列化体积 77,241,601 → 6,492,669 字节。详情及环境限制见 VALIDATION.md。 diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index e2aeac3..0eec4d9 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -1,8 +1,22 @@ -# CommandCodeBridge v0.2.9 +# CommandCodeBridge 发布说明 + +## 第二轮本地交付补充(v0.2.10 未发布源码) + +新增按凭据隔离的模型实测证据、运行数据检查点/损坏恢复、统计分层汇总与独立文件写入;采样保留逐凭据隔离并增加抖动。真实协议脚本支持请求预算、无网络预览和脱敏报告。Claude/图片/thinking/ZDR 真实验收及真实身份共享**待验证**,第三轮继续参照 CommandCode 官网控制台优化。详细验收见 [VALIDATION.md](VALIDATION.md),升级/恢复边界见 [DEPLOYMENT.md](DEPLOYMENT.md)。本地实现未发布、未部署。 + + +## v0.2.10 — 未发布源码 + +- 新增凭证运行登记诊断、保存/加载分别确认和脱敏摘要;区分账户查询、插件直测与 CPA 请求证据。 +- 新增升级兼容检查与共享基线,分别核对实际页面和快照后端;无法只读确认时显示未知。 +- 面板安装前预览目标、备份与重启条件;CPAMP 适配包含后端只读健康能力声明。 +- 本地验证和边界见 [VALIDATION.md](VALIDATION.md)。此轮未发布、未更新插件商店、未部署目标服务;下方为已发布 v0.2.9 的历史说明。 + +## 已发布 v0.2.9 发布日期:2026-10-13。CPA 原生插件,C ABI 1 / RPC schema 6;调用官方 Provider API。 -## 本次更新 +### 本次更新 - **最近请求自动更新**:CPAMP 凭证页读取插件保存的真实请求记录,每 30 秒同步时间和成功/失败状态;切回页面时立即同步。本地冷却跳过不覆盖实际请求,也不因超过 24 小时而隐藏最后一次请求。 - **额度持久化**:脱敏额度观察写入 `data_dir/usage.json`,插件重启和页面重载后恢复。文件更新时间、备注或模型配置变化不再清空已查额度。 @@ -10,7 +24,7 @@ - **失败保留**:额度刷新失败保留上次值和真实采集时间;读取同一旧快照不会把失败标记清掉。手动重试不再被自动采样的五分钟错误退避阻挡。 - 四平台插件内嵌匹配的新 CPAMP 页面,与独立前端包一致;保留 v0.2.8 的月额度、套餐名和原生窗口历史功能。 -## 升级步骤 +### 升级步骤 1. 在支持热升级的 CPA 插件商店更新至 **v0.2.9**,确认插件控制台运行版本。 2. 进入「设置 → CPAMP 原生面板」,点击「更新原生面板」并检查生效状态,再强制刷新浏览器。 @@ -21,7 +35,7 @@ **完整周期快照仍需 Manager Server 的平台名单接受 `commandcode`。** v0.2.8 已应用该补丁的环境无需再次重建;包内 `integrations/cpamp/apply.py` 提供对应源码适配,页面更新入口只替换 HTML。 -## 下载内容 +### 下载内容 Linux amd64、Linux arm64、Windows amd64、macOS arm64 四平台 ZIP,另附 `commandcodebridge_0.2.9_cpamp-web.zip`、各包 SHA256 文件和统一 `checksums.txt`。`BUILD.json` 记录来源提交、库和内嵌页面摘要。 @@ -29,7 +43,7 @@ Linux amd64、Linux arm64、Windows amd64、macOS arm64 四平台 ZIP,另附 ` 插件商店源:[registry.json](https://raw.githubusercontent.com/Gaoshou101/CommandCodeBridge/main/registry.json)。 -## 验证 +### 验证 发布流程执行 Go race/vet、前端回归和类型检查、四平台 CPA v8.0.23 原生协议与异常恢复联测、0.2.8 → 0.2.9 热升级、CPAMP 页面安装与热更新验证。新增原生宿主重启后的额度窗口、最近请求状态和原始观察时间恢复断言。 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 020934f..bcfb60c 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,5 +1,95 @@ # 开发验证记录 +## 第二轮:本地实现与模拟验收(2026-10-18,v0.2.10 未发布源码) + +**用户明确选择:先完成本地实现,真实验收标为待验证。** 本轮没有调用真实模型,没有发布/部署;第三轮 CommandCode 官网控制台视觉与页面设计优化仍保留后续排期。 + +### 交付与故障边界 + +- `GET /models/evidence?credential_id=...` 和模型页选择器:模型观察绑定密钥/更新时间、代理、上游、ZDR、账户及完整模型配置。插件直测、CPA 请求分别展示;24 小时过期,旧无作用域记录不充当新证据;证据随保留日志截断而丢失。普通 403 不推断套餐拒绝,仅明确 `MODEL_NOT_IN_PLAN` 标为不在套餐,429 为临时限流,局部失败不使整张凭证失效。 +- 日志新增客户端/上游协议及 ZDR 请求标记。实际 CPA 会把 `SourceFormat` 改为翻译后的插件输入,因此优先使用原始 `request_path` 识别 Responses;本地 13 请求验收对照了该字段。 +- 独立变更标记保留 250ms 批量写入;额度更新只写 `usage.json`。每分钟检查点、格式清单、单文件损坏隔离与恢复警告;无检查点只重建该观察文件,设置/未知格式仍失败。缺失主文件可恢复检查点,部分 JSON 解码不会污染恢复值。 +- 分层统计保持累计总量,近期分钟/历史 UTC 日;默认不删除日总量,非零保留天数需明确确认。查询重叠整日时返回精度提示。首次迁移、清空均保留副本;清空前检查点被移走,关闭刷盘与 epoch 回归保留。 +- 采样保留缓存、错误退避、请求合并和 3 并发,周期增加 0–20% 正抖动。真实个人/组织与同账号多 key 身份未核实,因此没有跨凭据合并查询。 + +### 自动化与实际 CPA 宿主 + +- Windows Go 1.26 本地测试/vet、WSL Linux race/vet 通过;Linux amd64 `.so` 和 Windows amd64 `.dll` 构建通过。新增作用域、过期、403/429 分类、恢复/损坏/设置拒绝、缺失主文件、独立写入、检查点节流、清空失败和迁移副本回归。 +- Node 管理登录/诊断/模型证据共 **19 项**通过:切换凭据和身份的较晚响应被丢弃、转义、来源区分、模型 403 不退出管理登录。Python/JavaScript 语法检查通过。 +- Windows CPA **8.0.23** 实际加载动态库运行 `tests/cpa_round2.py`:明确套餐拒绝、普通 403、429 再试恢复、单模型不污染凭据、多凭据隔离、换 key/换映射失效、重启恢复;损坏请求文件隔离并恢复检查点、缺检查点的额度文件单独重建、清空统计后重启不回流。 +- 扩展后的真实验收脚本本身在 loopback 模拟端走完 **13 次** Chat/Responses/Messages 流与非流、双协议工具往返、Messages 图片传输、thinking 签名返回/重放;逐条实际响应、插件统计、CPA usage queue 的 token 对账通过,模拟端实际收到 13 个 `X-Cmd-Zdr: 1` 请求头。 +- 原有 `cpa_e2e.py` 的 **25 次**协议模拟调用、`cpa_reliability.py` 异常/取消/超时/重启/用量对账,以及第一轮 `cpa_diagnostics.py` 均继续通过。 + +### 浏览器验证 + +实际访问动态库内嵌控制台,使用两张虚构本地凭据。1280px 桌面及 375/390px 手机、明暗主题已验证:凭据证据隔离、模型 403 错误留在测试窗口且保持管理登录、保留天数确认/取消、默认永久保留保存、刷盘状态、退出登录清空模型证据。新增证据列最初在窄屏被挤成逐字竖排,已修正为可聚焦、带提示的横向滚动表格;页面整体宽度与视口一致,证据和操作列可横向查看,浏览器运行错误 0。 + +截图位于本机忽略目录 `dist/round2/screenshots/`:`models-desktop.png`、`models-mobile-390-dark.png`、`models-mobile-dark.png`、`settings-desktop.png`、`settings-mobile-light.png`。仅包含虚构测试数据;临时浏览器与服务已清理。旧版纯额度刷盘会把空日志序列化为 `null`,已增加兼容回归,不把它误报为历史损坏。 + +### 本机合成测量 + +同一次 Windows Go 运行,90 天 × 2 模型 × 每分钟一条请求;固定 259,200 请求、每条 100 输入/20 输出 tokens。只对统计内存结构进行压缩前后对照,不调用上游。测量前两次 GC 排除上次 JSON 缓冲池暂留;不是生产负载与整进程内存承诺。 + +| 指标 | 压缩前 | 压缩后 | +| --- | ---: | ---: | +| 统计桶 | 259,200 | 21,768 | +| JSON 字节 | 77,241,601 | 6,492,669 | +| 序列化耗时 | 473.612ms | 43.071ms | +| JSON 解码耗时 | 883.126ms | 100.392ms | +| 40 次统计查询 P95 | 90.065ms | 5.033ms | +| GC 后 Go HeapAlloc | 66,310,272B | 5,730,944B | +| 累计请求数 | 259,200 | 259,200 | + +压缩耗时 129.314ms;JSON 缩减约 91.6%。这是可重复合成结构测量,解码耗时不是完整 CPA 启动时间。运行:`BRIDGE_MEASURE=1 go test ./internal/bridge -run TestRuntimeScaleMeasurement -v -count=1`。 + +原生 CPA + 固定模拟 SSE、每轮 32 请求、1,000 条日志缓冲的短样本对照: + +| 并发 | 第一轮 requests/s / P95 | 第二轮 requests/s / P95 | +| --- | ---: | ---: | +| 1 | 14.09 / 71.85ms | 14.41 / 84.68ms | +| 8 | 100.67 / 91.57ms | 104.99 / 76.43ms | + +两轮均使用同机 Windows CPA v8.0.23 与相同夹具。样本小、有模拟分片等待,单并发 P95 本次变慢,多并发本次变快,不能据此宣称吞吐优化或真实推理变快。分类写入由确定性测试核实:一次纯额度变更,原逻辑写三文件,当前只写一个;检查点首次写入会额外写一次,后续一分钟内不重复刷新。无新增 SQLite/WAL 依赖。 + +### 待真实验证 + +| 组合 | 本轮状态 | +| --- | --- | +| Claude Messages 流/非流、工具往返 | 模拟通过;真实待验证 | +| 图片语义理解 | 本地只验证传输;真实待验证 | +| thinking 签名返回/重放 | 模拟通过;真实模型/权限待验证 | +| ZDR 参数正确发送 | 模拟端实际请求头已验证 | +| ZDR 上游接受/服务端保留策略 | 真实待验证/策略需官方依据 | +| 个人/组织身份、同账号多 key 额度与冷却归属 | 真实待验证;当前不合并采样 | + +脚本支持无网络 `--dry-run`、最多 20 次请求/每次 8192 输出 tokens、仓库外凭据、脱敏报告和 token 对账;默认不生成。报告不含原始响应、thinking 签名或账户 ID。请求数和输出 token 上限不能直接等同费用金额。 + + +## v0.2.10 第一轮:登记诊断与升级兼容(2026-10-18,未发布源码) + +### 实现与自动化 + +- 新增 `/diagnostics`、`/diagnostics/summary` 和 `/compatibility` 管理接口;默认只读,不发模型生成或写入探测快照。凭证保存单独返回 `saved` 与 `registration`,会话重新分配返回 `host_confirmed`。 +- Go 回归覆盖正常/缺失/重复/旧 routing ID、启停未同步、变更待加载、宿主查询失败、文件回退未知、脱敏摘要及三类证据。CPA 的 live 文件登记也使用 `source=file`,以 `auth_index` 和运行 ID 区分磁盘回退;相同内容再次保存不使确认永久等待。 +- Windows Go 1.26.0 全部 `./internal/... ./cmd/...` 测试、vet 通过;最终源码在 WSL Linux 通过 `go test -race ./internal/... ./cmd/... -count=1` 和 vet,Linux amd64 `.so`、Windows amd64 `.dll` 构建通过。 +- Node 15 项管理登录与诊断回归通过,覆盖输出转义、较晚响应不能覆盖新结果、切换身份/退出登录后丢弃旧结果、401 拒绝立即清理诊断;JavaScript/Python 语法及 `git diff --check` 通过。 +- 兼容检查覆盖匹配/旧页面、支持/旧/明确不支持/类型错误的后端声明;远程目标与 HTTP 重定向不探测,不转发管理密钥。页面、后端和浏览器缓存分别报告,缺少依据时保持未知。 +- CPAMP `dbf61dd` 适配重复应用及 `--check` 通过;TypeScript 检查、生产单文件构建、五个相关前端文件共 40 项通过。最终 Manager 后端 `go test ./internal/service/quotasnapshot ./internal/http/controller/health -run TestCommandCode -count=1` 通过,覆盖名单变更与 GET 能力/POST 405。 + +### 隔离宿主与浏览器 + +- Windows CPA v8.0.23 使用最终动态库通过 `tests/cpa_diagnostics.py`:保存、三类证据隔离、停用/启用、会话重新分配、相同内容保存、重启、脱敏摘要;移除临时夹具文件后插件仍保留凭证、宿主登记缺失,客户端返回 503 且插件无新增执行日志,恢复文件后登记和请求恢复。 +- 最终 `tests/cpa_hot_reload.py` 验证 **0.2.9 → 0.2.10** 同进程热升级、配置即时生效/无效配置回滚,凭证、模型、记账与请求继续保留。此轮原生协议 25 次模拟请求、异常恢复、OAuth 接收器及页面安装/备份/幂等套件亦通过;均使用本机隔离目录和虚构凭证。 +- 浏览器访问最终动态库实际内嵌控制台:诊断/兼容重试、三类来源说明、脱敏摘要复制、插件直测范围提示、退出登录清除诊断通过。1280px 桌面及 375/390px 手机、明暗主题检查未见横向溢出或运行错误(console errors 0)。 +- 截图保存在本机忽略目录 `dist/round1/screenshots/`:`credentials-desktop.jpg`、`compatibility-desktop.jpg`、`compatibility-mobile-light.jpg`、`credentials-mobile-dark.jpg`、`compatibility-mobile-dark.jpg`;是虚构测试数据,不是目标部署。 + +### 发布与证据边界 + +- 安装包清单增加共享兼容基线;临时四平台清单夹具验证一致基线通过、缺失或不一致基线被拒绝,未生成发行包。CI 保留固定 v8.0.23 门槛,新增不阻断发布的较新 CPA 候选兼容报告。该工作流尚未在远端运行,本轮不声称最新 CPA 或四平台发行验证通过。 +- 本地 CPAMP 使用已有源码归档与依赖完成测试和页面构建,页面手动嵌入用于联测;嵌套源码归档不能作为发行来源证明,正式打包需要独立上游 Git checkout、来源提交及统一校验。 +- **v0.2.10 未发布、未更新 registry、未部署目标服务**;本轮没有真实模型请求。已有真实免费模型/账户结果见历史章节,不代表 Claude、图片、ZDR 等真实验收已完成。 +- 第三轮已在 [NEXT_STEPS.md](NEXT_STEPS.md) 明确安排:继续参照 CommandCode 官网控制台的美术风格和页面设计,另做逐页面视觉对照与响应式验收。 + ## v0.2.9 最近请求同步与额度持久化修复(2026-10-13) - 服务端将额度观察与账户标识哈希写入 `data_dir/usage.json`,复用异步原子落盘和关闭前最终刷新;重启后按密钥/代理/上游指纹恢复。管理接口返回脱敏额度和每个凭证最近十次实际请求,排除本地冷却跳过与旧密钥记录。 diff --git a/integrations/cpamp/README.md b/integrations/cpamp/README.md index 2787df3..4c8a962 100644 --- a/integrations/cpamp/README.md +++ b/integrations/cpamp/README.md @@ -122,3 +122,16 @@ loopback 指浏览器所在电脑。CPA 不需要监听 `45879`,无需开放 ## 回滚 恢复备份的管理页面和插件库,重启 CPA。新增凭证仍为正常 `type: commandcode` 文件,不需要修改现有模型映射或迁移数据库。 + +## v0.2.10 源码能力检查 + +开发中的适配脚本增加页面能力元信息,并给 Manager Server 的匿名 `GET /health` 添加 `capabilities.commandcode_quota_snapshots_v1` 布尔值,取自实际 `quotasnapshot.validProviders` 名单。该检查不读取或写入用户快照;旧服务器未声明能力时插件显示「未确认」。 + +在匹配源码上先运行 `apply.py --check`,再应用;全部插入点检查通过后才写入,重复应用安全。报错会列出缺失文件或不匹配插入点及已验证基线,不能据此认为任意上游版本均兼容。后端验证命令: + +```bash +cd /path/to/CPA-Manager-Plus/apps/manager-server +go test ./internal/service/quotasnapshot ./internal/http/controller/health -run TestCommandCode -count=1 +``` + +页面更新与后端更新分别生效。仅复制 HTML 无法新增后端健康能力;需按现有部署方式重建、备份并替换 Manager Server 后重启。已支持快照但尚无新健康声明的后端仍可工作,只是诊断显示未知。发布打包要求独立的上游 Git checkout 与明确提交,嵌套在本仓库中的源码归档只供本地验证,不能作为发行来源证明。 diff --git a/integrations/cpamp/apply.py b/integrations/cpamp/apply.py index 5ae0c0d..444d6f8 100644 --- a/integrations/cpamp/apply.py +++ b/integrations/cpamp/apply.py @@ -110,6 +110,16 @@ ], root / 'apps/manager-server/internal/service/quotasnapshot/service.go': [ ('validProviders = stringSet("codex", "claude", "antigravity", "kimi", "xai", "devin", "meta")', 'validProviders = stringSet("codex", "claude", "antigravity", "kimi", "xai", "devin", "meta", "commandcode")'), + ('func New(st *store.Store) *Service {', '''// SupportsCommandCode reports the actual allowlist without reading or writing snapshots. +func SupportsCommandCode() bool { + return validProviders["commandcode"] +} + +func New(st *store.Store) *Service {'''), + ], + root / 'apps/manager-server/internal/http/controller/health/handler.go': [ + ('"net/http"', '"net/http"\n\n quotasnapshotsvc "github.com/seakee/cpa-manager-plus/apps/manager-server/internal/service/quotasnapshot"'), + ('map[string]any{"ok": true, "service": h.ServiceID}', 'map[string]any{"ok": true, "service": h.ServiceID, "capabilities": map[string]bool{"commandcode_quota_snapshots_v1": quotasnapshotsvc.SupportsCommandCode()}}'), ], oauth: [ ("import { apiClient, createScopedApiRequestConfig, type ApiClientRequestScope } from './client';", "import { apiClient, createScopedApiRequestConfig, type ApiClientRequestScope } from './client';\nimport { normalizeApiBase } from '@/utils/connection';"), @@ -176,12 +186,16 @@ 'en': (f'CommandCodeBridge v{version}: Studio sends credentials in a POST body. Run commandcodebridge-login on your browser computer, paste this card’s official authorization link into it, then copy the receiver’s result and submit it below. A bare localhost URL has no credentials.', 'Paste the result copied from the local receiver', 'Authentication result'), } receiver_labels = {'zh-CN': '打开本地接收器', 'zh-TW': '開啟本地接收器', 'en': 'Open local receiver'} +page_index = root / 'apps/web/index.html' +changes[page_index] = [('', '\n')] for locale, (hint, placeholder, label) in translations.items(): changes[root / f'apps/web/src/i18n/locales/{locale}.json'] = [ ('"plugin_oauth_hint":', '"commandcode_oauth_hint": ' + json.dumps(hint, ensure_ascii=False) + ',\n "commandcode_callback_placeholder": ' + json.dumps(placeholder, ensure_ascii=False) + ',\n "commandcode_callback_label": ' + json.dumps(label, ensure_ascii=False) + ',\n "commandcode_open_receiver": ' + json.dumps(receiver_labels[locale], ensure_ascii=False) + ',\n "plugin_oauth_hint":'), ] prepared = {} for path, replacements in changes.items(): + if not path.is_file(): + raise SystemExit(f'Unsupported CPAMP source: required file missing: {path.relative_to(root)}. Verified baseline: dbf61ddf438f399558722df3467355c42af9005d. No prepared files have been written.') text = path.read_text(encoding='utf-8').replace('\r\n', '\n') if path.parent.name == 'locales': text = re.sub(r'^ "commandcode_(?:oauth_hint|callback_placeholder|callback_label|open_receiver)":.*\n', '', text, flags=re.MULTILINE) @@ -201,7 +215,7 @@ if new in text: continue if text.count(old) != 1: - raise SystemExit(f'Unsupported CPAMP source: insertion anchor missing or ambiguous in {path.name}') + raise SystemExit(f'Unsupported CPAMP source: insertion anchor missing or ambiguous in {path.relative_to(root)}. Verified baseline: dbf61ddf438f399558722df3467355c42af9005d. Run --check against matching source before upgrading; no prepared files have been written.') text = text.replace(old, new, 1) prepared[path] = text if not args.check: @@ -213,6 +227,7 @@ for name in ['commandCodeQuotaWindows.ts', 'commandCodeQuotaWindows.test.ts']: shutil.copy2(source / name, model / name) shutil.copy2(source / 'commandcode_quota_test.go.fragment', root / 'apps/manager-server/internal/service/quotasnapshot/commandcode_quota_test.go') + shutil.copy2(source / 'commandcode_health_test.go.fragment', root / 'apps/manager-server/internal/http/controller/health/commandcode_health_test.go') shutil.copy2(source / 'CommandCodeOAuth.test.ts', root / 'apps/web/src/services/api/CommandCodeOAuth.test.ts') shutil.copy2(source / 'commandCodeOAuth.ts', root / 'apps/web/src/services/api/commandCodeOAuth.ts') print('PASS: CPAMP native credential grid and quota detail integration' + (' compatibility check' if args.check else ' applied')) diff --git a/integrations/cpamp/commandcode_health_test.go.fragment b/integrations/cpamp/commandcode_health_test.go.fragment new file mode 100644 index 0000000..2de7845 --- /dev/null +++ b/integrations/cpamp/commandcode_health_test.go.fragment @@ -0,0 +1,21 @@ +package health + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +func TestCommandCodeReadOnlyHealthCapability(t *testing.T) { + handler := &Handler{ServiceID: "fixture-manager"} + response := httptest.NewRecorder() + handler.Health(response, httptest.NewRequest(http.MethodGet, "/health", nil)) + var body struct { Capabilities map[string]bool `json:"capabilities"` } + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &body) != nil || !body.Capabilities["commandcode_quota_snapshots_v1"] { + t.Fatalf("health capability not served: %d %s", response.Code, response.Body.String()) + } + response = httptest.NewRecorder() + handler.Health(response, httptest.NewRequest(http.MethodPost, "/health", nil)) + if response.Code != http.StatusMethodNotAllowed { t.Fatal("capability check must remain GET-only") } +} diff --git a/integrations/cpamp/commandcode_quota_test.go.fragment b/integrations/cpamp/commandcode_quota_test.go.fragment index 37e3cee..5d68058 100644 --- a/integrations/cpamp/commandcode_quota_test.go.fragment +++ b/integrations/cpamp/commandcode_quota_test.go.fragment @@ -6,6 +6,15 @@ import ( "time" ) +func TestCommandCodeCapabilityMatchesAllowlist(t *testing.T) { + if !SupportsCommandCode() { t.Fatal("CommandCode snapshot capability must match allowlist") } + delete(validProviders, "commandcode") + t.Cleanup(func() { validProviders["commandcode"] = true }) + if SupportsCommandCode() { t.Fatal("capability must not claim unsupported snapshots") } + validProviders["commandcode"] = false + if SupportsCommandCode() { t.Fatal("capability must respect disabled allowlist entries") } +} + func TestCommandCodeQuotaPersistenceAndCredentialIsolation(t *testing.T) { now := time.Date(2026, 10, 12, 14, 0, 0, 0, time.UTC).UnixMilli() service := newQuotaSnapshotTestService(t, now) diff --git a/internal/bridge/affinity.go b/internal/bridge/affinity.go index 680949c..c985097 100644 --- a/internal/bridge/affinity.go +++ b/internal/bridge/affinity.go @@ -81,9 +81,11 @@ func (s *Service) affinityFile(c Credential) (affinityFile, error) { // upserts a generic filename-based ID and would resurrect an obsolete auth. // Both paths merge into the original file so plugin-unknown fields survive. func (s *Service) saveCredential(c Credential) error { + started := time.Now().UTC() s.mu.RLock() current, filename, dir := s.creds[c.ID], s.files[c.ID], s.authDir s.mu.RUnlock() + changed := !bytes.Equal(jsonBytes(current), jsonBytes(c)) body := json.RawMessage(jsonBytes(c)) if current.RoutingID != "" || (dir != "" && filename != "") { file, err := s.affinityFile(current) @@ -126,14 +128,22 @@ func (s *Service) saveCredential(c Credential) error { if old, ok := s.creds[c.ID]; ok && (old.APIKey != c.APIKey || old.ProxyURL != c.ProxyURL) { delete(s.usage, c.ID) delete(s.accounts, c.ID) - s.persistDirty = true + s.markDirtyLocked(dirtyUsage) } s.creds[c.ID] = c + if s.expectedRegistration == nil { + s.expectedRegistration = make(map[string]time.Time) + } + if changed { + s.expectedRegistration[c.ID] = started + } s.mu.Unlock() return nil } type runtimeAuth struct { + AuthIndex string `json:"auth_index"` + Source string `json:"source"` ID string `json:"id"` Name string `json:"name"` Provider string `json:"provider"` @@ -358,7 +368,8 @@ func (s *Service) clearAffinity(r ManagementRequest) (any, error) { return rollback(err) } return managementJSON(200, map[string]any{ - "reset_count": len(next), - "message": "旧会话绑定已清除。下一条请求将按当前优先级重新选择可用账号;正在生成的回复会继续完成。", + "reset_count": len(next), + "host_confirmed": true, + "message": "旧会话绑定已清除。下一条请求将按当前优先级重新选择可用账号;正在生成的回复会继续完成。", }) } diff --git a/internal/bridge/compatibility.go b/internal/bridge/compatibility.go new file mode 100644 index 0000000..1c28250 --- /dev/null +++ b/internal/bridge/compatibility.go @@ -0,0 +1,130 @@ +package bridge + +import ( + "bytes" + _ "embed" + "encoding/json" + "io" + "net" + "net/http" + "regexp" + "strings" + "time" +) + +//go:embed compatibility.json +var compatibilityBaseline json.RawMessage + +type compatibilityCheck struct { + Name string `json:"name"` + Status string `json:"status"` + Message string `json:"message"` + Action string `json:"action,omitempty"` +} + +type compatibilityReport struct { + CheckedAt time.Time `json:"checked_at"` + Version string `json:"version"` + Baseline json.RawMessage `json:"baseline"` + Checks []compatibilityCheck `json:"checks"` + Panel nativePanelStatus `json:"panel"` +} + +func (s *Service) compatibility() compatibilityReport { + return buildCompatibility(inspectNativePanel(s.config())) +} + +func buildCompatibility(panel nativePanelStatus) compatibilityReport { + r := compatibilityReport{CheckedAt: time.Now().UTC(), Version: Version, Baseline: compatibilityBaseline, Panel: panel} + r.Checks = []compatibilityCheck{ + {Name: "plugin", Status: "ok", Message: "当前插件 " + Version + " 提供诊断、额度缓存和最近请求管理接口"}, + {Name: "host_version", Status: "unknown", Message: "宿主 RPC 未提供运行版本", Action: "核对 CPA 版本;已验证基线为 8.0.23,较新版本以兼容任务结果为准"}, + {Name: "page", Status: "unknown", Message: "未确认实际服务页面", Action: "同机填写实际路径后检查;异机或容器请在 Manager Server 所在环境检查页面与缓存"}, + {Name: "page_quota", Status: "unknown", Message: "未确认页面额度组件"}, + {Name: "page_recent_requests", Status: "unknown", Message: "未确认页面最近请求同步能力"}, + {Name: "page_windows", Status: "unknown", Message: "未确认页面周期历史组件"}, + {Name: "snapshot_backend", Status: "unknown", Message: "未确认 Manager Server 的 CommandCode 快照能力", Action: "在 Manager Server 运行环境应用匹配源码补丁、重建并重启;页面更新只替换 HTML"}, + {Name: "browser_cache", Status: "unknown", Message: "HTTP 核验不代表当前浏览器已载入新页面", Action: "强制刷新浏览器后核对版本"}, + } + if panel.ServedPage.Checked { + r.Checks[2].Status = "mismatch" + r.Checks[2].Message = "服务页面与内嵌页面不同;已识别版本:" + panel.ServedPage.Version + r.Checks[2].Action = "备份现有页面,更新原生面板后重新检查实际 HTTP 页面" + if panel.ServedPage.Matches { + r.Checks[2].Status, r.Checks[2].Message = "ok", "实际 HTTP 页面与插件内嵌页面摘要一致" + r.Checks[2].Action = "强制刷新浏览器后使用" + } + for i, enabled := range []bool{panel.ServedPage.NativeQuota, panel.ServedPage.RecentRequests, panel.ServedPage.NativeWindows} { + r.Checks[i+3].Status = "missing" + r.Checks[i+3].Action = "同时更新插件与匹配的 CPAMP 页面" + if enabled { + r.Checks[i+3].Status, r.Checks[i+3].Message, r.Checks[i+3].Action = "ok", "实际页面含对应能力标识;接口由当前插件提供", "" + } + } + } + if panel.nativePanelTarget != nil { + if supported, checked := observeSnapshotCapability(panel.nativePanelTarget); checked { + r.Checks[6].Status, r.Checks[6].Message, r.Checks[6].Action = "missing", "Manager Server 明确报告缺少 CommandCode 快照能力", "应用匹配版本的 Manager Server 快照补丁并重建、重启" + if supported { + r.Checks[6].Status, r.Checks[6].Message, r.Checks[6].Action = "ok", "Manager Server 只读健康接口报告支持 CommandCode 快照", "" + } + } + } + return r +} + +var panelVersionPattern = regexp.MustCompile(`CommandCodeBridge v([0-9]+\.[0-9]+\.[0-9]+)`) + +func annotatePanel(observation *panelObservation, actual []byte) { + if match := panelVersionPattern.FindSubmatch(actual); len(match) == 2 { + observation.Version = string(match[1]) + } + observation.NativeWindows = bytes.Contains(actual, []byte("data-commandcode-native-windows")) + observation.RecentRequests = bytes.Contains(actual, []byte("commandcodebridge-capabilities")) && bytes.Contains(actual, []byte("recent-requests")) +} + +// Read a dedicated anonymous capability assertion. Old health responses stay +// unknown; a successful generic health response cannot prove snapshot support. +func observeSnapshotCapability(target *nativePanelTarget) (bool, bool) { + address := panelLoopbackAddress(target.address) + if address == "" { + return false, false + } + client := http.Client{Timeout: 2 * time.Second, Transport: &http.Transport{Proxy: nil}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + defer client.CloseIdleConnections() + response, err := client.Get("http://" + address + "/health") + if err != nil { + return false, false + } + defer response.Body.Close() + var health struct { + Capabilities map[string]*bool `json:"capabilities"` + } + body, err := io.ReadAll(io.LimitReader(response.Body, 65537)) + if err != nil || len(body) > 65536 || response.StatusCode != http.StatusOK || json.Unmarshal(body, &health) != nil { + return false, false + } + value := health.Capabilities["commandcode_quota_snapshots_v1"] + if value == nil { + return false, false + } + return *value, true +} + +func panelLoopbackAddress(address string) string { + host, port, err := net.SplitHostPort(address) + if err != nil { + return "" + } + if host == "0.0.0.0" || host == "" || host == "localhost" { + host = "127.0.0.1" + } + if host == "::" { + host = "::1" + } + ip := net.ParseIP(strings.Trim(host, "[]")) + if ip == nil || !ip.IsLoopback() { + return "" + } + return net.JoinHostPort(host, port) +} diff --git a/internal/bridge/compatibility.json b/internal/bridge/compatibility.json new file mode 100644 index 0000000..bd2e991 --- /dev/null +++ b/internal/bridge/compatibility.json @@ -0,0 +1,13 @@ +{ + "schema": 1, + "cpa_baseline": "8.0.23", + "abi_version": 1, + "rpc_schema": 6, + "cpamp_source_commit": "dbf61ddf438f399558722df3467355c42af9005d", + "manager_baselines": ["1.13.1", "1.14.0"], + "minimum_quota_cache_plugin": "0.2.9", + "minimum_diagnostics_plugin": "0.2.10", + "snapshot_backend": "commandcode_quota_snapshots_v1", + "page_capabilities": ["quota", "recent-requests", "quota-windows"], + "notes": "Baselines are verified versions, not a guarantee for newer upstream releases. Full snapshot support requires the Manager Server patch." +} diff --git a/internal/bridge/compatibility_test.go b/internal/bridge/compatibility_test.go new file mode 100644 index 0000000..1ec2cce --- /dev/null +++ b/internal/bridge/compatibility_test.go @@ -0,0 +1,70 @@ +package bridge + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestCompatibilityPageAndBackendAreIndependent(t *testing.T) { + for _, tc := range []struct{ name, page, health, wantPage, wantSnapshot string }{ + {"matching", `CommandCodeBridge v` + Version + ``, `{"capabilities":{"commandcode_quota_snapshots_v1":true}}`, "ok", "ok"}, + {"old page", `CommandCodeBridge v0.2.1`, `{"capabilities":{"commandcode_quota_snapshots_v1":true}}`, "mismatch", "ok"}, + {"old backend", `CommandCodeBridge v0.2.1`, `{"ok":true}`, "mismatch", "unknown"}, + {"explicit unsupported", `old`, `{"capabilities":{"commandcode_quota_snapshots_v1":false}}`, "mismatch", "missing"}, + {"malformed capability", `old`, `{"capabilities":{"commandcode_quota_snapshots_v1":"true"}}`, "mismatch", "unknown"}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" || r.Header.Get("Authorization") != "" || r.Header.Get("X-Management-Key") != "" { + t.Error("check mutated state or forwarded credentials") + } + if r.URL.Path == "/management.html" { + _, _ = w.Write([]byte(tc.page)) + return + } + if r.URL.Path == "/health" { + _, _ = w.Write([]byte(tc.health)) + return + } + t.Error("unexpected probe", r.URL.Path) + })) + defer server.Close() + target := &nativePanelTarget{address: strings.TrimPrefix(server.URL, "http://")} + expected := []byte(tc.page) + if tc.wantPage != "ok" { + expected = []byte("new release") + } + panel := nativePanelStatus{nativePanelTarget: target, ServedPage: observePanel(target, expected)} + report := buildCompatibility(panel) + if report.Checks[2].Status != tc.wantPage || report.Checks[6].Status != tc.wantSnapshot { + t.Fatalf("capabilities conflated: %s", jsonBytes(report)) + } + if tc.wantPage == "ok" && (report.Checks[4].Status != "ok" || panel.ServedPage.Version != Version) { + t.Fatal("page version or recent request marker missing") + } + }) + } +} + +func TestCompatibilityUnknownRemoteAndRedirect(t *testing.T) { + if supported, checked := observeSnapshotCapability(&nativePanelTarget{address: "192.0.2.1:18317"}); supported || checked { + t.Fatal("remote target probed") + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "http://192.0.2.1/health", http.StatusFound) + })) + defer server.Close() + if supported, checked := observeSnapshotCapability(&nativePanelTarget{address: strings.TrimPrefix(server.URL, "http://")}); supported || checked { + t.Fatal("redirect treated as capability") + } + if buildCompatibility(nativePanelStatus{}).Checks[2].Status != "unknown" { + t.Fatal("unknown target is not confirmed") + } + var baseline map[string]any + if json.Unmarshal(compatibilityBaseline, &baseline) != nil || baseline["cpa_baseline"] != "8.0.23" { + t.Fatal("invalid shared compatibility baseline") + } +} diff --git a/internal/bridge/cpamp_panel.go b/internal/bridge/cpamp_panel.go index e1ea6b0..32e32e8 100644 --- a/internal/bridge/cpamp_panel.go +++ b/internal/bridge/cpamp_panel.go @@ -51,14 +51,18 @@ type nativePanelStatus struct { Installable bool `json:"installable"` HotUpdateReady bool `json:"hot_update_ready"` ServedPage panelObservation `json:"served_page"` + PlannedChanges []string `json:"planned_changes"` } type panelObservation struct { - Checked bool `json:"checked"` - HTTPStatus int `json:"http_status,omitempty"` - SHA256 string `json:"sha256,omitempty"` - NativeQuota bool `json:"native_quota"` - Matches bool `json:"matches"` + Version string `json:"version,omitempty"` + RecentRequests bool `json:"recent_requests"` + NativeWindows bool `json:"native_windows"` + Checked bool `json:"checked"` + HTTPStatus int `json:"http_status,omitempty"` + SHA256 string `json:"sha256,omitempty"` + NativeQuota bool `json:"native_quota"` + Matches bool `json:"matches"` } func expandedPath(path string) (string, error) { @@ -375,6 +379,7 @@ func panelStatus(c Config, targets []*nativePanelTarget, content []byte) nativeP } } status.Installable = len(content) > 0 + status.PlannedChanges = []string{"更新面板文件:" + status.PanelPath, "已存在且有变化的文件会先保存为同目录 .commandcodebridge-backup-* 私有副本"} installedHash := "" if data, e := os.ReadFile(status.PanelPath); e == nil { status.Installed = bytes.Equal(data, content) && len(content) > 0 @@ -407,6 +412,9 @@ func panelStatus(c Config, targets []*nativePanelTarget, content []byte) nativeP status.Message = "已找到通过环境变量运行的 CPAMP,config.json 不存在属正常情况;安装会创建最小面板配置,首次生效需重启 Manager Server" } } + if status.RestartRequired { + status.PlannedChanges = append(status.PlannedChanges, "首次启用或切换页面路径后需重启 Manager Server") + } return status } @@ -446,6 +454,7 @@ func observePanel(target *nativePanelTarget, content []byte) panelObservation { observation.Checked = true observation.SHA256 = hex.EncodeToString(sum[:]) observation.NativeQuota = bytes.Contains(actual, []byte("data-commandcode-native-quota")) + annotatePanel(&observation, actual) observation.Matches = len(content) > 0 && bytes.Equal(actual, content) return observation } diff --git a/internal/bridge/diagnostics.go b/internal/bridge/diagnostics.go new file mode 100644 index 0000000..673af0a --- /dev/null +++ b/internal/bridge/diagnostics.go @@ -0,0 +1,153 @@ +package bridge + +import ( + "path/filepath" + "sort" + "time" +) + +type diagnosticEvidence struct { + Source string `json:"source"` + Status string `json:"status"` + CheckedAt *time.Time `json:"checked_at,omitempty"` + Model string `json:"model,omitempty"` + HTTPStatus int `json:"http_status,omitempty"` +} + +type credentialDiagnostic struct { + ID string `json:"id,omitempty"` + Label string `json:"label,omitempty"` + Status string `json:"status"` + Message string `json:"message"` + Action string `json:"action"` + Registrations int `json:"registrations"` + Disabled bool `json:"disabled"` + Cooldown bool `json:"cooldown"` + Evidence []diagnosticEvidence `json:"evidence"` +} + +type diagnosticReport struct { + Version string `json:"version"` + CheckedAt time.Time `json:"checked_at"` + HostStatus string `json:"host_status"` + HostMessage string `json:"host_message"` + Models int `json:"models"` + UnmatchedRegistrations int `json:"unmatched_registrations"` + Credentials []credentialDiagnostic `json:"credentials"` +} + +// host.auth.list is metadata only. Never use host.auth.get here: its response +// contains credential material and is not needed to compare registrations. +func (s *Service) diagnostics(redacted bool) diagnosticReport { + entries, err := s.runtimeAuths() + now := time.Now().UTC() + report := diagnosticReport{Version: Version, CheckedAt: now, HostStatus: "ok", HostMessage: "已读取 CPA 运行登记;登记一致不代表所有模型均有权限", Credentials: []credentialDiagnostic{}} + if err != nil { + report.HostStatus, report.HostMessage = "unknown", "无法读取 CPA 登记,请确认宿主支持 host.auth.list 后重试" + } + s.mu.RLock() + defer s.mu.RUnlock() + report.Models = len(s.cfg.Models) + for _, entry := range entries { + if entry.Provider == Provider && !runtimeRegistrationKnown(entry) { + report.HostStatus, report.HostMessage = "unknown", "宿主返回了文件或未标明来源的登记,运行状态尚未确认" + } + } + matched := make(map[int]bool) + for _, c := range s.creds { + name := s.files[c.ID] + d := credentialDiagnostic{ID: c.ID, Label: c.Label, Disabled: c.Disabled, Status: "confirmed", Message: "凭证与 CPA 登记一致", Action: "如调用仍失败,请检查模型权限、客户端配置和请求日志", Evidence: []diagnosticEvidence{}} + matches := []runtimeAuth{} + for i, entry := range entries { + if entry.Provider == Provider && ((name != "" && sameAuthName(entry.Name, name)) || entry.ID == routingID(c, name) || entry.ID == c.ID) { + matches = append(matches, entry) + matched[i] = true + } + } + d.Registrations = len(matches) + switch { + case err != nil: + d.Status, d.Message, d.Action = "unknown", "CPA 运行登记尚未确认", "检查宿主连接后重新诊断;保存结果不会因此回滚" + case len(matches) == 0: + d.Status, d.Message, d.Action = "missing", "凭证已保存,但 CPA 未登记", "刷新后重新检查;持续缺失时查看 CPA 插件及凭证加载日志,并安排重新加载或重启" + case !runtimeRegistrationKnown(matches[0]): + d.Status, d.Message, d.Action = "unknown", "宿主仅提供文件信息,不能确认运行登记", "使用支持运行登记查询的 CPA 宿主后重新检查" + case len(matches) > 1: + d.Status, d.Message, d.Action = "duplicate", "同一凭证存在重复或旧登记", "检查会话重新分配结果和 CPA 加载日志,排除旧路由登记后重试" + case name == "" || matches[0].ID != routingID(c, name) || !sameAuthName(matches[0].Name, name): + d.Status, d.Message, d.Action = "routing_mismatch", "CPA 登记与当前路由不一致", "刷新诊断;必要时使用重新分配会话并检查宿主确认结果" + case matches[0].Disabled != c.Disabled: + d.Status, d.Message, d.Action = "disabled_mismatch", "凭证停用状态尚未同步到 CPA", "等待宿主加载变更后重新诊断,持续不一致时检查 CPA watcher 日志" + case matches[0].UpdatedAt.Before(s.expectedRegistration[c.ID]) || (c.KeyUpdatedAt != nil && matches[0].UpdatedAt.Before(*c.KeyUpdatedAt)): + d.Status, d.Message, d.Action = "pending", "凭证已保存,等待 CPA 确认本次变更", "稍后点击重新诊断;若持续等待,检查宿主凭证 watcher 日志" + case c.Disabled: + d.Status, d.Message, d.Action = "disabled", "凭证已停用,CPA 已确认", "需要调用时启用凭证,再检查宿主确认状态" + } + account := diagnosticEvidence{Source: "account_query", Status: "unknown"} + if cached := s.usage[c.ID]; cached != nil { + account.Status, account.CheckedAt, account.HTTPStatus = cached.value.Status, cached.value.CheckedAt, cached.value.HTTPStatus + } + d.Evidence = append(d.Evidence, account) + for _, source := range []string{"plugin_test", "cpa_request"} { + evidence := diagnosticEvidence{Source: source, Status: "unknown"} + for i := len(s.logs) - 1; i >= 0; i-- { + entry := s.logs[i] + if entry.CredentialID != c.ID || entry.Source != source || entry.UpstreamSkipped || (c.KeyUpdatedAt != nil && entry.Time.Before(*c.KeyUpdatedAt)) { + continue + } + evidence.Status = "success" + if entry.Status >= 400 { + evidence.Status = "error" + } + evidence.CheckedAt, evidence.HTTPStatus, evidence.Model = &entry.Time, entry.Status, entry.Model + break + } + d.Evidence = append(d.Evidence, evidence) + } + d.Cooldown = s.credentialHealthLocked(c, now).Status == "cooldown" + report.Credentials = append(report.Credentials, d) + } + for i, entry := range entries { + if entry.Provider == Provider && !matched[i] { + report.UnmatchedRegistrations++ + } + } + sort.Slice(report.Credentials, func(i, j int) bool { return report.Credentials[i].ID < report.Credentials[j].ID }) + if redacted { + for i := range report.Credentials { + report.Credentials[i].ID, report.Credentials[i].Label = "", "" + for j := range report.Credentials[i].Evidence { + report.Credentials[i].Evidence[j].Model = "" + } + } + } + return report +} + +func sameAuthName(left, right string) bool { + return left != "" && right != "" && routingID(Credential{}, filepath.Base(left)) == routingID(Credential{}, filepath.Base(right)) +} + +// CPA also labels live records with backing files as source=file. An auth_index +// is emitted by the runtime manager, but never by its disk-only fallback. +func runtimeRegistrationKnown(entry runtimeAuth) bool { + return entry.Source == "memory" || (entry.AuthIndex != "" && entry.ID != "") +} + +// Saving and loading are separate outcomes. A diagnostic failure must not turn +// a completed credential write into an error that encourages duplicate imports. +func (s *Service) credentialSaveDiagnostic(cid string) credentialDiagnostic { + for _, row := range s.diagnostics(false).Credentials { + if row.ID == cid { + return row + } + } + return credentialDiagnostic{Status: "unknown", Message: "凭证已保存,运行登记尚未确认", Action: "刷新凭证并重新诊断"} +} + +func evidenceSource(r ExecutorRequest) string { + if r.pluginTest { + return "plugin_test" + } + return "cpa_request" +} diff --git a/internal/bridge/diagnostics_test.go b/internal/bridge/diagnostics_test.go new file mode 100644 index 0000000..56ec713 --- /dev/null +++ b/internal/bridge/diagnostics_test.go @@ -0,0 +1,125 @@ +package bridge + +import ( + "errors" + "strings" + "testing" + "time" +) + +func TestRegistrationDiagnostics(t *testing.T) { + s, host, c := setup(t, func(string, map[string]any) mockReply { return streamReply(chatStream("ok")) }) + now := time.Now().UTC().Add(time.Second) + good := runtimeAuth{ID: routingID(c, c.ID+".json"), Name: c.ID + ".json", Provider: Provider, Source: "memory", UpdatedAt: now} + for _, tc := range []struct { + name, want string + entries []runtimeAuth + hostErr bool + }{ + {"registered", "confirmed", []runtimeAuth{good}, false}, + {"live file registration", "confirmed", []runtimeAuth{{ID: good.ID, Name: good.Name, Provider: Provider, Source: "file", AuthIndex: "runtime-index", UpdatedAt: now}}, false}, + {"missing", "missing", nil, false}, + {"duplicate", "duplicate", []runtimeAuth{good, good}, false}, + {"old route", "routing_mismatch", []runtimeAuth{{ID: "old-route", Name: good.Name, Provider: Provider, Source: "memory"}}, false}, + {"disable pending", "disabled_mismatch", []runtimeAuth{{ID: good.ID, Name: good.Name, Provider: Provider, Source: "memory", Disabled: true}}, false}, + {"file fallback", "unknown", []runtimeAuth{{ID: good.ID, Name: good.Name, Provider: Provider, Source: "file"}}, false}, + {"edit pending", "pending", []runtimeAuth{{ID: good.ID, Name: good.Name, Provider: Provider, Source: "memory"}}, false}, + {"host error", "unknown", nil, true}, + } { + t.Run(tc.name, func(t *testing.T) { + s.SetHost(func(method string, in, out any) error { + if method == "host.auth.list" { + if tc.hostErr { + return errors.New("private-error-" + c.APIKey) + } + return assign(out, map[string]any{"files": tc.entries}) + } + return host.call(method, in, out) + }) + report := s.diagnostics(false) + if len(report.Credentials) != 1 || report.Credentials[0].Status != tc.want { + t.Fatalf("unexpected diagnosis: %s", jsonBytes(report)) + } + if strings.Contains(string(jsonBytes(report)), c.APIKey) { + t.Fatal("secret leaked in diagnostic") + } + }) + } + if len(host.requests) != 0 { + t.Fatal("diagnosis made upstream requests") + } +} + +func TestDiagnosticsRedactionAndEvidence(t *testing.T) { + s, host, c := setup(t, func(string, map[string]any) mockReply { return streamReply(chatStream("ok")) }) + s.SetHost(func(method string, in, out any) error { + if method == "host.auth.list" { + return assign(out, map[string]any{"files": []runtimeAuth{{ID: c.ID + ".json", Name: c.ID + ".json", Provider: Provider, Source: "memory", UpdatedAt: time.Now().Add(time.Second)}}}) + } + return host.call(method, in, out) + }) + r := request(c) + r.pluginTest = true + if _, err := s.execute(r, false); err != nil { + t.Fatal(err) + } + r.pluginTest = false + if _, err := s.execute(r, false); err != nil { + t.Fatal(err) + } + row := s.diagnostics(false).Credentials[0] + if row.Evidence[0].Status != "unknown" || row.Evidence[1].Source != "plugin_test" || row.Evidence[1].Status != "success" || row.Evidence[2].Status != "success" { + t.Fatalf("sources merged: %+v", row.Evidence) + } + encoded := string(jsonBytes(s.diagnostics(true))) + for _, private := range []string{c.APIKey, c.Label, `"id":`, `"model":`, c.ID + ".json"} { + if strings.Contains(encoded, private) { + t.Fatalf("summary includes %q", private) + } + } + // Old logs predate the source field. Do not turn them into routing evidence. + s.mu.Lock() + s.logs[0].Source = "" + s.logs[1].Source = "" + s.mu.Unlock() + if row = s.diagnostics(false).Credentials[0]; row.Evidence[2].Status != "unknown" { + t.Fatal("old log falsely proves CPA request") + } +} + +func TestCredentialSaveSeparatesHostConfirmation(t *testing.T) { + s, _, _ := setup(t, func(string, map[string]any) mockReply { return mockReply{} }) + value, err := s.editCredential(ManagementRequest{Method: "POST", Body: jsonBytes(map[string]any{"api_key": "fixture-new-secret", "label": "saved account"})}) + if err != nil { + t.Fatal(err) + } + result := value.(map[string]any) + if result["saved"] != true || result["registration"].(credentialDiagnostic).Status != "missing" { + t.Fatal("save and registration were conflated") + } + if strings.Contains(string(jsonBytes(result)), "fixture-new-secret") { + t.Fatal("saved key exposed") + } +} + +func TestIdenticalSaveDoesNotInvalidateHostConfirmation(t *testing.T) { + s, host, c := setup(t, func(string, map[string]any) mockReply { return mockReply{} }) + c = s.creds[c.ID] // setup also saves the current model revision. + confirmedAt := time.Now().UTC() + expected := s.expectedRegistration[c.ID] + s.SetHost(func(method string, in, out any) error { + if method == "host.auth.list" { + return assign(out, map[string]any{"files": []runtimeAuth{{ID: c.ID + ".json", Name: c.ID + ".json", Provider: Provider, Source: "memory", UpdatedAt: confirmedAt}}}) + } + return host.call(method, in, out) + }) + if err := s.saveCredential(c); err != nil { + t.Fatal(err) + } + if !s.expectedRegistration[c.ID].Equal(expected) { + t.Fatal("identical save changed expected registration timestamp") + } + if got := s.diagnostics(false).Credentials[0].Status; got != "confirmed" { + t.Fatalf("identical save invalidated unchanged runtime registration: %s", got) + } +} diff --git a/internal/bridge/executor.go b/internal/bridge/executor.go index 5010695..58e7858 100644 --- a/internal/bridge/executor.go +++ b/internal/bridge/executor.go @@ -268,7 +268,10 @@ func (s *Service) execute(r ExecutorRequest, stream bool) (any, error) { r.Stream = stream start := time.Now() body, c, m, e := s.prepare(r) + executionConfig := s.config() entry := s.newLog(r, c, m, start) + entry.CredentialScope = credentialEvidenceScope(c, executionConfig) + entry.ZDRRequested = executionConfig.ZDR finish := func(err error) { err = redactError(err, c.APIKey) entry.Status = statusOf(err) @@ -343,7 +346,8 @@ func (s *Service) execute(r ExecutorRequest, stream bool) (any, error) { body["stream_options"] = opts } body["stream"] = true - up, e := s.openUpstream(map[string]any{"host_callback_id": r.HostCallbackID, "method": "POST", "url": s.config().BaseURL + path, "headers": upstreamHeaders(c, s.config().ZDR), "body": jsonBytes(body)}, start.Add(time.Duration(s.config().TimeoutSeconds)*time.Second)) + entry.UpstreamAttempted = true + up, e := s.openUpstream(map[string]any{"host_callback_id": r.HostCallbackID, "method": "POST", "url": executionConfig.BaseURL + path, "headers": upstreamHeaders(c, executionConfig.ZDR), "body": jsonBytes(body)}, start.Add(time.Duration(executionConfig.TimeoutSeconds)*time.Second)) if e != nil { release(e) return early(e) diff --git a/internal/bridge/management.go b/internal/bridge/management.go index 08ae81c..a543863 100644 --- a/internal/bridge/management.go +++ b/internal/bridge/management.go @@ -19,7 +19,7 @@ const apiBase = "/v0/management/commandcodebridge" func (s *Service) registerManagement() any { routes := []map[string]string{} - for method, paths := range map[string][]string{"GET": {"status", "config", "models", "credentials", "credentials/usage", "logs", "statistics", "cpamp/panel"}, "POST": {"credentials", "auth/complete", "auth/callback", "models/refresh", "models/test", "credentials/clear-affinity", "statistics/reset", "cpamp/panel/install"}, "PUT": {"credentials", "models", "models/reasoning", "config"}, "DELETE": {"credentials"}} { + for method, paths := range map[string][]string{"GET": {"status", "config", "models", "models/evidence", "credentials", "credentials/usage", "logs", "statistics", "cpamp/panel", "diagnostics", "diagnostics/summary", "compatibility"}, "POST": {"credentials", "auth/complete", "auth/callback", "models/refresh", "models/test", "credentials/clear-affinity", "statistics/reset", "cpamp/panel/install"}, "PUT": {"credentials", "models", "models/reasoning", "config"}, "DELETE": {"credentials"}} { for _, p := range paths { routes = append(routes, map[string]string{"Method": method, "Path": apiBase + "/" + p}) } @@ -73,9 +73,16 @@ func (s *Service) management(raw json.RawMessage) (any, error) { var value any var e error switch r.Method + " " + path { + case "GET /diagnostics": + value = s.diagnostics(false) + case "GET /diagnostics/summary": + compatibility := s.compatibility() + value = map[string]any{"registration": s.diagnostics(true), "compatibility": compatibility.Checks, "baseline": compatibility.Baseline} + case "GET /compatibility": + value = s.compatibility() case "GET /status": s.mu.RLock() - value = map[string]any{"version": Version, "models": len(s.cfg.Models), "credentials": len(s.creds), "storage_error": s.storageError, "storage_pending": s.persistDirty || s.persistWriting} + value = map[string]any{"version": Version, "models": len(s.cfg.Models), "credentials": len(s.creds), "storage_error": s.storageError, "storage_pending": s.persistDirty != 0 || s.persistWriting, "storage": s.storageStatusLocked()} s.mu.RUnlock() case "GET /config": value = s.config() @@ -85,6 +92,8 @@ func (s *Service) management(raw json.RawMessage) (any, error) { s.editMu.Lock() value, e = installNativePanel(s.config()) s.editMu.Unlock() + case "GET /models/evidence": + value = s.modelEvidence(r.Query.Get("credential_id")) case "GET /models": value = map[string]any{"models": s.config().Models} case "GET /credentials": @@ -177,7 +186,7 @@ func (s *Service) management(raw json.RawMessage) (any, error) { e = fail(400, "invalid settings JSON") } else { for k := range in { - if k != "timeout_seconds" && k != "log_retention" && k != "max_response_bytes" && k != "usage_refresh_seconds" && k != "zdr" && k != "cpamp_install_dir" && k != "cpamp_config_path" && k != "cpamp_panel_path" { + if k != "timeout_seconds" && k != "log_retention" && k != "max_response_bytes" && k != "usage_refresh_seconds" && k != "statistics_retention_days" && k != "zdr" && k != "cpamp_install_dir" && k != "cpamp_config_path" && k != "cpamp_panel_path" { e = fail(400, "unsupported editable setting") break } @@ -196,21 +205,7 @@ func (s *Service) management(raw json.RawMessage) (any, error) { case "POST /credentials/clear-affinity": return s.clearAffinity(r) case "POST /statistics/reset": - s.persistMu.Lock() - s.mu.Lock() - old := s.statistics - next := map[string]Counters{} - e = atomicJSON(filepath.Join(s.cfg.DataDir, "statistics-backup-"+id()+".json"), old) - if e == nil { - e = atomicJSON(filepath.Join(s.cfg.DataDir, "statistics.json"), next) - } - if e == nil { - s.statistics = next - s.statisticsEpoch++ - s.persistDirty = true - } - s.mu.Unlock() - s.persistMu.Unlock() + e = s.resetStatistics() value = map[string]bool{"reset": e == nil} default: return managementJSON(404, map[string]string{"error": "not found"}) @@ -274,7 +269,7 @@ func (s *Service) editCredential(r ManagementRequest) (any, error) { if e := s.saveCredential(c); e != nil { return nil, e } - return map[string]any{"id": c.ID, "label": c.Label, "disabled": c.Disabled, "priority": c.Priority}, nil + return map[string]any{"id": c.ID, "label": c.Label, "disabled": c.Disabled, "priority": c.Priority, "saved": true, "registration": s.credentialSaveDiagnostic(c.ID)}, nil } func (s *Service) deleteCredential(cid string) (any, error) { s.editMu.Lock() @@ -320,7 +315,7 @@ func (s *Service) deleteCredential(cid string) (any, error) { delete(s.usage, cid) delete(s.accounts, cid) s.revoked[cid] = true - s.persistDirty = true + s.markDirtyLocked(dirtyUsage) s.mu.Unlock() return map[string]bool{"deleted": true}, nil } @@ -401,7 +396,7 @@ func (s *Service) testModel(r ManagementRequest) (any, error) { } payload["reasoning_effort"] = in.Reasoning } - response, e := s.execute(ExecutorRequest{Model: in.Model, StorageJSON: jsonBytes(c), HostCallbackID: r.HostCallbackID, Payload: jsonBytes(payload)}, false) + response, e := s.execute(ExecutorRequest{Model: in.Model, StorageJSON: jsonBytes(c), HostCallbackID: r.HostCallbackID, Payload: jsonBytes(payload), pluginTest: true}, false) if e != nil { return nil, e } diff --git a/internal/bridge/model_evidence.go b/internal/bridge/model_evidence.go new file mode 100644 index 0000000..6cc66a3 --- /dev/null +++ b/internal/bridge/model_evidence.go @@ -0,0 +1,92 @@ +package bridge + +import ( + "strings" + "time" +) + +const modelEvidenceTTL = 24 * time.Hour + +// Hashes bind observations to a credential version, routing configuration and +// model configuration. They contain no reusable credential or account material. +func credentialEvidenceScope(c Credential, cfg Config) string { + return shaKey(string(jsonBytes([]any{c.APIKey, c.ProxyURL, cfg.BaseURL, c.KeyUpdatedAt, cfg.ZDR}))) +} +func modelEvidenceScope(m Model) string { return shaKey(string(jsonBytes(m))) } + +type modelObservation struct { + Source string `json:"source"` + Status string `json:"status"` + CheckedAt *time.Time `json:"checked_at,omitempty"` + HTTPStatus int `json:"http_status,omitempty"` + ErrorKind string `json:"error_kind,omitempty"` + RetryAt *time.Time `json:"retry_at,omitempty"` + ClientProtocol string `json:"client_protocol,omitempty"` + UpstreamProtocol string `json:"upstream_protocol,omitempty"` + ZDRRequested bool `json:"zdr_requested"` +} +type modelAvailability struct { + Model string `json:"model"` + UpstreamModel string `json:"upstream_model"` + CredentialID string `json:"credential_id"` + Status string `json:"status"` + Evidence []modelObservation `json:"evidence"` +} + +func observationStatus(row LogEntry, now time.Time) string { + if now.Sub(row.Time) > modelEvidenceTTL || row.Time.After(now.Add(time.Minute)) { + return "expired" + } + if row.Status >= 200 && row.Status < 400 { + return "available" + } + if strings.EqualFold(row.ErrorKind, "MODEL_NOT_IN_PLAN") { + return "not_in_plan" + } + switch row.Status { + case 401: + return "authentication_error" + case 403: + return "permission_unknown" + case 429: + return "temporary_limit" + default: + return "temporary_error" + } +} + +func (s *Service) modelEvidence(cid string) any { + s.mu.RLock() + defer s.mu.RUnlock() + now := time.Now().UTC() + rows := []modelAvailability{} + for _, m := range s.cfg.Models { + c, ok := s.creds[cid] + item := modelAvailability{Model: m.ID, UpstreamModel: m.UpstreamID, CredentialID: cid, Status: "unknown", Evidence: []modelObservation{}} + if ok && c.Disabled { + item.Status = "disabled" + } + if ok && !c.Disabled { + scope, modelScope := credentialEvidenceScope(c, s.cfg), modelEvidenceScope(m) + var latest time.Time + for _, source := range []string{"plugin_test", "cpa_request"} { + observation := modelObservation{Source: source, Status: "unknown"} + for i := len(s.logs) - 1; i >= 0; i-- { + log := s.logs[i] + if log.CredentialID != cid || log.Model != m.ID || log.UpstreamModel != m.UpstreamID || log.Source != source || !log.UpstreamAttempted || log.UpstreamSkipped || log.CredentialScope != scope || log.ModelScope != modelScope || log.AccountScope != s.accounts[cid] { + continue + } + observation = modelObservation{Source: source, Status: observationStatus(log, now), CheckedAt: &log.Time, HTTPStatus: log.Status, ErrorKind: log.ErrorKind, RetryAt: log.RetryAt, ClientProtocol: log.ClientProtocol, UpstreamProtocol: log.UpstreamProtocol, ZDRRequested: log.ZDRRequested} + if log.Time.After(latest) { + latest = log.Time + item.Status = observation.Status + } + break + } + item.Evidence = append(item.Evidence, observation) + } + } + rows = append(rows, item) + } + return map[string]any{"credential_id": cid, "checked_at": now, "expires_after_seconds": int(modelEvidenceTTL.Seconds()), "items": rows, "note": "目录可见不代表套餐有权限;证据来自保留日志,按凭证版本、账户和模型配置隔离,24 小时后过期。只读查询不会生成。"} +} diff --git a/internal/bridge/model_evidence_test.go b/internal/bridge/model_evidence_test.go new file mode 100644 index 0000000..1033ea0 --- /dev/null +++ b/internal/bridge/model_evidence_test.go @@ -0,0 +1,75 @@ +package bridge + +import ( + "testing" + "time" +) + +func evidenceItem(s *Service, cid string) modelAvailability { + return s.modelEvidence(cid).(map[string]any)["items"].([]modelAvailability)[0] +} + +func TestModelEvidenceScopesExpiryAndSources(t *testing.T) { + s, _, c := setup(t, func(string, map[string]any) mockReply { return streamReply(chatStream("ok")) }) + m := s.config().Models[0] + row := s.newLog(ExecutorRequest{Model: m.ID, pluginTest: true}, c, m, time.Now()) + row.UpstreamAttempted = true + row.Status = 200 + s.record(row) + if item := evidenceItem(s, c.ID); item.Status != "available" || item.Evidence[0].Status != "available" || item.Evidence[1].Status != "unknown" { + t.Fatal(item) + } + s.mu.Lock() + s.logs[0].Time = time.Now().Add(-25 * time.Hour) + s.mu.Unlock() + if evidenceItem(s, c.ID).Status != "expired" { + t.Fatal("old success not expired") + } + s.mu.Lock() + s.logs[0].Time = time.Now() + s.accounts[c.ID] = "new-account" + s.mu.Unlock() + if evidenceItem(s, c.ID).Status != "unknown" { + t.Fatal("account isolation failed") + } + s.mu.Lock() + delete(s.accounts, c.ID) + s.cfg.Models[0].UpstreamID = "changed" + s.mu.Unlock() + if evidenceItem(s, c.ID).Status != "unknown" { + t.Fatal("mapping isolation failed") + } + s.mu.Lock() + s.cfg.Models[0] = m + s.creds[c.ID] = Credential{ID: c.ID, APIKey: "replacement"} + s.mu.Unlock() + if evidenceItem(s, c.ID).Status != "unknown" { + t.Fatal("key isolation failed") + } +} + +func TestModelEvidenceFailureClassificationAndLocalSkips(t *testing.T) { + for _, tc := range []struct { + code int + kind, want string + }{{403, "MODEL_NOT_IN_PLAN", "not_in_plan"}, {403, "permission_error", "permission_unknown"}, {429, "rate_limit_error", "temporary_limit"}, {503, "upstream_error", "temporary_error"}, {401, "authentication_error", "authentication_error"}} { + t.Run(tc.want, func(t *testing.T) { + s, _, c := setup(t, func(string, map[string]any) mockReply { return streamReply(chatStream("ok")) }) + m := s.config().Models[0] + row := s.newLog(ExecutorRequest{Model: m.ID}, c, m, time.Now()) + row.Status = tc.code + row.ErrorKind = tc.kind + row.UpstreamAttempted = true + s.record(row) + if item := evidenceItem(s, c.ID); item.Status != tc.want || item.Evidence[1].Status != tc.want { + t.Fatal(item) + } + row.Status = 200 + row.UpstreamSkipped = true + s.record(row) + if evidenceItem(s, c.ID).Status != tc.want { + t.Fatal("local skip replaced real result") + } + }) + } +} diff --git a/internal/bridge/observability.go b/internal/bridge/observability.go index d291339..49a9382 100644 --- a/internal/bridge/observability.go +++ b/internal/bridge/observability.go @@ -10,6 +10,14 @@ var errStreamDone = errors.New("stream complete") type Attempt struct{ Provider, ProviderSource string } type LogEntry struct { + CredentialScope string `json:"credential_scope,omitempty"` + AccountScope string `json:"account_scope,omitempty"` + ModelScope string `json:"model_scope,omitempty"` + ClientProtocol string `json:"client_protocol,omitempty"` + UpstreamProtocol string `json:"upstream_protocol,omitempty"` + ZDRRequested bool `json:"zdr_requested"` + UpstreamAttempted bool `json:"upstream_attempted"` + Source string `json:"source,omitempty"` ID string `json:"id"` Time time.Time `json:"time"` Model string `json:"model"` @@ -40,22 +48,23 @@ type LogEntry struct { epoch uint64 } type Counters struct { - Time time.Time `json:"time"` - Model string `json:"model"` - Requests int64 `json:"requests"` - Success int64 `json:"success"` - Failed int64 `json:"failed"` - Skipped int64 `json:"skipped"` - WithUsage int64 `json:"with_usage"` - Input int64 `json:"input_tokens"` - Output int64 `json:"output_tokens"` - Cached int64 `json:"cached_tokens"` - CacheWrite int64 `json:"cache_write_tokens"` - DurationMS int64 `json:"duration_ms"` - TTFTMS int64 `json:"ttft_ms"` - TTFTSamples int64 `json:"ttft_samples"` - SpeedTokens int64 `json:"speed_tokens"` - SpeedMS int64 `json:"speed_ms"` + BucketSeconds int `json:"bucket_seconds,omitempty"` + Time time.Time `json:"time"` + Model string `json:"model"` + Requests int64 `json:"requests"` + Success int64 `json:"success"` + Failed int64 `json:"failed"` + Skipped int64 `json:"skipped"` + WithUsage int64 `json:"with_usage"` + Input int64 `json:"input_tokens"` + Output int64 `json:"output_tokens"` + Cached int64 `json:"cached_tokens"` + CacheWrite int64 `json:"cache_write_tokens"` + DurationMS int64 `json:"duration_ms"` + TTFTMS int64 `json:"ttft_ms"` + TTFTSamples int64 `json:"ttft_samples"` + SpeedTokens int64 `json:"speed_tokens"` + SpeedMS int64 `json:"speed_ms"` } func (a *Counters) add(b Counters) { @@ -77,8 +86,24 @@ func (a *Counters) add(b Counters) { func (s *Service) newLog(r ExecutorRequest, c Credential, m Model, start time.Time) LogEntry { s.mu.RLock() epoch := s.statisticsEpoch + scope := credentialEvidenceScope(c, s.cfg) + account := s.accounts[c.ID] + zdr := s.cfg.ZDR s.mu.RUnlock() - return LogEntry{ID: id(), Time: start.UTC(), Model: r.Model, UpstreamModel: m.UpstreamID, CredentialID: c.ID, Credential: c.Label, Stream: r.Stream, Provider: "unknown", ProviderSource: "not_reported", epoch: epoch} + protocol := "chat-completions" + // CPA can replace SourceFormat with the translated plugin input format. + // The original HTTP path remains authoritative for client evidence. + requestPath := str(r.Metadata["request_path"]) + if strings.HasSuffix(requestPath, "/responses") || strings.Contains(strings.ToLower(r.SourceFormat), "response") { + protocol = "responses" + } else if strings.HasSuffix(requestPath, "/messages") || r.Format == "claude" { + protocol = "messages" + } + upstream := "chat-completions" + if !contains(m.Endpoints, "/chat/completions") && contains(m.Endpoints, "/messages") { + upstream = "messages" + } + return LogEntry{CredentialScope: scope, AccountScope: account, ModelScope: modelEvidenceScope(m), ClientProtocol: protocol, UpstreamProtocol: upstream, ZDRRequested: zdr, ID: id(), Time: start.UTC(), Model: r.Model, UpstreamModel: m.UpstreamID, CredentialID: c.ID, Credential: c.Label, Stream: r.Stream, Source: evidenceSource(r), Provider: "unknown", ProviderSource: "not_reported", epoch: epoch} } func (s *Service) record(entry LogEntry) { s.mu.Lock() @@ -139,8 +164,9 @@ func (s *Service) record(entry LogEntry) { } } s.statistics[key] = c + s.markDirtyLocked(dirtyStatistics) } - s.persistDirty = true + s.markDirtyLocked(dirtyLogs) } func contentStarted(j map[string]any) bool { for _, v := range list(j["choices"]) { @@ -233,10 +259,18 @@ func (s *Service) statisticsView(r ManagementRequest) any { from, to := rangeTimes(r) total := Counters{} models := map[string]Counters{} + resolution := 60 for _, c := range s.statistics { - if (!from.IsZero() && c.Time.Before(from)) || (!to.IsZero() && !c.Time.Before(to)) { + seconds := c.BucketSeconds + if seconds == 0 { + seconds = 60 + } + if (!from.IsZero() && !c.Time.Add(time.Duration(seconds)*time.Second).After(from)) || (!to.IsZero() && !c.Time.Before(to)) { continue } + if seconds > resolution { + resolution = seconds + } total.add(c) v := models[c.Model] v.Model = c.Model @@ -256,5 +290,5 @@ func (s *Service) statisticsView(r ManagementRequest) any { v := float64(total.TTFTMS) / float64(total.TTFTSamples) ttft = &v } - return map[string]any{"totals": total, "models": models, "output_tokens_per_second": speed, "cache_hit_percent": hit, "average_ttft_ms": ttft, "storage_error": s.storageError} + return map[string]any{"totals": total, "models": models, "output_tokens_per_second": speed, "cache_hit_percent": hit, "average_ttft_ms": ttft, "storage_error": s.storageError, "storage": s.storageStatusLocked(), "bucket_seconds": resolution, "range_note": "历史日级统计按重叠整日纳入,自定义范围边界可能扩大至 UTC 日"} } diff --git a/internal/bridge/persistence.go b/internal/bridge/persistence.go index 5444ec4..66ce8ed 100644 --- a/internal/bridge/persistence.go +++ b/internal/bridge/persistence.go @@ -1,12 +1,28 @@ package bridge import ( + "os" "path/filepath" "time" ) const statisticsFlushInterval = 250 * time.Millisecond +type runtimeFiles uint8 + +const ( + dirtyLogs runtimeFiles = 1 << iota + dirtyStatistics + dirtyUsage +) + +func (s *Service) markDirtyLocked(files runtimeFiles) { + if s.persistSince.IsZero() { + s.persistSince = time.Now().UTC() + } + s.persistDirty |= files +} + // Only redacted observations and one-way identity hashes belong in data_dir. // The fingerprint is checked when CPA registers each credential after restart. type persistedUsage struct { @@ -48,36 +64,73 @@ func (s *Service) flushStatistics() { s.persistMu.Lock() defer s.persistMu.Unlock() s.mu.Lock() - if !s.loaded || !s.persistDirty { + if !s.loaded { s.mu.Unlock() return } - logs := append([]LogEntry(nil), s.logs...) - statistics := make(map[string]Counters, len(s.statistics)) - for key, value := range s.statistics { - statistics[key] = value + s.compactStatisticsLocked(time.Now().UTC()) + dirty := s.persistDirty + if dirty == 0 { + s.mu.Unlock() + return } - usage := make(map[string]persistedUsage, len(s.usage)) - for key, cached := range s.usage { - if cached.value.UpdatedAt != nil || cached.value.CheckedAt != nil { - usage[key] = persistedUsage{Fingerprint: cached.fingerprint, Value: cached.value, Account: s.accounts[key]} + values := map[string]any{} + if dirty&dirtyLogs != 0 { + values["requests.json"] = append([]LogEntry{}, s.logs...) + } + if dirty&dirtyStatistics != 0 { + statistics := make(map[string]Counters, len(s.statistics)) + for key, value := range s.statistics { + statistics[key] = value + } + values["statistics.json"] = statistics + } + if dirty&dirtyUsage != 0 { + usage := make(map[string]persistedUsage, len(s.usage)) + for key, cached := range s.usage { + if cached.value.UpdatedAt != nil || cached.value.CheckedAt != nil { + usage[key] = persistedUsage{Fingerprint: cached.fingerprint, Value: cached.value, Account: s.accounts[key]} + } } + values["usage.json"] = usage } dir := s.cfg.DataDir - s.persistDirty = false + s.persistDirty = 0 s.persistWriting = true s.mu.Unlock() - logErr := atomicJSON(filepath.Join(dir, "requests.json"), logs) - statsErr := atomicJSON(filepath.Join(dir, "statistics.json"), statistics) - usageErr := atomicJSON(filepath.Join(dir, "usage.json"), usage) + failed := runtimeFiles(0) + for name, value := range values { + err := s.writeRuntimeSnapshot(dir, name, value, false) + s.mu.Lock() + if s.persistErrors == nil { + s.persistErrors = map[string]bool{} + } + if s.persistWrites == nil { + s.persistWrites = map[string]uint64{} + } + if err != nil { + s.persistErrors[name] = true + failed |= map[string]runtimeFiles{"requests.json": dirtyLogs, "statistics.json": dirtyStatistics, "usage.json": dirtyUsage}[name] + } else { + delete(s.persistErrors, name) + s.persistWrites[name]++ + } + s.mu.Unlock() + } s.mu.Lock() s.persistWriting = false - if logErr != nil || statsErr != nil || usageErr != nil { + s.persistDirty |= failed + if len(s.persistErrors) > 0 { s.storageError = "request statistics or quota persistence failed" - s.persistDirty = true // Retry at the next tick, including on final shutdown. } else { s.storageError = "" } + if failed == 0 { + s.lastPersistAt = time.Now().UTC() + } + if s.persistDirty == 0 { + s.persistSince = time.Time{} + } s.mu.Unlock() } @@ -93,3 +146,33 @@ func (s *Service) stopPersistence() { <-done } } + +// Retire the previous checkpoint before committing a reset. A crash between +// these operations can lose a checkpoint, but cannot resurrect cleared totals. +func (s *Service) resetStatistics() error { + s.persistMu.Lock() + defer s.persistMu.Unlock() + s.mu.Lock() + defer s.mu.Unlock() + dir := s.cfg.DataDir + suffix := id() + if err := atomicJSON(filepath.Join(dir, "statistics-backup-"+suffix+".json"), s.statistics); err != nil { + return err + } + checkpoint := filepath.Join(dir, "statistics.json.last-good") + if err := os.Rename(checkpoint, filepath.Join(dir, "statistics-checkpoint-before-reset-"+suffix+".json")); err != nil && !os.IsNotExist(err) { + return err + } + next := map[string]Counters{} + if err := atomicJSON(filepath.Join(dir, "statistics.json"), next); err != nil { + return err + } + s.statistics = next + s.statisticsEpoch++ + s.markDirtyLocked(dirtyStatistics) + // Force the worker to create a fresh checkpoint, including after retry. + if s.checkpointAt != nil { + delete(s.checkpointAt, "statistics.json") + } + return nil +} diff --git a/internal/bridge/persistence_test.go b/internal/bridge/persistence_test.go index 9d2a138..3e7c8e9 100644 --- a/internal/bridge/persistence_test.go +++ b/internal/bridge/persistence_test.go @@ -64,7 +64,7 @@ func TestBatchedPersistenceRetriesWriteFailure(t *testing.T) { s.mu.RLock() dirty, reported := s.persistDirty, s.storageError s.mu.RUnlock() - if !dirty || reported == "" { + if dirty == 0 || reported == "" { t.Fatal("write failure was not retained for retry") } if err := os.Remove(path); err != nil { @@ -73,7 +73,7 @@ func TestBatchedPersistenceRetriesWriteFailure(t *testing.T) { s.flushStatistics() s.mu.RLock() defer s.mu.RUnlock() - if s.persistDirty || s.storageError != "" { + if s.persistDirty != 0 || s.storageError != "" { t.Fatal("successful retry did not clear persistence error") } } diff --git a/internal/bridge/runtime_recovery.go b/internal/bridge/runtime_recovery.go new file mode 100644 index 0000000..fd741cf --- /dev/null +++ b/internal/bridge/runtime_recovery.go @@ -0,0 +1,168 @@ +package bridge + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "time" +) + +type runtimeRecovery struct { + File string `json:"file"` + Quarantine string `json:"quarantine"` + Recovered bool `json:"recovered"` + CheckedAt time.Time `json:"checked_at"` + Message string `json:"message"` +} + +type runtimeFormat struct { + Schema int `json:"schema"` + Statistics string `json:"statistics"` + Recoveries []runtimeRecovery `json:"recoveries,omitempty"` +} + +// Data files retain their original array/map shape for rollback compatibility. +// Version metadata is separate; an unknown format must never be overwritten. +func (s *Service) loadRuntimeLocked() error { + dir := s.cfg.DataDir + format := runtimeFormat{Schema: 1, Statistics: "minute-and-day-v1"} + if raw, err := os.ReadFile(filepath.Join(dir, "runtime-format.json")); err == nil { + var stored runtimeFormat + if json.Unmarshal(raw, &stored) != nil || stored.Schema != 1 || stored.Statistics != "minute-and-day-v1" { + return fail(500, "unsupported runtime data format; preserve files and restore a compatible version") + } + format = stored + } else if !os.IsNotExist(err) { + return fail(500, "runtime format metadata cannot be read") + } + s.storageWarnings = format.Recoveries + var err error + if s.logs, err = loadRuntimeFile(s, "requests.json", []LogEntry{}); err != nil { + return err + } + if s.statistics, err = loadRuntimeFile(s, "statistics.json", map[string]Counters{}); err != nil { + return err + } + if len(s.statistics) > 0 { + backup := filepath.Join(dir, "statistics-before-daily-v1.json") + if _, err := os.Lstat(backup); os.IsNotExist(err) { + if atomicJSON(backup, s.statistics) != nil { + return fail(500, "statistics migration backup could not be saved") + } + } else if err != nil { + return fail(500, "statistics migration backup cannot be inspected") + } + } + saved, err := loadRuntimeFile(s, "usage.json", map[string]persistedUsage{}) + if err != nil { + return err + } + for cid, item := range saved { + s.usage[cid] = &usageCache{fingerprint: item.Fingerprint, value: item.Value} + if item.Account != "" { + s.accounts[cid] = item.Account + } + } + if len(s.storageWarnings) > 20 { + s.storageWarnings = s.storageWarnings[len(s.storageWarnings)-20:] + } + format.Recoveries = s.storageWarnings + if atomicJSON(filepath.Join(dir, "runtime-format.json"), format) != nil { + return fail(500, "runtime format metadata could not be saved") + } + return nil +} + +func loadRuntimeFile[T any](s *Service, name string, empty T) (T, error) { + path := filepath.Join(s.cfg.DataDir, name) + raw, err := readRegularRuntime(path) + if os.IsNotExist(err) { + // Also cover interruption after quarantine but before replacement. + if _, backupErr := os.Lstat(path + ".last-good"); os.IsNotExist(backupErr) { + return empty, nil + } + raw = []byte("{") + err = nil + } + if err != nil { + return empty, fail(500, "runtime file cannot be read: "+name) + } + var value T + if decodeRuntime(raw, &value) { + return value, nil + } + notice := runtimeRecovery{File: name, Quarantine: name + ".corrupt-" + id(), CheckedAt: time.Now().UTC(), Message: "历史文件损坏已隔离;没有可用检查点,此文件的历史范围未知,其他配置与历史保留"} + backup, backupErr := readRegularRuntime(path + ".last-good") + value = *new(T) // Unmarshal may partially fill a map before returning an error. + if backupErr == nil && decodeRuntime(backup, &value) { + notice.Recovered = true + notice.Message = "已从最近有效检查点恢复;检查点后的记录可能缺失,隔离原件保留" + } else { + value = empty + } + // Save the notice first so a crash after quarantine cannot silently discard + // the fact that history is incomplete. A failed recovery remains visible. + s.storageWarnings = append(s.storageWarnings, notice) + if atomicJSON(filepath.Join(s.cfg.DataDir, "runtime-format.json"), runtimeFormat{Schema: 1, Statistics: "minute-and-day-v1", Recoveries: s.storageWarnings}) != nil { + return empty, fail(500, "runtime recovery notice could not be saved: "+name) + } + if err := os.Rename(path, filepath.Join(s.cfg.DataDir, notice.Quarantine)); err != nil && !os.IsNotExist(err) { + return empty, fail(500, "corrupt runtime file could not be isolated: "+name) + } + if atomicJSON(path, value) != nil { + return empty, fail(500, "runtime recovery could not be saved: "+name) + } + return value, nil +} + +func readRegularRuntime(path string) ([]byte, error) { + info, err := os.Lstat(path) + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, os.ErrPermission + } + return os.ReadFile(path) +} +func decodeRuntime(raw []byte, target any) bool { + if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + // Older writers serialized an empty request slice as null whenever + // quota-only activity flushed all three files. This is valid legacy data. + if logs, ok := target.(*[]LogEntry); ok { + *logs = []LogEntry{} + return true + } + return false + } + if json.Unmarshal(raw, target) != nil { + return false + } + if counters, ok := target.(*map[string]Counters); ok { + for _, c := range *counters { + if c.Time.IsZero() || c.Model == "" || (c.BucketSeconds != 0 && c.BucketSeconds != 60 && c.BucketSeconds != 86400) { + return false + } + } + } + return true +} + +// Checkpoints are refreshed at most once a minute rather than doubling every +// request-log write. Forced checkpoints are used when explicitly resetting. +func (s *Service) writeRuntimeSnapshot(dir, name string, value any, force bool) error { + if err := atomicJSON(filepath.Join(dir, name), value); err != nil { + return err + } + if s.checkpointAt == nil { + s.checkpointAt = map[string]time.Time{} + } + if force || time.Since(s.checkpointAt[name]) >= time.Minute { + if err := atomicJSON(filepath.Join(dir, name+".last-good"), value); err != nil { + return err + } + s.checkpointAt[name] = time.Now() + } + return nil +} diff --git a/internal/bridge/runtime_recovery_test.go b/internal/bridge/runtime_recovery_test.go new file mode 100644 index 0000000..5c2d294 --- /dev/null +++ b/internal/bridge/runtime_recovery_test.go @@ -0,0 +1,204 @@ +package bridge + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + "time" +) + +func TestRuntimeRecoveryIsolatesOnlyDamagedFile(t *testing.T) { + for _, backup := range []bool{false, true} { + t.Run(map[bool]string{false: "missing_checkpoint", true: "checkpoint"}[backup], func(t *testing.T) { + s := NewService() + s.cfg.DataDir = t.TempDir() + // A partially decoded primary must not contaminate the restored map. + os.WriteFile(filepath.Join(s.cfg.DataDir, "statistics.json"), []byte(`{"partial":{"model":"bad"},"invalid":5}`), 0600) + good := map[string]Counters{"valid": {Time: time.Now().UTC().Truncate(time.Minute), Model: "kept", Requests: 9}} + if backup { + atomicJSON(filepath.Join(s.cfg.DataDir, "statistics.json.last-good"), good) + } + atomicJSON(filepath.Join(s.cfg.DataDir, "requests.json"), []LogEntry{{ID: "kept-log"}}) + if err := s.loadRuntimeLocked(); err != nil { + t.Fatal(err) + } + if len(s.logs) != 1 || len(s.statistics) != map[bool]int{false: 0, true: 1}[backup] { + t.Fatalf("recovery contaminated history: %+v", s.statistics) + } + if len(s.storageWarnings) != 1 || s.storageWarnings[0].Recovered != backup { + t.Fatal(s.storageWarnings) + } + if _, err := os.Stat(filepath.Join(s.cfg.DataDir, s.storageWarnings[0].Quarantine)); err != nil { + t.Fatal(err) + } + other := NewService() + other.cfg = s.cfg + if err := other.loadRuntimeLocked(); err != nil || len(other.storageWarnings) != 1 { + t.Fatal("recovery notice lost", err) + } + }) + } +} + +func TestRuntimeFormatAndSettingsFailClosed(t *testing.T) { + for _, name := range []string{"runtime-format.json", "settings.json"} { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + raw := []byte(`{"schema":99}`) + if name == "settings.json" { + raw = []byte(`broken`) + } + os.WriteFile(filepath.Join(dir, name), raw, 0600) + os.WriteFile(filepath.Join(dir, "requests.json"), []byte(`corrupt-preserved`), 0600) + s := NewService() + if err := s.configure(jsonBytes(map[string]any{"config_yaml": []byte("data_dir: " + filepath.ToSlash(dir))})); err == nil { + t.Fatal("unsafe format accepted") + } + got, _ := os.ReadFile(filepath.Join(dir, "requests.json")) + if string(got) != "corrupt-preserved" { + t.Fatal("runtime file touched") + } + }) + } +} + +func TestIndependentPersistenceAndCheckpointThrottle(t *testing.T) { + s, _, _ := setup(t, func(string, map[string]any) mockReply { return streamReply(chatStream("ok")) }) + s.flushStatistics() + s.mu.Lock() + s.markDirtyLocked(dirtyUsage) + s.mu.Unlock() + s.flushStatistics() + s.mu.RLock() + writes := s.storageStatusLocked().(map[string]any)["writes"].(map[string]uint64) + s.mu.RUnlock() + if writes["usage.json"] != 1 || writes["requests.json"] != 0 || writes["statistics.json"] != 0 { + t.Fatal(writes) + } + s.mu.Lock() + s.markDirtyLocked(dirtyUsage) + s.mu.Unlock() + s.flushStatistics() + if writes["usage.json"] != 1 { + t.Fatal("status snapshot aliases live map") + } + checkpoint := filepath.Join(s.cfg.DataDir, "usage.json.last-good") + before, _ := os.Stat(checkpoint) + s.mu.Lock() + s.markDirtyLocked(dirtyUsage) + s.mu.Unlock() + s.flushStatistics() + after, _ := os.Stat(checkpoint) + if before == nil || after == nil || !before.ModTime().Equal(after.ModTime()) { + t.Fatal("checkpoint rewritten within one minute") + } +} + +func TestResetCannotRestoreOldCheckpoint(t *testing.T) { + s, _, _ := setup(t, func(string, map[string]any) mockReply { return streamReply(chatStream("ok")) }) + s.record(LogEntry{Model: "alias", Status: 200}) + s.flushStatistics() + if err := s.resetStatistics(); err != nil { + t.Fatal(err) + } + // Simulate an immediate crash before the background worker runs. + s.stopPersistence() + os.WriteFile(filepath.Join(s.cfg.DataDir, "statistics.json"), []byte(`truncated`), 0600) + restored := NewService() + restored.cfg = s.cfg + if err := restored.loadRuntimeLocked(); err != nil || len(restored.statistics) != 0 { + t.Fatal("reset statistics resurrected", err) + } +} + +func TestStatisticsCompactionPreservesTotalsAndPrecision(t *testing.T) { + s := NewService() + now := time.Date(2026, 10, 18, 12, 0, 0, 0, time.UTC) + for i := 0; i < 60; i++ { + at := now.Add(-10 * 24 * time.Hour).Add(time.Duration(i) * time.Minute) + s.statistics[at.String()] = Counters{Time: at, Model: "old", Requests: 2, Input: 3, Output: 4} + } + s.statistics["recent"] = Counters{Time: now, Model: "recent", Requests: 1} + s.compactStatisticsLocked(now) + if len(s.statistics) != 2 { + t.Fatal(len(s.statistics)) + } + totals := s.statisticsView(ManagementRequest{}).(map[string]any) + if totals["totals"].(Counters).Requests != 121 || totals["bucket_seconds"] != 86400 { + t.Fatal(totals) + } + s.cfg.StatisticsRetentionDays = 9 + s.nextCompaction = time.Time{} + s.compactStatisticsLocked(now) + if len(s.statistics) != 1 { + t.Fatal("expiry ignored") + } +} + +func TestLegacyMigrationBackupBeforeCompaction(t *testing.T) { + s := NewService() + s.cfg.DataDir = t.TempDir() + old := map[string]Counters{"old": {Time: time.Now().UTC().Add(-10 * 24 * time.Hour).Truncate(time.Minute), Model: "old", Requests: 3}} + atomicJSON(filepath.Join(s.cfg.DataDir, "statistics.json"), old) + if err := s.loadRuntimeLocked(); err != nil { + t.Fatal(err) + } + s.compactStatisticsLocked(time.Now().UTC()) + raw, err := os.ReadFile(filepath.Join(s.cfg.DataDir, "statistics-before-daily-v1.json")) + var saved map[string]Counters + if err != nil || json.Unmarshal(raw, &saved) != nil || saved["old"].BucketSeconds != 0 || saved["old"].Requests != 3 { + t.Fatal("missing original precision backup", err) + } +} + +func TestSamplerJitterDoesNotIncreaseRate(t *testing.T) { + for i := 0; i < 100; i++ { + d := samplerDelay(time.Minute) + if d < time.Minute || d > 72*time.Second { + t.Fatal(d) + } + } +} + +func TestMissingPrimaryRecoversCheckpoint(t *testing.T) { + s := NewService() + s.cfg.DataDir = t.TempDir() + atomicJSON(filepath.Join(s.cfg.DataDir, "requests.json.last-good"), []LogEntry{{ID: "checkpoint"}}) + if err := s.loadRuntimeLocked(); err != nil || len(s.logs) != 1 || !s.storageWarnings[0].Recovered { + t.Fatal("missing primary recovery failed", err) + } +} + +func TestLegacyEmptyLogsNullNeedsNoRecovery(t *testing.T) { + s := NewService() + s.cfg.DataDir = t.TempDir() + os.WriteFile(filepath.Join(s.cfg.DataDir, "requests.json"), []byte("null"), 0600) + if err := s.loadRuntimeLocked(); err != nil || len(s.logs) != 0 || len(s.storageWarnings) != 0 { + t.Fatal("legacy empty logs misidentified", err) + } +} + +func TestResetWriteFailurePreservesMemory(t *testing.T) { + s, _, _ := setup(t, func(string, map[string]any) mockReply { return streamReply(chatStream("ok")) }) + s.record(LogEntry{Model: "kept", Status: 200}) + s.flushStatistics() + s.stopPersistence() + path := filepath.Join(s.cfg.DataDir, "statistics.json") + os.Remove(path) + os.Mkdir(path, 0700) + if err := s.resetStatistics(); err == nil { + t.Fatal("reset unexpectedly succeeded") + } + if len(s.statistics) == 0 || s.statisticsEpoch != 0 { + t.Fatal("failed reset erased in-memory observations") + } + os.Remove(path) + s.mu.Lock() + s.markDirtyLocked(dirtyStatistics) + s.mu.Unlock() + s.flushStatistics() + if s.storageError != "" { + t.Fatal(s.storageError) + } +} diff --git a/internal/bridge/runtime_scale_test.go b/internal/bridge/runtime_scale_test.go new file mode 100644 index 0000000..ffb72c1 --- /dev/null +++ b/internal/bridge/runtime_scale_test.go @@ -0,0 +1,62 @@ +package bridge + +import ( + "encoding/json" + "fmt" + "os" + "runtime" + "sort" + "testing" + "time" +) + +// Opt-in measurement, not a timing gate. Uses exactly the same observations +// before/after compaction; no upstream traffic or machine-specific threshold. +func TestRuntimeScaleMeasurement(t *testing.T) { + if os.Getenv("BRIDGE_MEASURE") != "1" { + t.Skip("set BRIDGE_MEASURE=1 for the synthetic scale measurement") + } + now := time.Now().UTC().Truncate(24 * time.Hour).Add(12 * time.Hour) + s := NewService() + for minute := 0; minute < 90*1440; minute++ { + at := now.Add(-time.Duration(minute) * time.Minute) + for model := 0; model < 2; model++ { + name := fmt.Sprintf("model-%d", model) + s.statistics[at.Format(time.RFC3339)+"|"+name] = Counters{Time: at, Model: name, Requests: 1, Success: 1, Input: 100, Output: 20} + } + } + measure := func() map[string]any { + runtime.GC() + runtime.GC() // Drop the previous JSON buffer from sync.Pool before sampling. + var mem runtime.MemStats + runtime.ReadMemStats(&mem) + start := time.Now() + raw := jsonBytes(s.statistics) + encode := time.Since(start) + start = time.Now() + var restored map[string]Counters + if json.Unmarshal(raw, &restored) != nil { + t.Fatal("decode") + } + decode := time.Since(start) + durations := []float64{} + var total int64 + for i := 0; i < 40; i++ { + start = time.Now() + v := s.statisticsView(ManagementRequest{}).(map[string]any) + total = v["totals"].(Counters).Requests + durations = append(durations, float64(time.Since(start).Microseconds())/1000) + } + sort.Float64s(durations) + return map[string]any{"buckets": len(s.statistics), "json_bytes": len(raw), "encode_ms": float64(encode.Microseconds()) / 1000, "decode_ms": float64(decode.Microseconds()) / 1000, "query_p95_ms": durations[38], "heap_inuse_bytes": mem.HeapInuse, "heap_alloc_bytes": mem.HeapAlloc, "requests": total} + } + before := measure() + start := time.Now() + s.compactStatisticsLocked(now) + compaction := time.Since(start) + after := measure() + if before["requests"] != after["requests"] { + t.Fatal("totals changed") + } + t.Log(string(jsonBytes(map[string]any{"fixture": "90 days x 2 models x 1 request/minute", "before": before, "after": after, "compaction_ms": float64(compaction.Microseconds()) / 1000}))) +} diff --git a/internal/bridge/service.go b/internal/bridge/service.go index 3720961..a53b8b1 100644 --- a/internal/bridge/service.go +++ b/internal/bridge/service.go @@ -1,6 +1,7 @@ package bridge import ( + "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" @@ -17,30 +18,38 @@ import ( ) type Service struct { - mu sync.RWMutex - editMu sync.Mutex - host HostCall - cfg Config - creds map[string]Credential - files map[string]string - revoked map[string]bool - authDir string - loaded, stopped, samplerStarted bool - stopCh chan struct{} - active sync.WaitGroup - streams map[string]bool - logs []LogEntry - statistics map[string]Counters - statisticsEpoch uint64 - storageError string - persistMu sync.Mutex - persistDirty, persistRunning, persistWriting bool - persistStop, persistDone chan struct{} - usage map[string]*usageCache - accounts map[string]string - cooldown map[string]time.Time - probes map[string]bool - logins map[string]*loginSession + mu sync.RWMutex + editMu sync.Mutex + host HostCall + cfg Config + creds map[string]Credential + files map[string]string + revoked map[string]bool + authDir string + loaded, stopped, samplerStarted bool + stopCh chan struct{} + active sync.WaitGroup + streams map[string]bool + logs []LogEntry + statistics map[string]Counters + statisticsEpoch uint64 + storageError string + persistMu sync.Mutex + persistRunning, persistWriting bool + persistDirty runtimeFiles + persistSince, lastPersistAt time.Time + checkpointAt map[string]time.Time + persistErrors map[string]bool + persistWrites map[string]uint64 + storageWarnings []runtimeRecovery + nextCompaction time.Time + persistStop, persistDone chan struct{} + usage map[string]*usageCache + accounts map[string]string + cooldown map[string]time.Time + probes map[string]bool + logins map[string]*loginSession + expectedRegistration map[string]time.Time } func NewService() *Service { @@ -107,9 +116,11 @@ func (s *Service) configure(raw json.RawMessage) error { _ = yaml.Unmarshal(r.ConfigYAML, &cpampPaths) } if b, e := os.ReadFile(filepath.Join(c.DataDir, "settings.json")); e == nil { - if json.Unmarshal(b, &c) != nil { + if bytes.Equal(bytes.TrimSpace(b), []byte("null")) || json.Unmarshal(b, &c) != nil { return fail(500, "stored settings are invalid") } + } else if !os.IsNotExist(e) { + return fail(500, "stored settings cannot be read") } // Explicit nonempty host configuration paths remain authoritative even // when the console has already persisted model/request settings. @@ -147,38 +158,21 @@ func (s *Service) configure(raw json.RawMessage) error { } s.cfg = c if !s.loaded { - if b, e := os.ReadFile(filepath.Join(c.DataDir, "requests.json")); e == nil { - if json.Unmarshal(b, &s.logs) != nil { - return fail(500, "stored request logs are invalid") - } - } - if b, e := os.ReadFile(filepath.Join(c.DataDir, "statistics.json")); e == nil { - if json.Unmarshal(b, &s.statistics) != nil { - return fail(500, "stored statistics are invalid") - } - } - if b, e := os.ReadFile(filepath.Join(c.DataDir, "usage.json")); e == nil { - var saved map[string]persistedUsage - if json.Unmarshal(b, &saved) != nil { - return fail(500, "stored quota observations are invalid") - } - for cid, item := range saved { - s.usage[cid] = &usageCache{fingerprint: item.Fingerprint, value: item.Value} - if item.Account != "" { - s.accounts[cid] = item.Account - } - } + if err := s.loadRuntimeLocked(); err != nil { + return err } s.loaded = true } if len(s.logs) > c.LogRetention { s.logs = s.logs[len(s.logs)-c.LogRetention:] } + s.compactStatisticsLocked(time.Now().UTC()) s.startPersistenceLocked() return nil } func registration() any { fields := []map[string]string{ + {"Name": "statistics_retention_days", "Type": "int", "Description": "Historical statistics expiry in days; 0 keeps daily totals indefinitely (0-3650)"}, {"Name": "data_dir", "Type": "string", "Description": "Persistent plugin data directory"}, {"Name": "public_base_url", "Type": "string", "Description": "Public CPA/CPAMP URL including any reverse proxy prefix; optional for same-origin panels"}, {"Name": "cpamp_install_dir", "Type": "string", "Description": "CPAMP native install directory; empty detects the running instance or ~/cpa-manager-plus"}, @@ -334,7 +328,7 @@ func (s *Service) parseAuth(raw json.RawMessage) (any, error) { if cached := s.usage[c.ID]; cached != nil && cached.fingerprint != shaKey(c.APIKey+"|"+c.ProxyURL+"|"+s.cfg.BaseURL) { delete(s.usage, c.ID) delete(s.accounts, c.ID) - s.persistDirty = true + s.markDirtyLocked(dirtyUsage) } s.creds[c.ID] = c s.files[c.ID] = filepath.Base(r.FileName) @@ -417,12 +411,14 @@ func (s *Service) saveConfig(c Config) error { } s.mu.Lock() s.cfg = c + s.nextCompaction = time.Time{} + s.compactStatisticsLocked(time.Now().UTC()) if c.BaseURL != old.BaseURL { s.usage = map[string]*usageCache{} s.accounts = map[string]string{} s.cooldown = map[string]time.Time{} s.probes = map[string]bool{} - s.persistDirty = true + s.markDirtyLocked(dirtyUsage) } creds := []Credential{} for _, v := range s.creds { diff --git a/internal/bridge/statistics_retention.go b/internal/bridge/statistics_retention.go new file mode 100644 index 0000000..7571029 --- /dev/null +++ b/internal/bridge/statistics_retention.go @@ -0,0 +1,71 @@ +package bridge + +import ( + "sort" + "time" +) + +// Seven complete UTC days keep minute resolution. Older data is combined by +// UTC day without losing totals. Expiry is opt-in (zero means keep all days). +func (s *Service) compactStatisticsLocked(now time.Time) { + if now.Before(s.nextCompaction) { + return + } + s.nextCompaction = now.Add(time.Hour) + day := now.Truncate(24 * time.Hour) + cutoff := day.Add(-7 * 24 * time.Hour) + retention := day.Add(-time.Duration(s.cfg.StatisticsRetentionDays) * 24 * time.Hour) + next := make(map[string]Counters) + changed := false + for _, counter := range s.statistics { + counter.Time = counter.Time.UTC() + seconds := counter.BucketSeconds + if seconds == 0 { + seconds = 60 + } + if s.cfg.StatisticsRetentionDays > 0 && !counter.Time.Add(time.Duration(seconds)*time.Second).After(retention) { + changed = true + continue + } + if counter.Time.Before(cutoff) { + if seconds != 86400 { + changed = true + } + counter.Time = counter.Time.Truncate(24 * time.Hour) + counter.BucketSeconds = 86400 + } + key := counter.Time.Format(time.RFC3339) + "|" + counter.Model + if existing, ok := next[key]; ok { + existing.add(counter) + next[key] = existing + changed = true + } else { + next[key] = counter + } + } + if changed { + s.statistics = next + s.markDirtyLocked(dirtyStatistics) + } +} + +func (s *Service) storageStatusLocked() any { + files := []string{} + for name, flag := range map[string]runtimeFiles{"requests.json": dirtyLogs, "statistics.json": dirtyStatistics, "usage.json": dirtyUsage} { + if s.persistDirty&flag != 0 { + files = append(files, name) + } + } + sort.Strings(files) + writes := map[string]uint64{} + for name, count := range s.persistWrites { + writes[name] = count + } + return map[string]any{"pending_files": files, "pending_since": optionalTime(s.persistSince), "last_success_at": optionalTime(s.lastPersistAt), "writing": s.persistWriting, "recovery_warnings": append([]runtimeRecovery{}, s.storageWarnings...), "statistics_buckets": len(s.statistics), "writes": writes, "statistics_retention_days": s.cfg.StatisticsRetentionDays, "precision": "最近七个完整 UTC 日保留分钟统计,更早按 UTC 日汇总;保留天数 0 表示不淘汰"} +} +func optionalTime(value time.Time) *time.Time { + if value.IsZero() { + return nil + } + return &value +} diff --git a/internal/bridge/types.go b/internal/bridge/types.go index fec57b8..f0f9363 100644 --- a/internal/bridge/types.go +++ b/internal/bridge/types.go @@ -12,7 +12,7 @@ import ( "time" ) -const Version = "0.2.9" +const Version = "0.2.10" const PluginID = "commandcodebridge" const Provider = "commandcode" @@ -37,6 +37,7 @@ func fail(status int, message string) error { type HostCall func(string, any, any) error type ExecutorRequest struct { + pluginTest bool AuthID, AuthProvider, Model, Format, SourceFormat, Alt string Stream bool Headers http.Header @@ -93,18 +94,19 @@ type Model struct { Reasoning ReasoningMapping `json:"reasoning_mapping" yaml:"reasoning_mapping"` } type Config struct { - DataDir string `json:"data_dir" yaml:"data_dir"` - BaseURL string `json:"base_url" yaml:"base_url"` - PublicBaseURL string `json:"public_base_url,omitempty" yaml:"public_base_url"` - CPAMPInstallDir string `json:"cpamp_install_dir" yaml:"cpamp_install_dir"` - CPAMPConfigPath string `json:"cpamp_config_path" yaml:"cpamp_config_path"` - CPAMPPanelPath string `json:"cpamp_panel_path" yaml:"cpamp_panel_path"` - Models []Model `json:"models" yaml:"models"` - TimeoutSeconds int `json:"timeout_seconds" yaml:"timeout_seconds"` - LogRetention int `json:"log_retention" yaml:"log_retention"` - MaxResponseBytes int `json:"max_response_bytes" yaml:"max_response_bytes"` - UsageRefreshSeconds int `json:"usage_refresh_seconds" yaml:"usage_refresh_seconds"` - ZDR bool `json:"zdr" yaml:"zdr"` + DataDir string `json:"data_dir" yaml:"data_dir"` + BaseURL string `json:"base_url" yaml:"base_url"` + PublicBaseURL string `json:"public_base_url,omitempty" yaml:"public_base_url"` + CPAMPInstallDir string `json:"cpamp_install_dir" yaml:"cpamp_install_dir"` + CPAMPConfigPath string `json:"cpamp_config_path" yaml:"cpamp_config_path"` + CPAMPPanelPath string `json:"cpamp_panel_path" yaml:"cpamp_panel_path"` + Models []Model `json:"models" yaml:"models"` + TimeoutSeconds int `json:"timeout_seconds" yaml:"timeout_seconds"` + LogRetention int `json:"log_retention" yaml:"log_retention"` + MaxResponseBytes int `json:"max_response_bytes" yaml:"max_response_bytes"` + UsageRefreshSeconds int `json:"usage_refresh_seconds" yaml:"usage_refresh_seconds"` + StatisticsRetentionDays int `json:"statistics_retention_days" yaml:"statistics_retention_days"` + ZDR bool `json:"zdr" yaml:"zdr"` } func defaultConfig() Config { @@ -114,6 +116,9 @@ func defaultConfig() Config { var efforts = map[string]bool{"unset": true, "none": true, "minimal": true, "low": true, "medium": true, "high": true, "xhigh": true, "max": true, "ultra": true} func (c *Config) validate() error { + if c.StatisticsRetentionDays < 0 || c.StatisticsRetentionDays > 3650 { + return fail(400, "statistics_retention_days must be 0 to 3650") + } for _, path := range []string{c.CPAMPInstallDir, c.CPAMPConfigPath, c.CPAMPPanelPath} { if strings.ContainsAny(path, "\x00\r\n") || len(path) > 4096 { return fail(400, "invalid CPAMP path") diff --git a/internal/bridge/ui/console.css b/internal/bridge/ui/console.css index 6a6af6e..58ee631 100644 --- a/internal/bridge/ui/console.css +++ b/internal/bridge/ui/console.css @@ -21,3 +21,11 @@ /* Keep secondary data readable without restoring explanatory copy. */ .summary small,.health-legend,.health-row .small,.health-meta,.account-foot,.quota-note,.log-main .small,.detail-grid dt{font-size:11px} .health-name{font-size:13px}.log-main{font-size:12px}.badge{font-size:11px} +.diagnostic-row{padding:14px 0;border-bottom:1px solid var(--line);overflow-wrap:anywhere}.diagnostic-row:last-child{border-bottom:0}.diagnostic-row p{margin:6px 0}.diagnostic-row .badge{display:inline-block;margin:4px 0}.diagnostic-head{flex-wrap:wrap;gap:12px} + +#storageStatus{white-space:pre-line;overflow-wrap:anywhere} +#modelRows td .small{max-width:32em;overflow-wrap:anywhere} + +#modelRows{overflow-x:auto}#modelRows table{min-width:900px;table-layout:auto}#modelRows th:first-child,#modelRows td:first-child{min-width:170px}#modelRows th:nth-child(4),#modelRows td:nth-child(4){min-width:270px} + +.model-scroll-hint{display:none}@media(max-width:767px){.model-scroll-hint{display:block}} diff --git a/internal/bridge/ui/console.js b/internal/bridge/ui/console.js index 18ec92f..a173e48 100644 --- a/internal/bridge/ui/console.js +++ b/internal/bridge/ui/console.js @@ -10,15 +10,38 @@ function globalError(e){$('globalError').textContent=e.message||String(e);$('glo function dialogError(id,e){$(id).querySelector('.form-error').textContent=e.message||String(e)} function openDialog(id){$(id).querySelectorAll('.form-error').forEach(x=>x.textContent='');if(!$(id).open)$(id).showModal()} function apiURL(path){return new URL(API_BASE+path,location.origin).href} -async function api(path,options={}){if(state.blocked&&!options.verify)throw new Error('管理访问已暂停,请重新验证登录');const headers={...(window.CommandCodeBridgeAuthHeaders?.()||{}),...options.headers};if(state.key){delete headers.Authorization;delete headers['X-Management-Key'];headers[state.authType==='x-management-key'?'X-Management-Key':'Authorization']=state.authType==='x-management-key'?state.key:'Bearer '+state.key}if(options.body!==undefined)headers['Content-Type']='application/json';state.busy++;$('busy').textContent='正在更新';try{const response=await fetch(apiURL(path),{method:options.method||'GET',headers,body:options.body===undefined?undefined:JSON.stringify(options.body),signal:AbortSignal.timeout(options.timeout||650000)});const text=await response.text();let data;try{data=JSON.parse(text)}catch{data={error:text.slice(0,200)}}if(!response.ok){if(response.status===401||response.status===403){state.authenticated=false;state.blocked=true;if(response.status===401){window.CommandCodeBridgeClearAuth?.(headers);state.key=''}openDialog('authDialog')}throw new Error(data.error||`HTTP ${response.status}`)}return data}finally{state.busy--;$('busy').textContent=state.busy?'正在更新':''}} +async function api(path,options={}){if(state.blocked&&!options.verify)throw new Error('管理访问已暂停,请重新验证登录');const headers={...(window.CommandCodeBridgeAuthHeaders?.()||{}),...options.headers};if(state.key){delete headers.Authorization;delete headers['X-Management-Key'];headers[state.authType==='x-management-key'?'X-Management-Key':'Authorization']=state.authType==='x-management-key'?state.key:'Bearer '+state.key}if(options.body!==undefined)headers['Content-Type']='application/json';state.busy++;$('busy').textContent='正在更新';try{const response=await fetch(apiURL(path),{method:options.method||'GET',headers,body:options.body===undefined?undefined:JSON.stringify(options.body),signal:AbortSignal.timeout(options.timeout||650000)});const text=await response.text();let data;try{data=JSON.parse(text)}catch{data={error:text.slice(0,200)}}if(!response.ok){if((response.status===401||response.status===403)&&path!=='/models/test'){state.authenticated=false;state.blocked=true;resetDiagnosticViews();if(response.status===401){window.CommandCodeBridgeClearAuth?.(headers);state.key=''}openDialog('authDialog')}throw new Error(data.error||`HTTP ${response.status}`)}return data}finally{state.busy--;$('busy').textContent=state.busy?'正在更新':''}} async function confirmed(title,text){$('confirmTitle').textContent=title;$('confirmText').textContent=text;openDialog('confirmDialog');return new Promise(resolve=>{let settled=false;const end=value=>{if(settled)return;settled=true;$('confirmDialog').close();resolve(value)};$('confirmCancel').onclick=()=>end(false);$('confirmYes').onclick=()=>end(true);$('confirmDialog').oncancel=()=>end(false)})} function period(){const range=$('statsRange').value;let from='',to='';if(range==='today'){const date=new Date();date.setHours(0,0,0,0);from=date.toISOString()}else if(range==='24h')from=new Date(Date.now()-86400000).toISOString();else if(range==='custom'){if($('statsFrom').value)from=new Date($('statsFrom').value).toISOString();if($('statsTo').value)to=new Date($('statsTo').value).toISOString()}const q=new URLSearchParams();if(from)q.set('from',from);if(to)q.set('to',to);return q.size?'?'+q.toString():''} -async function loadConfig(){state.config=await api('/config');renderModels();const f=$('settingsForm');for(const k of ['timeout_seconds','log_retention','usage_refresh_seconds'])f.elements[k].value=state.config[k];for(const k of ['cpamp_install_dir','cpamp_config_path','cpamp_panel_path'])f.elements[k].value=state.config[k]||'';f.elements.max_response_mb.value=state.config.max_response_bytes/1048576;f.elements.zdr.checked=state.config.zdr;$('dataDir').textContent=state.config.data_dir;const model=state.config.models[0]?.id||'你的模型名称';$('apiExample').textContent=JSON.stringify({model,messages:[{role:'user',content:'你好'}],stream:true},null,2);if(state.view==='settings')await loadCPAMPPanel()} -function showCPAMPPanel(result){const lines=[result.message];state.cpampPanel=result;$('installCPAMPPanel').textContent=result.hot_update_ready?'更新原生面板':'安装原生面板';if(result.pid)lines.push('运行实例:PID '+result.pid+' · '+result.install_dir);else if(result.default_install_dir)lines.push('默认目录:'+result.default_install_dir);if(result.config_path)lines.push('配置:'+result.config_path+(result.configuration_mode==='environment'?'(环境变量模式,尚无配置文件)':''));if(result.panel_path)lines.push('面板:'+result.panel_path);if(result.served_page?.checked)lines.push('当前服务页面:'+(result.served_page.native_quota?'含 CommandCode 原生额度组件':'缺少 CommandCode 原生额度组件')+(result.served_page.matches?' · 与内置版本一致':''));else if(result.config_path)lines.push('当前服务页面:无法完成本机 HTTP 核验');if(result.candidates?.length)lines.push('可选配置:'+result.candidates.join(','));if(result.backups?.length)lines.push('备份:'+result.backups.join(','));if(!result.available)lines.push('当前构建未包含面板,请升级官方发布包');$('cpampPanelStatus').textContent=lines.join('\n');$('cpampPanelStatus').style.whiteSpace='pre-wrap';$('installCPAMPPanel').disabled=!result.available||result.installable===false||result.active} +async function loadConfig(){const identity=diagnosticIdentity(),config=await api('/config');if(!state.authenticated||identity!==diagnosticIdentity())return;state.config=config;renderModels();const f=$('settingsForm');for(const k of ['timeout_seconds','log_retention','usage_refresh_seconds','statistics_retention_days'])f.elements[k].value=state.config[k];for(const k of ['cpamp_install_dir','cpamp_config_path','cpamp_panel_path'])f.elements[k].value=state.config[k]||'';f.elements.max_response_mb.value=state.config.max_response_bytes/1048576;f.elements.zdr.checked=state.config.zdr;$('dataDir').textContent=state.config.data_dir;const model=state.config.models[0]?.id||'你的模型名称';$('apiExample').textContent=JSON.stringify({model,messages:[{role:'user',content:'你好'}],stream:true},null,2);if(state.view==='settings')await Promise.all([loadCPAMPPanel(),loadCompatibility(),loadStorage()])} +function showCPAMPPanel(result){const lines=[result.message,...(result.planned_changes||[])];state.cpampPanel=result;$('installCPAMPPanel').textContent=result.hot_update_ready?'更新原生面板':'安装原生面板';if(result.pid)lines.push('运行实例:PID '+result.pid+' · '+result.install_dir);else if(result.default_install_dir)lines.push('默认目录:'+result.default_install_dir);if(result.config_path)lines.push('配置:'+result.config_path+(result.configuration_mode==='environment'?'(环境变量模式,尚无配置文件)':''));if(result.panel_path)lines.push('面板:'+result.panel_path);if(result.served_page?.checked)lines.push('当前服务页面:'+(result.served_page.native_quota?'含 CommandCode 原生额度组件':'缺少 CommandCode 原生额度组件')+(result.served_page.matches?' · 与内置版本一致':''));else if(result.config_path)lines.push('当前服务页面:无法完成本机 HTTP 核验');if(result.candidates?.length)lines.push('可选配置:'+result.candidates.join(','));if(result.backups?.length)lines.push('备份:'+result.backups.join(','));if(!result.available)lines.push('当前构建未包含面板,请升级官方发布包');$('cpampPanelStatus').textContent=lines.join('\n');$('cpampPanelStatus').style.whiteSpace='pre-wrap';$('installCPAMPPanel').disabled=!result.available||result.installable===false||result.active} async function loadCPAMPPanel(){showCPAMPPanel(await api('/cpamp/panel'))} async function saveCPAMPPaths(){const f=$('settingsForm'),paths={};for(const name of ['cpamp_install_dir','cpamp_config_path','cpamp_panel_path'])paths[name]=f.elements[name].value.trim();if(Object.entries(paths).some(([name,value])=>value!==(state.config?.[name]||'')))state.config=await api('/config',{method:'PUT',body:paths})} -async function loadCredentials(){state.credentials=(await api('/credentials')).credentials;renderCredentials();renderHealth()} -async function loadStats(){const d=await api('/statistics'+period()),t=d.totals;const metrics=[['请求数',fmt(t.requests),`${fmt(t.success)} 成功 · ${fmt(t.failed)} 失败`],['输入 / 输出 tokens',compactNumber(t.input_tokens)+' / '+compactNumber(t.output_tokens),`${fmt(t.with_usage)} 次有用量记录`],['缓存命中',d.cache_hit_percent==null?'—':fmt(d.cache_hit_percent,1)+'%',`${fmt(t.cached_tokens)} tokens 读取`],['输出速率',d.output_tokens_per_second==null?'—':fmt(d.output_tokens_per_second,1)+' tok/s',d.average_ttft_ms==null?'首字时间未知':'首字 '+fmt(d.average_ttft_ms/1000,2)+'s']];$('summary').innerHTML=metrics.map(([name,value,hint],i)=>`
| 模型 | 请求 | 成功 | 输入 tokens | 输出 tokens | 缓存 tokens |
|---|---|---|---|---|---|
| ${esc(x.model)} | ${fmt(x.requests)} | ${fmt(x.success)} | ${fmt(x.input_tokens)} | ${fmt(x.output_tokens)} | ${fmt(x.cached_tokens)} |
${esc(row.message)}
${esc(row.action)}
检查时间:${esc(when(report.checked_at))} · 映射模型 ${esc(report.models)} 个
${esc(report.host_message)}
${report.models===0?'尚未配置模型映射,请在模型映射页导入。
':''}${report.unmatched_registrations?`另有 ${esc(report.unmatched_registrations)} 个宿主登记无法匹配当前凭证,请检查 CPA 加载日志。
`:''}${rows||'暂无凭证,请先添加凭证。
'}`; +} +function renderCompatibility(report){return `检查时间:${esc(when(report.checked_at))} · 插件 ${esc(report.version)}
${report.checks.map(check=>`${esc(check.message)}
${check.action?`${esc(check.action)}
`:''}| 模型 | 请求 | 成功 | 输入 tokens | 输出 tokens | 缓存 tokens |
|---|---|---|---|---|---|
| ${esc(x.model)} | ${fmt(x.requests)} | ${fmt(x.success)} | ${fmt(x.input_tokens)} | ${fmt(x.output_tokens)} | ${fmt(x.cached_tokens)} |
| 客户端名称 / 上游模型 | 协议 | 思考映射 | 操作 |
|---|---|---|---|
${esc(m.id)} ${esc(m.upstream_id)} | ${m.supported_endpoints.includes('/chat/completions')?'OpenAI':'Anthropic'} ${m.context_length?fmt(m.context_length)+' 上下文':''} | ${m.reasoning_mapping.enabled?`已启用 ${esc(Object.entries(m.reasoning_mapping.rules||{}).map(([a,b])=>a+' → '+b).join(',')||'全部透传')} `:'透传'} |
| 客户端名称 / 上游模型 | 协议 | 思考映射 | 当前凭据证据 | 操作 |
|---|---|---|---|---|
${esc(m.id)} ${esc(m.upstream_id)} | ${m.supported_endpoints.includes('/chat/completions')?'OpenAI':'Anthropic'} ${m.context_length?fmt(m.context_length)+' 上下文':''} | ${m.reasoning_mapping.enabled?`已启用 ${esc(Object.entries(m.reasoning_mapping.rules||{}).map(([a,b])=>a+' → '+b).join(',')||'全部透传')} `:'透传'} | ${modelEvidenceHTML(m.id)} |
${esc(x.error)}本地冷却,未调用上游。
':''}目录可见不代表套餐有权限。证据按凭证版本、账户和映射隔离,24 小时后过期;读取状态不会发起生成。
窄屏可左右滑动模型表格查看证据与操作。
请求表现与凭据状态,一处查看。
目录可见不代表套餐有权限。证据按凭证版本、账户和映射隔离,24 小时后过期;读取状态不会发起生成。
窄屏可左右滑动模型表格查看证据与操作。
管理账号,查看最近一次观察到的额度。
选择凭据,按已有证据查找模型。
目录可见不代表套餐有权限。证据隔离到当前凭据与映射,24 小时后过期;读取与筛选不发起生成。
+查看路由、时延和错误,定位单次请求。
请求策略、数据保留与运行环境。
默认探测同机运行实例和 ~/cpa-manager-plus。首次启用需重启一次 Manager Server,后续原路径更新只需刷新浏览器。
检查和安装将先保存这些路径。