From 870a2a1f08d1fc2045b429f268d9873c29a9b42b Mon Sep 17 00:00:00 2001 From: Mag1cFall Date: Wed, 25 Nov 2026 12:22:28 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20Interactions=20?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E8=B7=AF=E7=94=B1=E4=B8=8E=E5=9B=9E=E5=A4=8D?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E8=B6=85=E6=97=B6=EF=BC=8C=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=8D=A2=E5=8F=B7=E4=B8=8E=E7=83=AD=E5=8A=A0=E8=BD=BD=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 按官网把被迁移账户的 gemini-4 全系经 CreateInteraction 以模型目标发送,补齐函数调用签名与流式解码 - 回复工具按自然段分多次 final 交付并在模型声明未写完时自动续接,续接失败以写明原因的错误结束 - 改 round-robin 为最久未用账户优先,启动时从请求记录读回用量,预热按权益层均衡 - 新增换号最短间隔与额度失败换号上限,17 项设置保存后下一次请求生效,运行中改后端时提供重启生成服务 - 改版本检查与在线更新走 Release 页面、releases.atom 与 SHA256SUMS,限流时写明恢复时间 - 指定账户缺少模型权益时返回写明所需权益与账户的错误 - 设置页增加模型可用账户与限高列表,账户页出口 IP 收为一行、成功任务自动关闭 - 撤销删除提示增加关闭按钮,关闭即提交删除 - 修复改代理时探测越界崩溃、管理登录开关与改密后的会话处理、无 ID 函数调用配对与搜索结果密钥 - 修复 Decisions 自定义文件名、Live 免责声明换号、出口地区不支持时反复重载与 Camoufox 重载遗留页面 - 修复试用页思考标题截断、获取代码弹窗崩溃、切换对话竞态与退出登录后的状态轮询 - 撤回 v0.3.14 中针对真实使用不会出现的输入所加的处理,按保护行为筛选正式仓库测试 --- .env.example | 10 +- .github/workflows/build.yml | 2 + README.md | 18 +- README_en.md | 18 +- docs/development.md | 18 +- docs/protocol.md | 79 +- internal/aistudio/accounts.go | 316 +++- internal/aistudio/benefit.go | 9 + internal/aistudio/channel.go | 40 +- internal/aistudio/channel_test.go | 74 - internal/aistudio/compatibility_test.go | 222 +-- internal/aistudio/generate.go | 150 +- internal/aistudio/hidden_models.go | 57 + internal/aistudio/interaction.go | 1487 ++++++++++++++--- internal/aistudio/interaction_media_test.go | 53 - internal/aistudio/interaction_routing_test.go | 339 ++++ internal/aistudio/models.go | 205 ++- .../aistudio/page_logging_context_test.go | 35 - internal/aistudio/proxy_pool.go | 92 +- internal/aistudio/quota.go | 33 +- internal/aistudio/reply_tool.go | 143 +- internal/aistudio/runtime_go.go | 55 +- internal/aistudio/runtime_lease_test.go | 30 - internal/aistudio/runtime_native.go | 2 +- internal/aistudio/schema_test.go | 116 -- internal/aistudio/service.go | 133 +- internal/aistudio/tool_contract.go | 26 +- internal/aistudio/tool_schema_test.go | 173 -- internal/aistudio/tool_validation.go | 6 +- internal/aistudio/transport_browser.go | 117 +- internal/aistudio/transport_browser_test.go | 46 - internal/aistudio/transport_http.go | 28 +- internal/aistudio/turns.go | 6 +- internal/aistudio/webchannel.go | 47 +- internal/api/account_tasks_browser_test.go | 85 - internal/api/admin.go | 136 +- internal/api/admin_auth.go | 124 +- internal/api/admin_auth_test.go | 120 ++ internal/api/anthropic.go | 8 +- internal/api/anthropic_search.go | 2 +- internal/api/decisions.go | 13 +- internal/api/empty_content_test.go | 49 - internal/api/gemini_output_test.go | 78 - internal/api/image_encoding_test.go | 36 - internal/api/interaction_input.go | 4 +- internal/api/interaction_resources.go | 4 - internal/api/ledger.go | 49 +- internal/api/mcp_tools.go | 2 +- internal/api/media.go | 11 +- internal/api/media_store_test.go | 76 - internal/api/middleware.go | 141 +- internal/api/middleware_test.go | 66 +- internal/api/responses_retrieval.go | 16 +- internal/api/router.go | 18 +- internal/api/thoughtsig_test.go | 11 - internal/api/update.go | 2 + internal/app/account_usage_seed.go | 47 + internal/app/admin.go | 112 +- internal/app/admin_config_test.go | 86 +- internal/app/api_key_accounts_test.go | 13 +- internal/app/app.go | 3 +- internal/app/auth_retry.go | 42 +- internal/app/auth_retry_test.go | 81 - internal/app/channels.go | 11 +- internal/app/hedge.go | 25 +- internal/app/lifecycle.go | 231 ++- internal/app/logfile.go | 13 +- internal/app/proxy_pool.go | 55 +- internal/app/request_logging.go | 12 +- internal/app/runtime.go | 533 +++++- internal/app/update.go | 384 ++++- internal/app/waa_backend.go | 18 +- internal/app/worker_manager.go | 53 +- internal/camoufoxnative/chat_turns_test.go | 71 - internal/camoufoxnative/generate.go | 5 + internal/camoufoxnative/generate_test.go | 34 - internal/camoufoxnative/page_test.go | 38 - internal/camoufoxnative/profile_test.go | 76 - internal/camoufoxnative/worker.go | 54 +- internal/chromeauth/bidi_test.go | 462 +---- internal/chromeauth/bound_test.go | 118 -- internal/chromeauth/platform_windows_test.go | 60 - internal/config/config.go | 66 +- internal/i18n/messages/de.json | 14 +- internal/i18n/messages/en.json | 14 +- internal/i18n/messages/fr.json | 14 +- internal/i18n/messages/ja.json | 14 +- internal/i18n/messages/ko.json | 14 +- internal/i18n/messages/zh-TW.json | 14 +- internal/pricing/pricing_test.go | 54 - internal/requestdb/records.go | 11 +- internal/requestdb/requestdb.go | 56 +- internal/requestdb/usage_seed.go | 71 + internal/setup/remote_test.go | 36 - internal/waa/clock_test.go | 77 - internal/waa/rhythm/rhythm_test.go | 64 - web/src/App.vue | 12 +- web/src/ConsoleRoot.vue | 1 + web/src/api.ts | 1 + web/src/components/AccessPanel.vue | 2 +- web/src/components/AccountExits.vue | 134 +- web/src/components/AccountFilterMenu.vue | 92 + web/src/components/AccountsPanel.vue | 37 +- web/src/components/AutoDismissRow.vue | 75 + web/src/components/FilterMenu.vue | 17 +- web/src/components/ImportFilterBar.vue | 5 +- web/src/components/ModelAccountRows.vue | 130 ++ web/src/components/ModelsTable.vue | 23 +- web/src/components/SettingRow.vue | 3 +- web/src/components/SettingsPanel.vue | 349 +++- web/src/components/VersionPanel.vue | 88 +- web/src/console.ts | 5 +- web/src/locales/de.ts | 48 +- web/src/locales/en.ts | 49 +- web/src/locales/fr.ts | 49 +- web/src/locales/ja.ts | 50 +- web/src/locales/ko.ts | 48 +- web/src/locales/zh-CN.ts | 43 +- web/src/locales/zh-TW.ts | 44 +- web/src/markdown.ts | 11 +- web/src/playground/CodeDialog.vue | 12 +- web/src/playground/ToolStepRow.vue | 4 +- web/src/playground/session.ts | 34 +- web/src/types.ts | 11 +- 124 files changed, 6142 insertions(+), 3627 deletions(-) delete mode 100644 internal/aistudio/channel_test.go delete mode 100644 internal/aistudio/interaction_media_test.go create mode 100644 internal/aistudio/interaction_routing_test.go delete mode 100644 internal/aistudio/page_logging_context_test.go delete mode 100644 internal/aistudio/runtime_lease_test.go delete mode 100644 internal/aistudio/schema_test.go delete mode 100644 internal/aistudio/tool_schema_test.go delete mode 100644 internal/aistudio/transport_browser_test.go delete mode 100644 internal/api/account_tasks_browser_test.go delete mode 100644 internal/api/media_store_test.go create mode 100644 internal/app/account_usage_seed.go delete mode 100644 internal/app/auth_retry_test.go delete mode 100644 internal/camoufoxnative/chat_turns_test.go delete mode 100644 internal/camoufoxnative/generate_test.go delete mode 100644 internal/camoufoxnative/page_test.go delete mode 100644 internal/camoufoxnative/profile_test.go delete mode 100644 internal/chromeauth/bound_test.go delete mode 100644 internal/chromeauth/platform_windows_test.go delete mode 100644 internal/pricing/pricing_test.go create mode 100644 internal/requestdb/usage_seed.go delete mode 100644 internal/waa/clock_test.go delete mode 100644 internal/waa/rhythm/rhythm_test.go create mode 100644 web/src/components/AccountFilterMenu.vue create mode 100644 web/src/components/AutoDismissRow.vue create mode 100644 web/src/components/ModelAccountRows.vue diff --git a/.env.example b/.env.example index db1d8f5a..4c1a6fa5 100644 --- a/.env.example +++ b/.env.example @@ -13,7 +13,7 @@ PROXY_API_KEY= # 各 key 可用的账户,每项写成 key:账户|账户,逗号分隔多项;未列出的 key 可用全部账户 API_KEY_ACCOUNTS= -# 管理程序启动后自动启动生成服务,修改后重启程序生效 +# 管理程序启动后自动启动生成服务,下次启动程序时生效 AUTO_START=false # macOS 桌面版只在菜单栏显示图标、不显示 Dock 图标,在设置页修改立即生效 @@ -28,7 +28,7 @@ LOG_FILE=true # 日志目录总量上限(MB),超出时删除最旧的文件,不小于 20 LOG_MAX_TOTAL_MB=500 -# 管理控制台登录,修改后重启程序生效 +# 管理控制台登录,在设置页保存后立即生效(关闭登录仅限本机访问) ADMIN_AUTH_ENABLED=false ADMIN_USERNAME=admin ADMIN_PASSWORD= @@ -63,6 +63,12 @@ ACCOUNT_ORDER= # 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,0 为不换号;登录失效与额度用尽不计入 MAX_ACCOUNT_SWITCHES=3 +# 同一请求内账户失败后切往下一个账户(含冷备账户启动 Worker)前的最短等待秒数;off 为不等待,正整数为秒数 +ACCOUNT_SWITCH_INTERVAL=off + +# 同一请求内因额度用尽(429)切换账户的次数上限;off 为不限制,0 为不换号,正整数为最多换号次数 +MAX_QUOTA_SWITCHES=off + # 生成请求使用的上游通道:playground、build(旧通道,上游已停用其生成),逗号分隔 UPSTREAM_CHANNELS=playground diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fceb314e..91dba2a0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -328,6 +328,8 @@ jobs: run: | flags=() if [[ "$RELEASE_TAG" == *-* ]]; then flags+=(--prerelease); fi + rm -f dist/SHA256SUMS + (cd dist && sha256sum -- * > ../SHA256SUMS && mv ../SHA256SUMS SHA256SUMS) gh release create "$RELEASE_TAG" dist/* --verify-tag --generate-notes --title "$RELEASE_TAG" "${flags[@]}" docker: diff --git a/README.md b/README.md index 02ab9c8f..f2c4d8ef 100644 --- a/README.md +++ b/README.md @@ -282,9 +282,10 @@ docker compose up -d 设置的生效时机: -- 保存后立即生效:账户选择策略、Worker 容量、换号次数上限、模型映射、非流式保活、假流式、搜索型号、全模型搜索、回复工具防截断、简体转繁体改写与媒体输出;进行中的请求沿用开始时的设置 -- 停止再启动生成服务后生效:其余生成服务配置,启动时读取最新 `.env` -- 重启管理进程后生效:管理页面地址、预览地址和 `PROXY_API_KEY` +- 绝大多数设置保存后对下一次请求立即生效(包括本地 API 密钥、管理登录、默认代理与代理池、上游通道、隐藏模型探测、超时、首字对冲、换号策略、请求改写与日志设置);进行中的请求沿用开始时的设置,默认代理变更会在各账户在途请求结束后自动切换 Worker +- 重启生成服务后生效:`WAA_BACKEND` 与 `AISTUDIO_AUTH_STATES`(生成服务运行时可在设置页直接点击重启生成服务) +- 重启管理进程后生效:`LISTEN_ADDR` 与 `PREVIEW_LISTEN_ADDR` +- 下次启动程序时生效:`AUTO_START` 退出程序: @@ -681,6 +682,8 @@ cp .env.example .env | `ROUTING_STRATEGY` | `round-robin` | `round-robin` 轮询;`fill-first` 账号粘性优先 | | `ACCOUNT_ORDER` | 空 | `fill-first` 依次使用的账户,逗号分隔,未列出的账户排在后面并按 ID 排序;也可在设置页调整,保存后立即生效 | | `MAX_ACCOUNT_SWITCHES` | `3` | 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,`0` 为不换号 | +| `ACCOUNT_SWITCH_INTERVAL` | `off` | 同一请求内前一个账户失败后,下一个账户向 Google 发出请求(或启动冷备 Worker)前从上次失败起等待的最短秒数;`off` 为不等待,正整数为秒数 | +| `MAX_QUOTA_SWITCHES` | `off` | 同一请求内因额度用尽(429)切换账户的次数上限;`off` 为不限制,依次尝试全部账户,`0` 为不换号,正整数为最多换号次数,超出后返回最后一次 429 | | `UPSTREAM_CHANNELS` | `playground` | 生成请求使用的上游通道,`playground`、`build` 逗号分隔;`build` 为旧通道,上游已停用其生成 | | `MODEL_MAPPING` | 空 | 客户端模型名到目录模型的映射,每项写成 `别名:模型 ID`,逗号分隔多项 | | `MODEL_CHANNELS` | 空 | 限定模型只走一个通道,每项写成 `模型 ID:playground` 或 `模型 ID:build`;也可在“模型目录”的模型详情中选择,保存后立即生效 | @@ -709,13 +712,14 @@ cp .env.example .env - `PREVIEW_LISTEN_ADDR`:无法监听时改用同一主机上的空闲端口;页面以当前访问的主机名加实际端口打开预览 - `AUTO_START`:网络等原因启动失败时按 5 秒起、翻倍至 5 分钟的间隔重试,手动启动或停止后不再重试 -- `MAX_ACCOUNT_SWITCHES`:登录失效与额度用尽不计入,照常依次尝试其余账户 +- `MAX_ACCOUNT_SWITCHES`:登录失效与额度用尽不计入;额度用尽的换号次数由 `MAX_QUOTA_SWITCHES` 单独控制(默认不限) +- `ACCOUNT_SWITCH_INTERVAL`:切往冷备账户时先等满间隔再启动 Worker,就绪后直接发送,不重复等待;等待期间客户端断开即结束 - `NONSTREAM_KEEPALIVE`:返回 200 后每 10 秒写出一个换行直到写出 JSON 正文,经 Cloudflare 等反向代理时连接不会因长时间无数据断开;此后才出现的错误以协议错误正文返回 - `STRIP_THOUGHT_SIGNATURES`:函数调用带 `skip_thought_signature_validator`;之前各轮的思考内容不随签名发给模型,长对话的输入 token 较少 - `DISCOVER_HIDDEN_MODELS`: - 在同步账户模型目录时探测:启动、每 24 小时与账户页“刷新全部” - 确认账户能用的模型加入目录,可直接用于各协议请求并列在 `/v1/models` 中,“模型目录”页标为“官网隐藏” - - 官网公开后改用官网的模型信息;关闭后下一次启动生成服务时从目录中移除 + - 官网公开后改用官网的模型信息;关闭后立即从目录中移除,开启后在后台自动探测 - `FIRST_EVENT_HEDGE`: - 备用请求优先用其他账户,没有时用原账户的空闲槽位;先出首字的一方继续,另一方取消 - `auto` 按各模型与通道近 24 小时首字等待的 p95,请求少于 20 次的模型与通道不发起 @@ -741,13 +745,13 @@ cp .env.example .env 管理控制台默认通过本机回环地址免密访问。远程管理时: -- 设置 `ADMIN_AUTH_ENABLED=true`、管理员账号和密码,重启程序后通过独立 `/login` 页面登录 +- 设置 `ADMIN_AUTH_ENABLED=true`、管理员账号和密码后通过独立 `/login` 页面登录(在设置页保存后立即生效,并为当前浏览器自动保持登录) - 登录会话有效期为 12 小时;勾选“30 天内保持登录”时为 30 天,程序重启后仍有效 - 支持退出登录,管理员共享同一个账户池、配置与日志 公开 API 使用独立的 `PROXY_API_KEY`。 -反向代理使用 HTTPS,并保留原始 `Host`、设置 `X-Forwarded-Proto: https`。管理页“服务配置”可调整登录开关及凭据,保存后重启程序生效。 +反向代理使用 HTTPS,并保留原始 `Host`、设置 `X-Forwarded-Proto: https`。管理页“服务配置”可调整登录开关及凭据,保存后立即生效(关闭登录仅限本机访问操作)。 API 试用页的 HTML 预览运行在 `PREVIEW_LISTEN_ADDR` 提供的独立来源,页面以当前访问的主机名加该端口打开预览: diff --git a/README_en.md b/README_en.md index 24a60a45..902f21cd 100644 --- a/README_en.md +++ b/README_en.md @@ -282,9 +282,10 @@ Add more accounts on the same page; [Account Management](#account-management) co When settings take effect: -- As soon as they are saved: the account selection strategy, worker capacity, max account switches, model mapping, non-streaming keepalive, fake streaming, search model variants, Google Search for all models, reply tool anti-truncation, Simplified to Traditional Chinese rewrite, and media output; requests already in progress keep the settings they started with -- After stopping and starting the generation service: the other data-plane settings, read from the latest `.env` at start -- After restarting the management process: `LISTEN_ADDR`, `PREVIEW_LISTEN_ADDR`, and `PROXY_API_KEY` +- On the next request as soon as they are saved: almost all settings (including `PROXY_API_KEY`, console login, default proxy and proxy pool, upstream channels, hidden model discovery, timeouts, first-event hedge, account switching policy, request rewrites, and logging); requests already in progress keep the settings they started with, and proxy changes drain and rebind affected account workers once their in-flight requests finish +- After restarting the generation service: `WAA_BACKEND` and `AISTUDIO_AUTH_STATES` (when the generation service is running, Settings offers a button to restart it) +- After restarting the management process: `LISTEN_ADDR` and `PREVIEW_LISTEN_ADDR` +- On the next program start: `AUTO_START` Exiting: @@ -681,6 +682,8 @@ Process environment variables override the same keys in `.env`, and those settin | `ROUTING_STRATEGY` | `round-robin` | `round-robin` rotates accounts; `fill-first` reuses the first available account | | `ACCOUNT_ORDER` | empty | Accounts `fill-first` uses in order, comma-separated; unlisted accounts follow in ID order. Also adjustable on the Settings page, applied on save | | `MAX_ACCOUNT_SWITCHES` | `3` | How many times a request moves to another account after a non-quota upstream error such as 403 or 5xx; `0` disables switching | +| `ACCOUNT_SWITCH_INTERVAL` | `off` | Minimum wait in seconds from a failed account attempt before the next account sends any request to Google (or cold-starts a standby worker); `off` disables waiting | +| `MAX_QUOTA_SWITCHES` | `off` | Maximum account switches for quota exhaustion (429) within one request; `off` tries all remaining accounts, `0` disables quota switching, and a positive integer returns the last 429 once exceeded | | `UPSTREAM_CHANNELS` | `playground` | Upstream channels for generation requests, `playground` and `build` comma separated; `build` is the legacy channel whose generation upstream has disabled | | `MODEL_MAPPING` | empty | Client model names mapped to catalog models, each item `alias:model ID`, comma separated | | `MODEL_CHANNELS` | empty | Limit a model to one channel, each item `model ID:playground` or `model ID:build`; also selectable in model details on the Model catalog page, applied on save | @@ -709,13 +712,14 @@ Notes: - `PREVIEW_LISTEN_ADDR`: when it cannot be bound, a free port on the same host is used; the page opens previews at the current host name with the port in use - `AUTO_START`: if startup fails for reasons such as the network, it retries at intervals starting at 5 seconds and doubling up to 5 minutes, until the service is started or stopped manually -- `MAX_ACCOUNT_SWITCHES`: expired sessions and quota errors do not count, and the remaining accounts are still tried in turn +- `MAX_ACCOUNT_SWITCHES`: expired sessions and quota errors do not count; quota-exhaustion switches are controlled separately by `MAX_QUOTA_SWITCHES` (unlimited by default) +- `ACCOUNT_SWITCH_INTERVAL`: when moving to a standby account, waits for the interval before starting the worker and sends immediately once ready without waiting again; stops immediately if the client disconnects - `NONSTREAM_KEEPALIVE`: after returning 200, a newline is written every 10 seconds until the JSON body, so reverse proxies such as Cloudflare keep the connection open; errors after that point come back as the protocol error body - `STRIP_THOUGHT_SIGNATURES`: function calls are sent with `skip_thought_signature_validator`; earlier turns' thinking is not passed to the model with the signatures, so long conversations use fewer input tokens - `DISCOVER_HIDDEN_MODELS`: - Discovery runs when account model catalogs sync: at startup, every 24 hours, and on Refresh all in Accounts - Models the account is confirmed to be able to use are added to the catalog; they can be used through every protocol, appear in `/v1/models`, and are marked Hidden in AI Studio on the Model catalog page - - Once AI Studio lists a model, its official details are used; turning this off removes them the next time the generation service starts + - Once AI Studio lists a model, its official details are used; turning this off removes hidden models immediately, and turning it on discovers them in the background - `FIRST_EVENT_HEDGE`: - The backup request uses another account first, otherwise a free slot on the same account; the first to answer continues and the other is cancelled - `auto` waits for the p95 of each model and channel over the last 24 hours, and models with fewer than 20 requests are not hedged @@ -741,13 +745,13 @@ The service loads every account from `AISTUDIO_AUTH_STATES`. Four settings contr The console allows passwordless loopback access by default. For remote management: -- Set `ADMIN_AUTH_ENABLED=true`, configure the administrator username and password, restart the process, and sign in on the separate `/login` page +- Set `ADMIN_AUTH_ENABLED=true`, configure the administrator username and password, and sign in on the separate `/login` page (saving in Settings takes effect immediately and keeps the current browser signed in) - A session lasts 12 hours; with "Stay signed in for 30 days" checked it lasts 30 days and survives restarts - Sign-out is supported; administrators share the instance's account pool, configuration, and logs Public APIs use the separate `PROXY_API_KEY`. -Use an HTTPS reverse proxy that preserves `Host` and sets `X-Forwarded-Proto: https`. Console login settings can also be saved from the settings page and take effect after restarting the process. +Use an HTTPS reverse proxy that preserves `Host` and sets `X-Forwarded-Proto: https`. Console login settings saved from the Settings page take effect immediately (disabling login is only allowed from loopback). HTML previews in the API playground run on a separate origin served at `PREVIEW_LISTEN_ADDR`, and the page opens them at the current host name with that port: diff --git a/docs/development.md b/docs/development.md index b51af435..a7d617ef 100644 --- a/docs/development.md +++ b/docs/development.md @@ -448,7 +448,7 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等 | `first_event_hedge`、`first_event_hedge_models`、`first_event_timeout` | 下一次启动生成服务时使用的首字超时备用请求与单次首字超时设置 | | `strip_thought_signatures` | 下一次启动生成服务时使用的思考签名去除开关 | | `routing_strategy`、`account_order` | 保存后立即作用于账户选择的策略与 `fill-first` 顺序 | -| `max_account_switches` | 保存后立即作用于换号判断的次数上限 | +| `max_account_switches`、`account_switch_interval`、`max_quota_switches` | 保存后立即作用于换号次数上限、换号间隔与额度用尽换号上限 | | `api_key_accounts` | 保存后立即作用于新请求的 API key 账户绑定 | | `model_channels`、`model_accounts` | 保存后立即作用于新请求的按模型通道与账户限定 | | `media_output`、`media_base_url` | 保存后立即作用于新请求的媒体引用方式与媒体服务地址 | @@ -457,17 +457,19 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等 | `hide_dock_icon` | macOS 桌面版是否隐藏 Dock 图标,保存后立即生效 | | `request_body_log` | 保存后立即决定是否保存请求与响应正文 | | `log_file`、`log_max_total_mb` | 保存后立即开关日志文件并按新的总量上限轮转 | -| `admin_auth_enabled`、`admin_username`、`admin_password` | 保存的管理登录配置;省略密码保留现值,密码只接受写入 | +| `admin_auth_enabled`、`admin_username`、`admin_password` | 管理登录配置,保存后立即生效;省略密码保留现值,密码只接受写入;本机启用或改密时自动为当前请求签发新会话 Cookie 并撤销其余会话,非回环请求禁止关闭登录 | | `admin_password_set` | 是否已配置管理密码 | -| `listen_addr`、`proxy_api_key` | 保存的管理监听配置 | +| `listen_addr` | 保存的管理监听地址,管理进程重启后生效 | +| `proxy_api_key` | 本机 API key,保存后立即作用于新请求 | | `preview_listen_addr` | 保存的 API 试用页预览来源监听地址,管理进程重启后生效 | | `active_preview_listen_addr` | 当前管理进程实际使用的预览来源地址 | -| `active_listen_addr`、`active_proxy_api_key` | 当前管理进程固定使用的值 | +| `active_listen_addr` | 当前管理进程实际使用的监听地址 | | `reserved_listen_addr` | 被 Windows 保留而改用 `active_listen_addr` 的监听地址,没有改用时为空 | | `active_proxy` | 当前生成服务使用的出口,代理池为逗号分隔的全部代理,`proxy` 为空时为系统代理,没有系统代理时为空 | | `proxy_pool` | 当前生成服务的代理池:每个代理的地址、是否可用、绑定账户数、最近检测时间与最近错误 | -| `management_restart_required` | 保存的监听地址、API key 或管理登录配置与当前管理进程不同 | -| `service_restart_required` | 保存的生成服务配置与当前生成服务实例不同 | +| `active_requests` | 当前生成服务进行中的请求数 | +| `management_restart_required` | 保存的 `listen_addr` 或 `preview_listen_addr` 与当前管理进程不同 | +| `service_restart_required` | 生成服务运行中,且保存的 `waa_backend` 或 `auth_states` 与当前生成服务实例不同 | | `environment` | 取自进程环境变量、覆盖 `.env` 的配置键 | | `invalid` | 取值无效而按默认值运行的项,每项为 `key`、`value` 与 `reason` | @@ -639,7 +641,7 @@ Worker 容量由热池目标、活动上限和单账户并发共同约束。 - 先用 Worker 已就绪且没有活动请求的其他账户,没有时用原账户的其余并发槽位 - 引用已上传文件或指定账户的请求只用原账户的其余并发槽位 - 都没有时每秒复查;同时进行的备用请求最多 4 个 -- 后台 Responses 与 Interaction、Deep Research 与 Antigravity 等经后台任务生成的 agent(`interaction_task`)与 `-build` 写代码助手请求不发起备用请求 +- 后台 Responses 与 Interaction、Deep Research 与 Antigravity 等 agent(`interaction_agent`)与 `-build` 写代码助手请求不发起备用请求 结果: @@ -647,7 +649,7 @@ Worker 容量由热池目标、活动上限和单账户并发共同约束。 - 被取消的请求同样计入上游的每日与每分钟请求额度 - 账本的 `attempts` 以 `hedge` 标记备用请求,以 `superseded` 标记被取代的一方 -`FIRST_EVENT_TIMEOUT` 不为 `off` 时,除后台 Responses、后台 Interactions 与经后台任务生成的 agent(`interaction_task`)外,每次生成尝试(含 `-build` 写代码助手)从取得账户起等待首个语义事件达到阈值后,取消该尝试并换号: +`FIRST_EVENT_TIMEOUT` 不为 `off` 时,除后台 Responses、后台 Interactions 与 agent(`interaction_agent`)外,每次生成尝试(含 `-build` 写代码助手)从取得账户起等待首个语义事件达到阈值后,取消该尝试并换号: - 计入 `MAX_ACCOUNT_SWITCHES`,不冷却账户、不改账户状态、不重建 Worker;没有可换账户或换号用尽时返回 504 并写明 `FIRST_EVENT_TIMEOUT` - 与 `FIRST_EVENT_HEDGE` 同开时原请求与备用请求各自计时,一方到期取消不影响另一方继续等待;`REQUEST_TIMEOUT` 管整个请求,更早到期时直接结束请求不换号 diff --git a/docs/protocol.md b/docs/protocol.md index b3a09bfd..cdc23e07 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -478,7 +478,7 @@ field 1 是 `request_key`,field 2 是 `botguard_response`。正确 proof、损 | 84 | `transcription_smart` | 85 | `speech_metadata` | | 46 | `speech_translation` | 48 | `code_assistant` | -每个主能力码都保留为 `capability_code_`,同时为上表中的已知码增加语义键;次能力码保留为 `secondary_capability_code_`;field 82 中默认开启的码保留为 `default_capability_code_`;有 field 79 的模型带 `interactions_api`,其中经后台任务生成的模型另带 `interaction_task`。 +每个主能力码都保留为 `capability_code_`,同时为上表中的已知码增加语义键;次能力码保留为 `secondary_capability_code_`;field 82 中默认开启的码保留为 `default_capability_code_`;field 79 的 kind 为 `1`(agent)或 `2`(模型)时带 `interactions_api`,按官网 `_.Ol`、`_.Pl`、`Rl`、`_.Sl` 换算为 `interaction_agent` / `interaction_model` 与 `interaction_stream`(非后台) / `interaction_task`(后台),其余未知 kind 走 `GenerateContent`。 图片与视频选项使用枚举码: @@ -1421,46 +1421,54 @@ Interaction 请求的内容转换: ### 后台 Interaction 任务 -模型目录 field 79 为后台任务的模型(`deep-research-preview-04-2026`、`deep-research-max-preview-04-2026`、`antigravity-preview-09-2026`)经两个 RPC 生成:`CreateInteraction` 创建任务,`GetInteractionStream` 按 interaction ID 读取任务的增量与终态。 +模型目录 field 79 的 kind 为 `1`(agent,如 `deep-research-preview-04-2026`、`deep-research-max-preview-04-2026`、`antigravity-preview-09-2026`)或 `2`(模型,如被迁移账户的 `gemini-4-*`)且 background 为真时,经两个 RPC 生成:`CreateInteraction` 创建任务,`GetInteractionStream` 按 interaction ID 读取任务的增量与终态。 -两个 RPC 的 WAA proof 都位于 field 5,`CreateInteraction` 的 binding 为发送的全部文本以空格连接,`GetInteractionStream` 的 binding 为 interaction ID: +两个 RPC 的 WAA proof 都位于 field 5,`CreateInteraction` 的 binding 为发送的 user/model 文本与内联图片 Base64 按内容顺序以空格连接(工具步骤不参与 binding),`GetInteractionStream` 的 binding 为 interaction ID: ```json [null, 1, 1, , "", 1] -["", 1, null, null, "", 1, "models/"] +["", 1, null, null, "", 1, "models/"] ``` | interaction 索引 | 内容 | | ---: | --- | | 6 | system instruction | | 7 | 工具列表,见下文 | +| 13 | `responseModalities`(模型目标且请求设置时) | +| 15 | `responseMimeType`(模型目标且请求设置时) | | 16 | 续接的上一轮 interaction ID | -| 18 | agent 目标,见下文 | -| 22 | 远程环境:field 1 源 `[[<类型>,"<源>","<目标>","<内容>","<编码>"]...]`(类型 gcs `2`、inline `3`、repository `4`),field 2 出站白名单 `[[["<域名>",[["<头>","<值>"]...],"<凭据>"]...]]`(有凭据时只发凭据),field 3 禁止出站 `1`,field 4 要更新的已有环境 ID;Antigravity 未设置环境时为 `[null,null,1]` | -| 23 | 只引用已有环境、不带源与网络设置时的环境 ID | -| 26 | 与 Omni Interaction 相同的 step 列表,见下文 | +| 17 | 模型目标(kind `2`):`["models/", ]`,保留 `models/` 前缀;配置按模型能力码发送 temperature(idx 0,码 `62`)、topP(idx 1,码 `23`)、seed(idx 2)、thinkingLevel(idx 5,MINIMAL=`1`、LOW=`2`、MEDIUM=`3`、HIGH=`4`、EXTRA_HIGH=`5`)、thinkingSummaries(idx 6=`1`)、maxOutputTokens(idx 7)、imageConfig(idx 12),仅视频输出聊天模型(`secondary_capability_code_14 && chat_model`)发送 videoTask(idx 24)与 interaction field 54 | +| 18 | agent 目标(kind `1`),见下文 | +| 22 | 远程环境(agent):field 1 源 `[[<类型>,"<源>","<目标>","<内容>","<编码>"]...]`(类型 gcs `2`、inline `3`、repository `4`),field 2 出站白名单 `[[["<域名>",[["<头>","<值>"]...],"<凭据>"]...]]`(有凭据时只发凭据),field 3 禁止出站 `1`,field 4 要更新的已有环境 ID;Antigravity 未设置环境时为 `[null,null,1]` | +| 23 | 只引用已有环境、不带源与网络设置时的环境 ID(agent) | +| 26 | step 列表,见下文 | -agent 目标的 field 1 为 agent 名称。Deep Research 为 `["", null, [<思考摘要>, <可视化>, <协作规划>]]`:思考摘要 `1` 为 auto、`2` 为 none,可视化 `2` 为 auto、`1` 为 off,协作规划开启时为 `true`、关闭时省略,默认 `[1,2]`。 +模型目标(kind `2`)的 step 列表在无 `previous_interaction_id` 时保留完整 user、model 与原生工具(field 4 `tool_call`、field 5 `tool_result`)多轮历史,带思考签名的函数调用 step 之前为 field 3 思考 step `[null,null,["<签名>"]]`,每轮第一个调用没有签名时签名为 `skip_thought_signature_validator`(上游拒绝不带签名的函数调用历史),图片内联发送,适用首字超时与备用请求,并在混合账户池中写入轮次缓存以与未迁移账户的 `GenerateContent` 接续思考签名。 + +agent 目标(kind `1`)的 field 1 为 agent 名称(不含 `models/` 前缀)。Deep Research 为 `["", null, [<思考摘要>, <可视化>, <协作规划>]]`:思考摘要 `1` 为 auto、`2` 为 none,可视化 `2` 为 auto、`1` 为 off,协作规划开启时为 `true`、关闭时省略,默认 `[1,2]`。 field 79 InteractionConfig 的 field 6 给出默认模型的 agent(Antigravity)为 `[""]`,指定模型或 token 上限时 field 12 为 `["",null,null,null,null,null,]`。公开 Interactions 的 `agent_config` 按官方取值写入这些位置。 工具列表依次为代码执行 `[null,[]]`、函数声明 `[["","",]]`(参数为 `google.protobuf.Value`)、Google 搜索 `[null,null,null,null,null,[]]` 与 URL 上下文 `[null,null,[]]`: -- Interactions 请求带 `tools` 时只用列出的工具,空列表时省略索引 7 -- 其他请求与不带 `tools` 的 Interactions 请求,在模型目录 field 82 默认开启的代码执行(9)、Google 搜索(12)与 URL 上下文(13)之上加入请求的工具;Deep Research 默认为搜索与 URL 上下文,Antigravity 另有代码执行 +- 模型目标只在请求声明工具且 `tool_choice` 不为 `none` 时发送对应工具 +- agent 目标:Interactions 请求带 `tools` 时只用列出的工具,空列表时省略索引 7;其余请求在目录 field 82 默认开启的代码执行(9)、Google 搜索(12)与 URL 上下文(13)之上加入请求的工具;Deep Research 默认为搜索与 URL 上下文,Antigravity 另有代码执行 - 没有任何工具时省略索引 7 - MCP 服务器、File Search、Computer Use 与其他 Google 工具在发送前返回 `400 INVALID_ARGUMENT` -step 列表只包含用户内容:历史中的模型轮、服务端工具步骤、代码执行与函数调用不发送,其中的附件也不上传,相邻的用户内容合并为一个 step。公开 Interactions 以 `previous_interaction_id` 续接同一 agent 的后台任务时,索引 16 为该任务的 interaction ID,step 列表只有本次输入,请求固定使用创建该任务的账户。 +agent 目标的 step 列表只包含用户内容:历史中的模型轮、服务端工具步骤、代码执行与函数调用不发送,其中的附件也不上传,相邻的用户内容合并为一个 step。公开 Interactions 以 `previous_interaction_id` 续接同一 agent 的后台任务时,索引 16 为该任务的 interaction ID,step 列表只有本次输入,请求固定使用创建该任务的账户。 -`CreateInteraction` 响应索引 0 为 interaction ID。`GetInteractionStream` 的事件格式与 Omni Interaction 相同,content delta 另有两项: +`CreateInteraction` 响应索引 0 为 interaction ID。`GetInteractionStream` 除事件索引 10 的 content delta 文本(field 1)、媒体(field 2–5)、思考摘要(field 6)与引用(field 10)外,同时解码以下事件与终态: -| content delta | 内容 | 映射 | +| 事件 / 字段 | 内容 | 映射 | | --- | --- | --- | -| field 2 | 图片 `[1,""]` | `image/png` 媒体 | -| field 10 | 引用 `[[[,,null,[""]]...]]`,起止为正文中引用标记的字符位置 | citation 事件 | +| event 索引 9(`step_start`)与 11(`step_end`) | 步骤类型(user/model/thought/tool_call/tool_result)与工具元信息 | 跟踪步骤状态并在 `step_end` 提交函数调用或服务端工具调用 | +| content delta field 7 | 思考签名 `[""]` | `EventThoughtSignature`(紧随函数调用时附带在调用上) | +| content delta field 11–14 | 函数参数 JSON 增量、代码执行/搜索/URL 上下文/MCP 服务端工具调用与结果 | `EventToolCall`、`EventExecutableCode`、`EventCodeExecutionResult`、`EventServerToolCall`、`EventServerToolResponse`、`EventGrounding` | +| 最终 interaction 状态 `2` / `3` | `requires_action` / `completed` | 输出用量(若有)与 `stop` 终态 | +| 最终 interaction 状态 `6` | `incomplete`(输出长度截断) | 输出用量(若有)与 `max_tokens` 终态 | +| 最终 interaction 状态 `4` / `5` | `failed`(读取 field 28 错误列表)/ `cancelled` | 502 `RPCError` | -- 最终 interaction 不含 usage,状态 `3` 产生 `stop` 终态 - 调用方在终态前断开时,服务以 `["interactions/"]` 发送 `CancelInteraction` 停止上游任务;取消在后台以同一账户发送,调用方释放账户租约后取得请求槽位,期限 1 分钟 ### Build 代理 @@ -1944,25 +1952,28 @@ Chrome 导入列表按 `Preferences.account_info` 中的 Gaia ID 与邮箱逐个 | 字段 | 读写与生效时机 | | --- | --- | -| `auth_states`、`proxy`、`init_timeout`、`request_timeout` | 保存值;下一次启动生成服务时使用 | -| `warm_worker_limit`、`max_active_workers`、`warm_startup_concurrency`、`per_account_concurrency`、`max_account_switches` | 保存值;保存后立即作用于当前生成服务 | -| `model_mapping`、`search_model_aliases`、`google_search`、`media_output`、`media_base_url` | 保存值;保存后作用于新请求,进行中的请求沿用开始时的值 | -| `build_native_nonstream` | 保存值;下一次启动生成服务时决定非流式请求是否优先选择 Build | +| `auth_states`、`waa_backend` | 保存值;重启生成服务后生效(生成服务运行中保存时返回 `service_restart_required: true` 与 `active_requests`,可经 `POST /api/control/restart` 一键重启) | +| `proxy`、`init_timeout`、`request_timeout`、`upstream_channels`、`discover_hidden_models` | 保存值;保存后立即作用于下一次请求与新启动的 Worker,不中断进行中的请求(修改 `proxy` 时后台排空换绑受影响账户的 Worker) | +| `warm_worker_limit`、`max_active_workers`、`warm_startup_concurrency`、`per_account_concurrency`、`max_account_switches`、`account_switch_interval`、`max_quota_switches` | 保存值;保存后立即作用于当前生成服务 | +| `model_mapping`、`search_model_aliases`、`google_search`、`media_output`、`media_base_url`、`continuation_rewrite`、`continuation_prompt`、`strip_thought_signatures` | 保存值;保存后作用于新请求,进行中的请求沿用开始时的值 | +| `build_native_nonstream`、`youtube_links` | 保存值;保存后作用于新请求,进行中的请求沿用开始时的值 | | `nonstream_keepalive`、`fake_stream` | 保存值;保存后决定新的非流式请求是否保活、新的流式请求是否按非流式生成 | -| `youtube_links` | 保存值;下一次启动生成服务时决定是否把用户消息文本中的 YouTube 链接作为视频外部媒体发送 | -| `first_event_hedge` | 保存值;`off`、`auto` 或正整数秒,下一次启动生成服务时决定原请求等待首字多久后发起备用请求 | -| `auto_start` | 保存值;下一管理进程就绪后是否自动启动生成服务 | -| `hide_dock_icon` | 保存值;macOS 桌面版是否只在菜单栏显示图标 | +| `first_event_hedge`、`first_event_hedge_models`、`first_event_timeout` | 保存值;保存后作用于新请求 | +| `auto_start` | 保存值;下次启动程序时是否自动启动生成服务(不触发重启标记) | +| `hide_dock_icon` | 保存值;macOS 桌面版是否只在菜单栏显示图标,保存后立即生效 | | `request_body_log` | 保存值;保存后立即决定是否保存请求与响应正文 | -| `admin_auth_enabled`、`admin_username` | 保存值;下一管理进程使用 | -| `admin_password` | 只写;省略时保留现值,下一管理进程使用 | +| `admin_auth_enabled`、`admin_username` | 保存值;保存后立即生效(非回环访问禁止关闭管理登录) | +| `admin_password` | 只写;省略时保留现值,保存后立即生效并为当前请求签发新会话 Cookie | | `admin_password_set` | response-only;是否已保存管理密码 | -| `listen_addr`、`proxy_api_key` | 保存值;下一管理进程使用 | -| `active_listen_addr`、`active_proxy_api_key` | response-only;当前管理进程固定值 | -| `management_restart_required` | response-only;保存的监听地址、API key 或管理凭据与当前管理进程不同 | -| `service_restart_required` | response-only;保存的生成服务配置与当前生成服务实例不同 | +| `proxy_api_key` | 保存值;保存后立即作用于新请求 | +| `listen_addr`、`preview_listen_addr` | 保存值;重启管理进程后生效 | +| `active_listen_addr`、`active_preview_listen_addr` | response-only;当前管理进程实际使用的监听地址与预览来源地址 | +| `active_proxy`、`proxy_pool` | response-only;当前生成服务实际使用的出口(含 `proxy` 留空时的系统代理)与代理池健康状态 | +| `active_requests` | response-only;当前生成服务进行中的请求数 | +| `management_restart_required` | response-only;保存的 `listen_addr` 或 `preview_listen_addr` 与当前管理进程不同 | +| `service_restart_required` | response-only;生成服务运行中,且保存的 `auth_states` 或 `waa_backend` 与当前生成服务实例不同 | -`PUT /api/config` 原子保存配置。监听地址、API key 和管理凭据在管理进程重启后生效;Worker 容量与换号次数上限保存后立即作用于当前生成服务;模型映射、非流式保活、假流式、搜索型号、全模型搜索与媒体输出设置在每个请求开始时读取,保存后作用于新请求,进行中的请求沿用开始时的值;账户路径、代理、timeout、临时对话与上游通道选项在 Stop/Start 创建的新生成服务实例中生效。启动时读取最新配置;配置加载、校验、实例创建失败或启用前取消时保留原实例,切换到新实例后由它完成启动或进入 `STOPPED`。 +`PUT /api/config` 原子保存配置。除监听地址(`listen_addr`、`preview_listen_addr`,需重启管理进程)、账户目录与 WAA 后端(`auth_states`、`waa_backend`,生成服务运行中需重启生成服务,可经 `POST /api/control/restart` 一键重启)以及 `auto_start`(下次启动程序生效)外,其余全部配置保存后对下一次请求立即生效且不中断进行中的请求。启动时读取最新配置;配置加载、校验、实例创建失败或启用前取消时保留原实例,切换到新实例后由它完成启动或进入 `STOPPED`。 `GET /api/events` 的初始顺序为 `status`、`models`、`accounts`、最近 200 条 `log`、`cooldowns`、按开始时间排序的活动 `request`。后续事件的 `data` 形状: @@ -2222,7 +2233,7 @@ Gemini `GET /v1beta/models` 返回 `{"models":[...]}`,单模型路由直接返 管理模型中的 `description`、token limits、capabilities、capability options、access modes 与 false `paid` 使用 `omitempty`;OpenAI 和 Gemini 响应始终包含身份、methods 与 token limits,并在 map/slice 非空或 `paid=true` 时增加对应扩展字段。 -管理目录合并全部账户的上游实时模型集合,顺序沿用各账户 `ListModels` 的上游顺序:只出现在后一个账户目录中的模型排在它在该目录中的前一个模型之后,没有前一个已知模型时排在该目录首个已知模型之前,该目录没有已知模型时排在末尾;在此顺序上依次排列有可用通道的普通模型、经后台任务生成的 agent(`interaction_task`,如 Antigravity 与 Deep Research,不论有无可用通道)与没有可用通道的普通模型。 +管理目录合并全部账户的上游实时模型集合,顺序沿用各账户 `ListModels` 的上游顺序:只出现在后一个账户目录中的模型排在它在该目录中的前一个模型之后,没有前一个已知模型时排在该目录首个已知模型之前,该目录没有已知模型时排在末尾;在此顺序上依次排列有可用通道的普通模型、agent(`interaction_agent`,如 Antigravity 与 Deep Research,不论有无可用通道)与没有可用通道的普通模型。 公开目录保留当前公开协议承载其调用方法、且已启用通道可以提供的模型;启用 Build 通道时同时包含 Build 独有的可生成模型,`channels` 列出可调用该模型的通道,见 [Build 通道](build.md)。启用账户的权益都不满足 AccessModes 的模型同样列出,不含 `channels`。短期冷却和忙碌状态由请求调度处理。 @@ -2972,7 +2983,7 @@ delta 联合类型为 `text_delta{text}`、`citations_delta{citation}`、`thinki 音频 `mime_type` 为 `audio/wav`、`audio/l16`、`audio/mp3`、`audio/ogg_opus`、`audio/alaw` 或 `audio/mulaw`,非流式默认 `audio/wav`,流式默认 `audio/l16`。输出内容的 `mime_type` 依次为 `audio/wav`、`audio/l16`、`audio/mp3`、`audio/ogg`、`audio/alaw`、`audio/mulaw`,`sample_rate` 与 `channels` 为实际值。 -- TTS 上游为 24 kHz、16-bit 小端、单声道 PCM,上游返回 WAV 时剥去 RIFF 头取 PCM,Lyria 等返回的 MP3 先解码为 PCM;请求 `audio/mp3` 且未改采样率、未指定 `bit_rate` 时原样返回上游 MP3 +- TTS 上游为 24 kHz、16-bit 小端、单声道 PCM,Lyria 等返回的 MP3 先解码为 PCM;请求 `audio/mp3` 且未改采样率、未指定 `bit_rate` 时原样返回上游 MP3 - `sample_rate` 省略时使用上游采样率,指定时重采样;MP3 取 32、44.1、48 kHz,Ogg Opus 取 8、12、16、24、48 kHz,均为不低于目标采样率的最小值,超出时取最高值 - `bit_rate` 以 bit/s 计,用于 MP3(CBR 32000–320000 取最接近值,默认 192000)与 Opus - 上游为 PCM 且不重采样时,`audio/l16`、`audio/alaw`、`audio/mulaw` 逐块输出,其余情况在音频汇总完成后发送一个完整块 diff --git a/internal/aistudio/accounts.go b/internal/aistudio/accounts.go index 074c276f..85555dc8 100644 --- a/internal/aistudio/accounts.go +++ b/internal/aistudio/accounts.go @@ -369,6 +369,10 @@ type Account struct { assistantBusy bool // pendingProofs 是已选定该账户、还没有取完 proof 的生成租约数 pendingProofs int + // quotaDayStart 是 quotaDayRequests 对应的配额日起点 + quotaDayStart time.Time + // quotaDayRequests 是账户在当前配额日内的请求数 + quotaDayRequests int64 } // AccountStatus 表示管理界面使用的脱敏账户状态 @@ -576,6 +580,44 @@ func (s *AccountStore) RecordRestrictedImport(email string, reason string) error return atomicWriteFile(filepath.Join(s.paths[0], restrictedImportsName), data, 0o600) } +// AccountUsageEntry 表示单个账户在指定模型与通道上的最近使用时刻 +type AccountUsageEntry struct { + Account string + Model string + Channel Channel + LastUsed time.Time +} + +// AccountUsageSeed 保存启动或换代时注入账户池的历史使用信息 +type AccountUsageSeed struct { + Entries []AccountUsageEntry + QuotaDayStart time.Time + QuotaDayRequests map[string]int64 +} + +// channelUseKey 是账户与通道组合的最近使用键 +type channelUseKey struct { + accountID string + channel Channel +} + +// quotaResetLocation 是配额日重置使用的太平洋时区 +var quotaResetLocation = mustLoadQuotaResetLocation() + +func mustLoadQuotaResetLocation() *time.Location { + location, err := time.LoadLocation(quotaResetTimezone) + if err != nil { + panic(err) + } + return location +} + +// QuotaDayStart 返回 now 所在配额日(太平洋时间 00:00)的起始时刻 +func QuotaDayStart(now time.Time) time.Time { + local := now.In(quotaResetLocation) + return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, quotaResetLocation) +} + // AccountPool 在账户之间执行能力与并发槽位调度 type AccountPool struct { mu sync.Mutex @@ -584,8 +626,8 @@ type AccountPool struct { resources map[string]string perAccountConcurrency int routingStrategy string - lastPicked map[string]string - lastPickedChannel map[string]Channel + lastPickTime time.Time + lastUsed map[string]map[channelUseKey]time.Time channels []Channel modelChannels map[string]Channel apiKeyAccounts map[string][]string @@ -1007,13 +1049,13 @@ func (p *AccountPool) PublicModels(models []Model) []Model { return callableFirst(public) } -// callableFirst 保持原顺序依次排列有通道的普通模型、经后台任务生成的 agent 与没有通道的普通模型 +// callableFirst 保持原顺序依次排列有通道的普通模型、agent 与没有通道的普通模型 func callableFirst(models []Model) []Model { ordered := make([]Model, 0, len(models)) var agents, restricted []Model for _, model := range models { switch { - case model.Capabilities["interaction_task"]: + case interactionRouting(model, GenerationDefaults{}, ChannelPlayground).IsAgent(): agents = append(agents, model) case len(model.Channels) == 0: restricted = append(restricted, model) @@ -1077,7 +1119,8 @@ func NewAccountPool(accounts []*Account, perAccountConcurrency int) *AccountPool p := &AccountPool{ accounts: append([]*Account(nil), accounts...), byID: make(map[string]*Account, len(accounts)), resources: make(map[string]string), perAccountConcurrency: perAccountConcurrency, changed: make(chan struct{}), - routingStrategy: "round-robin", lastPicked: make(map[string]string), lastPickedChannel: make(map[string]Channel), + routingStrategy: "round-robin", + lastUsed: make(map[string]map[channelUseKey]time.Time), } for _, account := range p.accounts { if account.runtime.Cooldowns == nil { @@ -1525,6 +1568,9 @@ func (p *AccountPool) noEligibleErrorLocked(selection AccountSelection) error { } selection.ModelID = strings.TrimPrefix(strings.TrimSpace(selection.ModelID), "models/") scope, bound := p.modelAccounts[selection.ModelID] + if err := p.scopedModelAccessErrorLocked(selection, scope, bound); err != nil { + return err + } var reasons []string var states []AccountState for _, account := range p.accounts { @@ -1550,6 +1596,40 @@ func (p *AccountPool) noEligibleErrorLocked(selection AccountSelection) error { return &AccountsNotReadyError{Reasons: reasons, States: states} } +// scopedModelAccessErrorLocked 返回请求限定的账户(按请求指定、key 绑定或模型绑定)只因权益不足而无法调用模型时写明账户与所需权益的错误 +func (p *AccountPool) scopedModelAccessErrorLocked(selection AccountSelection, scope []string, bound bool) error { + pinned := strings.TrimSpace(selection.AccountID) + if selection.ModelID == "" || pinned == "" && selection.AllowedAccountIDs == nil && !bound { + return nil + } + anyTier := selection + anyTier.anyTier = true + var accounts []string + var modes []int64 + for _, account := range p.accounts { + if !account.Config.Enabled || pinned != "" && account.ID != pinned || bound && !slices.Contains(scope, account.ID) || + selection.AllowedAccountIDs != nil && !slices.Contains(selection.AllowedAccountIDs, account.ID) { + continue + } + if p.accountSupportsAnyChannelLocked(account, selection) { + return nil + } + if !p.accountSupportsAnyChannelLocked(account, anyTier) { + continue + } + accounts = append(accounts, account.ID) + for _, model := range account.Models { + if modelMatchesID(model, selection.ModelID) { + modes = unionInt64(modes, model.AccessModes) + } + } + } + if len(accounts) == 0 { + return nil + } + return &ModelAccessError{Model: selection.ModelID, AccessModes: modes, Accounts: accounts} +} + func (p *AccountPool) markStaleAccountUnavailable(account *Account) { p.mu.Lock() defer p.mu.Unlock() @@ -2512,13 +2592,97 @@ func (p *AccountPool) ByBenefitTier(accountIDs []string) []string { return ordered } -// PreferWarmPool 按权益分层轮选初始热账户,fill-first 时 ACCOUNT_ORDER 列出的账户在前 -func (p *AccountPool) PreferWarmPool(accountIDs []string) []string { +// SeedUsage 把启动或换代时从请求账本读回的最近使用时间与当日请求数注入账户池 +func (p *AccountPool) SeedUsage(seed AccountUsageSeed) { + p.mu.Lock() + defer p.mu.Unlock() + byLabel := make(map[string]*Account, len(p.accounts)) + for _, account := range p.accounts { + if label := strings.TrimSpace(account.Config.Label); label != "" { + if _, exists := byLabel[label]; !exists { + byLabel[label] = account + } + } + } + resolve := func(name string) *Account { + name = strings.TrimSpace(name) + if name == "" { + return nil + } + if account := p.byID[name]; account != nil { + return account + } + return byLabel[name] + } + for _, entry := range seed.Entries { + account := resolve(entry.Account) + if account == nil || entry.LastUsed.IsZero() { + continue + } + at := entry.LastUsed.UTC() + if at.After(account.LastUsed) { + account.LastUsed = at + } + if at.After(p.lastPickTime) { + p.lastPickTime = at + } + scope := strings.TrimPrefix(strings.TrimSpace(entry.Model), "models/") + if scope == "" { + continue + } + channel := Channel(strings.TrimSpace(string(entry.Channel))) + if channel == "" { + channel = ChannelPlayground + } + byPair := p.lastUsed[scope] + if byPair == nil { + byPair = make(map[channelUseKey]time.Time) + p.lastUsed[scope] = byPair + } + key := channelUseKey{accountID: account.ID, channel: channel} + if at.After(byPair[key]) { + byPair[key] = at + } + } + if !seed.QuotaDayStart.IsZero() && len(seed.QuotaDayRequests) > 0 { + totals := make(map[string]int64, len(seed.QuotaDayRequests)) + for name, count := range seed.QuotaDayRequests { + if count <= 0 { + continue + } + if account := resolve(name); account != nil { + totals[account.ID] += count + } + } + for accountID, count := range totals { + account := p.byID[accountID] + if !account.quotaDayStart.Equal(seed.QuotaDayStart) { + account.quotaDayStart = seed.QuotaDayStart + account.quotaDayRequests = count + } else if count > account.quotaDayRequests { + account.quotaDayRequests = count + } + } + } +} + +// PreferWarmPool 按权益分层轮选初始热账户,round-robin 优先尚无或较少热账户的权益层,同层按覆盖度、当日用量少与最久未用优先,fill-first 时 ACCOUNT_ORDER 列出的账户在前 +func (p *AccountPool) PreferWarmPool(accountIDs []string, warm []string) []string { type warmCandidate struct { - id string - coverage int + id string + coverage int + quotaDayRequests int64 + lastUsed time.Time } + today := QuotaDayStart(time.Now()) p.mu.Lock() + roundRobin := p.routingStrategy == "round-robin" + warmByPriority := make(map[int]int) + for _, accountID := range warm { + if account := p.byID[accountID]; account != nil { + warmByPriority[benefitTierPriority(account.BenefitTier)]++ + } + } groups := make(map[int][]warmCandidate) for _, accountID := range accountIDs { account := p.byID[accountID] @@ -2531,19 +2695,55 @@ func (p *AccountPool) PreferWarmPool(accountIDs []string) []string { coverage++ } } + requests := int64(0) + if account.quotaDayStart.Equal(today) { + requests = account.quotaDayRequests + } priority := benefitTierPriority(account.BenefitTier) - groups[priority] = append(groups[priority], warmCandidate{id: accountID, coverage: coverage}) + groups[priority] = append(groups[priority], warmCandidate{ + id: accountID, + coverage: coverage, + quotaDayRequests: requests, + lastUsed: account.LastUsed, + }) } p.mu.Unlock() priorities := make([]int, 0, len(groups)) for priority, candidates := range groups { priorities = append(priorities, priority) sort.SliceStable(candidates, func(left int, right int) bool { - return candidates[left].coverage > candidates[right].coverage + if candidates[left].coverage != candidates[right].coverage { + return candidates[left].coverage > candidates[right].coverage + } + if !roundRobin { + return false + } + if candidates[left].quotaDayRequests != candidates[right].quotaDayRequests { + return candidates[left].quotaDayRequests < candidates[right].quotaDayRequests + } + if diff := compareLastUsed(candidates[left].lastUsed, candidates[right].lastUsed); diff != 0 { + return diff < 0 + } + return candidates[left].id < candidates[right].id }) groups[priority] = candidates } - sort.Ints(priorities) + sort.Slice(priorities, func(left, right int) bool { + leftP, rightP := priorities[left], priorities[right] + if warmByPriority[leftP] != warmByPriority[rightP] { + return warmByPriority[leftP] < warmByPriority[rightP] + } + if roundRobin { + leftTop, rightTop := groups[leftP][0], groups[rightP][0] + if leftTop.quotaDayRequests != rightTop.quotaDayRequests { + return leftTop.quotaDayRequests < rightTop.quotaDayRequests + } + if diff := compareLastUsed(leftTop.lastUsed, rightTop.lastUsed); diff != 0 { + return diff < 0 + } + } + return leftP < rightP + }) result := make([]string, 0, len(accountIDs)) for len(result) < len(accountIDs) { added := false @@ -3026,13 +3226,13 @@ func (p *AccountPool) Status() []AccountStatus { Message: message, Directory: account.Directory, - Transition: progress.operation, - TransitionStep: progress.step, - TransitionIndex: progress.index, - TransitionTotal: progress.total, - TransitionSince: progress.since, - CatalogError: catalogError, - ActiveRequests: account.active, + Transition: progress.operation, + TransitionStep: progress.step, + TransitionIndex: progress.index, + TransitionTotal: progress.total, + TransitionSince: progress.since, + CatalogError: catalogError, + ActiveRequests: account.active, CatalogSyncedAt: account.catalogSyncedAt, HiddenDiscovered: account.hiddenDiscovered, HiddenModels: len(account.hiddenModels), @@ -3211,9 +3411,13 @@ func (p *AccountPool) tryAcquireLocked(selection AccountSelection, now time.Time if candidate.channel == ChannelAssistant { account.assistantBusy = true } - account.LastUsed = now - p.lastPicked[selectionAccessScope(selection)] = account.ID - p.lastPickedChannel[selectionAccessScope(selection)] = candidate.channel + usedAt := now + if !usedAt.After(p.lastPickTime) { + usedAt = p.lastPickTime.Add(time.Nanosecond) + } + p.lastPickTime = usedAt + account.LastUsed = usedAt + p.recordSelectionUseLocked(selection, account, candidate.channel, usedAt) return &AccountLease{ pool: p, account: account, authGeneration: account.authGeneration, modelAccessGeneration: account.modelAccessGeneration, refreshRuntime: refreshRuntime, checkedAt: now.UTC(), @@ -3368,20 +3572,78 @@ func (p *AccountPool) selectionIndicesLocked(selection AccountSelection) ([]int, } indices = append(indices, index) } + if p.routingStrategy == "round-robin" { + scope := selectionAccessScope(selection) + channels := p.selectionChannelsLocked(selection) + sort.Slice(indices, func(left, right int) bool { + leftAccount, rightAccount := p.accounts[indices[left]], p.accounts[indices[right]] + if diff := compareLastUsed(p.accountLastUsedLocked(scope, leftAccount.ID, channels), p.accountLastUsedLocked(scope, rightAccount.ID, channels)); diff != 0 { + return diff < 0 + } + return leftAccount.ID < rightAccount.ID + }) + return indices, nil + } sort.Slice(indices, func(left, right int) bool { return p.accounts[indices[left]].ID < p.accounts[indices[right]].ID }) - if p.routingStrategy == "round-robin" { - last := p.lastPicked[selectionAccessScope(selection)] - start := sort.Search(len(indices), func(index int) bool { return p.accounts[indices[index]].ID > last }) - return append(indices[start:], indices[:start]...), nil - } sort.SliceStable(indices, func(left, right int) bool { return p.accountRankLocked(p.accounts[indices[left]].ID) < p.accountRankLocked(p.accounts[indices[right]].ID) }) return indices, nil } +// recordSelectionUseLocked 更新账户在作用域与通道上的最近使用时刻及当前配额日请求数 +func (p *AccountPool) recordSelectionUseLocked(selection AccountSelection, account *Account, channel Channel, usedAt time.Time) { + scope := selectionAccessScope(selection) + byPair := p.lastUsed[scope] + if byPair == nil { + byPair = make(map[channelUseKey]time.Time) + p.lastUsed[scope] = byPair + } + byPair[channelUseKey{accountID: account.ID, channel: channel}] = usedAt + if selection.ModelID != "" || selection.Method != "" { + today := QuotaDayStart(usedAt) + if !account.quotaDayStart.Equal(today) { + account.quotaDayStart = today + account.quotaDayRequests = 0 + } + account.quotaDayRequests++ + } +} + +// accountLastUsedLocked 返回账户在作用域可选通道中最早的最近使用时刻,读不到记录时返回零值 +func (p *AccountPool) accountLastUsedLocked(scope string, accountID string, channels []Channel) time.Time { + byPair := p.lastUsed[scope] + if len(byPair) == 0 { + return time.Time{} + } + if len(channels) == 0 { + return byPair[channelUseKey{accountID: accountID, channel: ChannelPlayground}] + } + earliest := byPair[channelUseKey{accountID: accountID, channel: channels[0]}] + for _, channel := range channels[1:] { + if at := byPair[channelUseKey{accountID: accountID, channel: channel}]; compareLastUsed(at, earliest) < 0 { + earliest = at + } + } + return earliest +} + +// compareLastUsed 比较两个最近使用时刻,零值表示未用过并排在最前 +func compareLastUsed(left, right time.Time) int { + switch { + case left.IsZero() && right.IsZero(): + return 0 + case left.IsZero(): + return -1 + case right.IsZero(): + return 1 + default: + return left.Compare(right) + } +} + // accountRankLocked 返回账户在 ACCOUNT_ORDER 中的位置,未列出的账户排在最后 func (p *AccountPool) accountRankLocked(accountID string) int { if rank, listed := p.accountOrder[accountID]; listed { diff --git a/internal/aistudio/benefit.go b/internal/aistudio/benefit.go index ba286222..f21b7610 100644 --- a/internal/aistudio/benefit.go +++ b/internal/aistudio/benefit.go @@ -117,6 +117,8 @@ func (c *Client) applyBenefitTier(method string, accountID string, header http.H type ModelAccessError struct { Model string AccessModes []int64 + // Accounts 是请求限定的账户(按请求指定、key 绑定或模型绑定),为空时指全部启用账户 + Accounts []string } func (e *ModelAccessError) Error() string { @@ -133,6 +135,13 @@ func (e *ModelAccessError) Error() string { names = append(names, fmt.Sprintf("访问方式 %d", mode)) } } + if len(e.Accounts) > 0 { + accounts := strings.Join(e.Accounts, ";") + if len(names) == 1 { + return fmt.Sprintf("模型 %s 需要 %s,本次请求可用的账户 %s 都不具备", e.Model, names[0], accounts) + } + return fmt.Sprintf("模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s", e.Model, accounts, strings.Join(names, ";")) + } if len(names) == 1 { return fmt.Sprintf("模型 %s 需要 %s,启用的账户都不具备", e.Model, names[0]) } diff --git a/internal/aistudio/channel.go b/internal/aistudio/channel.go index e565015d..bd7e15a8 100644 --- a/internal/aistudio/channel.go +++ b/internal/aistudio/channel.go @@ -318,7 +318,7 @@ func (p *AccountPool) accountChannelCooldownLocked(account *Account, selection A return earliest, !earliest.Until.IsZero() } -// channelCandidatesLocked 按 indices 的账户顺序与通道顺序展开候选,轮询策略改按账户 ID 排序并从上次选中组合之后开始 +// channelCandidatesLocked 按 indices 的账户顺序与通道顺序展开候选,轮询策略按最近使用时间最久优先排列 func (p *AccountPool) channelCandidatesLocked(indices []int, selection AccountSelection) []channelCandidate { channels := p.selectionChannelsLocked(selection) candidates := make([]channelCandidate, 0, len(indices)*len(channels)) @@ -330,25 +330,23 @@ func (p *AccountPool) channelCandidatesLocked(indices []int, selection AccountSe if p.routingStrategy != "round-robin" || len(indices) <= 1 && len(channels) <= 1 { return candidates } + scope := selectionAccessScope(selection) + byPair := p.lastUsed[scope] rank := func(channel Channel) int { return slices.Index(channels, channel) } sort.SliceStable(candidates, func(left, right int) bool { - leftID, rightID := p.accounts[candidates[left].index].ID, p.accounts[candidates[right].index].ID + leftID := p.accounts[candidates[left].index].ID + rightID := p.accounts[candidates[right].index].ID + leftUsed := byPair[channelUseKey{accountID: leftID, channel: candidates[left].channel}] + rightUsed := byPair[channelUseKey{accountID: rightID, channel: candidates[right].channel}] + if diff := compareLastUsed(leftUsed, rightUsed); diff != 0 { + return diff < 0 + } if leftID != rightID { return leftID < rightID } return rank(candidates[left].channel) < rank(candidates[right].channel) }) - key := selectionAccessScope(selection) - lastAccount := p.lastPicked[key] - lastChannel := p.lastPickedChannel[key] - start := sort.Search(len(candidates), func(position int) bool { - account := p.accounts[candidates[position].index].ID - if account != lastAccount { - return account > lastAccount - } - return lastChannel != "" && rank(candidates[position].channel) > rank(lastChannel) - }) - return append(candidates[start:], candidates[:start]...) + return candidates } // AssistantModel 判断模型是否为经 Build 写代码助手生成的 -build 模型 @@ -589,3 +587,19 @@ func (p *AccountPool) AccountChannelAvailable(accountID string, selection Accoun _, cooling := p.accountChannelCooldownLocked(account, selection, time.Now()) return !cooling } + +// AccountsMissingBuildCatalog 返回启用、可同步且尚未缓存 Build 模型目录的账户 ID +func (p *AccountPool) AccountsMissingBuildCatalog() []string { + p.mu.Lock() + defer p.mu.Unlock() + var ids []string + for _, account := range p.accounts { + if !account.Config.Enabled || len(account.buildModels) > 0 { + continue + } + if account.State == AccountReady || account.State == AccountBusy || account.State == AccountCooldown { + ids = append(ids, account.ID) + } + } + return ids +} diff --git a/internal/aistudio/channel_test.go b/internal/aistudio/channel_test.go deleted file mode 100644 index 99e4e132..00000000 --- a/internal/aistudio/channel_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package aistudio - -import ( - "context" - "reflect" - "testing" - "time" -) - -// TestChannelSelection 保留文件绑定与专属能力的通道资格 -func TestChannelSelection(t *testing.T) { - pool := NewAccountPool(nil, 1) - pool.SetUpstreamChannels([]Channel{ChannelPlayground, ChannelBuild}) - for _, item := range []struct { - selection AccountSelection - want []Channel - }{ - {AccountSelection{ModelID: "gemini", Method: "generateContent"}, []Channel{ChannelPlayground, ChannelBuild}}, - {AccountSelection{ModelID: "gemini", Method: "generateContent", Channel: ChannelBuild}, []Channel{ChannelBuild}}, - {AccountSelection{ModelID: "gemini", Method: "generateContent", ResourceID: "file", Channel: ChannelBuild}, []Channel{ChannelPlayground}}, - {AccountSelection{ModelID: "gemini", Method: "countTokens"}, []Channel{ChannelPlayground, ChannelBuild}}, - {AccountSelection{ModelID: "gemini", Method: "countTokens", Channel: ChannelBuild}, []Channel{ChannelBuild}}, - {AccountSelection{ModelID: "gemini", Method: "generateContent", PlaygroundOnly: true, Channel: ChannelBuild}, []Channel{ChannelPlayground}}, - } { - if got := pool.selectionChannelsLocked(item.selection); !reflect.DeepEqual(got, item.want) { - t.Errorf("selection=%+v channels=%v want=%v", item.selection, got, item.want) - } - } - pool.SetUpstreamChannels([]Channel{ChannelPlayground}) - if got := pool.selectionChannelsLocked(AccountSelection{ModelID: "gemini", Method: "generateContent", Channel: ChannelBuild}); len(got) != 0 { - t.Fatalf("disabled Build channels=%v", got) - } -} - -// TestPreferredChannelPerAccount 验证优先通道按账户生效,账户的优先通道冷却后由同账户其余通道接住 -func TestPreferredChannelPerAccount(t *testing.T) { - model := Model{ID: "gemini", Methods: []string{"generateContent"}, Capabilities: map[string]bool{"chat_model": true}} - accounts := []*Account{ - {ID: "a@example.com", Config: AccountConfig{Enabled: true}, State: AccountReady, Models: []Model{model}, modelAccessGeneration: 1}, - {ID: "b@example.com", Config: AccountConfig{Enabled: true}, State: AccountReady, Models: []Model{model}, modelAccessGeneration: 1}, - } - pool := NewAccountPool(accounts, 1) - pool.SetUpstreamChannels([]Channel{ChannelPlayground, ChannelBuild}) - for _, account := range accounts { - if err := pool.SetBuildCatalog(account.ID, []Model{model}); err != nil { - t.Fatal(err) - } - } - selection := AccountSelection{ModelID: "gemini", Method: "generateContent", PreferredChannel: ChannelBuild} - var picks []string - pick := func() { - lease, _, err := pool.TryAcquireFor(context.Background(), selection) - if err != nil || lease == nil { - t.Fatalf("lease=%v err=%v", lease, err) - } - picks = append(picks, lease.Account().ID+"/"+string(lease.Channel())) - if err := lease.Release(); err != nil { - t.Fatal(err) - } - } - for range 3 { - pick() - } - if err := pool.MarkCooldownIfGeneration("a@example.com", ChannelCooldownScope(ChannelBuild, "gemini"), 1, time.Now(), time.Now().Add(time.Hour), "fixture"); err != nil { - t.Fatal(err) - } - for range 2 { - pick() - } - want := []string{"a@example.com/build", "b@example.com/build", "a@example.com/build", "a@example.com/playground", "b@example.com/build"} - if !reflect.DeepEqual(picks, want) { - t.Fatalf("picks=%v want=%v", picks, want) - } -} diff --git a/internal/aistudio/compatibility_test.go b/internal/aistudio/compatibility_test.go index eae72f84..c5108615 100644 --- a/internal/aistudio/compatibility_test.go +++ b/internal/aistudio/compatibility_test.go @@ -1,159 +1,6 @@ package aistudio -import ( - "encoding/json" - "net/http" - "strings" - "testing" - "time" -) - -// TestAgentToolSchemaCompatibility 验证常见 Agent 工具 Schema 的稳定转换规则 -func TestAgentToolSchemaCompatibility(t *testing.T) { - t.Run("string const", func(t *testing.T) { - wire, err := encodeJSONSchema(json.RawMessage(`{ - "properties":{"mode":{"const":"agent_probe","title":"Mode","type":"string"}}, - "required":["mode"],"title":"record_literal_args","type":"object" - }`)) - if err != nil { - t.Fatal(err) - } - if len(wire) <= 6 || wire[0] != int64(6) { - t.Fatalf("schema wire=%#v", wire) - } - properties, ok := wire[6].([]any) - if !ok || len(properties) != 1 { - t.Fatalf("schema properties=%#v", wire[6]) - } - entry, ok := properties[0].([]any) - if !ok || len(entry) != 2 || entry[0] != "mode" { - t.Fatalf("schema property=%#v", properties[0]) - } - mode, ok := entry[1].([]any) - if !ok || len(mode) <= 4 || mode[0] != int64(1) { - t.Fatalf("mode schema=%#v", entry[1]) - } - values, ok := mode[4].([]string) - if !ok || len(values) != 1 || values[0] != "agent_probe" { - t.Fatalf("mode enum=%#v", mode[4]) - } - }) - - t.Run("nested const", func(t *testing.T) { - wire, err := encodeJSONSchema(json.RawMessage(`{"anyOf":[{"const":"fast"},{"const":"slow"}]}`)) - if err != nil { - t.Fatal(err) - } - if len(wire) <= 17 || wire[0] != int64(1) { - t.Fatalf("schema wire=%#v", wire) - } - variants, ok := wire[17].([]any) - if !ok || len(variants) != 2 { - t.Fatalf("schema variants=%#v", wire[17]) - } - for index, want := range []string{"fast", "slow"} { - variant, ok := variants[index].([]any) - if !ok || len(variant) <= 4 || variant[0] != int64(1) { - t.Fatalf("schema variant=%#v", variants[index]) - } - values, ok := variant[4].([]string) - if !ok || len(values) != 1 || values[0] != want { - t.Fatalf("schema variant enum=%#v", variant[4]) - } - } - }) - - t.Run("non-string const", func(t *testing.T) { - for _, raw := range []string{`{"const":1}`, `{"const":true}`, `{"const":null}`} { - if _, err := encodeJSONSchema(json.RawMessage(raw)); err == nil || !strings.Contains(err.Error(), "const") { - t.Fatalf("schema=%s error=%v", raw, err) - } - } - }) -} - -// TestFunctionCallThoughtSignature 验证历史工具调用的签名补齐与原值保留 -func TestFunctionCallThoughtSignature(t *testing.T) { - for _, test := range []struct { - name string - signature string - want string - }{ - {name: "missing", want: "skip_thought_signature_validator"}, - {name: "present", signature: "real-signature", want: "real-signature"}, - } { - t.Run(test.name, func(t *testing.T) { - wire, err := encodePart(Part{FunctionCall: &FunctionCall{ - ID: "call_123", Name: "fixture", Arguments: json.RawMessage(`{"value":"ok"}`), - ThoughtSignature: test.signature, - }}) - if err != nil { - t.Fatal(err) - } - if len(wire) <= 14 || wire[14] != test.want { - t.Fatalf("thought signature=%#v", wire) - } - }) - } -} - -// TestRPCErrorCompatibility 验证真实错误帧的解码与 Drive 授权缺失的判定 -func TestRPCErrorCompatibility(t *testing.T) { - t.Run("direct", func(t *testing.T) { - err := DecodeRPCError("GenerateAccessToken", http.StatusUnauthorized, []byte( - `[16,"OAuth error: unauthorized_client.",[["type.googleapis.com/google.internal.alkali.applications.makersuite.v1.AiStudioErrorDetails",[null,[]]]]]`, - )) - if err.Code != 16 || err.Message != "OAuth error: unauthorized_client." || !driveAuthorizationMissing(err) { - t.Fatalf("RPC error=%+v", err) - } - }) - - t.Run("wrapped", func(t *testing.T) { - err := DecodeRPCError("GenerateContent", http.StatusForbidden, []byte( - `[null,[7,"Permission denied",[["type.googleapis.com/google.rpc.ErrorInfo",["DENIED","google.com",[["reason","account_permission"]]]]]]]`, - )) - if err.Code != 7 || err.Message != "Permission denied" || err.Metadata["reason"] != "account_permission" { - t.Fatalf("RPC error=%+v", err) - } - }) - - t.Run("login failure", func(t *testing.T) { - err := DecodeRPCError("GenerateAccessToken", http.StatusUnauthorized, []byte( - `[16,"Request had invalid authentication credentials."]`, - )) - if driveAuthorizationMissing(err) { - t.Fatalf("login error classified as Drive authorization: %+v", err) - } - }) - - t.Run("different scope", func(t *testing.T) { - for _, err := range []*RPCError{ - {Method: "GenerateContent", StatusCode: http.StatusUnauthorized, Code: 16, Message: "OAuth error: unauthorized_client."}, - {Method: "GenerateAccessToken", StatusCode: http.StatusForbidden, Code: 16, Message: "OAuth error: unauthorized_client."}, - } { - if driveAuthorizationMissing(err) { - t.Fatalf("unrelated error classified as Drive authorization: %+v", err) - } - } - }) -} - -// TestEncodeContentsEmptyPartsFilter 验证多轮历史中空 parts 内容被自动忽略而不触发编码校验失败 -func TestEncodeContentsEmptyPartsFilter(t *testing.T) { - contents := []Content{ - {Role: RoleUser, Parts: []Part{{Text: "hello"}}}, - {Role: RoleAssistant, Parts: nil}, - {Role: RoleAssistant, Parts: []Part{}}, - {Role: RoleUser, Parts: []Part{{Text: "world"}}}, - } - wire, err := encodeContents(contents) - if err != nil { - t.Fatalf("encodeContents failed: %v", err) - } - if len(wire) != 2 { - t.Fatalf("expected 2 valid wire contents, got %d: %#v", len(wire), wire) - } -} +import "testing" // TestAttachYouTubeMediaPreservesText 验证普通文本与非空白字符在附加 YouTube 媒体时不被截断为空 func TestAttachYouTubeMediaPreservesText(t *testing.T) { @@ -204,70 +51,3 @@ func TestAttachYouTubeMediaVideoIDs(t *testing.T) { } } } - -// TestFunctionResultNameInference 验证工具结果的唯一关联与原始输入保留,关联不到调用的结果以 functionResponse 文本转录发送 -func TestFunctionResultNameInference(t *testing.T) { - call := func(id, name string) Part { - return Part{FunctionCall: &FunctionCall{ID: id, Name: name, Arguments: json.RawMessage(`{}`)}} - } - result := func(id string) Part { - return Part{FunctionResult: &FunctionResult{ID: id, Content: json.RawMessage(`{"ok":true}`)}} - } - for _, test := range []struct { - name string - contents []Content - want string - }{ - {"matching id", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup"), call("two", "weather")}}, {Role: RoleTool, Parts: []Part{result("one")}}}, "lookup"}, - {"unique mismatched id", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup")}}, {Role: RoleTool, Parts: []Part{result("opaque-id")}}}, "lookup"}, - {"missing id", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup")}}, {Role: RoleTool, Parts: []Part{result("")}}}, "lookup"}, - {"remaining call", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup"), call("two", "weather")}}, {Role: RoleTool, Parts: []Part{result("one")}}, {Role: RoleTool, Parts: []Part{result("opaque-id")}}}, "weather"}, - {"split calls", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup")}}, {Role: RoleAssistant, Parts: []Part{call("two", "weather")}}, {Role: RoleTool, Parts: []Part{result("two")}}, {Role: RoleTool, Parts: []Part{result("one")}}}, "lookup"}, - {"consumed call", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup")}}, {Role: RoleTool, Parts: []Part{result("one")}}, {Role: RoleTool, Parts: []Part{result("call_other")}}}, ""}, - {"user result", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup")}}, {Role: RoleUser, Parts: []Part{result("one")}}}, "lookup"}, - {"ambiguous id", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup"), call("two", "weather")}}, {Role: RoleTool, Parts: []Part{result("call_other")}}}, ""}, - {"orphan id", []Content{{Role: RoleTool, Parts: []Part{result("opaque-id")}}}, ""}, - {"closed turn", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup")}}, {Role: RoleTool, Parts: []Part{result("one")}}, {Role: RoleAssistant, Parts: []Part{{Text: "done"}}}, {Role: RoleTool, Parts: []Part{result("call_other")}}}, ""}, - {"new turn", []Content{{Role: RoleAssistant, Parts: []Part{call("one", "lookup")}}, {Role: RoleUser, Parts: []Part{{Text: "new question"}}}, {Role: RoleTool, Parts: []Part{result("call_other")}}}, ""}, - } { - t.Run(test.name, func(t *testing.T) { - wire, err := encodeContents(test.contents) - if err != nil { - t.Fatal(err) - } - part := wire[len(wire)-1].([]any)[0].([]any)[0].([]any) - if test.want == "" { - text, _ := part[1].(string) - if len(part) > 11 || !strings.HasPrefix(text, `{"functionResponse":`) { - t.Fatalf("unresolved result part=%#v", part) - } - } else if last := part[11].([]any); last[0] != test.want { - t.Fatalf("name=%v want=%s", last[0], test.want) - } - if test.contents[len(test.contents)-1].Parts[0].FunctionResult.Name != "" { - t.Fatal("input mutated") - } - }) - } -} - -// TestPlanLimitQuotaCooldown 验证上游以 usage limit 拒绝且没有给出恢复时间时按套餐限额从 1 分钟递增到 60 分钟冷却 -func TestPlanLimitQuotaCooldown(t *testing.T) { - now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) - err := &RPCError{Method: "GenerateContent", StatusCode: http.StatusTooManyRequests, Code: 8, Message: "You've reached your usage limit. Please try again later."} - cooldown, ok := QuotaCooldownForError(err, now) - if !ok || cooldown.Kind != PlanLimitKind || !cooldown.Escalate || !RequestQuotaCooldown(cooldown.Reason) { - t.Fatalf("cooldown=%+v ok=%v", cooldown, ok) - } - var state CooldownState - exists := false - current := now - for _, want := range []time.Duration{time.Minute, 5 * time.Minute, 15 * time.Minute, 30 * time.Minute, time.Hour} { - state = planLimitCooldown(state, exists, current, cooldown.Reason) - exists = true - if got := state.Until.Sub(current); got != want { - t.Fatalf("backoff=%s want=%s state=%+v", got, want, state) - } - current = state.Until - } -} diff --git a/internal/aistudio/generate.go b/internal/aistudio/generate.go index cf5e61ad..50a64ca6 100644 --- a/internal/aistudio/generate.go +++ b/internal/aistudio/generate.go @@ -768,7 +768,7 @@ func validateGenerateEntry(request GenerateRequest, entry modelEntry) error { if err := validateTranscriptionConfig(request.Config.TranscriptionConfig, entry.model); err != nil { return fmt.Errorf("%w: %v", ErrInvalidArgument, err) } - if stream, task := interactionRoute(entry.model, entry.defaults, ChannelPlayground); stream || task { + if interactionRouting(entry.model, entry.defaults, ChannelPlayground).IsInteraction() { return nil } if _, err := encodeGenerationConfig(applyModelMediaDefaults(request.Config, entry.model), entry.defaults); err != nil { @@ -797,7 +797,7 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan if build { channel = ChannelBuild } - interaction, task := interactionRoute(entry.model, entry.defaults, channel) + route := interactionRouting(entry.model, entry.defaults, channel) apiKey, _ := ctx.Value(apiKeyContextKey{}).(string) assistant := entry.model.Capabilities["assistant_route"] if chineseRewriteEligible(request, entry) { @@ -809,11 +809,15 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan if thinkingGuardEligible(request, entry) { request = applyThinkingGuard(request, entry) } - restoring := request.restoreModelTurns && !build && !assistant && !interaction && !task - if restoring { - var tip turnLink - request.Contents, request.turnToken, tip = c.turns.restore(apiKey, request.Contents) - request.turnChain = turnChain{contents: request.Contents, tip: tip} + restoring := request.restoreModelTurns && !build && !assistant && !route.IsAgent() + if restoring && c.turns != nil { + if !route.IsInteraction() { + var tip turnLink + request.Contents, request.turnToken, tip = c.turns.restore(apiKey, request.Contents) + request.turnChain = turnChain{contents: request.Contents, tip: tip} + } else { + request.turnChain = turnChain{contents: request.Contents, tip: turnChain{}.tipOf(request.Contents)} + } } if err := validateVideoParts(request.Contents); err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err) @@ -828,14 +832,16 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err) } } - if interaction { + if route.IsStream() && entry.defaults.VideoOutput { request.Tools = Tools{} } - request, contract, err := prepareToolRequest(request, true) + useReplyTool := !route.IsInteraction() && replyToolEligible(request, entry, build, assistant) + request, contract, err := prepareToolRequestWithReplyTool(request, true, useReplyTool) if err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err) } - if !interaction && !task && replyToolEligible(request, entry, build, assistant) { + reportReplyToolActive(ctx, useReplyTool) + if useReplyTool { request = applyReplyTool(request) if contract == nil { contract = &toolContract{} @@ -852,11 +858,19 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan return nil, err } } - if interaction { - return c.generateInteraction(ctx, request, entry) + if route.IsStream() { + events, err := c.generateInteraction(ctx, request, entry, route, apiKey, restoring) + if err != nil { + return nil, err + } + return contract.forward(ctx, events), nil } - if task { - return c.generateInteractionTask(ctx, request, entry) + if route.IsTask() { + events, err := c.generateInteractionTask(ctx, request, entry, route, apiKey, restoring) + if err != nil { + return nil, err + } + return contract.forward(ctx, events), nil } request.Config = applyModelMediaDefaults(request.Config, entry.model) request.ImageRoute = entry.defaults.ImageRoute @@ -931,6 +945,15 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan held = nil return nil } + // roundParts 记录当前上游回合收到的未合并 Part,用于回复工具在 more=true 提前收尾时自动构造续接轮 + var roundParts []Part + var replyStopMatcher *stopSequenceMatcher + replyStopMatched := false + replyHasFinalText := false + replyLastEndedNewline := false + if useReplyTool && len(request.Config.StopSequences) > 0 { + replyStopMatcher = newStopSequenceMatcher(request.Config.StopSequences) + } matchedStopSequence := "" emitEvent := func(event Event) error { turn.turnToken = cmp.Or(event.TurnToken, turn.turnToken) @@ -951,8 +974,26 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan } if !hiddenTool || !serverToolReplayable(event) { output.Add(event) - if restoring && event.HasContent() { - turn.parts = append(turn.parts, clonePart(event.Part)) + if event.HasContent() { + if restoring { + turn.parts = append(turn.parts, clonePart(event.Part)) + } + if useReplyTool { + roundParts = append(roundParts, clonePart(event.Part)) + } + } + if replyStopMatcher != nil && !replyStopMatched && event.Kind == EventToolCall && event.FunctionCall != nil && isReplyToolName(event.FunctionCall.Name) { + if text, _, ok := replyToolCallArgs(event.FunctionCall.Arguments); ok && text != "" { + chunk := text + if replyHasFinalText && !replyLastEndedNewline && !strings.HasPrefix(text, "\n") && !strings.HasPrefix(text, "\r") { + chunk = "\n\n" + text + } + replyHasFinalText = true + replyLastEndedNewline = strings.HasSuffix(text, "\n") || strings.HasSuffix(text, "\r") + if _, seq := replyStopMatcher.write(chunk); seq != "" { + replyStopMatched = true + } + } } committed = committed || !event.Thought && event.payload() } @@ -999,7 +1040,11 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan } stopClose() _ = response.Body.Close() - usage, finish, held, turn, roundUsage, output = nil, nil, nil, modelTurn{}, nil, Output{} + usage, finish, held, turn, roundUsage, output, roundParts = nil, nil, nil, modelTurn{}, nil, Output{}, nil + replyStopMatched, replyHasFinalText, replyLastEndedNewline = false, false, false + if useReplyTool && len(request.Config.StopSequences) > 0 { + replyStopMatcher = newStopSequenceMatcher(request.Config.StopSequences) + } if response, decodeStream, err = sendRequest(); err != nil { if ctx.Err() == nil { _ = send(Event{Kind: EventError, Err: err}) @@ -1010,16 +1055,74 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan matcher = newStopSequenceMatcher(request.Config.StopSequences) err = decodeStream(observeStreamActivity(ctx, response.Body), roundEmit()) } - if errors.Is(err, errStopSequenceMatched) { + // 模型在回复工具开启时若发出 final(more=true) 后即结束回合(期待工具返回),自动回传 functionResponse 续接剩余段落 + replyContinued := false + for replyRound := 0; useReplyTool && !build && !assistant && replyRound < maxReplyToolContinuationRounds && ctx.Err() == nil && err == nil && finish != nil && finish.FinishReason == "stop" && !replyStopMatched; replyRound++ { + results, ok := replyToolContinuationResults(roundParts) + if !ok { + break + } + replyContinued = true + reportReplyToolContinuation(ctx) + stopClose() _ = response.Body.Close() + prevUsage := cmp.Or(usage, roundUsage) + wireRequest.Contents = append(slices.Clip(wireRequest.Contents), + Content{Role: RoleAssistant, Parts: roundParts}, + Content{Role: RoleUser, Parts: results}, + ) + wireRequest.continuationProof = "" + wireRequest.continuationToken = "" + wireRequest.continuationRound = 0 + wireRequest.turnToken = "" + usage, finish, roundUsage, roundParts = nil, nil, nil, nil + response, decodeStream, err = sendRequest() + for err != nil && retryableAccountError(err) { + accounts, ok := accountCtx.Value(continuationAccountsKey{}).(ContinuationAccounts) + if !ok { + break + } + next, switchErr := accounts(accountCtx, err) + if switchErr != nil { + if !errors.Is(switchErr, ErrNoEligibleAccount) { + err = errors.Join(err, switchErr) + } + break + } + lease, _ := AccountLeaseFromContext(next) + switched(next, lease.Account().ID) + response, decodeStream, err = sendRequest() + } + if err != nil { + stopClose = func() bool { return false } + usage = prevUsage + break + } + stopClose = closeOnCancel(response) + err = decodeStream(observeStreamActivity(ctx, response.Body), roundEmit()) + if prevUsage != nil { + if current := cmp.Or(usage, roundUsage); current != nil { + merged := mergeContinuedUsage(*prevUsage, *current) + usage = &merged + } else { + usage = prevUsage + } + } + } + if errors.Is(err, errStopSequenceMatched) { + if response != nil && response.Body != nil { + _ = response.Body.Close() + } if releaseHeld() != nil { return } finishAtStopSequence(ctx, request, output, stopTokenCount, matchedStopSequence, send) return } - if closeErr := response.Body.Close(); err == nil { - err = closeErr + if response != nil && response.Body != nil { + if closeErr := response.Body.Close(); err == nil { + err = closeErr + } } if ctx.Err() == nil && matcher != nil { if pending := matcher.flush(); pending != "" { @@ -1034,17 +1137,18 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan err = &ContentPolicyError{Reason: feedback.Reason, Message: feedback.Message} usage = cmp.Or(usage, feedback.Usage) } - // trailing 是上游在函数调用之后结束生成的错误,客户端已收到完整的函数调用,按正常完成结束 + // trailing 是上游在首轮函数调用之后结束生成的错误,客户端已收到完整的函数调用,按正常完成结束; + // 回复工具自动续接轮中出错或遇内容策略时不吞错,交由下方流中错误路径写明原因结束。 var trailing error switch { case ctx.Err() != nil: - case err != nil && calledFunction(output): + case err != nil && !replyContinued && calledFunction(output): trailing, err = err, nil finish = &Event{Kind: EventFinish, FinishReason: "stop"} if usage == nil { usage = roundUsage } - case finish != nil && contentPolicyFinish(finish.FinishReason) && calledFunction(output): + case finish != nil && !replyContinued && contentPolicyFinish(finish.FinishReason) && calledFunction(output): trailing = &ContentPolicyError{Reason: finish.FinishReason, Message: finish.FinishMessage} finish.FinishReason, finish.FinishMessage = "stop", "" } diff --git a/internal/aistudio/hidden_models.go b/internal/aistudio/hidden_models.go index c994751c..1e4838f3 100644 --- a/internal/aistudio/hidden_models.go +++ b/internal/aistudio/hidden_models.go @@ -179,3 +179,60 @@ func (catalog modelCatalog) withHidden(hidden map[string]string) modelCatalog { catalog.models, catalog.entries = models, entries return catalog } + +// withoutHidden 返回去掉官网隐藏模型后的目录副本 +func (catalog modelCatalog) withoutHidden() modelCatalog { + if !slices.ContainsFunc(catalog.models, func(model Model) bool { return model.Hidden }) { + return catalog + } + models := make([]Model, 0, len(catalog.models)) + entries := make(map[string]modelEntry, len(catalog.entries)) + for _, model := range catalog.models { + if model.Hidden { + continue + } + models = append(models, model) + if entry, ok := catalog.entries[model.ID]; ok { + entries[model.ID] = entry + } + } + catalog.models, catalog.entries = models, entries + return catalog +} + +// ClearHiddenModels 从账户当前内存目录中移除官网隐藏模型 +func (c *Client) ClearHiddenModels(accountID string) { + c.catalogMu.Lock() + if catalog, ok := c.catalogs[accountID]; ok { + c.catalogs[accountID] = catalog.withoutHidden() + } + c.catalogMu.Unlock() +} + +// ClearHiddenModels 从全部账户的内存目录与隐藏模型记录中移除官网隐藏模型,返回发生变化的账户 ID +func (p *AccountPool) ClearHiddenModels() []string { + p.mu.Lock() + defer p.mu.Unlock() + var changed []string + for _, account := range p.accounts { + hasHidden := len(account.hiddenModels) > 0 || account.hiddenDiscovered || + slices.ContainsFunc(account.Models, func(model Model) bool { return model.Hidden }) + if !hasHidden { + continue + } + filtered := make([]Model, 0, len(account.Models)) + for _, model := range account.Models { + if !model.Hidden { + filtered = append(filtered, model) + } + } + account.Models = filtered + account.hiddenModels = nil + account.hiddenDiscovered = false + changed = append(changed, account.ID) + } + if len(changed) > 0 { + p.notifyLocked() + } + return changed +} diff --git a/internal/aistudio/interaction.go b/internal/aistudio/interaction.go index 71c91b6e..ff5e9a4a 100644 --- a/internal/aistudio/interaction.go +++ b/internal/aistudio/interaction.go @@ -1,6 +1,7 @@ package aistudio import ( + "cmp" "context" "encoding/base64" "encoding/json" @@ -15,8 +16,8 @@ import ( "time" ) -// interactionThinkingLevels 把 GenerateContent thinking level 换算为 Interaction 枚举 -var interactionThinkingLevels = map[int64]int64{4: 1, 1: 2, 2: 3, 3: 4} +// interactionThinkingLevels 把 GenerateContent thinking level 换算为 Interaction 枚举,含 extra_high(5) +var interactionThinkingLevels = map[int64]int64{4: 1, 1: 2, 2: 3, 3: 4, 5: 5} // interactionCancelTimeout 是取消后台任务的期限,包含等待账户请求槽位的时间 const interactionCancelTimeout = time.Minute @@ -39,7 +40,7 @@ func interactionImageCode(mime string) (int64, bool) { return 0, false } -// InteractionInlineMIME 表示该 MIME 的附件经 CreateInteractionStream 与官网一样以内联数据发送,范围为图片枚举表中的类型 +// InteractionInlineMIME 表示该 MIME 的附件经 Interaction 模型路径与官网一样以内联数据发送,范围为图片枚举表中的类型 func InteractionInlineMIME(mime string) bool { _, ok := interactionImageCode(mime) return ok @@ -58,68 +59,341 @@ var interactionStatusHTTP = map[int64]int{ 14: http.StatusServiceUnavailable, 16: http.StatusUnauthorized, } +// interactionVideoAspectRatios 是 Interaction 视频输出格式的宽高比枚举 +var interactionVideoAspectRatios = map[string]int64{"16:9": 1, "9:16": 2} + +// interactionVideoResolutions 是 Interaction 视频输出格式的分辨率枚举 +var interactionVideoResolutions = map[string]int64{"360p": 1, "720p": 2, "1080p": 3, "4k": 4} + +// interactionVideoTasks 是 Interaction 视频任务枚举,名称取 Interactions API video_config.task +var interactionVideoTasks = map[string]int64{"text_to_video": 1, "image_to_video": 2, "reference_to_video": 3, "edit": 4, "extend": 5} + +// thinkingLevelCode 把目录中保存的思考档位名称换算回 ListModels 数值码 +func thinkingLevelCode(name string) int64 { + for code, label := range buildThinkingLevels { + if strings.EqualFold(label, strings.TrimSpace(name)) { + return code + } + } + return 0 +} + +// modelGenerationDefaults 从 Model 还原 Interaction 编码所需的生成默认值 +func modelGenerationDefaults(model Model) GenerationDefaults { + defaults := GenerationDefaults{ + MaxOutputTokens: model.OutputTokenLimit, + Temperature: model.Temperature, + TopP: model.TopP, + TopK: model.TopK, + Thinking: model.Capabilities["thinking"], + ThinkingBudget: model.Capabilities["thinking_budget"], + ThinkingLevel: model.Capabilities["thinking_level"], + DefaultThinkingLevel: 2, + ImageRoute: model.Capabilities["image_route"], + OutputResolution: model.Capabilities["output_resolution"], + InteractionStream: model.Capabilities["interaction_stream"], + InteractionTask: model.Capabilities["interaction_task"], + InteractionAgent: model.Capabilities["interaction_agent"], + InteractionModel: model.Capabilities["interaction_model"], + VideoOutput: model.Capabilities["secondary_capability_code_14"] && model.Capabilities["chat_model"], + } + if code := thinkingLevelCode(model.DefaultThinkingLevel); code > 0 { + defaults.DefaultThinkingLevel = code + } + for _, name := range model.ThinkingLevels { + if code := thinkingLevelCode(name); code > 0 { + defaults.ThinkingLevels = append(defaults.ThinkingLevels, code) + } + } + if resolutions := model.CapabilityOptions["video_output_resolutions"]; len(resolutions) > 0 { + defaults.VideoResolution = resolutions[0] + } + return defaults +} + // EncodeCreateInteractionStreamRequest 编码官网 CreateInteractionStream 请求并返回参与 WAA 绑定的文本内容 func EncodeCreateInteractionStreamRequest(request GenerateRequest, defaults GenerationDefaults) ([]byte, int, []Content, error) { - steps, binding, hasModelTurn, err := encodeInteractionSteps(request.Contents) + capabilities := map[string]bool{} + if defaults.VideoOutput || defaults.VideoResolution != "" { + capabilities["secondary_capability_code_14"] = true + capabilities["chat_model"] = true + } + if defaults.Thinking { + capabilities["thinking"] = true + } + if defaults.ThinkingLevel { + capabilities["thinking_level"] = true + } + model := Model{ + ID: strings.TrimPrefix(strings.TrimSpace(request.Model), "models/"), + OutputTokenLimit: defaults.MaxOutputTokens, + Temperature: defaults.Temperature, + TopP: defaults.TopP, + TopK: defaults.TopK, + Capabilities: capabilities, + } + route := interactionRouting(model, defaults, ChannelPlayground) + if !route.IsStream() { + kind := int64(2) + if route.IsAgent() { + kind = 1 + } + route = ResolveInteractionRouting(kind, false) + } + return encodeInteractionRequest(request, model, defaults, route) +} + +// EncodeCreateInteractionRequest 编码官网 CreateInteraction 请求并返回参与 WAA 绑定的内容,按 field 79 选路写入模型目标(field 18)或 agent 目标(field 19) +func EncodeCreateInteractionRequest(request GenerateRequest, model Model) ([]byte, int, []Content, error) { + defaults := modelGenerationDefaults(model) + route := interactionRouting(model, defaults, ChannelPlayground) + if !route.IsTask() { + kind := int64(1) + if route.IsModel() { + kind = 2 + } + route = ResolveInteractionRouting(kind, true) + } + return encodeInteractionRequest(request, model, defaults, route) +} + +// encodeInteractionRequest 统一编码 CreateInteractionStream 与 CreateInteraction 请求:按 route.Target 选择模型(field 18)或 agent(field 19),按 route.Method 选择流式或后台信封 +func encodeInteractionRequest(request GenerateRequest, model Model, defaults GenerationDefaults, route InteractionRouting) ([]byte, int, []Content, error) { + streamFlag, taskFlag := any(nil), any(int64(1)) + if route.IsStream() { + streamFlag, taskFlag = int64(1), nil + } + if route.IsAgent() { + interaction, binding, err := encodeAgentInteraction(request, model) + if err != nil { + return nil, 0, nil, err + } + body, proofAt, _ := marshalWAAArray([]any{streamFlag, int64(1), taskFlag, interaction, nil, int64(1)}, 5) + return body, proofAt, binding, nil + } + interaction, binding, err := encodeModelInteraction(request, model, defaults) if err != nil { return nil, 0, nil, err } - level, err := interactionThinkingLevel(request.Config, defaults) + body, proofAt, _ := marshalWAAArray([]any{streamFlag, int64(1), taskFlag, interaction, nil, int64(1)}, 5) + return body, proofAt, binding, nil +} + +// encodeModelInteraction 编码 field 79 kind == 2 模型目标的 Interaction 正文(写入 field 18,保留多轮历史,仅视频输出聊天模型发送 field 54 与 config[24]) +func encodeModelInteraction(request GenerateRequest, model Model, defaults GenerationDefaults) ([]any, []Content, error) { + if request.AgentConfig != nil { + return nil, nil, fmt.Errorf("模型 %s 不接受 agent_config", request.Model) + } + contents := request.Contents + if request.PreviousInteractionID != "" { + // 续接上游 interaction 时与官网 oLb 一样只发送最后一个模型轮之后的新输入与工具结果 + contents = AgentInput(request.Contents, true) + } + nativeTools := model.Capabilities["function_declarations"] + steps, binding, hasModelTurn, err := encodeInteractionSteps(contents, nativeTools) if err != nil { - return nil, 0, nil, err + return nil, nil, err } - maxOutput := defaults.MaxOutputTokens - if request.Config.MaxOutputTokens != nil { - maxOutput = *request.Config.MaxOutputTokens + level, err := interactionThinkingLevel(request.Config, defaults) + if err != nil { + return nil, nil, err } - if maxOutput > defaults.MaxOutputTokens { + var maxOutput int64 + if defaults.MaxOutputTokens > 0 || request.Config.MaxOutputTokens != nil { maxOutput = defaults.MaxOutputTokens + if request.Config.MaxOutputTokens != nil { + maxOutput = *request.Config.MaxOutputTokens + } + if defaults.MaxOutputTokens > 0 && maxOutput > defaults.MaxOutputTokens { + maxOutput = defaults.MaxOutputTokens + } + if maxOutput <= 0 { + return nil, nil, fmt.Errorf("max output tokens %d 超出模型范围 1-%d", maxOutput, defaults.MaxOutputTokens) + } } - if maxOutput <= 0 { - return nil, 0, nil, fmt.Errorf("max output tokens %d 超出模型范围 1-%d", maxOutput, defaults.MaxOutputTokens) + isVideo := defaults.VideoOutput || defaults.VideoResolution != "" || (model.Capabilities["secondary_capability_code_14"] && model.Capabilities["chat_model"]) + var video []any + var task int64 + if isVideo { + video, task, err = interactionVideoFormat(request.Config.VideoConfig, defaults.VideoResolution) + if err != nil { + return nil, nil, err + } } - video, task, err := interactionVideoFormat(request.Config.VideoConfig, defaults.VideoResolution) - if err != nil { - return nil, 0, nil, err + // GenerationConfig (JZa):按官网 sLb/NMb 门控温度、topP、seed、思考档位、思考摘要、输出上限、图像与视频任务 + config := make([]any, 25) + if model.Capabilities["capability_code_62"] { + if temperature := cmp.Or(request.Config.Temperature, defaults.Temperature); temperature != nil { + if *temperature < 0 || *temperature > 2 { + return nil, nil, fmt.Errorf("temperature 必须在 0 到 2 之间") + } + config[0] = *temperature + } + } + if model.Capabilities["capability_code_23"] { + if topP := cmp.Or(request.Config.TopP, defaults.TopP); topP != nil { + if *topP < 0 || *topP > 1 { + return nil, nil, fmt.Errorf("top_p 必须在 0 到 1 之间") + } + config[1] = *topP + } + } + if request.Config.Seed != nil { + config[2] = *request.Config.Seed } - // GenerationConfig:field 6 thinking level、field 7 thinking summaries、field 8 max output tokens、field 25 视频任务 - config := make([]any, 8) if level != 0 { config[5] = level } - config[6] = int64(1) - config[7] = maxOutput - if !hasModelTurn || task != 0 { - config = append(config, make([]any, 17)...) + if defaults.Thinking || defaults.ThinkingLevel || len(defaults.ThinkingLevels) > 0 { + config[6] = int64(1) + } + if maxOutput > 0 { + config[7] = maxOutput + } + if image := request.Config.ImageConfig; image != nil { + aspect := "" + if model.Capabilities["aspect_ratio"] && !isVideo { + aspect = strings.TrimSpace(image.AspectRatio) + } + resolution := "" + if model.Capabilities["output_resolution"] { + resolution = strings.TrimSpace(image.ImageSize) + } + if aspect != "" || resolution != "" { + config[12] = trimWireNil([]any{emptyNil(aspect), emptyNil(resolution)}) + } + } + if isVideo && (!hasModelTurn || task != 0) { config[24] = []any{} if task != 0 { config[24] = []any{task} } } + config = trimWireNil(config) + + system := request.System + responseMIME := strings.TrimSpace(request.Config.ResponseMIMEType) + if schema := request.Config.responseSchema(); len(schema) > 0 { + if _, err := encodeResponseSchema(schema); err != nil { + return nil, nil, fmt.Errorf("response schema: %w", err) + } + system = append(slices.Clone(system), describedSchema("", schema)) + if responseMIME == "" { + responseMIME = "application/json" + } + } + var tools []any + if !isVideo && request.Tools.ToolConfig.Mode != "none" { + tools, err = interactionTools(request.Tools, model, false) + if err != nil { + return nil, nil, err + } + } + var modalities []int64 + if len(request.Config.ResponseModalities) > 0 { + modalities, err = encodeResponseModalities(request.Config.ResponseModalities) + if err != nil { + return nil, nil, err + } + } + interaction := make([]any, 54) - if system := strings.TrimSpace(SystemText(request.System)); system != "" { - interaction[6] = system + if text := strings.TrimSpace(SystemText(system)); text != "" { + interaction[6] = text + } + if len(tools) > 0 { + interaction[7] = tools + } + if len(modalities) > 0 { + interaction[13] = modalities + } + if responseMIME != "" { + interaction[15] = responseMIME + } + if request.PreviousInteractionID != "" { + interaction[16] = request.PreviousInteractionID } - interaction[17] = []any{wireModelName(request.Model), config} + target := []any{wireModelName(request.Model)} + if len(config) > 0 { + target = append(target, config) + } + interaction[17] = target interaction[26] = []any{steps} - // field 54 输出格式:视频格式 field 4 宽高比、field 5 时长、field 6 分辨率,编辑任务不带输出格式 - if task == interactionVideoTasks["edit"] { - interaction = interaction[:27] - } else { + // field 54 输出格式:官网仅对视频输出聊天模型(_.rl)且非编辑任务发送,其余模型截止到索引 26 + if isVideo && task != interactionVideoTasks["edit"] && interactionVideoFormatNonEmpty(video) { interaction[53] = []any{[]any{[]any{nil, nil, nil, video}}} + } else { + interaction = interaction[:27] } - body, proofAt, _ := marshalWAAArray([]any{int64(1), int64(1), nil, interaction, nil, int64(1)}, 5) - return body, proofAt, binding, nil + return interaction, binding, nil } -// interactionVideoAspectRatios 是 CreateInteractionStream 视频输出格式的宽高比枚举 -var interactionVideoAspectRatios = map[string]int64{"16:9": 1, "9:16": 2} - -// interactionVideoResolutions 是 CreateInteractionStream 视频输出格式的分辨率枚举 -var interactionVideoResolutions = map[string]int64{"360p": 1, "720p": 2, "1080p": 3, "4k": 4} +// encodeAgentInteraction 编码 field 79 kind == 1 agent 目标的 Interaction 正文(写入 field 19) +func encodeAgentInteraction(request GenerateRequest, model Model) ([]any, []Content, error) { + agent := strings.TrimPrefix(strings.TrimSpace(request.Model), "models/") + // kind 是该 agent 的 agent_config 类型:带默认模型的 agent 为 antigravity,其余为 deep-research + kind := "deep-research" + if model.AgentModel != "" { + kind = "antigravity" + } + if config := request.AgentConfig; config != nil && config.Type != kind { + return nil, nil, fmt.Errorf("agent_config.type %q 与 agent %s 不匹配,应为 %q", config.Type, agent, kind) + } + steps, binding, _, err := encodeInteractionSteps(AgentInput(request.Contents, request.PreviousInteractionID != ""), false) + if err != nil { + return nil, nil, err + } + tools, err := interactionTools(request.Tools, model, true) + if err != nil { + return nil, nil, err + } + interaction := make([]any, 27) + if system := strings.TrimSpace(SystemText(request.System)); system != "" { + interaction[6] = system + } + if len(tools) > 0 { + interaction[7] = tools + } + // field 17 为续接的上一轮 interaction ID + if request.PreviousInteractionID != "" { + interaction[16] = request.PreviousInteractionID + } + // field 19 为 agent 目标:field 1 agent 名称,Deep Research 的 field 3 为 agent 配置 + target := []any{agent, nil, deepResearchConfig(request.AgentConfig)} + if model.AgentModel != "" { + // Antigravity:field 12 为所选模型与 token 上限 + target = target[:1] + if config := request.AgentConfig; config != nil && (config.Model != "" || config.MaxTotalTokens > 0) { + antigravity := make([]any, 7) + if config.Model != "" { + antigravity[0] = strings.TrimPrefix(config.Model, "models/") + } + if config.MaxTotalTokens > 0 { + antigravity[6] = config.MaxTotalTokens + } + target = append(target, make([]any, 11)...) + target[11] = antigravity + } + } + if request.Environment != nil || model.AgentModel != "" { + if err := setInteractionEnvironment(interaction, request.Environment); err != nil { + return nil, nil, err + } + } + interaction[18] = target + interaction[26] = []any{steps} + return interaction, binding, nil +} -// interactionVideoTasks 是 CreateInteractionStream 视频任务枚举,名称取 Interactions API video_config.task -var interactionVideoTasks = map[string]int64{"text_to_video": 1, "image_to_video": 2, "reference_to_video": 3, "edit": 4, "extend": 5} +// interactionVideoFormatNonEmpty 判断视频输出格式数组中是否至少有一项非空参数 +func interactionVideoFormatNonEmpty(format []any) bool { + for _, item := range format { + if item != nil { + return true + } + } + return false +} // interactionVideoFormat 编码视频输出格式并返回任务枚举:宽高比与分辨率取最接近的上游取值,未设置分辨率时取模型默认分辨率 func interactionVideoFormat(config *VideoConfig, resolution string) ([]any, int64, error) { @@ -160,52 +434,191 @@ func interactionVideoFormat(config *VideoConfig, resolution string) ([]any, int6 return format, task, nil } -// encodeInteractionSteps 把规范消息编码为用户 step field 1 与模型 step field 2 交替的 input steps -func encodeInteractionSteps(contents []Content) ([]any, []Content, bool, error) { - type step struct { - model bool - parts []any +// encodeInteractionSteps 把规范消息编码为 Interaction input steps(field 1 user、field 2 model、nativeTools 时支持 field 4 tool_call 与 field 5 tool_result),并返回参与 WAA 绑定的内容 +func encodeInteractionSteps(contents []Content, nativeTools bool) ([]any, []Content, bool, error) { + if !nativeTools { + var err error + contents, err = transcribeFunctionParts(contents) + if err != nil { + return nil, nil, false, fmt.Errorf("Interaction 模型的 %w", err) + } } - contents, err := transcribeFunctionParts(contents) - if err != nil { - return nil, nil, false, fmt.Errorf("Interaction 模型的 %w", err) + callNames := make(map[string]string) + if nativeTools { + for _, content := range contents { + for _, part := range content.Parts { + if part.FunctionCall != nil && part.FunctionCall.ID != "" { + callNames[part.FunctionCall.ID] = part.FunctionCall.Name + } + } + } } - steps := make([]step, 0, len(contents)) + wire := make([]any, 0, len(contents)) binding := make([]Content, 0, len(contents)) + hasModelTurn := false + var currentRole bool + var currentParts []any + var currentHasStep bool + flushText := func() { + if !currentHasStep || len(currentParts) == 0 { + currentHasStep = false + currentParts = nil + return + } + if currentRole { + wire = append(wire, []any{nil, []any{currentParts}}) + hasModelTurn = true + } else { + wire = append(wire, []any{[]any{currentParts}}) + } + currentHasStep = false + currentParts = nil + } + appendTextPart := func(model bool, part any) { + if currentHasStep && currentRole != model { + flushText() + } + currentRole = model + currentHasStep = true + currentParts = append(currentParts, part) + } var carried []any var carriedBinding []Part + // callSeq 为不带 ID 的调用生成序号,pendingCalls 与 pendingCodes 是尚未收到结果的函数调用与代码执行 + callSeq := 0 + type pendingCall struct{ id, name string } + var pendingCalls []pendingCall + var pendingCodes []string for index, content := range contents { if content.Role != RoleUser && content.Role != RoleAssistant && content.Role != RoleTool { return nil, nil, false, fmt.Errorf("Interaction 模型不接受 %s 消息", content.Role) } model := content.Role == RoleAssistant - parts := make([]any, 0, len(content.Parts)) bindingParts := make([]Part, 0, len(content.Parts)) + if !model && len(carried) > 0 { + for _, item := range carried { + appendTextPart(false, item) + } + bindingParts = append(bindingParts, carriedBinding...) + carried, carriedBinding = nil, nil + } + // signature 是本轮紧邻函数调用之前、只带思考签名的 Part 的签名,signed 表示本轮已写出签名步骤 + signature, signed := "", false for _, part := range content.Parts { + if part.Text == "" && part.ThoughtSignature != "" && part.InlineData == nil && part.File == nil && part.FunctionCall == nil && part.FunctionResult == nil && + part.ExecutableCode == nil && part.CodeExecutionResult == nil && part.ToolCall == nil && part.ToolResponse == nil { + signature = part.ThoughtSignature + continue + } + if part.Thought { + continue + } + pending := signature + signature = "" switch { - case part.VideoMetadata != nil || part.MediaProcessing != "" || part.ToolCall != nil || part.ToolResponse != nil: + case part.VideoMetadata != nil || part.MediaProcessing != "": return nil, nil, false, fmt.Errorf("Interaction 模型的 contents[%d] 不接受视频截取、采样、处理方式与处理步骤", index) - case part.Thought: - continue - case part.ExecutableCode != nil || part.CodeExecutionResult != nil: + case !nativeTools && (part.ToolCall != nil || part.ToolResponse != nil): + step := part.ToolCall + if step == nil { + step = part.ToolResponse + } + return nil, nil, false, fmt.Errorf("Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s", index, step.Type) + case nativeTools && part.FunctionCall != nil: + flushText() + // 函数调用历史之前写出思考步骤签名(Ww field 3 MZa field 1),本轮第一个调用没有签名时写跳过校验的占位签名 + sig := cmp.Or(part.ThoughtSignature, part.FunctionCall.ThoughtSignature, pending) + if sig == "" && !signed { + sig = "skip_thought_signature_validator" + } + if sig != "" { + wire = append(wire, []any{nil, nil, []any{sig}}) + signed = true + } + id := part.FunctionCall.ID + if id == "" { + callSeq++ + id = fmt.Sprintf("call_%d", callSeq) + } + pendingCalls = append(pendingCalls, pendingCall{id: id, name: part.FunctionCall.Name}) + step, err := encodeInteractionFunctionCall(part.FunctionCall, id) + if err != nil { + return nil, nil, false, fmt.Errorf("Interaction 模型的 contents[%d]: %w", index, err) + } + wire = append(wire, step) + hasModelTurn = true + case nativeTools && part.FunctionResult != nil: + flushText() + // 结果按显式 ID、同名的待完成调用或唯一的待完成调用沿用调用的 ID + id := part.FunctionResult.ID + match := slices.IndexFunc(pendingCalls, func(call pendingCall) bool { + return id != "" && call.id == id || id == "" && call.name == part.FunctionResult.Name + }) + if match < 0 && id == "" && len(pendingCalls) == 1 { + match = 0 + } + name := part.FunctionResult.Name + if match >= 0 { + id, name = pendingCalls[match].id, cmp.Or(name, pendingCalls[match].name) + pendingCalls = slices.Delete(pendingCalls, match, match+1) + } + if id == "" { + callSeq++ + id = fmt.Sprintf("call_%d", callSeq) + } + step, err := encodeInteractionFunctionResult(part.FunctionResult, id, cmp.Or(name, callNames[id])) + if err != nil { + return nil, nil, false, fmt.Errorf("Interaction 模型的 contents[%d]: %w", index, err) + } + wire = append(wire, step) + case nativeTools && part.ExecutableCode != nil: + flushText() + id := part.ExecutableCode.ID + if id == "" { + callSeq++ + id = fmt.Sprintf("code_%d", callSeq) + } + pendingCodes = append(pendingCodes, id) + wire = append(wire, encodeInteractionExecutableCode(part.ExecutableCode, id)) + hasModelTurn = true + case nativeTools && part.CodeExecutionResult != nil: + flushText() + id := part.CodeExecutionResult.ID + if match := slices.Index(pendingCodes, id); match >= 0 { + pendingCodes = slices.Delete(pendingCodes, match, match+1) + } else if id == "" && len(pendingCodes) > 0 { + id, pendingCodes = pendingCodes[0], pendingCodes[1:] + } + if id == "" { + callSeq++ + id = fmt.Sprintf("code_%d", callSeq) + } + wire = append(wire, encodeInteractionCodeResult(part.CodeExecutionResult, id)) + case nativeTools && part.ToolCall != nil && part.ToolCall.Type == "GOOGLE_SEARCH_WEB": + flushText() + wire = append(wire, encodeInteractionServerToolCall(part.ToolCall)) + hasModelTurn = true + case nativeTools && part.ToolResponse != nil && part.ToolResponse.Type == "GOOGLE_SEARCH_WEB": + flushText() + wire = append(wire, encodeInteractionServerToolResponse(part.ToolResponse)) + case part.ExecutableCode != nil || part.CodeExecutionResult != nil || part.ToolCall != nil || part.ToolResponse != nil: + // 官网现场确认不了写法的服务端工具步骤与不接受原生工具的模型的代码执行转录为文本 transcript, err := ToolPartTranscript(part) if err != nil { return nil, nil, false, fmt.Errorf("Interaction 模型的 contents[%d]: %w", index, err) } - parts = append(parts, []any{[]any{transcript}}) + appendTextPart(model, []any{[]any{transcript}}) bindingParts = append(bindingParts, Part{Text: transcript}) case part.Text != "" && part.InlineData == nil && part.File == nil: - parts = append(parts, []any{[]any{part.Text}}) + appendTextPart(model, []any{[]any{part.Text}}) bindingParts = append(bindingParts, Part{Text: part.Text}) - case part.Text == "" && part.ThoughtSignature != "" && part.InlineData == nil && part.File == nil: - continue case part.File != nil && strings.TrimSpace(part.File.ID) != "" && part.Text == "": // Content field 9 为 Drive 文件引用 file := []any{nil, nil, nil, nil, nil, nil, nil, nil, []any{strings.TrimSpace(part.File.ID)}} if model { carried = append(carried, file) } else { - parts = append(parts, file) + appendTextPart(false, file) } case part.InlineData != nil: code, ok := interactionImageCode(part.InlineData.MIME) @@ -218,42 +631,114 @@ func encodeInteractionSteps(contents []Content) ([]any, []Content, bool, error) carried = append(carried, media) carriedBinding = append(carriedBinding, Part{InlineData: part.InlineData}) } else { - parts = append(parts, media) + appendTextPart(false, media) bindingParts = append(bindingParts, Part{InlineData: part.InlineData}) } default: return nil, nil, false, fmt.Errorf("Interaction 模型的 contents[%d] 只接受文本、附件与工具 part", index) } } - if !model && len(carried) > 0 { - parts = append(carried, parts...) - bindingParts = append(carriedBinding, bindingParts...) - carried, carriedBinding = nil, nil - } - if len(parts) == 0 { - continue - } - if last := len(steps) - 1; last >= 0 && steps[last].model == model { - steps[last].parts = append(steps[last].parts, parts...) - } else { - steps = append(steps, step{model: model, parts: parts}) + if len(bindingParts) > 0 { + binding = append(binding, Content{Role: content.Role, Parts: bindingParts}) } - binding = append(binding, Content{Role: content.Role, Parts: bindingParts}) } - if len(steps) == 0 { + flushText() + if len(wire) == 0 { return nil, nil, false, fmt.Errorf("CreateInteractionStream contents 不能为空") } - wire := make([]any, 0, len(steps)) - hasModelTurn := false - for _, step := range steps { - if step.model { - wire = append(wire, []any{nil, []any{step.parts}}) - hasModelTurn = true + return wire, binding, hasModelTurn, nil +} + +// encodeInteractionFunctionCall 按官网 $qb 编码函数调用为 Ww field 4 (_.a_a field 3) +func encodeInteractionFunctionCall(call *FunctionCall, id string) ([]any, error) { + args := map[string]any{} + if trimmed := strings.TrimSpace(string(call.Arguments)); trimmed != "" { + if err := json.Unmarshal([]byte(trimmed), &args); err != nil { + return nil, fmt.Errorf("function call %q arguments: %w", call.Name, err) + } + } + fn := []any{wireFunctionName(call.Name), encodeWireStruct(args)} + return []any{nil, nil, nil, []any{id, nil, fn}}, nil +} + +// encodeInteractionFunctionResult 按官网 $qb 编码函数结果为 Ww field 5 (_.Pw field 3 _.Gw) +func encodeInteractionFunctionResult(result *FunctionResult, id string, name string) ([]any, error) { + if name != "" { + name = wireFunctionName(name) + } + gw := make([]any, 12) + if name != "" { + gw[1] = name + } + trimmed := strings.TrimSpace(string(result.Content)) + if trimmed == "" { + gw[9] = encodeWireStruct(map[string]any{}) + } else { + var parsed any + if err := json.Unmarshal([]byte(trimmed), &parsed); err == nil { + switch typed := parsed.(type) { + case map[string]any: + gw[9] = encodeWireStruct(typed) + case string: + gw[11] = typed + default: + gw[11] = trimmed + } } else { - wire = append(wire, []any{[]any{step.parts}}) + gw[11] = trimmed } } - return wire, binding, hasModelTurn, nil + return []any{nil, nil, nil, nil, []any{id, nil, trimWireNil(gw)}}, nil +} + +// encodeInteractionExecutableCode 按官网 $qb 编码代码执行为 Ww field 4 (_.a_a field 4) +func encodeInteractionExecutableCode(code *ExecutableCode, id string) []any { + lang := int64(0) + if strings.EqualFold(code.Language, "python") { + lang = 1 + } + return []any{nil, nil, nil, []any{id, nil, nil, []any{[]any{lang, code.Code}}}} +} + +// encodeInteractionCodeResult 按官网 $qb 编码代码执行结果为 Ww field 5 (_.Pw field 4) +func encodeInteractionCodeResult(result *CodeExecutionResult, id string) []any { + var isError any + if result.Outcome != "" && result.Outcome != "OUTCOME_OK" { + isError = true + } + return []any{nil, nil, nil, nil, []any{id, nil, nil, trimWireNil([]any{result.Output, isError})}} +} + +// encodeInteractionServerToolCall 按官网 $qb 编码 Google Search 服务端工具调用步骤 +func encodeInteractionServerToolCall(step *ServerToolStep) []any { + var data struct { + Queries []string `json:"queries"` + } + _ = json.Unmarshal(step.Data, &data) + queries := make([]any, 0, len(data.Queries)) + for _, query := range data.Queries { + queries = append(queries, query) + } + return []any{nil, nil, nil, []any{step.ID, nil, nil, nil, nil, nil, []any{[]any{queries}}}} +} + +// encodeInteractionServerToolResponse 按官网 $qb 编码 Google Search 服务端工具结果步骤 +func encodeInteractionServerToolResponse(step *ServerToolStep) []any { + var data struct { + SearchSuggestions string `json:"search_suggestions"` + Results []struct { + SearchSuggestions string `json:"search_suggestions"` + } `json:"results"` + } + _ = json.Unmarshal(step.Data, &data) + entries := make([]any, 0, len(data.Results)+1) + if data.SearchSuggestions != "" { + entries = append(entries, []any{nil, nil, nil, nil, data.SearchSuggestions}) + } + for _, item := range data.Results { + entries = append(entries, []any{nil, nil, nil, nil, item.SearchSuggestions}) + } + return []any{nil, nil, nil, nil, []any{step.ID, nil, nil, nil, nil, []any{entries}}} } // interactionThinkingLevel 按请求的思考强度或预算选择模型支持的 Interaction thinking level,模型没有思考档位能力时与官网一样不发送并返回 0 @@ -270,8 +755,10 @@ func interactionThinkingLevel(config GenerationConfig, defaults GenerationDefaul level = 1 case "medium": level = 2 - case "high", "xhigh", "extra_high", "max": + case "high": level = 3 + case "xhigh", "extra_high", "max": + level = 5 default: return 0, fmt.Errorf("reasoning effort 必须是 none、minimal、low、medium、high、xhigh、extra_high 或 max") } @@ -287,13 +774,13 @@ func interactionThinkingLevel(config GenerationConfig, defaults GenerationDefaul } // generateInteraction 经 CreateInteractionStream 生成并映射为规范事件 -func (c *Client) generateInteraction(ctx context.Context, request GenerateRequest, entry modelEntry) (<-chan Event, error) { +func (c *Client) generateInteraction(ctx context.Context, request GenerateRequest, entry modelEntry, route InteractionRouting, apiKey string, restoring bool) (<-chan Event, error) { reason := "" if request.Unary { reason = "该模型使用 CreateInteractionStream,收集完成后返回" } reportUpstreamMode(ctx, "CreateInteractionStream", "stream", 0, reason) - body, proofAt, binding, err := EncodeCreateInteractionStreamRequest(request, entry.defaults) + body, proofAt, binding, err := encodeInteractionRequest(request, entry.model, entry.defaults, route) if err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err) } @@ -310,18 +797,19 @@ func (c *Client) generateInteraction(ctx context.Context, request GenerateReques if err != nil { return nil, err } - return c.interactionEvents(ctx, request, entry, "CreateInteractionStream", response, nil) + return c.interactionEvents(ctx, request, entry, "CreateInteractionStream", response, nil, apiKey, restoring) } -// interactionTask 是 CreateInteraction 后台任务的上游 interaction ID、所属账户与取消任务的函数 +// interactionTask 是 CreateInteraction 后台任务的上游 interaction ID、所属账户、是否为 agent 目标与取消任务的函数 type interactionTask struct { id string account string + agent bool cancel func() } -// interactionEvents 解码 Interaction 流并映射为规范事件;task 为后台任务时结束事件带上 interaction ID 与账户,流在读到最终 interaction 之前因调用方取消而结束时取消任务 -func (c *Client) interactionEvents(ctx context.Context, request GenerateRequest, entry modelEntry, method string, response *RPCResponse, task *interactionTask) (<-chan Event, error) { +// interactionEvents 解码 Interaction 流并映射为规范事件;task 为后台 agent 任务时结束事件带上 interaction ID 与账户,流在读到最终 interaction 之前因调用方取消而结束时取消任务 +func (c *Client) interactionEvents(ctx context.Context, request GenerateRequest, entry modelEntry, method string, response *RPCResponse, task *interactionTask, apiKey string, restoring bool) (<-chan Event, error) { matcher := newStopSequenceMatcher(request.Config.StopSequences) var stopTokenCount <-chan tokenCountResult cancelTokenCount := context.CancelFunc(func() {}) @@ -338,19 +826,15 @@ func (c *Client) interactionEvents(ctx context.Context, request GenerateRequest, }) defer stopClose() committed := false - send := func(event Event) error { - if request.Config.HideThinking && event.Kind == EventReasoning { - if event.ThoughtSignature == "" { - return nil - } - event.Kind, event.Text = EventThoughtSignature, "" - } + var held []Event + var turn modelTurn + writeEvent := func(event Event) error { if !committed { committed = true ready <- nil } event.ProviderModel = entry.model.ID - if event.Kind == EventFinish && task != nil { + if event.Kind == EventFinish && task != nil && task.agent { event.InteractionID, event.AccountID = task.id, task.account } select { @@ -360,6 +844,43 @@ func (c *Client) interactionEvents(ctx context.Context, request GenerateRequest, return ctx.Err() } } + releaseHeld := func() error { + for _, event := range held { + if err := writeEvent(event); err != nil { + return err + } + } + held = nil + return nil + } + send := func(event Event) error { + hiddenTool := serverToolHidden(request, event) + if hiddenTool { + if event.ThoughtSignature == "" { + return nil + } + event = Event{Kind: EventThoughtSignature, Part: Part{ThoughtSignature: event.ThoughtSignature}} + } + if restoring && event.HasContent() { + turn.parts = append(turn.parts, clonePart(event.Part)) + } + if request.Config.HideThinking && event.Kind == EventReasoning { + if event.ThoughtSignature == "" { + return nil + } + event.Kind, event.Text = EventThoughtSignature, "" + } + if !committed && event.Kind == EventThoughtSignature { + held = append(held, event) + return nil + } + if len(held) > 0 { + if err := releaseHeld(); err != nil { + return err + } + } + return writeEvent(event) + } var output Output var usage *Event finished := false @@ -391,6 +912,7 @@ func (c *Client) interactionEvents(ctx context.Context, request GenerateRequest, if matcher != nil { emit = stopSequenceEmitter(matcher, forward, &matchedStopSequence) } + emit = restoreFunctionNames(request.Tools.Functions, emit) var err error defer func() { if !finished && task != nil && (ctx.Err() != nil || err != nil) { @@ -400,11 +922,17 @@ func (c *Client) interactionEvents(ctx context.Context, request GenerateRequest, err = DecodeInteractionStream(method, observeStreamActivity(ctx, response.Body), emit) if errors.Is(err, errStopSequenceMatched) { _ = response.Body.Close() - finishAtStopSequence(ctx, request, output, stopTokenCount, matchedStopSequence, send) + if len(held) > 0 { + _ = releaseHeld() + } + finishAtStopSequence(ctx, request, output, stopTokenCount, matchedStopSequence, writeEvent) err = ctx.Err() } else if closeErr := response.Body.Close(); err == nil && ctx.Err() == nil { err = closeErr } + if err == nil && finished && restoring && c.turns != nil { + c.turns.store(apiKey, request.turnChain.tip, turn) + } if err == nil || ctx.Err() != nil { if !committed { ready <- ctx.Err() @@ -415,7 +943,7 @@ func (c *Client) interactionEvents(ctx context.Context, request GenerateRequest, ready <- err return } - _ = send(Event{Kind: EventError, Err: err}) + _ = writeEvent(Event{Kind: EventError, Err: err}) }() select { case err := <-ready: @@ -430,11 +958,58 @@ func (c *Client) interactionEvents(ctx context.Context, request GenerateRequest, return events, nil } +// interactionStepState 保存流式解码中单个步骤的类型与增量缓冲 +type interactionStepState struct { + kind string + toolType string + callID string + funcName string + argsMap map[string]any + argsJSON strings.Builder + codeLang string + codeText strings.Builder + queries []string + emitted bool +} + +// interactionStreamDecoder 维护 Interaction 流式解码的步骤与签名状态 +type interactionStreamDecoder struct { + method string + steps map[int64]*interactionStepState + callSteps map[string]*interactionStepState + pendingSignature string +} + +// flushSignature 把暂存的思考签名作为独立 EventThoughtSignature 发出 +func (d *interactionStreamDecoder) flushSignature(emit func(Event) error) error { + if d.pendingSignature == "" { + return nil + } + sig := d.pendingSignature + d.pendingSignature = "" + return emit(Event{Kind: EventThoughtSignature, ThoughtSignature: sig}) +} + +// step 返回指定索引的步骤状态,不存在时按默认空步骤初始化 +func (d *interactionStreamDecoder) step(index int64) *interactionStepState { + step, ok := d.steps[index] + if !ok { + step = &interactionStepState{} + d.steps[index] = step + } + return step +} + // DecodeInteractionStream 按网络顺序解码 CreateInteractionStream 或 GetInteractionStream 的事件与流尾状态 func DecodeInteractionStream(method string, source io.Reader, emit func(Event) error) error { reader := &streamReadRecorder{source: source} decoder := json.NewDecoder(newSparseJSONReader(reader)) decoder.UseNumber() + state := &interactionStreamDecoder{ + method: method, + steps: make(map[int64]*interactionStepState), + callSteps: make(map[string]*interactionStepState), + } index := 0 fail := func(path string, detail string) error { return reader.failure(method, index, &ProtocolEvidenceError{Method: method, Path: path, Detail: detail}) @@ -454,7 +1029,7 @@ func DecodeInteractionStream(method string, source io.Reader, emit func(Event) e if err := decoder.Decode(&raw); err != nil { return fail(fmt.Sprintf("$[0][%d]", index), err.Error()) } - done, err := decodeInteractionEvent(method, raw, emit) + done, err := state.decodeEvent(raw, emit) if err != nil { return err } @@ -495,14 +1070,26 @@ func DecodeInteractionStream(method string, source io.Reader, emit func(Event) e return nil } -// decodeInteractionEvent 解码单个流事件,返回是否为最终 interaction -func decodeInteractionEvent(method string, raw json.RawMessage, emit func(Event) error) (bool, error) { +// decodeEvent 解码单个流事件(step_start、content_delta、step_end 与最终 interaction),返回是否为最终 interaction +func (d *interactionStreamDecoder) decodeEvent(raw json.RawMessage, emit func(Event) error) (bool, error) { event, err := rawArray(raw, "$event", raw) if err != nil { - return false, withMethod(err, method) + return false, withMethod(err, d.method) } - if delta := rawAt(event, 10); !isJSONNull(delta) { - return false, decodeInteractionDelta(method, delta, emit) + if start := rawAt(event, 9); !isJSONNull(start) { + if err := d.decodeStepStart(start, raw, emit); err != nil { + return false, err + } + } + if delta := rawAt(event, 10); !isJSONNull(delta) { + if err := d.decodeDelta(delta, raw, emit); err != nil { + return false, err + } + } + if end := rawAt(event, 11); !isJSONNull(end) { + if err := d.decodeStepEnd(end, raw, emit); err != nil { + return false, err + } } final := rawAt(event, 19) if isJSONNull(final) { @@ -513,27 +1100,38 @@ func decodeInteractionEvent(method string, raw json.RawMessage, emit func(Event) } wrapper, err := rawArray(final, "$event[19]", raw) if err != nil || len(wrapper) == 0 { - return false, &ProtocolEvidenceError{Method: method, Path: "$event[19]", Detail: "最终 interaction 为空", Raw: cloneRaw(raw)} + return false, &ProtocolEvidenceError{Method: d.method, Path: "$event[19]", Detail: "最终 interaction 为空", Raw: cloneRaw(raw)} } interaction, err := rawArray(wrapper[0], "$event[19][0]", raw) if err != nil { - return false, withMethod(err, method) + return false, withMethod(err, d.method) } status, err := optionalIntField(interaction, 1, "$event[19][0]", raw) if err != nil { - return false, withMethod(err, method) + return false, withMethod(err, d.method) } + finishReason := "stop" switch status { - case 3: + case 2, 3: + case 6: + // 状态 6(Incomplete)对应输出上限截断,统一映射为规范终态 max_tokens + finishReason = "max_tokens" case 4: - return false, &RPCError{Method: method, StatusCode: http.StatusBadGateway, Message: "interaction failed"} + message := decodeInteractionErrors(rawAt(interaction, 27)) + if message == "" { + message = "interaction failed" + } + return false, &RPCError{Method: d.method, StatusCode: http.StatusBadGateway, Message: message} case 5: - return false, &RPCError{Method: method, StatusCode: http.StatusBadGateway, Message: "interaction cancelled"} + return false, &RPCError{Method: d.method, StatusCode: http.StatusBadGateway, Message: "interaction cancelled"} default: - return false, &ProtocolEvidenceError{Method: method, Path: "$event[19][0][1]", Detail: fmt.Sprintf("未识别的最终状态 %d", status), Raw: cloneRaw(raw)} + return false, &ProtocolEvidenceError{Method: d.method, Path: "$event[19][0][1]", Detail: fmt.Sprintf("未识别的最终状态 %d", status), Raw: cloneRaw(raw)} + } + if err := d.flushSignature(emit); err != nil { + return false, err } if usage := rawAt(interaction, 12); !isJSONNull(usage) { - decoded, err := decodeInteractionUsage(method, usage, raw) + decoded, err := decodeInteractionUsage(d.method, usage, raw) if err != nil { return false, err } @@ -544,21 +1142,286 @@ func decodeInteractionEvent(method string, raw json.RawMessage, emit func(Event) environmentID := "" if value := rawAt(interaction, 24); !isJSONNull(value) { if environmentID, err = rawString(value, "$event[19][0][24]", raw); err != nil { - return false, withMethod(err, method) + return false, withMethod(err, d.method) + } + } + return true, emit(Event{Kind: EventFinish, FinishReason: finishReason, EnvironmentID: environmentID}) +} + +// decodeInteractionErrors 提取 interaction field 28 (_.ex) 中的错误码与消息 +func decodeInteractionErrors(raw json.RawMessage) string { + if isJSONNull(raw) { + return "" + } + items, err := rawArray(raw, "$errors", raw) + if err != nil { + return "" + } + var messages []string + for _, item := range items { + fields, err := rawArray(item, "$errors[]", raw) + if err != nil { + continue + } + code, _ := optionalStringField(fields, 0, "$errors[]", raw) + msg, _ := optionalStringField(fields, 1, "$errors[]", raw) + switch { + case msg != "" && code != "": + messages = append(messages, code+": "+msg) + case msg != "": + messages = append(messages, msg) + case code != "": + messages = append(messages, code) + } + } + return strings.Join(messages, "; ") +} + +// decodeStepStart 解码 event[9] (_.C1a) 步骤开始:记录步骤类型与工具调用/结果初始信息 +func (d *interactionStreamDecoder) decodeStepStart(raw json.RawMessage, evidence json.RawMessage, emit func(Event) error) error { + fields, err := rawArray(raw, "$step_start", evidence) + if err != nil { + return withMethod(err, d.method) + } + stepIndex, err := optionalIntField(fields, 0, "$step_start", evidence) + if err != nil { + return withMethod(err, d.method) + } + stepMsg := rawAt(fields, 1) + if isJSONNull(stepMsg) { + return nil + } + stepWire, err := rawArray(stepMsg, "$step_start[1]", evidence) + if err != nil { + return withMethod(err, d.method) + } + state := &interactionStepState{} + d.steps[stepIndex] = state + switch { + case !isJSONNull(rawAt(stepWire, 0)): + state.kind = "user_input" + case !isJSONNull(rawAt(stepWire, 1)): + state.kind = "model_output" + case !isJSONNull(rawAt(stepWire, 2)): + state.kind = "thought" + case !isJSONNull(rawAt(stepWire, 3)): + state.kind = "tool_call" + if err := d.decodeToolCallStep(state, rawAt(stepWire, 3), evidence); err != nil { + return err + } + if state.callID != "" { + d.callSteps[state.callID] = state + } + case !isJSONNull(rawAt(stepWire, 4)): + state.kind = "tool_result" + if err := d.decodeToolResultStep(state, rawAt(stepWire, 4), evidence, emit); err != nil { + return err + } + } + return nil +} + +// decodeToolCallStep 解析 step_start 中 Ww field 4 (_.a_a) 工具调用元信息与初始参数 +func (d *interactionStreamDecoder) decodeToolCallStep(state *interactionStepState, raw json.RawMessage, evidence json.RawMessage) error { + call, err := rawArray(raw, "$tool_call", evidence) + if err != nil { + return withMethod(err, d.method) + } + state.callID, err = optionalStringField(call, 0, "$tool_call", evidence) + if err != nil { + return withMethod(err, d.method) + } + switch { + case !isJSONNull(rawAt(call, 2)): + // field 3 (UZa): 函数调用 [name, Struct(args)] + state.toolType = "function" + fn, err := rawArray(call[2], "$tool_call[2]", evidence) + if err != nil { + return withMethod(err, d.method) + } + state.funcName, err = optionalStringField(fn, 0, "$tool_call[2]", evidence) + if err != nil { + return withMethod(err, d.method) + } + if argsRaw := rawAt(fn, 1); !isJSONNull(argsRaw) { + if decoded, err := decodeWireStructObject(argsRaw, "$tool_call[2][1]", evidence); err == nil { + state.argsMap = decoded + } + } + case !isJSONNull(rawAt(call, 3)): + // field 4 (_.RZa): 代码执行 [[lang, code]] + state.toolType = "code_execution" + wrapper, err := rawArray(call[3], "$tool_call[3]", evidence) + if err == nil && !isJSONNull(rawAt(wrapper, 0)) { + if inner, err := rawArray(wrapper[0], "$tool_call[3][0]", evidence); err == nil { + langCode, _ := optionalIntField(inner, 0, "$tool_call[3][0]", evidence) + state.codeLang = interactionCodeLanguage(langCode) + if code, _ := optionalStringField(inner, 1, "$tool_call[3][0]", evidence); code != "" { + state.codeText.WriteString(code) + } + } + } + case !isJSONNull(rawAt(call, 4)): + state.toolType = "url_context" + case !isJSONNull(rawAt(call, 5)): + // field 6 (ZZa): MCP 工具调用 [name, Struct(args)] + state.toolType = "mcp" + if mcp, err := rawArray(call[5], "$tool_call[5]", evidence); err == nil { + state.funcName, _ = optionalStringField(mcp, 0, "$tool_call[5]", evidence) + if argsRaw := rawAt(mcp, 1); !isJSONNull(argsRaw) { + if decoded, err := decodeWireStructObject(argsRaw, "$tool_call[5][1]", evidence); err == nil { + state.argsMap = decoded + } + } + } + case !isJSONNull(rawAt(call, 6)): + // field 7 (_.YZa): Google 搜索 [[queries]] + state.toolType = "google_search" + if wrapper, err := rawArray(call[6], "$tool_call[6]", evidence); err == nil && !isJSONNull(rawAt(wrapper, 0)) { + if inner, err := rawArray(wrapper[0], "$tool_call[6][0]", evidence); err == nil { + if queries, err := stringSliceField(inner, 0, "$tool_call[6][0]", evidence); err == nil { + state.queries = append(state.queries, queries...) + } + } + } + case !isJSONNull(rawAt(call, 7)): + state.toolType = "file_search" + case !isJSONNull(rawAt(call, 8)): + state.toolType = "google_maps" + } + return nil +} + +// decodeToolResultStep 解析 step_start 中 Ww field 5 (_.Pw) 工具结果 +func (d *interactionStreamDecoder) decodeToolResultStep(state *interactionStepState, raw json.RawMessage, evidence json.RawMessage, emit func(Event) error) error { + result, err := rawArray(raw, "$tool_result", evidence) + if err != nil { + return withMethod(err, d.method) + } + state.callID, err = optionalStringField(result, 0, "$tool_result", evidence) + if err != nil { + return withMethod(err, d.method) + } + if linked := d.callSteps[state.callID]; linked != nil { + state.toolType = linked.toolType + state.funcName = linked.funcName + } + switch { + case !isJSONNull(rawAt(result, 3)): + // field 4 (_.c_a): 代码执行结果 [output, isError] + return d.emitCodeExecutionResult(state.callID, result[3], evidence, emit) + case !isJSONNull(rawAt(result, 4)): + // field 5 (l_a): URL 上下文结果 [[[url, status]...], isError] + if fields, err := rawArray(result[4], "$tool_result[4]", evidence); err == nil { + return d.emitURLContextResult(state.callID, rawAt(fields, 0), evidence, emit) + } + case !isJSONNull(rawAt(result, 5)): + // field 6 (j_a): Google 搜索结果 [[[..., search_suggestions(4)]...], isError] + if fields, err := rawArray(result[5], "$tool_result[5]", evidence); err == nil { + return d.emitSearchResult(state.callID, rawAt(fields, 0), 4, evidence, emit) + } + case !isJSONNull(rawAt(result, 6)): + // field 7 (_.k_a): MCP 结果 [name, nil, struct(2), str(3)] + if fields, err := rawArray(result[6], "$tool_result[6]", evidence); err == nil { + name, _ := optionalStringField(fields, 0, "$tool_result[6]", evidence) + data := decodeToolPayload(rawAt(fields, 2), rawAt(fields, 3), evidence) + return emit(Event{Kind: EventServerToolResponse, ToolResponse: &ServerToolStep{ID: state.callID, Type: "CUSTOM", Name: name, Data: data}}) + } + } + return nil +} + +// decodeStepEnd 处理 event[11] (_.oy) 步骤结束:把缓冲的客户端函数调用或服务端工具调用提交为规范事件 +func (d *interactionStreamDecoder) decodeStepEnd(raw json.RawMessage, evidence json.RawMessage, emit func(Event) error) error { + fields, err := rawArray(raw, "$step_end", evidence) + if err != nil { + return withMethod(err, d.method) + } + stepIndex, err := optionalIntField(fields, 0, "$step_end", evidence) + if err != nil { + return withMethod(err, d.method) + } + state, ok := d.steps[stepIndex] + if !ok || state.emitted || state.kind != "tool_call" { + return nil + } + state.emitted = true + switch state.toolType { + case "function": + args := json.RawMessage(`{}`) + if rawArgs := strings.TrimSpace(state.argsJSON.String()); rawArgs != "" && json.Valid([]byte(rawArgs)) { + args = json.RawMessage(rawArgs) + } else if len(state.argsMap) > 0 { + if encoded, err := json.Marshal(state.argsMap); err == nil { + args = encoded + } + } + sig := d.pendingSignature + d.pendingSignature = "" + call := &FunctionCall{ID: state.callID, Name: state.funcName, Arguments: args, ThoughtSignature: sig} + return emit(Event{Kind: EventToolCall, FunctionCall: call, ThoughtSignature: sig}) + case "code_execution": + if err := d.flushSignature(emit); err != nil { + return err + } + lang := state.codeLang + if lang == "" { + lang = "PYTHON" + } + return emit(Event{Kind: EventExecutableCode, ExecutableCode: &ExecutableCode{ID: state.callID, Language: lang, Code: state.codeText.String()}}) + case "google_search": + if err := d.flushSignature(emit); err != nil { + return err + } + payload, _ := json.Marshal(map[string]any{"queries": state.queries}) + if err := emit(Event{Kind: EventServerToolCall, ToolCall: &ServerToolStep{ID: state.callID, Type: "GOOGLE_SEARCH_WEB", Data: payload}}); err != nil { + return err + } + if len(state.queries) > 0 { + return emit(Event{Kind: EventGrounding, Grounding: &GroundingMetadata{WebSearchQueries: slices.Clone(state.queries)}}) + } + case "url_context": + if err := d.flushSignature(emit); err != nil { + return err + } + return emit(Event{Kind: EventServerToolCall, ToolCall: &ServerToolStep{ID: state.callID, Type: "URL_CONTEXT"}}) + case "google_maps": + if err := d.flushSignature(emit); err != nil { + return err + } + return emit(Event{Kind: EventServerToolCall, ToolCall: &ServerToolStep{ID: state.callID, Type: "GOOGLE_MAPS"}}) + case "file_search": + if err := d.flushSignature(emit); err != nil { + return err + } + return emit(Event{Kind: EventServerToolCall, ToolCall: &ServerToolStep{ID: state.callID, Type: "FILE_SEARCH"}}) + case "mcp": + if err := d.flushSignature(emit); err != nil { + return err + } + var data json.RawMessage + if len(state.argsMap) > 0 { + data, _ = json.Marshal(state.argsMap) } + return emit(Event{Kind: EventServerToolCall, ToolCall: &ServerToolStep{ID: state.callID, Type: "CUSTOM", Name: state.funcName, Data: data}}) } - return true, emit(Event{Kind: EventFinish, FinishReason: "stop", EnvironmentID: environmentID}) + return nil } -// decodeInteractionDelta 解码 content delta:field 1 文本、field 2 图片、field 3 音频、field 4 文档、field 5 视频、field 6 思考摘要、field 7 思考签名、field 10 引用 -func decodeInteractionDelta(method string, raw json.RawMessage, emit func(Event) error) error { - delta, err := rawArray(raw, "$delta", raw) +// decodeDelta 解码 content delta:field 1 文本、field 2-5 媒体、field 6 思考摘要、field 7 思考签名、field 10 引用、field 11-14 工具增量 +func (d *interactionStreamDecoder) decodeDelta(raw json.RawMessage, evidence json.RawMessage, emit func(Event) error) error { + delta, err := rawArray(raw, "$delta", evidence) if err != nil || len(delta) < 2 { - return &ProtocolEvidenceError{Method: method, Path: "$delta", Detail: "content delta 字段不足", Raw: cloneRaw(raw)} + return &ProtocolEvidenceError{Method: d.method, Path: "$delta", Detail: "content delta 字段不足", Raw: cloneRaw(raw)} } - content, err := rawArray(delta[1], "$delta[1]", raw) + stepIndex, err := optionalIntField(delta, 0, "$delta", evidence) if err != nil { - return withMethod(err, method) + return withMethod(err, d.method) + } + state := d.step(stepIndex) + content, err := rawArray(delta[1], "$delta[1]", evidence) + if err != nil { + return withMethod(err, d.method) } for index, value := range content { if isJSONNull(value) { @@ -566,19 +1429,31 @@ func decodeInteractionDelta(method string, raw json.RawMessage, emit func(Event) } switch index { case 0: - text, err := rawArray(value, "$delta[1][0]", raw) + text, err := rawArray(value, "$delta[1][0]", evidence) if err != nil || len(text) == 0 { - return &ProtocolEvidenceError{Method: method, Path: "$delta[1][0]", Detail: "文本 delta 无效", Raw: cloneRaw(raw)} + return &ProtocolEvidenceError{Method: d.method, Path: "$delta[1][0]", Detail: "文本 delta 无效", Raw: cloneRaw(raw)} } - decoded, err := rawString(text[0], "$delta[1][0][0]", raw) + decoded, err := rawString(text[0], "$delta[1][0][0]", evidence) if err != nil { - return withMethod(err, method) + return withMethod(err, d.method) } - if err := emit(Event{Kind: EventText, Text: decoded}); err != nil { - return err + if state.kind == "thought" { + if err := emit(Event{Kind: EventReasoning, Text: decoded, Thought: true}); err != nil { + return err + } + } else { + if err := d.flushSignature(emit); err != nil { + return err + } + if err := emit(Event{Kind: EventText, Text: decoded}); err != nil { + return err + } } case 1, 2, 3, 4: - media, err := decodeInteractionMedia(method, value, index, raw) + if err := d.flushSignature(emit); err != nil { + return err + } + media, err := decodeInteractionMedia(d.method, value, index, evidence) if err != nil { return err } @@ -593,17 +1468,287 @@ func decodeInteractionDelta(method string, raw json.RawMessage, emit func(Event) } } case 6: + // field 7 为思考签名 [""],暂存以便紧随的函数调用附带或在下个非函数事件前发出 + sig := "" + if items, err := rawArray(value, "$delta[1][6]", evidence); err == nil && len(items) > 0 && !isJSONNull(items[0]) { + sig, _ = rawString(items[0], "$delta[1][6][0]", evidence) + } + if sig != "" { + if err := d.flushSignature(emit); err != nil { + return err + } + d.pendingSignature = sig + } case 9: - if err := decodeInteractionCitations(method, value, raw, emit); err != nil { + if err := decodeInteractionCitations(d.method, value, evidence, emit); err != nil { + return err + } + case 10: + // field 11 (_.u1a): 函数调用参数 JSON 字符串增量,field 2 (idx 1) 为片段 + fields, err := rawArray(value, "$delta[1][10]", evidence) + if err != nil { + return withMethod(err, d.method) + } + if fragment, err := optionalStringField(fields, 1, "$delta[1][10]", evidence); err != nil { + return withMethod(err, d.method) + } else if fragment != "" { + state.argsJSON.WriteString(fragment) + } + case 11: + // field 12 (_.v1a): 服务端工具调用增量(oneof 2..8) + if err := d.decodeServerToolCallDelta(state, value, evidence); err != nil { + return err + } + case 12: + // field 13 (_.w1a): 服务端工具结果增量(oneof 2..8) + if err := d.decodeServerToolResultDelta(state, value, evidence, emit); err != nil { + return err + } + case 13: + // field 14 (_.Yx): 工具结果增量 [name(0), isError(1), ..., str(4), struct(5)] + if err := d.decodeGenericToolResultDelta(state, value, evidence, emit); err != nil { return err } default: - return &ProtocolEvidenceError{Method: method, Path: fmt.Sprintf("$delta[1][%d]", index), Detail: "未识别的 content delta 字段", Raw: cloneRaw(raw)} + return &ProtocolEvidenceError{Method: d.method, Path: fmt.Sprintf("$delta[1][%d]", index), Detail: "未识别的 content delta 字段", Raw: cloneRaw(raw)} + } + } + return nil +} + +// decodeServerToolCallDelta 解码 content delta field 12 (_.v1a) 的服务端工具调用参数增量 +func (d *interactionStreamDecoder) decodeServerToolCallDelta(state *interactionStepState, raw json.RawMessage, evidence json.RawMessage) error { + fields, err := rawArray(raw, "$delta[1][11]", evidence) + if err != nil { + return withMethod(err, d.method) + } + switch { + case !isJSONNull(rawAt(fields, 1)): + // field 2 (_.Ox): [_.IAa = [lang(0), code(1)]] + state.toolType = "code_execution" + if ox, err := rawArray(fields[1], "$delta[1][11][1]", evidence); err == nil && !isJSONNull(rawAt(ox, 0)) { + if ia, err := rawArray(ox[0], "$delta[1][11][1][0]", evidence); err == nil { + if langCode, err := optionalIntField(ia, 0, "$delta[1][11][1][0]", evidence); err == nil && langCode != 0 { + state.codeLang = interactionCodeLanguage(langCode) + } + if fragment, err := optionalStringField(ia, 1, "$delta[1][11][1][0]", evidence); err == nil && fragment != "" { + state.codeText.WriteString(fragment) + } + } + } + case !isJSONNull(rawAt(fields, 2)): + state.toolType = "url_context" + case !isJSONNull(rawAt(fields, 3)): + // field 4 (_.Rx): [_.NAa = [queries(0)]] + state.toolType = "google_search" + if rx, err := rawArray(fields[3], "$delta[1][11][3]", evidence); err == nil && !isJSONNull(rawAt(rx, 0)) { + if na, err := rawArray(rx[0], "$delta[1][11][3][0]", evidence); err == nil { + if queries, err := stringSliceField(na, 0, "$delta[1][11][3][0]", evidence); err == nil { + for _, query := range queries { + if !slices.Contains(state.queries, query) { + state.queries = append(state.queries, query) + } + } + } + } + } + case !isJSONNull(rawAt(fields, 4)): + state.toolType = "mcp" + case !isJSONNull(rawAt(fields, 5)): + state.toolType = "file_search" + case !isJSONNull(rawAt(fields, 6)): + state.toolType = "google_maps" + } + return nil +} + +// decodeServerToolResultDelta 解码 content delta field 13 (_.w1a) 的服务端工具结果增量 +func (d *interactionStreamDecoder) decodeServerToolResultDelta(state *interactionStepState, raw json.RawMessage, evidence json.RawMessage, emit func(Event) error) error { + fields, err := rawArray(raw, "$delta[1][12]", evidence) + if err != nil { + return withMethod(err, d.method) + } + switch { + case !isJSONNull(rawAt(fields, 1)): + // field 2 (_.Wx): 代码执行结果 [output(0), isError(1)] + return d.emitCodeExecutionResult(state.callID, fields[1], evidence, emit) + case !isJSONNull(rawAt(fields, 2)): + // field 3 (j1a): URL 上下文结果 [nil, items(1), isError(2)] + if j1a, err := rawArray(fields[2], "$delta[1][12][2]", evidence); err == nil { + return d.emitURLContextResult(state.callID, rawAt(j1a, 1), evidence, emit) + } + case !isJSONNull(rawAt(fields, 3)): + // field 4 (h1a): Google 搜索结果 [nil, items(1), isError(2)],search_suggestions 位于 field 4 (idx 3) + if h1a, err := rawArray(fields[3], "$delta[1][12][3]", evidence); err == nil { + return d.emitSearchResult(state.callID, rawAt(h1a, 1), 3, evidence, emit) + } + case !isJSONNull(rawAt(fields, 4)): + // field 5 (_.i1a): MCP 工具结果 [name(0), isError(1), nil, nil, str(4), struct(5)] + if i1a, err := rawArray(fields[4], "$delta[1][12][4]", evidence); err == nil { + name, _ := optionalStringField(i1a, 0, "$delta[1][12][4]", evidence) + data := decodeToolPayload(rawAt(i1a, 5), rawAt(i1a, 4), evidence) + return emit(Event{Kind: EventServerToolResponse, ToolResponse: &ServerToolStep{ID: state.callID, Type: "CUSTOM", Name: name, Data: data}}) + } + } + return nil +} + +// decodeGenericToolResultDelta 解码 content delta field 14 (_.Yx) 工具结果增量 +func (d *interactionStreamDecoder) decodeGenericToolResultDelta(state *interactionStepState, raw json.RawMessage, evidence json.RawMessage, emit func(Event) error) error { + fields, err := rawArray(raw, "$delta[1][13]", evidence) + if err != nil { + return withMethod(err, d.method) + } + name, _ := optionalStringField(fields, 0, "$delta[1][13]", evidence) + if name == "" { + name = state.funcName + } + data := decodeToolPayload(rawAt(fields, 5), rawAt(fields, 4), evidence) + return emit(Event{Kind: EventServerToolResponse, ToolResponse: &ServerToolStep{ID: state.callID, Type: "CUSTOM", Name: name, Data: data}}) +} + +// emitCodeExecutionResult 把代码执行结果 [output, isError] 发为 EventCodeExecutionResult +func (d *interactionStreamDecoder) emitCodeExecutionResult(callID string, raw json.RawMessage, evidence json.RawMessage, emit func(Event) error) error { + fields, err := rawArray(raw, "$code_result", evidence) + if err != nil { + return withMethod(err, d.method) + } + output, _ := optionalStringField(fields, 0, "$code_result", evidence) + isErr := false + if v := rawAt(fields, 1); !isJSONNull(v) { + isErr, _ = rawBool(v, "$code_result[1]", evidence) + } + outcome := "OUTCOME_OK" + if isErr { + outcome = "OUTCOME_FAILED" + } + return emit(Event{Kind: EventCodeExecutionResult, CodeExecutionResult: &CodeExecutionResult{ID: callID, Outcome: outcome, Output: output}}) +} + +// emitURLContextResult 把 URL 上下文读取条目发为 EventServerToolResponse 与 EventGrounding +func (d *interactionStreamDecoder) emitURLContextResult(callID string, itemsRaw json.RawMessage, evidence json.RawMessage, emit func(Event) error) error { + if isJSONNull(itemsRaw) { + return nil + } + items, err := rawArray(itemsRaw, "$url_results", evidence) + if err != nil { + return nil + } + var urls []URLMetadata + var metadata []map[string]any + for _, item := range items { + fields, err := rawArray(item, "$url_results[]", evidence) + if err != nil { + continue + } + url, _ := optionalStringField(fields, 0, "$url_results[]", evidence) + statusCode, _ := optionalIntField(fields, 1, "$url_results[]", evidence) + status := interactionURLStatus(statusCode) + if url != "" { + urls = append(urls, URLMetadata{RetrievedURL: url, Status: status}) + metadata = append(metadata, map[string]any{"retrieved_url": url, "url_retrieval_status": status}) + } + } + data, _ := json.Marshal(map[string]any{"url_metadata": metadata}) + if err := emit(Event{Kind: EventServerToolResponse, ToolResponse: &ServerToolStep{ID: callID, Type: "URL_CONTEXT", Data: data}}); err != nil { + return err + } + if len(urls) > 0 { + return emit(Event{Kind: EventGrounding, Grounding: &GroundingMetadata{URLContext: urls}}) + } + return nil +} + +// emitSearchResult 把 Google 搜索结果条目发为 EventServerToolResponse,含 search_suggestions 时附带 EventGrounding +func (d *interactionStreamDecoder) emitSearchResult(callID string, itemsRaw json.RawMessage, suggestionIndex int, evidence json.RawMessage, emit func(Event) error) error { + if isJSONNull(itemsRaw) { + return nil + } + items, err := rawArray(itemsRaw, "$search_results", evidence) + if err != nil { + return nil + } + var chunks []GroundingChunk + var rendered string + var results []map[string]any + for _, item := range items { + fields, err := rawArray(item, "$search_results[]", evidence) + if err != nil { + continue + } + entry := map[string]any{} + if url, _ := optionalStringField(fields, 0, "$search_results[]", evidence); url != "" { + title, _ := optionalStringField(fields, 1, "$search_results[]", evidence) + chunks = append(chunks, GroundingChunk{Source: "web", URI: url, Title: title}) + entry["url"] = url + if title != "" { + entry["title"] = title + } + } + if suggestion, _ := optionalStringField(fields, suggestionIndex, "$search_results[]", evidence); suggestion != "" { + if rendered == "" { + rendered = suggestion + } + entry["search_suggestions"] = suggestion + } + if len(entry) > 0 { + results = append(results, entry) + } + } + data, _ := json.Marshal(map[string]any{"results": results}) + if err := emit(Event{Kind: EventServerToolResponse, ToolResponse: &ServerToolStep{ID: callID, Type: "GOOGLE_SEARCH_WEB", Data: data}}); err != nil { + return err + } + if len(chunks) > 0 || rendered != "" { + grounding := &GroundingMetadata{Chunks: chunks} + if rendered != "" { + grounding.SearchEntryPoint = &SearchEntryPoint{RenderedContent: rendered} + } + return emit(Event{Kind: EventGrounding, Grounding: grounding}) + } + return nil +} + +// decodeToolPayload 从 Struct 槽位或字符串槽位提取工具结果 JSON +func decodeToolPayload(structRaw json.RawMessage, strRaw json.RawMessage, evidence json.RawMessage) json.RawMessage { + if !isJSONNull(structRaw) { + if decoded, err := decodeWireStruct(structRaw, "$tool_payload", evidence); err == nil { + return decoded + } + } + if !isJSONNull(strRaw) { + if text, err := rawString(strRaw, "$tool_payload", evidence); err == nil { + encoded, _ := json.Marshal(map[string]any{"result": text}) + return encoded } } return nil } +// interactionCodeLanguage 把代码执行语言枚举码换算为规范名称 +func interactionCodeLanguage(code int64) string { + switch code { + case 1: + return "PYTHON" + case 2: + return "BASH" + default: + return "LANGUAGE_UNSPECIFIED" + } +} + +// interactionURLStatus 把 URL 上下文状态码换算为 Gemini API 枚举名 +func interactionURLStatus(code int64) string { + switch code { + case 1: + return "URL_RETRIEVAL_STATUS_SUCCESS" + case 2: + return "URL_RETRIEVAL_STATUS_ERROR" + default: + return "URL_RETRIEVAL_STATUS_UNSPECIFIED" + } +} + // interactionStrings 按顺序收集嵌套数组中的全部字符串 func interactionStrings(raw json.RawMessage) []string { var value any @@ -649,15 +1794,19 @@ func decodeInteractionUsage(method string, raw json.RawMessage, evidence json.Ra return usage, nil } -// agentTools 按官网的构造编码 CreateInteraction field 8 的工具列表,依次为代码执行、函数声明、Google 搜索与网址读取;请求带有工具列表字段时只用列出的工具,否则在目录 field 82 默认开启的工具上加入请求的工具 -func agentTools(tools Tools, model Model) ([]any, error) { +// interactionTools 按官网 wLb 顺序编码 Interaction field 8 的工具列表:代码执行、函数声明、Google 搜索与网址读取;applyDefaults 为 true 时对未显式传 tools 的 agent 加入目录 field 82 默认开启的工具 +func interactionTools(tools Tools, model Model, applyDefaults bool) ([]any, error) { + subject := "Interaction 模型" + if applyDefaults { + subject = "agent" + } switch { case len(tools.MCPServers) > 0: - return nil, fmt.Errorf("agent 不接受 %s 工具", "mcp_server") + return nil, fmt.Errorf("%s 不接受 %s 工具", subject, "mcp_server") case len(tools.FileSearch) > 0: - return nil, fmt.Errorf("agent 不接受 %s 工具", "file_search") + return nil, fmt.Errorf("%s 不接受 %s 工具", subject, "file_search") case tools.ComputerUse != nil: - return nil, fmt.Errorf("agent 不接受 %s 工具", "computer_use") + return nil, fmt.Errorf("%s 不接受 %s 工具", subject, "computer_use") } code, search, fetch := false, tools.GoogleSearch != nil && tools.GoogleSearch.WebSearch, false for _, name := range tools.Google { @@ -669,10 +1818,10 @@ func agentTools(tools Tools, model Model) ([]any, error) { case "url_context": fetch = true default: - return nil, fmt.Errorf("agent 不接受 %s 工具", name) + return nil, fmt.Errorf("%s 不接受 %s 工具", subject, name) } } - if !tools.Explicit { + if applyDefaults && !tools.Explicit { code = code || model.Capabilities["default_capability_code_9"] search = search || model.Capabilities["default_capability_code_12"] fetch = fetch || model.Capabilities["default_capability_code_13"] @@ -683,7 +1832,11 @@ func agentTools(tools Tools, model Model) ([]any, error) { } for _, function := range tools.Functions { // Tool field 1 为函数声明:field 1 名称、field 2 说明、field 3 以 Value 表示的参数 - declaration := []any{function.Name, nil, nil} + name := function.Name + if !applyDefaults { + name = wireFunctionName(name) + } + declaration := []any{name, nil, nil} if function.Description != "" { declaration[1] = function.Description } @@ -804,64 +1957,6 @@ func trimWireNil(values []any) []any { return values } -// EncodeCreateInteractionRequest 编码官网后台 agent 的 CreateInteraction 请求并返回参与 WAA 绑定的文本内容 -func EncodeCreateInteractionRequest(request GenerateRequest, model Model) ([]byte, int, []Content, error) { - agent := strings.TrimPrefix(strings.TrimSpace(request.Model), "models/") - // kind 是该 agent 的 agent_config 类型:带默认模型的 agent 为 antigravity,其余为 deep-research - kind := "deep-research" - if model.AgentModel != "" { - kind = "antigravity" - } - if config := request.AgentConfig; config != nil && config.Type != kind { - return nil, 0, nil, fmt.Errorf("agent_config.type %q 与 agent %s 不匹配,应为 %q", config.Type, agent, kind) - } - steps, binding, _, err := encodeInteractionSteps(AgentInput(request.Contents, request.PreviousInteractionID != "")) - if err != nil { - return nil, 0, nil, err - } - tools, err := agentTools(request.Tools, model) - if err != nil { - return nil, 0, nil, err - } - interaction := make([]any, 27) - if system := strings.TrimSpace(SystemText(request.System)); system != "" { - interaction[6] = system - } - if len(tools) > 0 { - interaction[7] = tools - } - // field 17 为续接的上一轮 interaction ID - if request.PreviousInteractionID != "" { - interaction[16] = request.PreviousInteractionID - } - // field 19 为 agent 目标:field 1 agent 名称,Deep Research 的 field 3 为 agent 配置 - target := []any{agent, nil, deepResearchConfig(request.AgentConfig)} - if model.AgentModel != "" { - // Antigravity:field 12 为所选模型与 token 上限 - target = target[:1] - if config := request.AgentConfig; config != nil && (config.Model != "" || config.MaxTotalTokens > 0) { - antigravity := make([]any, 7) - if config.Model != "" { - antigravity[0] = strings.TrimPrefix(config.Model, "models/") - } - if config.MaxTotalTokens > 0 { - antigravity[6] = config.MaxTotalTokens - } - target = append(target, make([]any, 11)...) - target[11] = antigravity - } - } - if request.Environment != nil || model.AgentModel != "" { - if err := setInteractionEnvironment(interaction, request.Environment); err != nil { - return nil, 0, nil, err - } - } - interaction[18] = target - interaction[26] = []any{steps} - body, proofAt, _ := marshalWAAArray([]any{nil, int64(1), int64(1), interaction, nil, int64(1)}, 5) - return body, proofAt, binding, nil -} - // EncodeGetInteractionStreamRequest 编码按 interaction ID 读取后台任务增量与终态的请求 func EncodeGetInteractionStreamRequest(id string, model string) ([]byte, int, error) { return marshalWAAArray([]any{id, int64(1), nil, nil, nil, int64(1), wireModelName(model)}, 5) @@ -881,13 +1976,13 @@ func decodeCreateInteractionResponse(raw []byte) (string, error) { } // generateInteractionTask 经 CreateInteraction 创建后台任务,再经 GetInteractionStream 读取增量与终态,调用方中途取消时发送 CancelInteraction -func (c *Client) generateInteractionTask(ctx context.Context, request GenerateRequest, entry modelEntry) (<-chan Event, error) { +func (c *Client) generateInteractionTask(ctx context.Context, request GenerateRequest, entry modelEntry, route InteractionRouting, apiKey string, restoring bool) (<-chan Event, error) { reason := "" if request.Unary { reason = "该模型使用 CreateInteraction 后台任务,收集完成后返回" } reportUpstreamMode(ctx, "GetInteractionStream", "stream", 0, reason) - body, proofAt, binding, err := EncodeCreateInteractionRequest(request, entry.model) + body, proofAt, binding, err := encodeInteractionRequest(request, entry.model, entry.defaults, route) if err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err) } @@ -954,7 +2049,7 @@ func (c *Client) generateInteractionTask(ctx context.Context, request GenerateRe cancel() return nil, err } - return c.interactionEvents(ctx, request, entry, "GetInteractionStream", response, &interactionTask{id: id, account: accountID, cancel: cancel}) + return c.interactionEvents(ctx, request, entry, "GetInteractionStream", response, &interactionTask{id: id, account: accountID, agent: route.IsAgent(), cancel: cancel}, apiKey, restoring) } // decodeInteractionCitations 解码 content field 10 的引用:每项为正文中引用标记的起止字符位置与来源网址 diff --git a/internal/aistudio/interaction_media_test.go b/internal/aistudio/interaction_media_test.go deleted file mode 100644 index 76a8b3a6..00000000 --- a/internal/aistudio/interaction_media_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package aistudio - -import ( - "bytes" - "encoding/json" - "strings" - "testing" -) - -// TestDecodeInteractionMediaMIME 核对各类媒体 delta 按官网枚举表取 MIME,枚举缺省或不在表中时取该类的默认 MIME -func TestDecodeInteractionMediaMIME(t *testing.T) { - data := []byte("\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom") - for _, tc := range []struct { - field int - code any - mime string - }{ - {4, nil, "video/mp4"}, - {4, 1, "video/mp4"}, - {4, 7, "video/webm"}, - {4, 42, "video/mp4"}, - {1, nil, "image/jpeg"}, - {1, 1, "image/png"}, - {1, 3, "image/webp"}, - {2, nil, "audio/wav"}, - {2, 11, "audio/opus"}, - {3, nil, "application/pdf"}, - } { - content := make([]any, tc.field+1) - content[tc.field] = []any{tc.code, data} - delta := make([]any, 11) - delta[10] = []any{0, content} - final := make([]any, 20) - final[19] = []any{[]any{nil, 3}} - wire, err := json.Marshal([]any{[]any{delta, final}, []any{0}}) - if err != nil { - t.Fatal(err) - } - var media *Blob - err = DecodeInteractionStream("CreateInteractionStream", strings.NewReader(string(wire)), func(event Event) error { - if event.Kind == EventMedia { - media = event.InlineData - } - return nil - }) - if err != nil { - t.Fatalf("field %d code %v: %v", tc.field, tc.code, err) - } - if media == nil || media.MIME != tc.mime || !bytes.Equal(media.Data, data) { - t.Fatalf("field %d code %v: media=%+v", tc.field, tc.code, media) - } - } -} diff --git a/internal/aistudio/interaction_routing_test.go b/internal/aistudio/interaction_routing_test.go new file mode 100644 index 00000000..69e20bcc --- /dev/null +++ b/internal/aistudio/interaction_routing_test.go @@ -0,0 +1,339 @@ +package aistudio + +import ( + "encoding/json" + "reflect" + "strings" + "testing" +) + +// listModelRowWithField79 构造带指定 field 79 的最小 ListModels 模型行用于核对官网路由换算 +func listModelRowWithField79(id string, field79 any, extraCaps ...int64) []any { + row := make([]any, 79) + row[0] = "models/" + id + row[3] = id + row[6] = 65536 + row[7] = []any{"generateContent", "countTokens"} + caps := append([]int64{1, 8, 9, 10, 12, 13, 25, 52, 64}, extraCaps...) + row[64] = caps + row[71] = []any{nil, nil, nil, nil, nil, 3, []any{1, 2, 3, 5}} + row[78] = field79 + return row +} + +// TestField79InteractionRoutingMatrix 按官网 m=_b 四个谓词(_.Ol/_.Pl/Rl/_.Sl)核对 field 79 全部 kind 与 background 组合的选路、能力标记与编码信封目标槽位 +func TestField79InteractionRoutingMatrix(t *testing.T) { + cases := []struct { + name string + field79 any + wantMethod InteractionMethod + wantTarget InteractionTarget + wantInteract bool + wantStream bool + wantTask bool + wantAgent bool + wantModel bool + wantAgentModel string + }{ + { + name: "nil field79 uses GenerateContent", + field79: nil, + wantMethod: InteractionMethodGenerateContent, + wantTarget: InteractionTargetNone, + }, + { + name: "empty field79 uses GenerateContent", + field79: []any{}, + wantMethod: InteractionMethodGenerateContent, + wantTarget: InteractionTargetNone, + }, + { + name: "kind=0 background=false uses GenerateContent", + field79: []any{nil, nil, nil, 0}, + wantMethod: InteractionMethodGenerateContent, + wantTarget: InteractionTargetNone, + }, + { + name: "kind=nil background=true uses GenerateContent", + field79: []any{nil, nil, 1}, + wantMethod: InteractionMethodGenerateContent, + wantTarget: InteractionTargetNone, + }, + { + name: "kind=0 background=true uses GenerateContent", + field79: []any{nil, nil, 1, 0}, + wantMethod: InteractionMethodGenerateContent, + wantTarget: InteractionTargetNone, + }, + { + name: "unknown kind=3 background=false uses GenerateContent", + field79: []any{nil, nil, nil, 3}, + wantMethod: InteractionMethodGenerateContent, + wantTarget: InteractionTargetNone, + }, + { + name: "unknown kind=3 background=true uses GenerateContent", + field79: []any{nil, nil, 1, 3}, + wantMethod: InteractionMethodGenerateContent, + wantTarget: InteractionTargetNone, + }, + { + name: "kind=2 background=false routes to CreateInteractionStream model target", + field79: []any{nil, nil, nil, 2}, + wantMethod: InteractionMethodCreateInteractionStream, + wantTarget: InteractionTargetModel, + wantInteract: true, + wantStream: true, + wantModel: true, + }, + { + name: "kind=2 background=true routes to CreateInteraction model target", + field79: []any{nil, nil, 1, 2}, + wantMethod: InteractionMethodCreateInteraction, + wantTarget: InteractionTargetModel, + wantInteract: true, + wantTask: true, + wantModel: true, + }, + { + name: "kind=1 background=false routes to CreateInteractionStream agent target", + field79: []any{nil, nil, nil, 1}, + wantMethod: InteractionMethodCreateInteractionStream, + wantTarget: InteractionTargetAgent, + wantInteract: true, + wantStream: true, + wantAgent: true, + }, + { + name: "kind=1 background=true routes to CreateInteraction agent target", + field79: []any{nil, nil, 1, 1, 1, "models/gemini-3.8-flash"}, + wantMethod: InteractionMethodCreateInteraction, + wantTarget: InteractionTargetAgent, + wantInteract: true, + wantTask: true, + wantAgent: true, + wantAgentModel: "gemini-3.8-flash", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + raw, err := json.Marshal([]any{[]any{listModelRowWithField79("gemini-4-hydrogen", tc.field79)}}) + if err != nil { + t.Fatal(err) + } + catalog, err := parseModelCatalog(strings.NewReader(string(raw))) + if err != nil { + t.Fatal(err) + } + entry := catalog.entries["gemini-4-hydrogen"] + route := interactionRouting(entry.model, entry.defaults, ChannelPlayground) + if route.Method != tc.wantMethod || route.Target != tc.wantTarget { + t.Fatalf("route=%+v want={Method:%s Target:%s}", route, tc.wantMethod, tc.wantTarget) + } + if entry.model.Capabilities["interactions_api"] != tc.wantInteract || + entry.model.Capabilities["interaction_stream"] != tc.wantStream || + entry.model.Capabilities["interaction_task"] != tc.wantTask || + entry.model.Capabilities["interaction_agent"] != tc.wantAgent || + entry.model.Capabilities["interaction_model"] != tc.wantModel { + t.Fatalf("caps=%v", entry.model.Capabilities) + } + if entry.defaults.InteractionStream != tc.wantStream || + entry.defaults.InteractionTask != tc.wantTask || + entry.defaults.InteractionAgent != tc.wantAgent || + entry.defaults.InteractionModel != tc.wantModel { + t.Fatalf("defaults=%+v", entry.defaults) + } + if entry.model.AgentModel != tc.wantAgentModel { + t.Fatalf("agentModel=%q want=%q", entry.model.AgentModel, tc.wantAgentModel) + } + if tc.wantInteract { + body, _, _, err := encodeInteractionRequest(GenerateRequest{ + Model: "gemini-4-hydrogen", + Contents: []Content{{Role: RoleUser, Parts: []Part{{Text: "hello"}}}}, + }, entry.model, entry.defaults, route) + if err != nil { + t.Fatal(err) + } + var wire []any + if err := json.Unmarshal(body, &wire); err != nil { + t.Fatal(err) + } + if tc.wantStream && (wire[0] != float64(1) || wire[2] != nil) { + t.Fatalf("stream envelope=%v", wire[:3]) + } + if tc.wantTask && (wire[0] != nil || wire[2] != float64(1)) { + t.Fatalf("task envelope=%v", wire[:3]) + } + interaction := wire[3].([]any) + if tc.wantModel && (interaction[17] == nil || interaction[18] != nil) { + t.Fatalf("expected model target in index 17, got [17]=%v [18]=%v", interaction[17], interaction[18]) + } + if tc.wantAgent && (interaction[17] != nil || interaction[18] == nil) { + t.Fatalf("expected agent target in index 18, got [17]=%v [18]=%v", interaction[17], interaction[18]) + } + } + // Build 通道始终走 GenerateContent + if buildRoute := interactionRouting(entry.model, entry.defaults, ChannelBuild); buildRoute.Method != InteractionMethodGenerateContent || buildRoute.Target != InteractionTargetNone { + t.Fatalf("build route=%+v", buildRoute) + } + }) + } +} + +// TestCreateInteractionModelTargetMatchesOfficialShape 对照 2026-11-24 官网 gemini-4-hydrogen 现场核对模型目标、思考档位 1-5、多轮历史、原生工具步骤与省略 field 54 +func TestCreateInteractionModelTargetMatchesOfficialShape(t *testing.T) { + raw, err := json.Marshal([]any{[]any{listModelRowWithField79("gemini-4-hydrogen", []any{nil, nil, 1, 2})}}) + if err != nil { + t.Fatal(err) + } + catalog, err := parseModelCatalog(strings.NewReader(string(raw))) + if err != nil { + t.Fatal(err) + } + model := catalog.entries["gemini-4-hydrogen"].model + + // Turn 1 对照官网现场:默认 High(4) 思考、Google Search、无 field 54、模型名写 interaction[17] 带 models/ 前缀、interaction[18] 为 nil + body, _, binding, err := EncodeCreateInteractionRequest(GenerateRequest{ + Model: "gemini-4-hydrogen", + Contents: []Content{{Role: RoleUser, Parts: []Part{{Text: "Reply with the single word OK."}}}}, + Tools: Tools{Google: []string{"google_search"}}, + }, model) + if err != nil { + t.Fatal(err) + } + var got []any + if err := json.Unmarshal(body, &got); err != nil { + t.Fatal(err) + } + wantInteraction := make([]any, 27) + wantInteraction[7] = []any{[]any{nil, nil, nil, nil, nil, []any{}}} + wantInteraction[17] = []any{"models/gemini-4-hydrogen", []any{nil, nil, nil, nil, nil, float64(4), float64(1), float64(65536)}} + wantInteraction[26] = []any{[]any{[]any{[]any{[]any{[]any{[]any{"Reply with the single word OK."}}}}}}} + want := []any{nil, float64(1), float64(1), wantInteraction, nil, float64(1)} + if !reflect.DeepEqual(got, want) { + wantJSON, _ := json.Marshal(want) + t.Fatalf("\n got=%s\nwant=%s", body, wantJSON) + } + if prompt, err := bindingPrompt(GenerateRequest{Contents: binding}); err != nil || prompt != "Reply with the single word OK." { + t.Fatalf("binding=%q err=%v", prompt, err) + } + + // Turn 2 对照官网续接现场:带 previous_interaction_id 写 interaction[16],只发最后模型轮后的新输入 + prevID := "v1_ChcwRVFGYTVPb0JLZVZtdGtQMk1YR2lBMBIXMEVRRmE1T29CS2VWbXRrUDJNWEdpQTA" + body, _, binding, err = EncodeCreateInteractionRequest(GenerateRequest{ + Model: "gemini-4-hydrogen", + PreviousInteractionID: prevID, + Contents: []Content{ + {Role: RoleUser, Parts: []Part{{Text: "Reply with the single word OK."}}}, + {Role: RoleAssistant, Parts: []Part{{Text: "OK"}}}, + {Role: RoleUser, Parts: []Part{{Text: "Now reply with the single word YES."}}}, + }, + Tools: Tools{Google: []string{"google_search"}}, + }, model) + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(body, &got); err != nil { + t.Fatal(err) + } + wantInteraction[16] = prevID + wantInteraction[26] = []any{[]any{[]any{[]any{[]any{[]any{[]any{"Now reply with the single word YES."}}}}}}} + if !reflect.DeepEqual(got, want) { + wantJSON, _ := json.Marshal(want) + t.Fatalf("Turn 2\n got=%s\nwant=%s", body, wantJSON) + } + if prompt, err := bindingPrompt(GenerateRequest{Contents: binding}); err != nil || prompt != "Now reply with the single word YES." { + t.Fatalf("Turn 2 binding=%q err=%v", prompt, err) + } + + // Turn 3 Low(2) 与 ExtraHigh(5) 思考档位对照官网 hLb/mMb 枚举映射 + for effort, wantLevel := range map[string]float64{"low": 2, "medium": 3, "high": 4, "xhigh": 5, "extra_high": 5, "max": 5} { + body, _, _, err := EncodeCreateInteractionRequest(GenerateRequest{ + Model: "gemini-4-hydrogen", + Contents: []Content{{Role: RoleUser, Parts: []Part{{Text: "hi"}}}}, + Config: GenerationConfig{ReasoningEffort: effort}, + }, model) + if err != nil { + t.Fatalf("effort=%s: %v", effort, err) + } + var wire []any + if err := json.Unmarshal(body, &wire); err != nil { + t.Fatal(err) + } + interaction := wire[3].([]any) + if len(interaction) != 27 { + t.Fatalf("effort=%s interaction len=%d, want 27 (no field 54)", effort, len(interaction)) + } + cfg := interaction[17].([]any)[1].([]any) + if cfg[5] != wantLevel || cfg[6] != float64(1) || cfg[7] != float64(65536) || len(cfg) != 8 { + t.Fatalf("effort=%s genConfig=%v", effort, cfg) + } + } + + // 无 previous_interaction_id 时保留多轮 user+model 与原生工具步骤,且工具步骤不参与 WAA binding(对齐官网 wLb + $qb + _.Aub) + body, _, binding, err = EncodeCreateInteractionRequest(GenerateRequest{ + Model: "gemini-4-hydrogen", + Contents: []Content{ + {Role: RoleUser, Parts: []Part{{Text: "Remember code 7391 and check weather."}}}, + {Role: RoleAssistant, Parts: []Part{ + {Thought: true, Text: "thinking"}, + {ThoughtSignature: "EtMCCtAC"}, + {FunctionCall: &FunctionCall{ID: "call_1", Name: "get_weather", Arguments: json.RawMessage(`{"city":"Tokyo"}`)}}, + }}, + {Role: RoleTool, Parts: []Part{ + {FunctionResult: &FunctionResult{ID: "call_1", Content: json.RawMessage(`{"temp":22}`)}}, + }}, + {Role: RoleAssistant, Parts: []Part{{Text: "Noted 7391. Tokyo is 22C."}}}, + {Role: RoleUser, Parts: []Part{{Text: "What code?"}}}, + }, + }, model) + if err != nil { + t.Fatal(err) + } + var multi []any + if err := json.Unmarshal(body, &multi); err != nil { + t.Fatal(err) + } + steps := multi[3].([]any)[26].([]any)[0].([]any) + if len(steps) != 6 { + t.Fatalf("expected 6 steps (user, thought, tool_call, tool_result, model, user), got %d: %s", len(steps), body) + } + // 上游接受函数调用历史的前提是调用之前带思考步骤签名 Ww field 3 MZa field 1(官网流中签名所在的思考步骤) + if !reflect.DeepEqual(steps[1], []any{nil, nil, []any{"EtMCCtAC"}}) { + t.Fatalf("thought step=%v, want signature step before tool_call: %s", steps[1], body) + } + if steps[0].([]any)[0] == nil || steps[2].([]any)[3] == nil || steps[3].([]any)[4] == nil || steps[4].([]any)[1] == nil || steps[5].([]any)[0] == nil { + t.Fatalf("step kinds mismatch: %s", body) + } + // WAA binding 仅含 user/model 文本,不含 tool_call/tool_result + if prompt, err := bindingPrompt(GenerateRequest{Contents: binding}); err != nil || prompt != "Remember code 7391 and check weather. Noted 7391. Tokyo is 22C. What code?" { + t.Fatalf("binding=%q err=%v", prompt, err) + } + + // 客户端没有回传签名的函数调用历史以占位签名步骤开头,上游现场接受该形状 + body, _, _, err = EncodeCreateInteractionRequest(GenerateRequest{ + Model: "gemini-4-hydrogen", + Contents: []Content{ + {Role: RoleUser, Parts: []Part{{Text: "Check weather."}}}, + {Role: RoleAssistant, Parts: []Part{ + {FunctionCall: &FunctionCall{ID: "call_1", Name: "get_weather", Arguments: json.RawMessage(`{"city":"Tokyo"}`)}}, + {FunctionCall: &FunctionCall{ID: "call_2", Name: "get_weather", Arguments: json.RawMessage(`{"city":"Osaka"}`)}}, + }}, + {Role: RoleTool, Parts: []Part{ + {FunctionResult: &FunctionResult{ID: "call_1", Content: json.RawMessage(`{"temp":22}`)}}, + {FunctionResult: &FunctionResult{ID: "call_2", Content: json.RawMessage(`{"temp":25}`)}}, + }}, + }, + }, model) + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(body, &multi); err != nil { + t.Fatal(err) + } + steps = multi[3].([]any)[26].([]any)[0].([]any) + if len(steps) != 6 || !reflect.DeepEqual(steps[1], []any{nil, nil, []any{"skip_thought_signature_validator"}}) || steps[2].([]any)[3] == nil || steps[3].([]any)[3] == nil { + t.Fatalf("unsigned parallel calls: %s", body) + } +} diff --git a/internal/aistudio/models.go b/internal/aistudio/models.go index 9e55dd76..5054bf62 100644 --- a/internal/aistudio/models.go +++ b/internal/aistudio/models.go @@ -68,6 +68,129 @@ var videoTasks = map[int64]string{1: "text_to_video", 2: "image_to_video", 3: "r // videoInputs 为视频能力 field 70[7] 中的输入方式编号,4 为起始帧与尾帧,5 为参考图 var videoInputs = map[int64]string{4: "frames", 5: "reference_images"} +// InteractionMethod 表示模型经 ListModels field 79 选定的生成接口 +type InteractionMethod string + +const ( + // InteractionMethodGenerateContent 表示走普通 GenerateContent 接口 + InteractionMethodGenerateContent InteractionMethod = "GenerateContent" + // InteractionMethodCreateInteractionStream 表示走非后台 CreateInteractionStream 接口 + InteractionMethodCreateInteractionStream InteractionMethod = "CreateInteractionStream" + // InteractionMethodCreateInteraction 表示走后台 CreateInteraction 与 GetInteractionStream 接口 + InteractionMethodCreateInteraction InteractionMethod = "CreateInteraction" +) + +// InteractionTarget 表示 Interaction 请求中目标写入模型槽位还是 agent 槽位 +type InteractionTarget string + +const ( + // InteractionTargetNone 表示不走 Interactions API + InteractionTargetNone InteractionTarget = "" + // InteractionTargetModel 表示模型目标(field 79 kind == 2,写 interaction field 18) + InteractionTargetModel InteractionTarget = "model" + // InteractionTargetAgent 表示 agent 目标(field 79 kind == 1,写 interaction field 19) + InteractionTargetAgent InteractionTarget = "agent" +) + +// InteractionRouting 是由 ListModels field 79 换算出的生成接口与目标位置 +type InteractionRouting struct { + Method InteractionMethod + Target InteractionTarget +} + +// IsInteraction 表示模型经 Interactions API 生成 +func (r InteractionRouting) IsInteraction() bool { + return r.Method == InteractionMethodCreateInteractionStream || r.Method == InteractionMethodCreateInteraction +} + +// IsStream 表示模型经 CreateInteractionStream 生成 +func (r InteractionRouting) IsStream() bool { + return r.Method == InteractionMethodCreateInteractionStream +} + +// IsTask 表示模型经 CreateInteraction 创建后台任务并经 GetInteractionStream 读取结果 +func (r InteractionRouting) IsTask() bool { + return r.Method == InteractionMethodCreateInteraction +} + +// IsAgent 表示目标为 agent(field 79 kind == 1) +func (r InteractionRouting) IsAgent() bool { + return r.Target == InteractionTargetAgent +} + +// IsModel 表示目标为模型(field 79 kind == 2) +func (r InteractionRouting) IsModel() bool { + return r.Target == InteractionTargetModel +} + +// ResolveInteractionRouting 按官网 _.Ol、_.Pl、Rl、_.Sl 四个谓词把 ListModels field 79 的 kind 与 background 换算为接口与目标位置;不识别的 kind 走 GenerateContent +func ResolveInteractionRouting(kind int64, background bool) InteractionRouting { + agent := kind == 1 + interaction := agent || kind == 2 + if !interaction { + return InteractionRouting{Method: InteractionMethodGenerateContent} + } + target := InteractionTargetModel + if agent { + target = InteractionTargetAgent + } + if !background { + return InteractionRouting{Method: InteractionMethodCreateInteractionStream, Target: target} + } + return InteractionRouting{Method: InteractionMethodCreateInteraction, Target: target} +} + +// interactionRouting 返回模型在指定通道上的 Interaction 选路,全部选路判断统一经由 ResolveInteractionRouting +func interactionRouting(model Model, defaults GenerationDefaults, channel Channel) InteractionRouting { + if channel == ChannelBuild { + return ResolveInteractionRouting(0, false) + } + var kind int64 + switch { + case model.Capabilities["interaction_agent"] || defaults.InteractionAgent: + kind = 1 + case model.Capabilities["interaction_model"] || defaults.InteractionModel: + kind = 2 + case model.Capabilities["interaction_stream"] || defaults.InteractionStream: + kind = 2 + case model.Capabilities["interaction_task"] || defaults.InteractionTask: + kind = 1 + } + background := model.Capabilities["interaction_task"] || defaults.InteractionTask + return ResolveInteractionRouting(kind, background) +} + +// decodeInteractionField79 解析 ListModels field 79 InteractionConfig 并经 ResolveInteractionRouting 换算接口与目标位置 +func decodeInteractionField79(config json.RawMessage, path string, evidence json.RawMessage) (InteractionRouting, string, error) { + if isJSONNull(config) { + return ResolveInteractionRouting(0, false), "", nil + } + interaction, err := rawArray(config, path, evidence) + if err != nil { + return InteractionRouting{}, "", withMethod(err, "ListModels") + } + background := false + if value := rawAt(interaction, 2); !isJSONNull(value) { + background, err = rawBool(value, path+"[2]", evidence) + if err != nil { + return InteractionRouting{}, "", withMethod(err, "ListModels") + } + } + kind, err := optionalIntField(interaction, 3, path, evidence) + if err != nil { + return InteractionRouting{}, "", err + } + agentModel := "" + if value := rawAt(interaction, 5); !isJSONNull(value) { + rawModel, err := rawString(value, path+"[5]", evidence) + if err != nil { + return InteractionRouting{}, "", withMethod(err, "ListModels") + } + agentModel = strings.TrimPrefix(rawModel, "models/") + } + return ResolveInteractionRouting(kind, background), agentModel, nil +} + // GenerationDefaults 保存 ListModels 返回的生成默认值 type GenerationDefaults struct { MaxOutputTokens int64 @@ -87,6 +210,12 @@ type GenerationDefaults struct { InteractionStream bool // InteractionTask 表示官网经 CreateInteraction 创建后台任务、经 GetInteractionStream 读取结果的模型 InteractionTask bool + // InteractionAgent 表示 field 79 kind == 1 的 agent 目标 + InteractionAgent bool + // InteractionModel 表示 field 79 kind == 2 的模型目标 + InteractionModel bool + // VideoOutput 表示具备次能力码 14 与 chat_model 的视频输出聊天模型(官网 _.rl) + VideoOutput bool // VideoResolution 为视频输出分辨率选项中的第一项,Interaction 视频输出格式的默认分辨率 VideoResolution string // ContinuedOutputTokens 表示自动续写模型的输出总上限,其他模型为 0 @@ -219,10 +348,6 @@ func decodeModelRow(raw json.RawMessage, rowIndex int) (modelEntry, error) { for _, code := range defaultCodes { capabilities["default_capability_code_"+strconv.FormatInt(code, 10)] = true } - if !isJSONNull(rawAt(row, 78)) { - // field 79 InteractionConfig 表示模型只经 Interactions API 生成 - capabilities["interactions_api"] = true - } accessModes, err := intSliceField(row, 82, path, raw) if err != nil { return modelEntry{}, err @@ -271,34 +396,27 @@ func decodeModelRow(raw json.RawMessage, rowIndex int) (modelEntry, error) { AccessModes: append([]int64(nil), accessModes...), Paid: paidCode == 2, } - if config := rawAt(row, 78); !isJSONNull(config) { - // field 79 InteractionConfig 的 field 3 表示经 CreateInteraction 后台任务生成,field 6 是 agent 默认使用的模型 - interaction, err := rawArray(config, path+"[78]", raw) - if err != nil { - return modelEntry{}, withMethod(err, "ListModels") - } - if value := rawAt(interaction, 2); !isJSONNull(value) { - background, err := rawBool(value, path+"[78][2]", raw) - if err != nil { - return modelEntry{}, withMethod(err, "ListModels") - } - model.Capabilities["interaction_task"] = background - } - kind, err := optionalIntField(interaction, 3, path+"[78]", raw) - if err != nil { - return modelEntry{}, withMethod(err, "ListModels") - } - // field 4 为 2 且不是后台任务的模型经 CreateInteractionStream 生成,与官网一样以内联数据发送图片 - model.Capabilities["interaction_stream"] = kind == 2 && !model.Capabilities["interaction_task"] - if value := rawAt(interaction, 5); !isJSONNull(value) { - agentModel, err := rawString(value, path+"[78][5]", raw) - if err != nil { - return modelEntry{}, withMethod(err, "ListModels") - } - model.AgentModel = strings.TrimPrefix(agentModel, "models/") - } + routing, agentModel, err := decodeInteractionField79(rawAt(row, 78), path+"[78]", raw) + if err != nil { + return modelEntry{}, err + } + if routing.IsInteraction() { + capabilities["interactions_api"] = true + } + if routing.IsStream() { + capabilities["interaction_stream"] = true + } + if routing.IsTask() { + capabilities["interaction_task"] = true } - defaults, err := decodeGenerationDefaults(row, path, raw, capabilities) + if routing.IsAgent() { + capabilities["interaction_agent"] = true + model.AgentModel = agentModel + } + if routing.IsModel() { + capabilities["interaction_model"] = true + } + defaults, err := decodeGenerationDefaults(row, path, raw, capabilities, routing) if err != nil { return modelEntry{}, err } @@ -508,11 +626,14 @@ func decodeCapabilityOptions(row []json.RawMessage, path string, evidence json.R return options, nil } -func decodeGenerationDefaults(row []json.RawMessage, path string, evidence json.RawMessage, capabilities map[string]bool) (GenerationDefaults, error) { +func decodeGenerationDefaults(row []json.RawMessage, path string, evidence json.RawMessage, capabilities map[string]bool, routing InteractionRouting) (GenerationDefaults, error) { defaults := GenerationDefaults{ Thinking: capabilities["thinking"], ThinkingBudget: capabilities["thinking_budget"], ThinkingLevel: capabilities["thinking_level"], DefaultThinkingLevel: 2, ImageRoute: capabilities["image_route"], OutputResolution: capabilities["output_resolution"], + InteractionStream: routing.IsStream(), InteractionTask: routing.IsTask(), + InteractionAgent: routing.IsAgent(), InteractionModel: routing.IsModel(), + VideoOutput: capabilities["secondary_capability_code_14"] && capabilities["chat_model"], } maxOutput, err := optionalIntField(row, 6, path, evidence) if err != nil { @@ -541,26 +662,6 @@ func decodeGenerationDefaults(row []json.RawMessage, path string, evidence json. converted := int(value) defaults.TopK = &converted } - if raw := rawAt(row, 78); !isJSONNull(raw) { - // field 79 InteractionConfig:field 3 为后台任务,field 4 类型 1 为 agent、2 为模型 - interaction, err := rawArray(raw, path+"[78]", evidence) - if err != nil { - return GenerationDefaults{}, withMethod(err, "ListModels") - } - kind, err := optionalIntField(interaction, 3, path+"[78]", evidence) - if err != nil { - return GenerationDefaults{}, err - } - background := false - if value := rawAt(interaction, 2); !isJSONNull(value) { - background, err = rawBool(value, path+"[78][2]", evidence) - if err != nil { - return GenerationDefaults{}, withMethod(err, "ListModels") - } - } - defaults.InteractionStream = kind == 2 && !background - defaults.InteractionTask = background - } if video := rawAt(row, 70); !isJSONNull(video) { items, err := rawArray(video, path+"[70]", evidence) if err != nil { diff --git a/internal/aistudio/page_logging_context_test.go b/internal/aistudio/page_logging_context_test.go deleted file mode 100644 index 6bdffd56..00000000 --- a/internal/aistudio/page_logging_context_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package aistudio - -import ( - "testing" - "time" -) - -// TestLoggingContextRecentResult 按官网页面脚本:GetLoggingContext 响应后 localStorage 的 ais_glcr 记下时间与第 2 项是否为 B;之后载入的页面(同一窗口新开的标签页、重新载入)在页面数据 NHyHAe 毫秒内以 [1] 或 [0] 带上该结果,超时、没有记录或 NHyHAe 为 0 时正文为 [] -func TestLoggingContextRecentResult(t *testing.T) { - if maxAge := parsePageFlags([]byte(`window.WIZ_global_data = {"MsAAre":false,"NHyHAe":60000,"rU9UAf":86400000};`)).loggingContextMaxAge; maxAge != 60000 { - t.Fatalf("NHyHAe=%d", maxAge) - } - now := time.UnixMilli(1_800_000_000_000) - storage := map[string]string{loggingContextStorageKey: loggingContextRecord([]byte(`[null,"B"]`), now)} - if got := storage[loggingContextStorageKey]; got != `{"timestamp":1800000000000,"result":"true"}` { - t.Fatalf("ais_glcr=%s", got) - } - cases := []struct { - storage map[string]string - maxAge int64 - at time.Time - want string - }{ - {storage, 60000, now.Add(19 * time.Second), "[1]"}, - {storage, 60000, now.Add(61 * time.Second), "[]"}, - {storage, 0, now.Add(time.Second), "[]"}, - {map[string]string{}, 60000, now, "[]"}, - {map[string]string{loggingContextStorageKey: loggingContextRecord([]byte(`[null,"A"]`), now)}, 60000, now.Add(time.Second), "[0]"}, - } - for _, item := range cases { - if got := string(loggingContextRequest(item.storage, item.maxAge, item.at)); got != item.want { - t.Fatalf("storage=%v maxAge=%d 正文 %s,期望 %s", item.storage, item.maxAge, got, item.want) - } - } -} diff --git a/internal/aistudio/proxy_pool.go b/internal/aistudio/proxy_pool.go index d200f42b..eb7e1358 100644 --- a/internal/aistudio/proxy_pool.go +++ b/internal/aistudio/proxy_pool.go @@ -58,6 +58,79 @@ func (p *ProxyPool) Assign() ([]string, error) { return p.assignLocked() } +// SetProxies 热替换代理池条目并重新分配未固定代理的账户:保留仍在池中代理的健康状态与已有绑定,切回直连时清除账户的代理池绑定;返回实际出口发生变化的账户 ID +func (p *ProxyPool) SetProxies(previousGlobal string, proxies []string) ([]string, error) { + if p == nil { + return nil, nil + } + p.mu.Lock() + defer p.mu.Unlock() + previousGlobal = strings.TrimSpace(previousGlobal) + existing := make(map[string]*proxyEntry, len(p.entries)) + for _, entry := range p.entries { + existing[entry.proxy] = entry + } + entries := make([]*proxyEntry, 0, len(proxies)) + for _, proxy := range proxies { + proxy = strings.TrimSpace(proxy) + if proxy == "" { + continue + } + if prev := existing[proxy]; prev != nil { + entries = append(entries, prev) + continue + } + entries = append(entries, &proxyEntry{proxy: proxy}) + } + p.pool.mu.Lock() + accounts := slices.Clone(p.pool.accounts) + p.pool.mu.Unlock() + before := make(map[string]string, len(accounts)) + for _, account := range accounts { + if strings.TrimSpace(account.Config.Proxy) != "" { + continue + } + before[account.ID] = account.PoolProxy(previousGlobal) + } + p.entries = entries + var errs []error + if len(p.entries) == 0 { + for _, account := range accounts { + if strings.TrimSpace(account.Config.Proxy) != "" { + continue + } + _, err := p.pool.updateRuntime(account.ID, func(_ *Account, runtimeState *accountRuntimeState) (bool, func(*Account), error) { + if runtimeState.Proxy == "" { + return false, nil, nil + } + runtimeState.Proxy = "" + return true, nil, nil + }) + if err != nil { + errs = append(errs, err) + } + account.boundProxy.Store(nil) + } + } else if _, err := p.assignLocked(); err != nil { + errs = append(errs, err) + } + nextGlobal := "" + if len(p.entries) > 0 { + nextGlobal = p.entries[0].proxy + } + var changed []string + for _, account := range accounts { + prev, tracked := before[account.ID] + if !tracked { + continue + } + if account.PoolProxy(nextGlobal) != prev { + changed = append(changed, account.ID) + } + } + return changed, errors.Join(errs...) +} + func (p *ProxyPool) assignLocked() ([]string, error) { if len(p.entries) == 0 { return nil, nil @@ -249,11 +322,17 @@ func (p *ProxyPool) Probe(ctx context.Context, check func(context.Context, strin if p == nil { return nil, nil } - results := make([]error, len(p.entries)) - var wait sync.WaitGroup + p.mu.Lock() + proxies := make([]string, len(p.entries)) for index, entry := range p.entries { + proxies[index] = entry.proxy + } + p.mu.Unlock() + results := make([]error, len(proxies)) + var wait sync.WaitGroup + for index, proxy := range proxies { wait.Go(func() { - results[index] = check(ctx, entry.proxy) + results[index] = check(ctx, proxy) }) } wait.Wait() @@ -263,7 +342,12 @@ func (p *ProxyPool) Probe(ctx context.Context, check func(context.Context, strin p.mu.Lock() defer p.mu.Unlock() now := time.Now().UTC() - for index, entry := range p.entries { + // 结果按代理回写到仍在池中的条目,检测期间新增的代理保持未检测 + for index, proxy := range proxies { + entry := p.entryLocked(proxy) + if entry == nil { + continue + } entry.checkedAt = now if results[index] != nil { entry.down = true diff --git a/internal/aistudio/quota.go b/internal/aistudio/quota.go index aa8453e3..20b962f7 100644 --- a/internal/aistudio/quota.go +++ b/internal/aistudio/quota.go @@ -41,11 +41,8 @@ var rejectedSizeBackoff = []time.Duration{5 * time.Minute, 15 * time.Minute, 30 // quotaLimitPattern 匹配额度错误中逐项列出的额度上限 var quotaLimitPattern = regexp.MustCompile(`limit: (\d+)`) -// usageLimitResetPattern 匹配套餐限额错误中 resets in 之后的恢复等待时长片段 -var usageLimitResetPattern = regexp.MustCompile(`resets in\s+(\d+\s+(?:days?|hours?|minutes?|seconds?)(?:(?:,\s*(?:and\s+)?|\s+and\s+|\s+)\d+\s+(?:days?|hours?|minutes?|seconds?))*)`) - -// usageLimitResetUnitPattern 匹配恢复等待时长片段中的每一项数值与单位 -var usageLimitResetUnitPattern = regexp.MustCompile(`(\d+)\s+(day|hour|minute|second)s?`) +// usageLimitResetPattern 匹配套餐限额错误中 resets in 之后的小时与分钟 +var usageLimitResetPattern = regexp.MustCompile(`resets in (?:(\d+) hours?)?(?:, )?(?:(\d+) minutes?)?`) // CooldownState 表示账户或模型暂时不可调度的状态 type CooldownState struct { @@ -168,30 +165,12 @@ func zeroQuotaLimit(message string) bool { // usageLimitReset 返回套餐限额错误写明的恢复等待时长 func usageLimitReset(message string) (time.Duration, bool) { match := usageLimitResetPattern.FindStringSubmatch(message) - if match == nil { - return 0, false - } - var total time.Duration - for _, unit := range usageLimitResetUnitPattern.FindAllStringSubmatch(match[1], -1) { - value, err := strconv.Atoi(unit[1]) - if err != nil { - continue - } - switch unit[2] { - case "day": - total += time.Duration(value) * 24 * time.Hour - case "hour": - total += time.Duration(value) * time.Hour - case "minute": - total += time.Duration(value) * time.Minute - case "second": - total += time.Duration(value) * time.Second - } - } - if total <= 0 { + if match == nil || match[1] == "" && match[2] == "" { return 0, false } - return total, true + hours, _ := strconv.Atoi(match[1]) + minutes, _ := strconv.Atoi(match[2]) + return time.Duration(hours)*time.Hour + time.Duration(minutes)*time.Minute, true } // planLimitCooldown 按同一范围上一次套餐限额冷却计算本次冷却;上一次仍未结束时沿用它 diff --git a/internal/aistudio/reply_tool.go b/internal/aistudio/reply_tool.go index b7b8dc0e..a6d5c9fb 100644 --- a/internal/aistudio/reply_tool.go +++ b/internal/aistudio/reply_tool.go @@ -10,13 +10,65 @@ import ( // replyToolName 是回复工具注入的内部函数名 const replyToolName = "final" -// replyToolInstruction 是回复工具开启时追加到系统指令的固定提示 -const replyToolInstruction = "Deliver every reply to the user by calling the `final` function with the complete response text in its `content` argument. Do not output the reply as plain text outside `final`. When you also need to call other tools in the same turn, call them directly alongside `final` without wrapping them inside `final`." +// maxReplyToolContinuationRounds 是模型发出 final(more=true) 后提前结束回合时服务端自动回传 functionResponse 续接的上限 +const maxReplyToolContinuationRounds = 8 -// replyToolParameters 是 final 函数的参数 JSON Schema -var replyToolParameters = json.RawMessage(`{"type":"object","properties":{"content":{"type":"string","description":"The complete reply to the user."}},"required":["content"]}`) +// replyToolContinuationResponse 是模型以 more=true 提前结束回合时自动回传给上游的 final 工具结果 +var replyToolContinuationResponse = json.RawMessage(`{"status":"delivered","instruction":"Continue immediately from where you left off. Emit ALL remaining paragraphs now as consecutive parallel final(content, more) calls in this single turn, setting more=false on the final chunk."}`) + +// replyToolInstructionBase 是回复工具开启时追加到系统指令的固定提示(不含其他工具共存句) +const replyToolInstructionBase = "[DELIVERY RULE / 回复交付规则]\n" + + "You MUST deliver 100% of your user-facing reply through the `final` tool and NEVER output reply text directly outside `final`.\n" + + "`final` is a one-way streaming output sink and NEVER returns a tool result—there is NO follow-up turn. You MUST emit the ENTIRE complete reply in this single turn before stopping.\n" + + "Split every multi-paragraph reply into consecutive parallel `final` calls within this SAME turn (~300–600 characters or 1–2 paragraphs per call): set `more: true` on each continuing chunk and immediately emit the next `final` call, and set `more: false` ONLY on the final chunk after the entire requested length and story beat are complete.\n" + +// replyToolInstructionWithOtherTools 在客户端声明了其他工具时附加共存规则 +const replyToolInstructionWithOtherTools = "When you also need to call other tools in the same turn, call them directly alongside `final` without wrapping them inside `final`.\n" + +// replyToolInstructionNoOtherTools 在客户端未声明任何其他工具时附加禁止编造工具规则 +const replyToolInstructionNoOtherTools = "No other tools exist—NEVER call or invent any tool other than `final`.\n" + +// replyToolInstructionChinese 是中文硬性交付规则,防止长中文角色扮演设定淹没英文规则 +const replyToolInstructionChinese = "【回复交付硬性要求】必须完全通过 `final(content=..., more=...)` 交付全部正文,禁止在 `final` 外直接输出正文。`final` 为单向流式输出,不会返回结果也没有后续回合;长回复必须在当前这一回合内连续并行发出全部段落的 `final` 调用(每段约 300–600 字),未写完前设 `more: true` 并紧接着发出下一个 `final`,只有整篇达到要求长度并彻底写完后的最后一段才设 `more: false` 并结束回合。" + +// replyToolInstructionChineseNoOtherTools 在无其他工具时附加中文禁止编造工具提示 +const replyToolInstructionChineseNoOtherTools = "没有其他工具,严禁调用或编造 `final` 以外的任何函数。" + +// replyToolParameters 是 final 函数的参数 JSON Schema(more 供模型显式锚定是否还有后续分段,解包时只读取 content) +var replyToolParameters = json.RawMessage(`{"type":"object","properties":{"content":{"type":"string","description":"One chunk (1-2 natural paragraphs, ~300-600 characters) of the reply."},"more":{"type":"boolean","description":"Set true if more paragraphs will follow in additional parallel final calls in this SAME turn; set false ONLY on the very last final call that finishes the entire reply."}},"required":["content","more"]}`) type replyToolBypassContextKey struct{} +type replyToolObserverContextKey struct{} + +// ReplyToolObserver 接收回复工具本次尝试的实际启用状态、每次成功解包 final 与每次 more=true 自动续接时的回调 +type ReplyToolObserver struct { + OnActive func(enabled bool) + OnCall func() + OnContinuation func() +} + +// ContextWithReplyToolObserver 绑定回复工具启用与调用次数观察器 +func ContextWithReplyToolObserver(ctx context.Context, observer ReplyToolObserver) context.Context { + return context.WithValue(ctx, replyToolObserverContextKey{}, observer) +} + +func reportReplyToolActive(ctx context.Context, enabled bool) { + if observer, ok := ctx.Value(replyToolObserverContextKey{}).(ReplyToolObserver); ok && observer.OnActive != nil { + observer.OnActive(enabled) + } +} + +func reportReplyToolCall(ctx context.Context) { + if observer, ok := ctx.Value(replyToolObserverContextKey{}).(ReplyToolObserver); ok && observer.OnCall != nil { + observer.OnCall() + } +} + +func reportReplyToolContinuation(ctx context.Context) { + if observer, ok := ctx.Value(replyToolObserverContextKey{}).(ReplyToolObserver); ok && observer.OnContinuation != nil { + observer.OnContinuation() + } +} // ContextWithReplyToolBypassObserver 在开启回复工具但模型直接输出正文时调用 observer func ContextWithReplyToolBypassObserver(ctx context.Context, observer func()) context.Context { @@ -72,35 +124,102 @@ func nonTextGeneration(request GenerateRequest, entry modelEntry) bool { slices.Contains(request.Config.ResponseModalities, ResponseModalityAudio) } +// hasClientOtherTools 判断客户端请求是否声明了除内部回复工具外的其他工具 +func hasClientOtherTools(tools Tools) bool { + return len(tools.Functions) > 0 || + len(tools.Google) > 0 || + tools.GoogleSearch != nil || + tools.URLContext != nil || + len(tools.MCPServers) > 0 +} + +// isReplyToolName 判断上游返回的函数名是否指向内部回复工具(兼容 Gemini 偶发附带的 default_api: 前缀) +func isReplyToolName(name string) bool { + return name == replyToolName || name == "default_api:"+replyToolName +} + // applyReplyTool 返回追加了 final 函数声明与固定系统指令的请求副本 func applyReplyTool(request GenerateRequest) GenerateRequest { + hasOther := hasClientOtherTools(request.Tools) request.Tools.Functions = append(slices.Clip(request.Tools.Functions), FunctionDeclaration{ Name: replyToolName, - Description: "Deliver the complete reply to the user.", + Description: "Deliver one chunk of your reply to the user (one-way output; never returns a tool result). Emit ALL chunks as consecutive parallel calls in this single turn: set more=true on every chunk except the last, and more=false ONLY when the entire reply is finished.", Parameters: replyToolParameters, }) - instruction := replyToolInstruction + var instruction string + if hasOther { + instruction = replyToolInstructionBase + replyToolInstructionWithOtherTools + replyToolInstructionChinese + } else { + instruction = replyToolInstructionBase + replyToolInstructionNoOtherTools + replyToolInstructionChinese + replyToolInstructionChineseNoOtherTools + } if len(request.System) > 0 { - instruction = "\n" + instruction + instruction = "\n\n" + instruction } request.System = appendSystem(request.System, instruction) return request } -// replyToolText 从 final 函数调用参数中提取正文内容 -func replyToolText(arguments json.RawMessage) (string, bool) { +// replyToolCallArgs 从 final 函数调用参数中提取正文与 more 续段标志 +func replyToolCallArgs(arguments json.RawMessage) (string, bool, bool) { var payload struct { Content *string `json:"content"` + More bool `json:"more"` } if err := json.Unmarshal(arguments, &payload); err != nil || payload.Content == nil { - return "", false + return "", false, false + } + return *payload.Content, payload.More, true +} + +// replyToolText 从 final 函数调用参数中提取正文内容 +func replyToolText(arguments json.RawMessage) (string, bool) { + content, _, ok := replyToolCallArgs(arguments) + return content, ok +} + +// replyToolContinuationResults 判断本轮上游输出是否仅包含 final 调用且最后一段声明 more=true,是则返回自动续接所需的 FunctionResult 列表 +func replyToolContinuationResults(parts []Part) ([]Part, bool) { + var results []Part + hasNonEmpty := false + lastMore := false + for _, part := range parts { + if part.Thought { + continue + } + if part.Text != "" { + return nil, false + } + if part.FunctionCall == nil { + continue + } + if !isReplyToolName(part.FunctionCall.Name) { + return nil, false + } + content, more, ok := replyToolCallArgs(part.FunctionCall.Arguments) + if !ok { + return nil, false + } + if content != "" { + hasNonEmpty = true + } + lastMore = more + results = append(results, Part{ + FunctionResult: &FunctionResult{ + ID: part.FunctionCall.ID, + Name: part.FunctionCall.Name, + Content: replyToolContinuationResponse, + }, + }) + } + if len(results) == 0 || !hasNonEmpty || !lastMore { + return nil, false } - return *payload.Content, true + return results, true } // calledReplyTool 判断本轮上游输出是否包含 final 函数调用 func calledReplyTool(output Output) bool { return slices.ContainsFunc(output.Parts, func(part Part) bool { - return part.FunctionCall != nil && part.FunctionCall.Name == replyToolName + return part.FunctionCall != nil && isReplyToolName(part.FunctionCall.Name) }) } diff --git a/internal/aistudio/runtime_go.go b/internal/aistudio/runtime_go.go index 34ff489c..44e29ae7 100644 --- a/internal/aistudio/runtime_go.go +++ b/internal/aistudio/runtime_go.go @@ -3,7 +3,6 @@ package aistudio import ( "bytes" "context" - "crypto/sha256" "encoding/base64" "encoding/json" "errors" @@ -96,8 +95,8 @@ type goWAARuntime struct { previous *goWAARuntime // running 是最近一次点击 Run 或 Rerun 取 proof 的 VM,随后的 GenerateContent 响应开始与结束时在其中派发指针下元素被替换的事件 running *waa.Runtime - // chat 是本页点击后发出的上一个 GenerateContent 各对话轮次的 SHA-256 摘要,页面还没有对话、点过 New chat 或上一次响应不是 200 时为 nil;与 running 同由 vmMu 保护 - chat [][sha256.Size]byte + // chat 是本页点击后发出的上一个 GenerateContent 的对话轮次,页面还没有对话、点过 New chat 或上一次响应不是 200 时为 nil;与 running 同由 vmMu 保护 + chat []json.RawMessage // uiLocale 是官网前端主程序地址声明的界面语言 uiLocale string @@ -1342,52 +1341,6 @@ func generateContents(body []byte) []json.RawMessage { return contents } -// chatDigests 返回 GenerateContent 正文各对话轮次的 SHA-256 摘要,不持有正文底层数组 -func chatDigests(body []byte) [][sha256.Size]byte { - contents := generateContents(body) - if contents == nil { - return nil - } - digests := make([][sha256.Size]byte, len(contents)) - for index, content := range contents { - digests[index] = sha256.Sum256(content) - } - return digests -} - -// startsNewChat 返回页面上一次发出的对话轮次摘要 previous 之后要发出 contents 时是否先开新对话 -func startsNewChat(previous [][sha256.Size]byte, contents []json.RawMessage) bool { - if previous == nil { - return false - } - samePrefix := func() bool { - for index, digest := range previous { - if sha256.Sum256(contents[index]) != digest { - return false - } - } - return true - } - if len(contents) == len(previous) && samePrefix() { - return false - } - if len(contents) == len(previous)+2 && samePrefix() && wireContentRole(contents[len(previous)]) == "model" { - return false - } - return true -} - -// wireContentRole 返回 GenerateContent 对话轮次 [parts, role] 的角色 -func wireContentRole(content json.RawMessage) string { - fields, ok := wireArray(content) - if !ok || len(fields) <= 1 { - return "" - } - var role string - _ = json.Unmarshal(fields[1], &role) - return role -} - // userGestureKey 标记 proof 所属请求在官网由页面上的点击或按键触发 type userGestureKey struct{} @@ -1454,7 +1407,7 @@ func (runtime *goWAARuntime) proof(ctx context.Context, digest string, prompt st switch { case run: var newChat func(at time.Time) - if startsNewChat(runtime.chat, contents) { + if camoufoxnative.StartsNewChat(runtime.chat, contents) { newChat = runtime.newChat } proof, err = vm.RunProofAfter(ctx, digest, prompt, newChat, settings, pickedPause) @@ -1533,7 +1486,7 @@ func (runtime *goWAARuntime) SendProtected(ctx context.Context, rawURL string, h runtime.vmMu.Lock() running, runtime.running = runtime.running, nil if running != nil { - runtime.chat = chatDigests(body) + runtime.chat = generateContents(body) } runtime.vmMu.Unlock() turn = runtime.elements.turn(body, counting) diff --git a/internal/aistudio/runtime_lease_test.go b/internal/aistudio/runtime_lease_test.go deleted file mode 100644 index 52ec93e1..00000000 --- a/internal/aistudio/runtime_lease_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package aistudio - -import ( - "os" - "runtime" - "testing" -) - -// TestUserCacheRootWithoutEnvironment 验证目录环境变量缺失时仍解析到同一个用户缓存目录 -func TestUserCacheRootWithoutEnvironment(t *testing.T) { - expected, err := os.UserCacheDir() - if err != nil { - t.Skipf("当前环境没有用户缓存目录: %v", err) - } - if runtime.GOOS == "windows" { - t.Setenv("LOCALAPPDATA", "") - } else { - if os.Getenv("XDG_CACHE_HOME") != "" { - t.Skip("XDG_CACHE_HOME 指定了非默认缓存目录") - } - t.Setenv("HOME", "") - } - actual, err := userCacheRoot() - if err != nil { - t.Fatalf("userCacheRoot: %v", err) - } - if actual != expected { - t.Fatalf("userCacheRoot = %q, want %q", actual, expected) - } -} diff --git a/internal/aistudio/runtime_native.go b/internal/aistudio/runtime_native.go index 4ae9374f..a9d4702b 100644 --- a/internal/aistudio/runtime_native.go +++ b/internal/aistudio/runtime_native.go @@ -52,7 +52,7 @@ type camoufoxRuntime struct { *camoufoxnative.Worker } -// Reload 按官网冷启动重新载入页面:当前标签页空闲时在其中重新载入,有进行中的请求时在新标签页中载入并切换过去,原标签页在请求结束后关闭;返回同一 runtime +// Reload 在新标签页中按官网冷启动重新载入页面,载入成功后切换过去并关闭空闲原标签页,原标签页有进行中的请求时在其请求结束后关闭;返回同一 runtime func (runtime camoufoxRuntime) Reload(ctx context.Context) (workerRuntime, error) { return runtime, runtime.Worker.Reload(ctx) } diff --git a/internal/aistudio/schema_test.go b/internal/aistudio/schema_test.go deleted file mode 100644 index 43202618..00000000 --- a/internal/aistudio/schema_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package aistudio - -import ( - "encoding/json" - "reflect" - "slices" - "testing" -) - -// TestEncodeJSONSchema_NullFields 核对可选空值与数据空值的编码字段 -func TestEncodeJSONSchema_NullFields(t *testing.T) { - fields := []string{"format", "description", "nullable", "enum", "items", "properties", "required", "minItems", "maxItems", "minProperties", "maxProperties", "minimum", "maximum", "minLength", "maxLength", "pattern", "oneOf", "anyOf", "allOf", "not", "default"} - for _, field := range fields { - t.Run(field, func(t *testing.T) { - wire, err := encodeJSONSchema(json.RawMessage(`{"type":"string","` + field + `":null}`)) - if err != nil || !reflect.DeepEqual(wire, []any{int64(1)}) { - t.Fatalf("wire=%#v error=%v", wire, err) - } - }) - } - wire, err := encodeJSONSchema(json.RawMessage(`{"type":"string","example":null}`)) - if err != nil || len(wire) <= 15 || !reflect.DeepEqual(wire[15], []any{int64(0)}) { - t.Fatalf("null example wire=%#v error=%v", wire, err) - } -} - -// TestEncodeJSONSchema_NotVariants 核对禁止约束和排除值的实际语义 -func TestEncodeJSONSchema_NotVariants(t *testing.T) { - for _, raw := range []string{`{"type":"string","not":null}`, `{"type":"string","not":false}`} { - wire, err := encodeJSONSchema(json.RawMessage(raw)) - if err != nil || !reflect.DeepEqual(wire, []any{int64(1)}) { - t.Fatalf("schema=%s wire=%#v error=%v", raw, wire, err) - } - } - for _, raw := range []string{`{"type":"string","not":true}`, `{"type":"string","not":{}}`, `{"type":"object","properties":{"deny":false},"required":["deny"]}`} { - if wire, err := encodeResponseSchema(json.RawMessage(raw)); err == nil { - t.Fatalf("forbidden schema=%s wire=%#v", raw, wire) - } - } - if _, err := encodeResponseSchema(json.RawMessage(`{"type":"object","properties":{"deny":false}}`)); err != nil { - t.Fatalf("optional false property: %v", err) - } - wire, err := encodeJSONSchema(json.RawMessage(`{"type":["string","null"],"not":{"type":"null"}}`)) - if err != nil || len(wire) <= 3 || wire[3] != false { - t.Fatalf("not null wire=%#v error=%v", wire, err) - } - for _, raw := range []string{`{"type":"string","not":""}`, `{"type":"string","not":{"enum":[""]}}`} { - wire, err := encodeJSONSchema(json.RawMessage(raw)) - if err != nil || len(wire) > 19 || len(wire) <= 12 || wire[12] != int64(1) { - t.Fatalf("not empty schema=%s wire=%#v error=%v", raw, wire, err) - } - } - for _, value := range []string{`"denied"`, `["a","b"]`, `["","a","b"]`} { - wire, err := encodeJSONSchema(json.RawMessage(`{"type":"string","not":` + value + `}`)) - if err != nil || len(wire) <= 19 { - t.Fatalf("not enum wire=%#v error=%v", wire, err) - } - excluded := wire[19].([]any) - var expected []string - if value[0] == '[' { - _ = json.Unmarshal([]byte(value), &expected) - expected = slices.DeleteFunc(expected, func(item string) bool { return item == "" }) - } else { - var text string - _ = json.Unmarshal([]byte(value), &text) - expected = []string{text} - } - if len(excluded) <= 4 || !reflect.DeepEqual(excluded[4], expected) { - t.Fatalf("excluded=%#v expected=%#v", excluded, expected) - } - } -} - -// TestGeminiSchemaNotEmptyString 核对 not 排除空串只收紧空串:联合类型仍接受其余类型,带其他约束的排除不额外要求非空 -func TestGeminiSchemaNotEmptyString(t *testing.T) { - union, err := geminiSchema(json.RawMessage(`{"type":["integer","string"],"not":{"enum":["","reserved"]}}`)) - if err != nil || union["type"] == "STRING" || union["minLength"] != nil { - t.Fatalf("联合类型被收窄为字符串 schema=%#v error=%v", union, err) - } - variants, _ := union["anyOf"].([]any) - if !slices.ContainsFunc(variants, func(variant any) bool { return variant.(map[string]any)["type"] == "INTEGER" }) { - t.Fatalf("联合类型缺少整数分支 anyOf=%#v", union["anyOf"]) - } - pattern, err := geminiSchema(json.RawMessage(`{"type":"string","not":{"enum":["","reserved"],"pattern":"^reserved$"}}`)) - not, _ := pattern["not"].(map[string]any) - if err != nil || pattern["minLength"] != nil || not == nil || !reflect.DeepEqual(not["enum"], []string{"reserved"}) || not["pattern"] != "^reserved$" { - t.Fatalf("带 pattern 的排除 schema=%#v error=%v", pattern, err) - } -} - -// TestEncodeJSONSchema_TopLevelNullOrEmpty 核对省略参数使用对象结构 -func TestEncodeJSONSchema_TopLevelNullOrEmpty(t *testing.T) { - for _, raw := range []string{"", " ", "null"} { - wire, err := encodeJSONSchema(json.RawMessage(raw)) - if err != nil || !reflect.DeepEqual(wire, []any{int64(6)}) { - t.Fatalf("schema=%q wire=%#v error=%v", raw, wire, err) - } - } -} - -// TestEncodeJSONSchema_DirectConst 核对常量属性的类型和枚举值 -func TestEncodeJSONSchema_DirectConst(t *testing.T) { - wire, err := encodeJSONSchema(json.RawMessage(`{"type":"object","properties":{"type":{"const":"tool_call","title":"Type"}}}`)) - if err != nil || len(wire) <= 6 { - t.Fatalf("wire=%#v error=%v", wire, err) - } - properties := wire[6].([]any) - if len(properties) != 1 { - t.Fatalf("properties=%#v", properties) - } - property := properties[0].([]any) - value := property[1].([]any) - if property[0] != "type" || len(value) <= 4 || value[0] != int64(1) || !reflect.DeepEqual(value[4], []string{"tool_call"}) { - t.Fatalf("property=%#v", property) - } -} diff --git a/internal/aistudio/service.go b/internal/aistudio/service.go index 62395f00..4adef0a3 100644 --- a/internal/aistudio/service.go +++ b/internal/aistudio/service.go @@ -13,15 +13,28 @@ import ( "sort" "strings" "sync" + "sync/atomic" "time" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" ) +// RequestOptions 保存单次请求与目录同步可热替换的行为选项 +type RequestOptions struct { + BuildNativeNonstream bool + YouTubeLinks bool + DiscoverHiddenModels bool + StripThoughtSignatures bool + ContinuationRewrite bool + ContinuationPrompt string +} + // PooledService 在账户租约内调用协议客户端 type PooledService struct { pool *AccountPool client *Client + // options 为运行时热替换的原子请求行为快照;为空时回退读取下方兼容字段 + options atomic.Pointer[RequestOptions] // BuildNativeNonstream 让非流式请求优先使用具备资格的 Build 通道 BuildNativeNonstream bool // YouTubeLinks 把 user 文本中的 YouTube 链接作为视频外部媒体发送 @@ -42,6 +55,65 @@ type PooledService struct { inlineMediaUses map[string]int } +// SetRequestOptions 原子替换后续请求与目录同步使用的行为选项,不中断进行中的请求 +func (s *PooledService) SetRequestOptions(opts RequestOptions) { + copyOpts := opts + s.options.Store(©Opts) +} + +// requestOptions 返回当前生效的行为选项快照 +func (s *PooledService) requestOptions() RequestOptions { + if opts := s.options.Load(); opts != nil { + return *opts + } + return RequestOptions{ + BuildNativeNonstream: s.BuildNativeNonstream, + YouTubeLinks: s.YouTubeLinks, + DiscoverHiddenModels: s.DiscoverHiddenModels, + StripThoughtSignatures: s.StripThoughtSignatures, + ContinuationRewrite: s.ContinuationRewrite, + ContinuationPrompt: s.ContinuationPrompt, + } +} + +// ClearHiddenModels 从内存目录与磁盘目录缓存中移除全部官网隐藏模型,返回发生变化的账户数 +func (s *PooledService) ClearHiddenModels() int { + changed := s.pool.ClearHiddenModels() + for _, accountID := range changed { + s.client.ClearHiddenModels(accountID) + if source := s.client.modelCatalogSource(accountID); len(source) > 0 { + if err := s.pool.SaveCatalogCache(accountID, source); err != nil { + slog.Warn("账户模型目录缓存保存失败", "account", accountID, "error", err) + } + } + } + return len(changed) +} + +// RefreshBuildCatalog 为单个账户拉取并保存 Build 通道模型目录 +func (s *PooledService) RefreshBuildCatalog(ctx context.Context, accountID string) (bool, error) { + lease, owned, err := resolveAccountLease(ctx, s.pool, AccountSelection{AccountID: accountID}) + if err != nil { + return false, err + } + if owned { + defer func() { _ = lease.Release() }() + } + models, err := s.client.BuildModelsForAccount(ContextWithAccountLease(ctx, lease), accountID) + if err != nil { + return false, err + } + if err := s.pool.SetBuildCatalog(accountID, models); err != nil { + return false, err + } + if source := s.client.modelCatalogSource(accountID); len(source) > 0 { + if err := s.pool.SaveCatalogCache(accountID, source); err != nil { + slog.Warn("账户模型目录缓存保存失败", "account", accountID, "error", err) + } + } + return len(models) > 0, nil +} + // PoolRequestContextProvider 从租约账户读取协议上下文 type PoolRequestContextProvider struct { pool *AccountPool @@ -70,10 +142,15 @@ type WorkerProtectedTransportOptions struct { type WorkerProtectedTransport struct { transport *MakerSuiteHTTPTransport workers ProtectedPreparerProvider - setupTimeout time.Duration + setupTimeout atomic.Int64 runs *pageRuns } +// SetSetupTimeout 更新后续实时会话建连使用的初始化超时 +func (t *WorkerProtectedTransport) SetSetupTimeout(timeout time.Duration) { + t.setupTimeout.Store(int64(timeout)) +} + var _ Service = (*PooledService)(nil) var _ RequestContextProvider = (*PoolRequestContextProvider)(nil) var _ ProtectedTransport = (*WorkerProtectedTransport)(nil) @@ -97,9 +174,11 @@ func NewPoolRequestContextProvider(pool *AccountPool) *PoolRequestContextProvide // NewWorkerProtectedTransport 创建基于 lazy WAA preparer 的受保护传输 func NewWorkerProtectedTransport(options WorkerProtectedTransportOptions) *WorkerProtectedTransport { - return &WorkerProtectedTransport{ - transport: options.Transport, workers: options.Workers, setupTimeout: options.SetupTimeout, runs: newPageRuns(), + transport := &WorkerProtectedTransport{ + transport: options.Transport, workers: options.Workers, runs: newPageRuns(), } + transport.setupTimeout.Store(int64(options.SetupTimeout)) + return transport } // DoProtected 写入 fresh proof 后经账户的 WAA 运行时发送 GenerateContent、Build 代理或写代码助手请求,binding 与写入页面输入框的提示词取自关联函数结果后的 contents,页面提示词为最后一个轮次的文本;账户页面再次运行同一对话的 GenerateContent 按官网 Rerun 不写入提示词 @@ -636,22 +715,13 @@ func (l *AccountLease) Model(modelID string) (Model, bool) { return Model{}, false } -// InteractionRoute 返回模型在租约账户与当前通道上是否走 CreateInteractionStream 或 CreateInteraction 后台任务 -func (l *AccountLease) InteractionRoute(modelID string) (stream bool, task bool) { +// InteractionRoute 返回模型在租约账户与当前通道上的 Interaction 选路 +func (l *AccountLease) InteractionRoute(modelID string) InteractionRouting { model, ok := l.Model(modelID) if !ok { - return false, false + return ResolveInteractionRouting(0, false) } - return interactionRoute(model, GenerationDefaults{}, l.Channel()) -} - -// interactionRoute 返回模型在指定通道上是否走 CreateInteractionStream 或 CreateInteraction 后台任务 -func interactionRoute(model Model, defaults GenerationDefaults, channel Channel) (stream bool, task bool) { - if channel == ChannelBuild { - return false, false - } - return model.Capabilities["interaction_stream"] || defaults.InteractionStream, - model.Capabilities["interaction_task"] || defaults.InteractionTask + return interactionRouting(model, GenerationDefaults{}, l.Channel()) } // DefinitiveAuthenticationFailure 判断上游是否明确要求重新认证 @@ -710,14 +780,15 @@ func (s *PooledService) modelsForLease(ctx context.Context, lease *AccountLease, if err != nil { return nil, s.catalogFailure(leaseCtx, lease, err) } + opts := s.requestOptions() var hidden map[string]string - if s.DiscoverHiddenModels { + if opts.DiscoverHiddenModels { if hidden, err = s.client.DiscoverHiddenModels(leaseCtx, account.ID); err != nil { slog.Warn("探测官网隐藏模型失败", "account", account.ID, "error", err) } models = s.client.accountModels(account.ID) } - if err := s.pool.SetHiddenModels(account.ID, hidden, s.DiscoverHiddenModels && err == nil); err != nil { + if err := s.pool.SetHiddenModels(account.ID, hidden, opts.DiscoverHiddenModels && err == nil); err != nil { return nil, err } buildEnabled := s.pool.BuildEnabled() @@ -773,12 +844,13 @@ func (s *PooledService) CountTokens(ctx context.Context, request TokenCountReque if modelID == "" { return TokenCount{}, fmt.Errorf("%w: CountTokens model 不能为空", ErrInvalidArgument) } + opts := s.requestOptions() request.System = clientSystem(request.System) request.Contents = dropUserRejected(request.Contents) - if s.YouTubeLinks { + if opts.YouTubeLinks { request.Contents = attachYouTubeLinks(request.Contents) } - if s.StripThoughtSignatures { + if opts.StripThoughtSignatures { request.Contents = stripThoughtSignatures(request.Contents) } systemOnly := len(request.Contents) == 0 @@ -863,7 +935,8 @@ func (s *PooledService) ValidateGenerateRequest(request GenerateRequest) error { if modelID == "" { return fmt.Errorf("%w: GenerateContent model 不能为空", ErrInvalidArgument) } - request.System, request.Contents = normalizeTurns(request.System, request.Contents, s.rewritesAssistantTail(modelID), s.ContinuationPrompt) + opts := s.requestOptions() + request.System, request.Contents = normalizeTurns(request.System, request.Contents, shouldRewriteAssistantTail(modelID, opts.ContinuationRewrite), opts.ContinuationPrompt) if len(request.Contents) == 0 { return fmt.Errorf("%w: 请求没有系统提示或对话内容", ErrInvalidArgument) } @@ -876,12 +949,17 @@ func (s *PooledService) ValidateGenerateRequest(request GenerateRequest) error { // generateTurns 返回 Generate 发往上游前改写的系统指令与对话轮 func (s *PooledService) generateTurns(request GenerateRequest) ([]string, []Content) { + return s.generateTurnsWith(request, s.requestOptions()) +} + +// generateTurnsWith 按指定选项快照改写系统指令与对话轮 +func (s *PooledService) generateTurnsWith(request GenerateRequest, opts RequestOptions) ([]string, []Content) { modelID := strings.TrimPrefix(strings.TrimSpace(request.Model), "models/") - system, contents := normalizeTurns(request.System, request.Contents, s.rewritesAssistantTail(modelID), s.ContinuationPrompt) - if s.YouTubeLinks { + system, contents := normalizeTurns(request.System, request.Contents, shouldRewriteAssistantTail(modelID, opts.ContinuationRewrite), opts.ContinuationPrompt) + if opts.YouTubeLinks { contents = attachYouTubeLinks(contents) } - if s.StripThoughtSignatures { + if opts.StripThoughtSignatures { contents = stripThoughtSignatures(contents) } return system, contents @@ -893,11 +971,12 @@ func (s *PooledService) Generate(ctx context.Context, request GenerateRequest) ( if modelID == "" { return nil, fmt.Errorf("%w: GenerateContent model 不能为空", ErrInvalidArgument) } - request.System, request.Contents = s.generateTurns(request) + opts := s.requestOptions() + request.System, request.Contents = s.generateTurnsWith(request, opts) if len(request.Contents) == 0 { return nil, fmt.Errorf("%w: 请求没有系统提示或对话内容", ErrInvalidArgument) } - request.restoreModelTurns = !s.StripThoughtSignatures + request.restoreModelTurns = !opts.StripThoughtSignatures resourceID, err := s.pool.ResourceIDForContents(ctx, request.Contents) if err != nil { return nil, err @@ -908,7 +987,7 @@ func (s *PooledService) Generate(ctx context.Context, request GenerateRequest) ( AccountID: strings.TrimSpace(request.AccountID), ResourceID: resourceID, } - if RequestNeedsBuild(request) || request.Unary && s.BuildNativeNonstream { + if RequestNeedsBuild(request) || request.Unary && opts.BuildNativeNonstream { selection.PreferredChannel = ChannelBuild } pinned := selection.AccountID != "" || selection.ResourceID != "" diff --git a/internal/aistudio/tool_contract.go b/internal/aistudio/tool_contract.go index 2f7d8388..1d2d1672 100644 --- a/internal/aistudio/tool_contract.go +++ b/internal/aistudio/tool_contract.go @@ -26,6 +26,11 @@ type toolContract struct { // prepareToolRequest 将工具选择与约束转换为共同生成请求,compile 为 true 时编译严格函数的参数 Schema 供校验函数调用参数 func prepareToolRequest(request GenerateRequest, compile bool) (GenerateRequest, *toolContract, error) { + return prepareToolRequestWithReplyTool(request, compile, false) +} + +// prepareToolRequestWithReplyTool 将工具选择与约束转换为共同生成请求,replyTool 为 true 时单次工具调用提示不约束内部 final 工具 +func prepareToolRequestWithReplyTool(request GenerateRequest, compile bool, replyTool bool) (GenerateRequest, *toolContract, error) { config := request.Tools.ToolConfig if config.Mode == "none" { return request, nil, nil @@ -126,9 +131,13 @@ func prepareToolRequest(request GenerateRequest, compile bool) (GenerateRequest, request.System = appendSystem(request.System, "\nUse one of these tools in this response: "+strings.Join(names, ", ")+". Use the tool before answering.") } if contract.parallel != nil { - request.System = appendSystem(request.System, "\nCall at most one function in this response.") + if replyTool { + request.System = appendSystem(request.System, "\nCall at most one non-final tool in this response (this limit does not apply to `final`).") + } else { + request.System = appendSystem(request.System, "\nCall at most one function in this response.") + } } - if !contract.required && len(config.AllowedFunctionNames) == 0 && len(contract.schemas) == 0 && contract.parallel == nil { + if !replyTool && !contract.required && len(config.AllowedFunctionNames) == 0 && len(contract.schemas) == 0 && contract.parallel == nil { contract = nil } return request, contract, nil @@ -217,6 +226,8 @@ func (contract *toolContract) forward(ctx context.Context, source <-chan Event) serverSideUsed := false failed := false usedReplyTool := false + hasFinalText := false + lastFinalEndedNewline := false sawPlainText := false bypassReported := false matchedStop := "" @@ -297,7 +308,7 @@ func (contract *toolContract) forward(ctx context.Context, source <-chan Event) } continue } - if contract.replyTool && event.Kind == EventToolCall && event.FunctionCall != nil && event.FunctionCall.Name == replyToolName { + if contract.replyTool && event.Kind == EventToolCall && event.FunctionCall != nil && isReplyToolName(event.FunctionCall.Name) { text, ok := replyToolText(event.FunctionCall.Arguments) if !ok { failed = true @@ -308,7 +319,16 @@ func (contract *toolContract) forward(ctx context.Context, source <-chan Event) continue } usedReplyTool = true + reportReplyToolCall(ctx) lastTextEvent = event + rawText := text + if rawText != "" { + if hasFinalText && !lastFinalEndedNewline && !strings.HasPrefix(rawText, "\n") && !strings.HasPrefix(rawText, "\r") { + text = "\n\n" + rawText + } + hasFinalText = true + lastFinalEndedNewline = strings.HasSuffix(rawText, "\n") || strings.HasSuffix(rawText, "\r") + } if matcher != nil { var sequence string text, sequence = matcher.write(text) diff --git a/internal/aistudio/tool_schema_test.go b/internal/aistudio/tool_schema_test.go deleted file mode 100644 index 78a0d883..00000000 --- a/internal/aistudio/tool_schema_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package aistudio - -import ( - "encoding/json" - "reflect" - "strings" - "testing" -) - -// questionToolParameters 表示支持文字或对象选项的问题工具 -const questionToolParameters = `{"type":"object","properties":{"questions":{"type":"array","items":{"type":"object","properties":{"multiSelect":{"type":"boolean"},"options":{"type":"array","items":{"anyOf":[{"type":"string"},{"type":"object","properties":{"description":{"type":"string"},"label":{"type":"string"}},"required":["label"]}]}},"question":{"type":"string"}},"required":["question","options"]}}},"required":["questions"]}` - -// TestToolSchemaMixedOptions 验证复杂问题工具保持原始声明且直接使用 Playground -func TestToolSchemaMixedOptions(t *testing.T) { - declaration := FunctionDeclaration{Name: "asktool", Parameters: json.RawMessage(questionToolParameters)} - before, _ := json.Marshal(declaration) - wire, err := encodeFunctionDeclaration(declaration) - if err != nil { - t.Fatal(err) - } - after, _ := json.Marshal(declaration) - if string(before) != string(after) { - t.Fatal("原始工具声明发生变化") - } - normalized, err := normalizeFunctionParameters(declaration.Parameters) - if err != nil || !strings.Contains(wire[1].(string), string(normalized)) || schemaWireNeedsBuild(wire[2].([]any)) { - t.Fatalf("完整约束或可发送的参数结构缺失: %#v", wire) - } - request := GenerateRequest{Tools: Tools{Functions: []FunctionDeclaration{declaration}}} - if RequestNeedsBuild(request) { - t.Fatal("工具声明触发 Build 分流") - } - request.Config.ResponseSchema = json.RawMessage(`{"type":"object","properties":{"value":{}}}`) - if !RequestNeedsBuild(request) { - t.Fatal("结构化输出的原生通道选择丢失") - } -} - -// TestToolSchemaUnionBranches 验证联合分支与首个数组元素类型保留 -func TestToolSchemaUnionBranches(t *testing.T) { - for _, test := range []struct { - name, schema string - index int - }{ - {"string object", `{"anyOf":[{"type":"string","minLength":2},{"type":"object","properties":{"label":{"type":"string"}},"required":["label"]}]}`, 17}, - {"object string", `{"anyOf":[{"type":"object","properties":{"label":{"type":"string"}},"required":["label"]},{"type":"string"}]}`, 17}, - {"overlapping oneOf", `{"oneOf":[{"type":"string"},{"type":"string","minLength":3},{"type":"object"}]}`, 16}, - {"array first", `{"anyOf":[{"type":"array","items":{"type":"integer"},"minItems":1},{"type":"string"}]}`, 17}, - } { - t.Run(test.name, func(t *testing.T) { - wire, err := encodeFunctionDeclaration(FunctionDeclaration{Name: "pick", Parameters: json.RawMessage(test.schema)}) - if err != nil { - t.Fatal(err) - } - parameters := wire[2].([]any) - var original map[string][]json.RawMessage - _ = json.Unmarshal([]byte(test.schema), &original) - key := "anyOf" - if test.index == 16 { - key = "oneOf" - } - actual := parameters[test.index].([]any) - if len(actual) != len(original[key]) { - t.Fatal("联合分支数量变化") - } - for index, branch := range original[key] { - expected, err := encodeJSONSchema(branch) - if err != nil || !reflect.DeepEqual(actual[index], expected) { - t.Fatalf("联合分支 %d 变化: %#v, %v", index, actual[index], err) - } - } - if test.name == "array first" && parameters[5].([]any)[0] != int64(3) { - t.Fatal("数组元素类型变化") - } - }) - } -} - -// TestToolSchemaOpenNodes 验证开放、引用与组合节点携带完整原始约束 -func TestToolSchemaOpenNodes(t *testing.T) { - for _, raw := range []string{ - `{"type":"object","properties":{"value":true}}`, - `{"type":"array"}`, - `{"anyOf":[{},{"type":"string"}]}`, - `{"anyOf":[{"type":"array"},{"type":"string"}]}`, - `{"anyOf":[{"type":"string"},{"type":"object"}],"not":{"type":"string"}}`, - `{"type":"object","properties":{"value":{"const":7}}}`, - `{"type":"object","properties":{"value":{"const":null}}}`, - `{"type":"object","properties":{"value":{"$ref":"#/$defs/item"}},"$defs":{"item":{"type":"string"}}}`, - } { - t.Run(raw, func(t *testing.T) { - wire, err := encodeFunctionDeclaration(FunctionDeclaration{Name: "pick", Parameters: json.RawMessage(raw)}) - if err != nil { - t.Fatal(err) - } - normalized, err := normalizeFunctionParameters(json.RawMessage(raw)) - if err != nil || !strings.Contains(wire[1].(string), string(normalized)) || schemaWireNeedsBuild(wire[2].([]any)) { - t.Fatalf("约束或参数结构缺失: %#v", wire) - } - }) - } -} - -// TestToolSchemaKeepsFileTools 验证问题工具与文件工具共同编码时保留普通声明 -func TestToolSchemaKeepsFileTools(t *testing.T) { - tools := Tools{Functions: []FunctionDeclaration{ - {Name: "Read", Parameters: json.RawMessage(`{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}`)}, - {Name: "asktool", Parameters: json.RawMessage(questionToolParameters)}, - {Name: "Write", Parameters: json.RawMessage(`{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path","content"]}`)}, - }} - before, _ := json.Marshal(tools) - wire, _, err := encodeRequestedTools(tools) - if err != nil { - t.Fatal(err) - } - declarations := wire[0].([]any)[1].([]any) - for _, index := range []int{0, 2} { - expected, err := encodeFunctionDeclaration(tools.Functions[index]) - if err != nil || !reflect.DeepEqual(declarations[index], expected) { - t.Fatalf("文件工具 %d 变化", index) - } - } - after, _ := json.Marshal(tools) - if string(before) != string(after) { - t.Fatal("原始工具集发生变化") - } -} - -// TestToolSchemaLongFunctionNames 验证超过 63 字符的函数名以不超过 63 字符的同一名称声明与回传历史,上游调用以原名交给客户端 -func TestToolSchemaLongFunctionNames(t *testing.T) { - prefix := "mcp__codex_apps__codex_document_control___execute_document_" - names := []string{prefix + "command", prefix + "commands", "Read"} - functions := make([]FunctionDeclaration, 0, len(names)) - for _, name := range names { - functions = append(functions, FunctionDeclaration{Name: name, Parameters: json.RawMessage(`{"type":"object"}`)}) - } - wire, _, err := encodeRequestedTools(Tools{Functions: functions}) - if err != nil { - t.Fatal(err) - } - sent := make([]string, 0, len(names)) - for _, declaration := range wire[0].([]any)[1].([]any) { - sent = append(sent, declaration.([]any)[0].(string)) - } - if len(sent[0]) > 63 || len(sent[1]) > 63 || sent[0] == sent[1] || sent[2] != "Read" { - t.Fatalf("声明的函数名 %q", sent) - } - contents, err := encodeContents([]Content{ - {Role: RoleUser, Parts: []Part{{Text: "run"}}}, - {Role: RoleAssistant, Parts: []Part{{FunctionCall: &FunctionCall{ID: "call-1", Name: names[0], Arguments: json.RawMessage(`{}`)}}}}, - {Role: RoleUser, Parts: []Part{{FunctionResult: &FunctionResult{ID: "call-1", Name: names[0], Content: json.RawMessage(`{"ok":true}`)}}}}, - }) - if err != nil { - t.Fatal(err) - } - history, _ := json.Marshal(contents) - if strings.Count(string(history), `"`+sent[0]+`"`) != 2 || strings.Contains(string(history), names[0]) { - t.Fatalf("历史中的函数名与声明不一致: %s", history) - } - var received []string - emit := restoreFunctionNames(functions, func(event Event) error { - received = append(received, event.FunctionCall.Name) - return nil - }) - for _, name := range sent { - if err := emit(Event{Kind: EventToolCall, FunctionCall: &FunctionCall{Name: name}}); err != nil { - t.Fatal(err) - } - } - if !reflect.DeepEqual(received, names) { - t.Fatalf("回传的函数名 %q", received) - } -} diff --git a/internal/aistudio/tool_validation.go b/internal/aistudio/tool_validation.go index a0398aa6..feb693b5 100644 --- a/internal/aistudio/tool_validation.go +++ b/internal/aistudio/tool_validation.go @@ -81,7 +81,7 @@ func transcribeFunctionParts(contents []Content) ([]Content, error) { return transcribed, nil } -// ToolPartTranscript 返回函数调用、函数结果与代码执行 part 的 Gemini API JSON 文本 +// ToolPartTranscript 返回函数调用、函数结果、代码执行与服务端工具步骤 part 的 Gemini API JSON 文本 func ToolPartTranscript(part Part) (string, error) { var value map[string]any switch { @@ -93,6 +93,10 @@ func ToolPartTranscript(part Part) (string, error) { value = map[string]any{"executableCode": part.ExecutableCode} case part.CodeExecutionResult != nil: value = map[string]any{"codeExecutionResult": part.CodeExecutionResult} + case part.ToolCall != nil: + value = map[string]any{"toolCall": map[string]any{"id": part.ToolCall.ID, "toolType": part.ToolCall.Type, "args": transcriptJSON(part.ToolCall.Data)}} + case part.ToolResponse != nil: + value = map[string]any{"toolResponse": map[string]any{"id": part.ToolResponse.ID, "toolType": part.ToolResponse.Type, "response": transcriptJSON(part.ToolResponse.Data)}} } encoded, err := json.Marshal(value) if err != nil { diff --git a/internal/aistudio/transport_browser.go b/internal/aistudio/transport_browser.go index 261dc4a2..fed51514 100644 --- a/internal/aistudio/transport_browser.go +++ b/internal/aistudio/transport_browser.go @@ -11,6 +11,7 @@ import ( "net/url" "slices" "sort" + "strconv" "strings" "sync" "time" @@ -47,12 +48,6 @@ const ( firefoxWindowUpdateThreshold = 4 << 20 // firefoxMaxPersistentConns 是 Firefox network.http.max-persistent-connections-per-server:一类请求对一个主机的已建立与建立中连接数上限 firefoxMaxPersistentConns = 6 - // firefoxPreflightCacheSize 是 Firefox nsPreflightCache 的条目上限 - firefoxPreflightCacheSize = 100 - // firefoxPreflightDefaultMaxAge 是 Firefox Access-Control-Max-Age 缺省或为空时的缓存有效期 - firefoxPreflightDefaultMaxAge = 5 * time.Second - // firefoxPreflightMaxAgeLimit 是 Firefox Access-Control-Max-Age 的上限秒数(24 小时) - firefoxPreflightMaxAgeLimit = 86400 ) // firefoxDirectDialer 是直连拨号器,按 Firefox network.http.connection-timeout 设置 90 秒上限 @@ -229,17 +224,14 @@ type browserRoundTripper struct { transport *http2.Transport pool *firefoxConnPool mu sync.Mutex - // preflights 按 preflightCacheKey 记录 CORS 预检缓存 + // preflights 按 preflightKey 记录 CORS 预检缓存 preflights map[string]preflightGrant - // preflightSeq 递增记录预检缓存条目的最近使用顺序 - preflightSeq uint64 } -// preflightGrant 是一个 URL 的 CORS 预检缓存:预检响应允许的方法与请求头(小写)各自的到期时刻与最近使用序号,与 Firefox nsPreflightCache 相同 +// preflightGrant 是一个 URL 的 CORS 预检缓存:预检响应允许的方法与请求头(小写)各自的到期时刻,与 Firefox nsPreflightCache 相同 type preflightGrant struct { methods map[string]time.Time headers map[string]time.Time - used uint64 } // allows 判断缓存是否覆盖请求:GET 与 POST 不查方法,其余方法与每个脚本设置的请求头都在有效期内 @@ -255,21 +247,6 @@ func (grant preflightGrant) allows(method string, headers []string, now time.Tim return true } -// purgeExpired 删除缓存项中已到期的方法与请求头,全部清空时返回 true -func (grant preflightGrant) purgeExpired(now time.Time) bool { - for method, expiry := range grant.methods { - if !now.Before(expiry) { - delete(grant.methods, method) - } - } - for name, expiry := range grant.headers { - if !now.Before(expiry) { - delete(grant.headers, name) - } - } - return len(grant.methods) == 0 && len(grant.headers) == 0 -} - type browserResponseBody struct { body io.ReadCloser source *fhttp.Response @@ -685,10 +662,8 @@ func (transport *browserRoundTripper) RoundTrip(request *stdhttp.Request) (*stdh upstream.Header[fhttp.HeaderOrderKey] = orderedHeaderNames(upstream.Header, request.URL.Host) response, err := transport.roundTrip(upstream, requestClassOf(request.Context()).anonymous) if err != nil { - target := request.URL.String() transport.mu.Lock() - delete(transport.preflights, preflightCacheKey(target, false)) - delete(transport.preflights, preflightCacheKey(target, true)) + delete(transport.preflights, preflightKey(request)) transport.mu.Unlock() return nil, err } @@ -775,34 +750,15 @@ func standardHeader(source fhttp.Header) stdhttp.Header { return result } -// preflightCacheKey 返回 URL 与是否匿名的 CORS 预检缓存键,与 Firefox nsPreflightCache 一样区分是否携带凭据 -func preflightCacheKey(target string, anonymous bool) string { - if anonymous { - return "anonymous " + target - } - return target -} - -// parsePreflightMaxAge 按 Firefox nsCORSPreflightListener::AddResultToCache 解析 Access-Control-Max-Age:空值按 5 秒,纯数字按秒封顶 24 小时,0 或含非数字字符时不缓存 -func parsePreflightMaxAge(value string) (time.Duration, bool) { - if value == "" { - return firefoxPreflightDefaultMaxAge, true - } - var seconds uint64 - for i := range len(value) { - ch := value[i] - if ch < '0' || ch > '9' { - return 0, false - } - seconds = min(seconds*10+uint64(ch-'0'), firefoxPreflightMaxAgeLimit) - } - if seconds == 0 { - return 0, false +// preflightKey 返回请求的 CORS 预检缓存键:与 Firefox nsPreflightCache 一样按 URL 与是否携带凭据区分 +func preflightKey(request *stdhttp.Request) string { + if requestClassOf(request.Context()).anonymous { + return "anonymous " + request.URL.String() } - return time.Duration(seconds) * time.Second, true + return request.URL.String() } -// ensurePreflight 为带 Origin 的跨域 cors 请求按 Firefox 的流程先发 CORS 预检:携带凭据的请求先在后台预先拨出带凭据的连接,预检走匿名连接,预检响应允许的方法与请求头按 Access-Control-Max-Age(上限 24 小时、缓存上限 100 条)逐个缓存;no-cors 请求与只带安全头的 GET、HEAD、POST 不预检 +// ensurePreflight 为带 Origin 的跨域 cors 请求按 Firefox 的流程先发 CORS 预检:携带凭据的请求先在后台预先拨出带凭据的连接,预检走匿名连接,预检响应允许的方法与请求头按 Access-Control-Max-Age(上限 24 小时)逐个缓存;no-cors 请求与只带安全头的 GET、HEAD、POST 不预检 func (transport *browserRoundTripper) ensurePreflight(request *stdhttp.Request) error { origin, err := url.Parse(request.Header.Get("Origin")) if request.Method == stdhttp.MethodOptions || request.Header.Get("Sec-Fetch-Mode") == "no-cors" || err != nil || origin.Host == "" || origin.Host == request.URL.Host { @@ -814,16 +770,9 @@ func (transport *browserRoundTripper) ensurePreflight(request *stdhttp.Request) } target := request.URL.String() class := requestClassOf(request.Context()) - key := preflightCacheKey(target, class.anonymous) - now := time.Now() + key := preflightKey(request) transport.mu.Lock() - grant, exists := transport.preflights[key] - if exists { - transport.preflightSeq++ - grant.used = transport.preflightSeq - transport.preflights[key] = grant - } - cached := exists && grant.allows(request.Method, unsafe, now) + cached := transport.preflights[key].allows(request.Method, unsafe, time.Now()) transport.mu.Unlock() if cached { return nil @@ -860,47 +809,23 @@ func (transport *browserRoundTripper) ensurePreflight(request *stdhttp.Request) if response.StatusCode < 200 || response.StatusCode > 299 { return fmt.Errorf("CORS 预检返回 HTTP %d", response.StatusCode) } - maxAge, ok := parsePreflightMaxAge(response.Header.Get("Access-Control-Max-Age")) - if !ok { - return nil + maxAge := 5 * time.Second + if seconds, err := strconv.Atoi(response.Header.Get("Access-Control-Max-Age")); err == nil { + maxAge = min(time.Duration(seconds)*time.Second, 24*time.Hour) } - storedAt := time.Now() - expiry := storedAt.Add(maxAge) + expiry := time.Now().Add(maxAge) transport.mu.Lock() - grant, exists = transport.preflights[key] - if !exists { - if len(transport.preflights) >= firefoxPreflightCacheSize { - for cachedKey, cachedGrant := range transport.preflights { - if cachedGrant.purgeExpired(storedAt) { - delete(transport.preflights, cachedKey) - } - } - if len(transport.preflights) >= firefoxPreflightCacheSize { - var oldestKey string - var oldestUsed uint64 - for cachedKey, cachedGrant := range transport.preflights { - if oldestKey == "" || cachedGrant.used < oldestUsed { - oldestKey, oldestUsed = cachedKey, cachedGrant.used - } - } - delete(transport.preflights, oldestKey) - } - } + grant := transport.preflights[key] + if grant.headers == nil { grant = preflightGrant{methods: map[string]time.Time{}, headers: map[string]time.Time{}} + transport.preflights[key] = grant } - transport.preflightSeq++ - grant.used = transport.preflightSeq for _, method := range strings.Split(response.Header.Get("Access-Control-Allow-Methods"), ",") { - if method = strings.TrimSpace(method); method != "" { - grant.methods[method] = expiry - } + grant.methods[strings.TrimSpace(method)] = expiry } for _, name := range strings.Split(response.Header.Get("Access-Control-Allow-Headers"), ",") { - if name = strings.ToLower(strings.TrimSpace(name)); name != "" { - grant.headers[name] = expiry - } + grant.headers[strings.ToLower(strings.TrimSpace(name))] = expiry } - transport.preflights[key] = grant transport.mu.Unlock() return nil } diff --git a/internal/aistudio/transport_browser_test.go b/internal/aistudio/transport_browser_test.go deleted file mode 100644 index b2df3e4e..00000000 --- a/internal/aistudio/transport_browser_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package aistudio - -import ( - "reflect" - "testing" - "time" - - fhttp "github.com/Mag1cFall/fhttp" - "github.com/Mag1cFall/fhttp/http2" -) - -// TestBrowserRoundTripperFirefoxHTTP2 验证浏览器传输使用 Firefox 158 的 HTTP/2 帧参数、按请求类别的 HEADERS 优先级与 PING 保活 -func TestBrowserRoundTripperFirefoxHTTP2(t *testing.T) { - roundTripper, err := newBrowserRoundTripper("") - if err != nil { - t.Fatal(err) - } - transport := roundTripper.(*browserRoundTripper).transport - if transport.ReadIdleTimeout != 58*time.Second || transport.PingTimeout != 8*time.Second { - t.Fatalf("PING 阈值=%s 超时=%s,应为 Firefox 默认的 58s 与 8s", transport.ReadIdleTimeout, transport.PingTimeout) - } - settings := map[http2.SettingID]uint32{http2.SettingHeaderTableSize: 65536, http2.SettingEnablePush: 0, http2.SettingInitialWindowSize: 131072, http2.SettingMaxFrameSize: 16384} - order := []http2.SettingID{http2.SettingHeaderTableSize, http2.SettingEnablePush, http2.SettingInitialWindowSize, http2.SettingMaxFrameSize} - if !reflect.DeepEqual(transport.Settings, settings) || !reflect.DeepEqual(transport.SettingsOrder, order) { - t.Fatalf("SETTINGS=%v 顺序=%v,应为 Firefox 158 的 %v 顺序 %v", transport.Settings, transport.SettingsOrder, settings, order) - } - if transport.ConnectionFlow != 12517377 || transport.StreamWindowUpdate != 12451840 || transport.WindowUpdateThreshold != 4<<20 || transport.InitialStreamID != 3 { - t.Fatalf("连接窗口=%d 流窗口增量=%d 补窗阈值=%d 首个流=%d,应为 Firefox 158 的 12517377、12451840、4 MiB 与 3", transport.ConnectionFlow, transport.StreamWindowUpdate, transport.WindowUpdateThreshold, transport.InitialStreamID) - } - if !reflect.DeepEqual(transport.PseudoHeaderOrder, []string{":method", ":path", ":authority", ":scheme"}) { - t.Fatalf("伪头顺序=%v,应为 Firefox 158 的 m,p,a,s", transport.PseudoHeaderOrder) - } - for _, item := range []struct { - dest string - priority string - weight uint8 - }{{"document", "u=0, i", 41}, {"empty", "u=0", 41}, {"empty", "", 21}, {"script", "", 21}, {"image", "u=5, i", 11}} { - header := fhttp.Header{"Sec-Fetch-Dest": {item.dest}} - if item.priority != "" { - header.Set("Priority", item.priority) - } - if got := firefoxStreamPriority(header); got != (http2.PriorityParam{Weight: item.weight}) { - t.Fatalf("Sec-Fetch-Dest=%s Priority=%q 的头部优先级=%+v,Firefox 158 的权重字节为 %d", item.dest, item.priority, got, item.weight) - } - } -} diff --git a/internal/aistudio/transport_http.go b/internal/aistudio/transport_http.go index 61bc06d9..aaaa0ebb 100644 --- a/internal/aistudio/transport_http.go +++ b/internal/aistudio/transport_http.go @@ -15,6 +15,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "golang.org/x/sync/singleflight" @@ -56,7 +57,7 @@ type MakerSuiteHTTPTransport struct { pool *AccountPool signer *Signer headers ProtocolHeaderProvider - globalProxy string + globalProxy atomic.Pointer[string] now func() time.Time clientsMu sync.Mutex clients map[string]*http.Client @@ -118,18 +119,35 @@ func NewMakerSuiteHTTPTransport(options HTTPTransportOptions) (*MakerSuiteHTTPTr pool: options.Pool, signer: signer, headers: options.Headers, - globalProxy: strings.TrimSpace(options.GlobalProxy), now: time.Now, clients: make(map[string]*http.Client), accountClients: make(map[string]accountHTTPClient), driveDiscovered: make(map[string]bool), } - if _, err := transport.clientForProxy(transport.globalProxy); err != nil { + if err := transport.SetGlobalProxy(options.GlobalProxy); err != nil { return nil, err } return transport, nil } +// GlobalProxy 返回当前默认出口代理 +func (t *MakerSuiteHTTPTransport) GlobalProxy() string { + if proxy := t.globalProxy.Load(); proxy != nil { + return *proxy + } + return "" +} + +// SetGlobalProxy 替换默认出口代理并校验可建立代理客户端,不中断进行中的请求 +func (t *MakerSuiteHTTPTransport) SetGlobalProxy(proxy string) error { + trimmed := strings.TrimSpace(proxy) + if _, err := t.clientForProxy(trimmed); err != nil { + return err + } + t.globalProxy.Store(&trimmed) + return nil +} + // sendHTTP 发送 HTTP 请求,请求失败时错误中的地址不含查询参数 func sendHTTP(client *http.Client, request *http.Request) (*http.Response, error) { response, err := client.Do(request) @@ -359,7 +377,7 @@ func (t *MakerSuiteHTTPTransport) FetchStatic(ctx context.Context, accountID str if err != nil { return nil, err } - client, err := t.clientForProxy(account.EffectiveProxy(t.globalProxy)) + client, err := t.clientForProxy(account.EffectiveProxy(t.GlobalProxy())) if err != nil { return nil, err } @@ -393,7 +411,7 @@ func (t *MakerSuiteHTTPTransport) CloseIdleConnections() { // clientForAccount 返回账户专用的固定出口客户端,与每账户一个浏览器的 Firefox 一致,按账户隔离连接池、预检缓存与 TLS 票据缓存 func (t *MakerSuiteHTTPTransport) clientForAccount(account *Account) (*http.Client, error) { - proxyURL := account.EffectiveProxy(t.globalProxy) + proxyURL := account.EffectiveProxy(t.GlobalProxy()) t.clientsMu.Lock() if entry, ok := t.accountClients[account.ID]; ok && entry.proxyURL == proxyURL { t.clientsMu.Unlock() diff --git a/internal/aistudio/turns.go b/internal/aistudio/turns.go index 152ca31d..4c1c0fae 100644 --- a/internal/aistudio/turns.go +++ b/internal/aistudio/turns.go @@ -21,7 +21,11 @@ var nativePrefillModels = map[string]bool{ // rewritesAssistantTail 判断末尾 assistant 轮是否改写:ContinuationRewrite 打开且模型不接受以 model 轮结尾的请求 func (s *PooledService) rewritesAssistantTail(modelID string) bool { - return s.ContinuationRewrite && !nativePrefillModels[modelID] && !strings.HasPrefix(modelID, "gemma-") + return shouldRewriteAssistantTail(modelID, s.requestOptions().ContinuationRewrite) +} + +func shouldRewriteAssistantTail(modelID string, rewrite bool) bool { + return rewrite && !nativePrefillModels[modelID] && !strings.HasPrefix(modelID, "gemma-") } // normalizeTurns 按 clientSystem 改写客户端系统提示,按 dropUserRejected 删去 user 轮中的客户端身份句;在 rewrite 时改写末尾连续 assistant 轮:prompt 非空时正文作为续写前缀连同 prompt 写入系统指令,为空时正文作为最后一轮 user;没有对话内容时以系统提示作为 user 轮 diff --git a/internal/aistudio/webchannel.go b/internal/aistudio/webchannel.go index 0f68e592..fefdf8a2 100644 --- a/internal/aistudio/webchannel.go +++ b/internal/aistudio/webchannel.go @@ -151,41 +151,40 @@ func (s *PooledService) OpenBidi(ctx context.Context, request BidiRequest) (*Bid return nil, err } request.AccountID = lease.Account().ID + var session *BidiSession if lease.Channel() == ChannelPlayground { - entry, err := s.client.modelEntry(ctx, request.AccountID, modelID) - if err != nil { + entry, entryErr := s.client.modelEntry(ctx, request.AccountID, modelID) + if entryErr != nil { if owned { - err = errors.Join(err, lease.Release()) + entryErr = errors.Join(entryErr, lease.Release()) } - return nil, err + return nil, entryErr } request.generationDefaults = entry.defaults if request.Mode == BidiModeLive { request.variant = bidiVariantFor(entry.model) } - if err := s.client.EnsureDisclaimerAcknowledged(ContextWithAccountLease(ctx, lease), request.AccountID, request.Mode); err != nil { - if owned { - err = errors.Join(err, lease.Release()) - } - return nil, err - } + err = s.client.EnsureDisclaimerAcknowledged(ContextWithAccountLease(ctx, lease), request.AccountID, request.Mode) } - runtime := RequestContext{} - if s.client.contextProvider != nil { - runtime, err = s.client.contextProvider.RequestContext(ctx, request.AccountID) - if err != nil { - if owned { - err = errors.Join(err, lease.Release()) + if err == nil { + runtime := RequestContext{} + if s.client.contextProvider != nil { + var runtimeErr error + runtime, runtimeErr = s.client.contextProvider.RequestContext(ctx, request.AccountID) + if runtimeErr != nil { + if owned { + runtimeErr = errors.Join(runtimeErr, lease.Release()) + } + return nil, fmt.Errorf("读取 AI Studio bidi 请求上下文: %w", runtimeErr) } - return nil, fmt.Errorf("读取 AI Studio bidi 请求上下文: %w", err) } + var release func() error + if owned { + release = lease.Release + } + attemptCtx := ContextWithAccountLease(ctx, lease) + session, err = transport.OpenBidiProtected(attemptCtx, request, runtime, lease, release) } - var release func() error - if owned { - release = lease.Release - } - attemptCtx := ContextWithAccountLease(ctx, lease) - session, err := transport.OpenBidiProtected(attemptCtx, request, runtime, lease, release) if err == nil { if stateErr := lease.MarkAuthenticationValid(); stateErr != nil { slog.Error("Bidi 账户认证状态保存失败", "account", request.AccountID, "error", stateErr) @@ -410,7 +409,7 @@ func (t *WorkerProtectedTransport) OpenBidiProtected( return nil, err } requestCtx, cancel := context.WithCancel(ctx) - setupCtx, cancelSetup := context.WithTimeout(ctx, t.setupTimeout) + setupCtx, cancelSetup := context.WithTimeout(ctx, time.Duration(t.setupTimeout.Load())) defer cancelSetup() session := &BidiSession{ ctx: requestCtx, cancel: cancel, lease: lease, release: release, worker: worker, client: client, diff --git a/internal/api/account_tasks_browser_test.go b/internal/api/account_tasks_browser_test.go deleted file mode 100644 index 568eedda..00000000 --- a/internal/api/account_tasks_browser_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "github.com/gorilla/websocket" -) - -// TestBrowserCookieCacheSharesSingleBiDiSession 验证同一批导入多选同一 Firefox 地址时只建一次 BiDi 会话,并发读取不触发单会话冲突 -func TestBrowserCookieCacheSharesSingleBiDiSession(t *testing.T) { - upgrader := websocket.Upgrader{} - var active atomic.Int32 - var sessions atomic.Int32 - mux := http.NewServeMux() - mux.HandleFunc("/json/version", http.NotFound) - mux.HandleFunc("/session", func(w http.ResponseWriter, r *http.Request) { - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - return - } - defer conn.Close() - for { - var msg struct { - ID int `json:"id"` - Method string `json:"method"` - } - if err := conn.ReadJSON(&msg); err != nil { - return - } - switch msg.Method { - case "session.new": - if active.Add(1) > 1 { - active.Add(-1) - _ = conn.WriteJSON(map[string]any{"id": msg.ID, "error": "session not created", "message": "Maximum number of active sessions"}) - return - } - sessions.Add(1) - time.Sleep(50 * time.Millisecond) - _ = conn.WriteJSON(map[string]any{"id": msg.ID, "result": map[string]any{"sessionId": "s1", "capabilities": map[string]any{"browserName": "firefox"}}}) - case "storage.getCookies": - _ = conn.WriteJSON(map[string]any{"id": msg.ID, "result": map[string]any{"cookies": []map[string]any{ - {"name": "SID", "value": map[string]string{"type": "string", "value": "v"}, "domain": ".google.com", "path": "/"}, - }}}) - case "session.end": - active.Add(-1) - _ = conn.WriteJSON(map[string]any{"id": msg.ID, "result": map[string]any{}}) - return - } - } - }) - server := httptest.NewServer(mux) - t.Cleanup(server.Close) - address := strings.TrimPrefix(server.URL, "http://") - - cache := newBrowserCookieCache(context.Background()) - var group sync.WaitGroup - results := make([]string, 4) - errs := make([]error, 4) - for i := range results { - group.Go(func() { - results[i], errs[i] = cache.read(context.Background(), address) - }) - } - group.Wait() - for i := range results { - if errs[i] != nil { - t.Fatalf("第 %d 项读取失败: %v", i, errs[i]) - } - var cookies []map[string]any - if err := json.Unmarshal([]byte(results[i]), &cookies); err != nil || len(cookies) != 1 { - t.Fatalf("第 %d 项 Cookie 无效: %q (%v)", i, results[i], err) - } - } - if got := sessions.Load(); got != 1 { - t.Fatalf("同一地址并发导入应只建立 1 次 BiDi 会话,实际 %d 次", got) - } -} diff --git a/internal/api/admin.go b/internal/api/admin.go index 12506b29..2fa710b9 100644 --- a/internal/api/admin.go +++ b/internal/api/admin.go @@ -33,6 +33,7 @@ type AdminService interface { RefreshAccount(context.Context, string) (AdminAccountRefresh, error) StartService(context.Context) (AdminStatus, error) StopService(context.Context) (AdminStatus, error) + RestartService(context.Context) (AdminStatus, error) DownloadCamoufox(context.Context) (AdminStatus, error) ClearLogs(context.Context) error RuntimeConfig(context.Context) (RuntimeConfig, error) @@ -102,30 +103,33 @@ type LogStage struct { // RequestLog 保存可关联的请求状态、用量与诊断字段 type RequestLog struct { - ID string `json:"id"` - State string `json:"state"` - StartedAt time.Time `json:"started_at,omitzero"` - Model string `json:"model,omitempty"` - Method string `json:"method,omitempty"` - Path string `json:"path,omitempty"` - Status int `json:"status,omitempty"` - DurationMS float64 `json:"duration_ms,omitempty"` - Usage *RequestLogUsage `json:"usage,omitempty"` - ToolCalls int `json:"tool_calls,omitempty"` - FinishReason string `json:"finish_reason,omitempty"` - Error string `json:"error,omitempty"` - InputMessages int `json:"input_messages,omitempty"` - InputTextChars int `json:"input_text_chars,omitempty"` - InputMedia int `json:"input_media,omitempty"` - InputMediaBytes int64 `json:"input_media_bytes,omitempty"` - InputFiles int `json:"input_files,omitempty"` - Parameters map[string]string `json:"parameters,omitempty"` - FirstEventMS float64 `json:"first_event_ms,omitempty"` - QueueMS float64 `json:"queue_ms,omitempty"` - ProofMS float64 `json:"proof_ms,omitempty"` - ProofPhases *RequestLogProofPhases `json:"proof_phases,omitempty"` - UpstreamBytes int64 `json:"upstream_bytes,omitempty"` - Channel string `json:"channel,omitempty"` + ID string `json:"id"` + State string `json:"state"` + StartedAt time.Time `json:"started_at,omitzero"` + Model string `json:"model,omitempty"` + Method string `json:"method,omitempty"` + Path string `json:"path,omitempty"` + Status int `json:"status,omitempty"` + DurationMS float64 `json:"duration_ms,omitempty"` + Usage *RequestLogUsage `json:"usage,omitempty"` + ToolCalls int `json:"tool_calls,omitempty"` + ReplyTool bool `json:"reply_tool,omitempty"` + ReplyToolCalls *int `json:"reply_tool_calls,omitempty"` + ReplyToolContinuations *int `json:"reply_tool_continuations,omitempty"` + FinishReason string `json:"finish_reason,omitempty"` + Error string `json:"error,omitempty"` + InputMessages int `json:"input_messages,omitempty"` + InputTextChars int `json:"input_text_chars,omitempty"` + InputMedia int `json:"input_media,omitempty"` + InputMediaBytes int64 `json:"input_media_bytes,omitempty"` + InputFiles int `json:"input_files,omitempty"` + Parameters map[string]string `json:"parameters,omitempty"` + FirstEventMS float64 `json:"first_event_ms,omitempty"` + QueueMS float64 `json:"queue_ms,omitempty"` + ProofMS float64 `json:"proof_ms,omitempty"` + ProofPhases *RequestLogProofPhases `json:"proof_phases,omitempty"` + UpstreamBytes int64 `json:"upstream_bytes,omitempty"` + Channel string `json:"channel,omitempty"` } // RequestLogProofPhases 是请求日志中生成 WAA proof 的分项,SettingsSkipped 是空闲不够而没有做的运行设置步数 @@ -147,37 +151,40 @@ type RequestLogUsage struct { // AccessLog 表示一次公开 API 请求的最终访问记录 type AccessLog struct { - Status int - Latency time.Duration - FirstEvent time.Duration - FirstOutput int64 - TrailingError string - QueueWait time.Duration - Proof ProofTiming - UpstreamBytes int64 - Usage *aistudio.Usage - ToolCalls int - InputMessages int - InputTextChars int - InputMedia int - InputMediaBytes int64 - InputFiles int - Temperature string - TopP string - Thinking string - MaxOutputTokens string - RequestID string - Method string - Path string - Model string - Account string - Channel string - FinishReason string - Error string - Canceled bool - Generation bool - Attempts []RequestAttempt - Authorized bool + Status int + Latency time.Duration + FirstEvent time.Duration + FirstOutput int64 + TrailingError string + QueueWait time.Duration + Proof ProofTiming + UpstreamBytes int64 + Usage *aistudio.Usage + ToolCalls int + ReplyTool bool + ReplyToolCalls int + ReplyToolContinuations int + InputMessages int + InputTextChars int + InputMedia int + InputMediaBytes int64 + InputFiles int + Temperature string + TopP string + Thinking string + MaxOutputTokens string + RequestID string + Method string + Path string + Model string + Account string + Channel string + FinishReason string + Error string + Canceled bool + Generation bool + Attempts []RequestAttempt + Authorized bool } // AdminAccountCounts 表示账户状态计数 @@ -370,9 +377,9 @@ type RuntimeConfig struct { ReservedListenAddr string `json:"reserved_listen_addr"` PreviewListenAddr string `json:"preview_listen_addr"` ActivePreviewListenAddr string `json:"active_preview_listen_addr"` - ActiveAPIKey string `json:"active_proxy_api_key"` ManagementRestartRequired bool `json:"management_restart_required"` ServiceRestartRequired bool `json:"service_restart_required"` + ActiveRequests int `json:"active_requests"` Proxy string `json:"proxy"` ActiveProxy string `json:"active_proxy"` ProxyPool []AdminProxy `json:"proxy_pool"` @@ -385,6 +392,8 @@ type RuntimeConfig struct { RoutingStrategy string `json:"routing_strategy"` AccountOrder string `json:"account_order"` MaxAccountSwitches int `json:"max_account_switches"` + AccountSwitchInterval string `json:"account_switch_interval"` + MaxQuotaSwitches string `json:"max_quota_switches"` UpstreamChannels []string `json:"upstream_channels"` ModelMapping string `json:"model_mapping"` ModelChannels string `json:"model_channels"` @@ -455,6 +464,7 @@ func (s *server) registerAdmin(mux *http.ServeMux) { mux.HandleFunc("POST /api/accounts/refresh", s.handleRefreshAccounts) mux.HandleFunc("POST /api/control/start", s.handleStartService) mux.HandleFunc("POST /api/control/stop", s.handleStopService) + mux.HandleFunc("POST /api/control/restart", s.handleRestartService) mux.HandleFunc("POST /api/camoufox/download", s.handleDownloadCamoufox) mux.HandleFunc("DELETE /api/logs", s.handleClearLogs) mux.HandleFunc("GET /api/config", s.handleRuntimeConfig) @@ -653,6 +663,15 @@ func (s *server) handleStopService(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, status) } +func (s *server) handleRestartService(w http.ResponseWriter, r *http.Request) { + status, err := s.config.Admin.RestartService(r.Context()) + if err != nil { + writeAdminUpstreamError(w, err) + return + } + writeJSON(w, http.StatusOK, status) +} + func (s *server) handleClearLogs(w http.ResponseWriter, r *http.Request) { if err := s.config.Admin.ClearLogs(r.Context()); err != nil { writeAdminUpstreamError(w, err) @@ -681,11 +700,16 @@ func (s *server) handleUpdateRuntimeConfig(w http.ResponseWriter, r *http.Reques writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) return } + if err := s.adminAuth.ValidateConfigUpdate(r, config.AdminAuthEnabled); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_config", err.Error()) + return + } updated, err := s.config.Admin.UpdateRuntimeConfig(r.Context(), config) if err != nil { writeAdminUpstreamError(w, err) return } + s.adminAuth.ApplyConfig(updated.AdminAuthEnabled, updated.AdminUsername, updated.SavedAdminPassword, w, r) writeJSON(w, http.StatusOK, updated) } diff --git a/internal/api/admin_auth.go b/internal/api/admin_auth.go index 5e5da6de..7bc46136 100644 --- a/internal/api/admin_auth.go +++ b/internal/api/admin_auth.go @@ -101,6 +101,9 @@ func (auth *adminAuth) addSession(token string, expires time.Time, remembered bo // saveRemembered 在持锁期间把记住我的会话写入会话文件 func (auth *adminAuth) saveRemembered() error { + if auth.config.AdminSessionPath == "" { + return nil + } saved := rememberedSessions{Credential: auth.credential(), Sessions: []rememberedSessionRow{}} for token, session := range auth.sessions { if session.remembered { @@ -118,17 +121,94 @@ func (auth *adminAuth) saveRemembered() error { return os.Rename(temporary, auth.config.AdminSessionPath) } +// isEnabled 返回当前是否开启了管理登录 +func (auth *adminAuth) isEnabled() bool { + auth.mu.Lock() + defer auth.mu.Unlock() + return auth.config.AdminAuthEnabled +} + +// ValidateConfigUpdate 校验远程请求不可关闭管理登录,防止关闭后立刻被回环限制拒绝访问 +func (auth *adminAuth) ValidateConfigUpdate(r *http.Request, nextEnabled bool) error { + if auth == nil || nextEnabled || !auth.isEnabled() { + return nil + } + if !isLoopbackRequest(r) { + return errors.New("只能在本机访问时关闭管理登录") + } + return nil +} + +// ApplyConfig 热更新管理登录开关与凭据:开启或改密时撤销旧会话并为当前请求签发新会话 Cookie,关闭时清除全部会话 +func (auth *adminAuth) ApplyConfig(enabled bool, username, password string, w http.ResponseWriter, r *http.Request) { + if auth == nil { + return + } + auth.mu.Lock() + defer auth.mu.Unlock() + if auth.config.AdminAuthEnabled == enabled && (!enabled || (auth.config.AdminUsername == username && auth.config.AdminPassword == password)) { + return + } + currentToken := "" + remembered := false + if r != nil { + if cookie, err := r.Cookie(adminCookieName); err == nil { + currentToken = cookie.Value + if current := auth.sessions[currentToken]; current != nil { + remembered = current.remembered + } + } + } + for token, session := range auth.sessions { + // 当前保存请求的上下文绑定在 currentToken 上,该会话在保存请求结束、响应写回之后撤销 + if token == currentToken { + context.AfterFunc(r.Context(), session.cancel) + } else { + session.cancel() + } + delete(auth.sessions, token) + } + clear(auth.attempts) + auth.config.AdminAuthEnabled = enabled + auth.config.AdminUsername = username + auth.config.AdminPassword = password + if !enabled { + if err := auth.saveRemembered(); err != nil { + slog.Warn("写入管理会话文件失败", "path", auth.config.AdminSessionPath, "error", err) + } + if w != nil && r != nil { + auth.setCookie(w, r, "", -1) + } + return + } + now := time.Now() + lifetime := adminSessionLifetime + if remembered { + lifetime = adminRememberLifetime + } + if w != nil && r != nil { + token := rand.Text() + auth.addSession(token, now.Add(lifetime), remembered) + auth.setCookie(w, r, token, int(lifetime.Seconds())) + } + if err := auth.saveRemembered(); err != nil { + slog.Warn("写入管理会话文件失败", "path", auth.config.AdminSessionPath, "error", err) + } +} + // handler 统一管理认证、同源检查与会话接口 func (auth *adminAuth) handler(next http.Handler) http.Handler { - mux := http.NewServeMux() - mux.HandleFunc("GET /api/auth/session", auth.status) - mux.HandleFunc("POST /api/auth/login", auth.login) - mux.HandleFunc("POST /api/auth/logout", auth.logout) - mux.Handle("/", auth.requireSession(next)) - var handler http.Handler = sameOriginMiddleware(mux) - if !auth.config.AdminAuthEnabled { - handler = loopbackMiddleware(handler) + routes := func(root http.Handler) http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /api/auth/session", auth.status) + mux.HandleFunc("POST /api/auth/login", auth.login) + mux.HandleFunc("POST /api/auth/logout", auth.logout) + mux.Handle("/", root) + return sameOriginMiddleware(mux) } + // loopback 是关闭管理登录时只放行本机来源的链,guarded 是开启时要求有效会话的链;每个请求只按进入时读取的开关走其中一条 + loopback := loopbackMiddleware(routes(next)) + guarded := routes(auth.requireSession(next)) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") limit := int64(1 << 20) @@ -139,7 +219,11 @@ func (auth *adminAuth) handler(next http.Handler) http.Handler { limit = maxPublicBodyBytes } r.Body = http.MaxBytesReader(w, r.Body, limit) - handler.ServeHTTP(w, r) + if !auth.isEnabled() { + loopback.ServeHTTP(w, r) + return + } + guarded.ServeHTTP(w, r) }) } @@ -159,13 +243,9 @@ func (auth *adminAuth) session(r *http.Request) *adminSession { return session } -// requireSession 在管理请求期间同时监听退出登录和会话到期 +// requireSession 要求有效会话,并在管理请求期间同时监听退出登录和会话到期 func (auth *adminAuth) requireSession(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !auth.config.AdminAuthEnabled { - next.ServeHTTP(w, r) - return - } session := auth.session(r) if session == nil { writeAdminError(w, http.StatusUnauthorized, "admin_login_required", "Sign in to the console") @@ -181,19 +261,23 @@ func (auth *adminAuth) requireSession(next http.Handler) http.Handler { // status 返回登录页面需要的会话状态 func (auth *adminAuth) status(w http.ResponseWriter, r *http.Request) { - loggedIn := auth.config.AdminAuthEnabled && auth.session(r) != nil + auth.mu.Lock() + enabled := auth.config.AdminAuthEnabled + configuredUser := auth.config.AdminUsername + auth.mu.Unlock() + loggedIn := enabled && auth.session(r) != nil username := "" if loggedIn { - username = auth.config.AdminUsername + username = configuredUser } writeJSON(w, http.StatusOK, map[string]any{ - "enabled": auth.config.AdminAuthEnabled, "authenticated": loggedIn || !auth.config.AdminAuthEnabled, "username": username, + "enabled": enabled, "authenticated": loggedIn || !enabled, "username": username, }) } // login 验证管理员凭据并签发限时会话 func (auth *adminAuth) login(w http.ResponseWriter, r *http.Request) { - if !auth.config.AdminAuthEnabled { + if !auth.isEnabled() { auth.status(w, r) return } @@ -211,6 +295,10 @@ func (auth *adminAuth) login(w http.ResponseWriter, r *http.Request) { now := time.Now() auth.mu.Lock() defer auth.mu.Unlock() + if !auth.config.AdminAuthEnabled { + writeJSON(w, http.StatusOK, map[string]any{"enabled": false, "authenticated": true, "username": ""}) + return + } for address, attempt := range auth.attempts { if !now.Before(attempt.until) { delete(auth.attempts, address) diff --git a/internal/api/admin_auth_test.go b/internal/api/admin_auth_test.go index 8cbf4e1a..02ba57e1 100644 --- a/internal/api/admin_auth_test.go +++ b/internal/api/admin_auth_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "path/filepath" "strings" "testing" "time" @@ -108,3 +109,122 @@ func TestAdminLoginRateLimit(t *testing.T) { } authExchange(handler, "POST", "/api/auth/logout", "", login.Result().Cookies()[0]) } + +// TestAdminAuthHotReload 验证管理登录开关与账号密码热切换:开启或改密时自动签发新会话防踢出并撤销其余旧会话,远程请求禁止关闭登录,本机关闭后恢复免密与回环限制 +func TestAdminAuthHotReload(t *testing.T) { + sessionPath := filepath.Join(t.TempDir(), "admin-sessions.json") + auth := newAdminAuth(Config{AdminAuthEnabled: false, AdminSessionPath: sessionPath}) + handler := auth.handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/test/enable": + auth.ApplyConfig(true, "admin", "pass-1", w, r) + w.WriteHeader(http.StatusOK) + case "/api/test/rotate": + auth.ApplyConfig(true, "admin2", "pass-2", w, r) + if r.Context().Err() != nil { + t.Errorf("current save request context was canceled during ApplyConfig: %v", r.Context().Err()) + } + w.WriteHeader(http.StatusOK) + case "/api/test/disable": + if err := auth.ValidateConfigUpdate(r, false); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_config", err.Error()) + return + } + auth.ApplyConfig(false, "admin2", "pass-2", w, r) + w.WriteHeader(http.StatusOK) + default: + w.WriteHeader(http.StatusNoContent) + } + })) + + // 1. 初始关闭:本机免密,远程 403 + if got := authExchange(handler, "GET", "/api/status", ""); got.Code != http.StatusNoContent { + t.Fatalf("disabled local status=%d", got.Code) + } + remoteGet := func(path string, cookies ...*http.Cookie) *httptest.ResponseRecorder { + r := httptest.NewRequest("GET", "https://console.example"+path, nil) + r.RemoteAddr = "192.0.2.10:5000" + r.Header.Set("Origin", "https://console.example") + for _, c := range cookies { + r.AddCookie(c) + } + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + return w + } + if got := remoteGet("/api/auth/session"); got.Code != http.StatusForbidden { + t.Fatalf("disabled remote session=%d want 403", got.Code) + } + + // 2. 热开启管理登录:当前请求自动收到新 Cookie,无 Cookie 被拒 401,远程会话接口开放 200 + enabledResp := authExchange(handler, "POST", "/api/test/enable", "") + if enabledResp.Code != http.StatusOK || len(enabledResp.Result().Cookies()) != 1 { + t.Fatalf("enable resp=%d cookies=%d", enabledResp.Code, len(enabledResp.Result().Cookies())) + } + currentCookie := enabledResp.Result().Cookies()[0] + if got := authExchange(handler, "GET", "/api/status", ""); got.Code != http.StatusUnauthorized { + t.Fatalf("enabled unauthenticated=%d want 401", got.Code) + } + if got := authExchange(handler, "GET", "/api/status", "", currentCookie); got.Code != http.StatusNoContent { + t.Fatalf("enabled current cookie=%d want 204", got.Code) + } + if got := remoteGet("/api/auth/session"); got.Code != http.StatusOK { + t.Fatalf("enabled remote session=%d want 200", got.Code) + } + + // 另一个记住我的客户端登录 + otherLogin := authExchange(handler, "POST", "/api/auth/login", `{"username":"admin","password":"pass-1","remember":true}`) + if otherLogin.Code != http.StatusOK || len(otherLogin.Result().Cookies()) != 1 { + t.Fatalf("other login=%d", otherLogin.Code) + } + otherCookie := otherLogin.Result().Cookies()[0] + otherSession := auth.sessions[otherCookie.Value] + + // 3. 热改账号密码:撤销其余会话,当前请求上下文不被取消并签发新 Cookie,旧密码登录失败、新密码登录成功 + rotateResp := authExchange(handler, "POST", "/api/test/rotate", "", currentCookie) + if rotateResp.Code != http.StatusOK || len(rotateResp.Result().Cookies()) != 1 { + t.Fatalf("rotate resp=%d cookies=%d", rotateResp.Code, len(rotateResp.Result().Cookies())) + } + rotatedCookie := rotateResp.Result().Cookies()[0] + if otherSession.ctx.Err() == nil { + t.Fatal("other session was not canceled on password rotation") + } + if got := authExchange(handler, "GET", "/api/status", "", otherCookie); got.Code != http.StatusUnauthorized { + t.Fatalf("revoked other cookie=%d want 401", got.Code) + } + if got := authExchange(handler, "GET", "/api/status", "", currentCookie); got.Code != http.StatusUnauthorized { + t.Fatalf("old current cookie=%d want 401", got.Code) + } + if got := authExchange(handler, "GET", "/api/status", "", rotatedCookie); got.Code != http.StatusNoContent { + t.Fatalf("rotated cookie=%d want 204", got.Code) + } + if got := authExchange(handler, "POST", "/api/auth/login", `{"username":"admin","password":"pass-1"}`); got.Code != http.StatusUnauthorized { + t.Fatalf("old credentials login=%d want 401", got.Code) + } + if got := authExchange(handler, "POST", "/api/auth/login", `{"username":"admin2","password":"pass-2"}`); got.Code != http.StatusOK { + t.Fatalf("new credentials login=%d want 200", got.Code) + } + + // 4. 远程关闭管理登录被拒绝 400 + remoteDisable := httptest.NewRequest("POST", "https://console.example/api/test/disable", nil) + remoteDisable.RemoteAddr = "192.0.2.10:5000" + remoteDisable.Header.Set("Origin", "https://console.example") + remoteDisable.AddCookie(rotatedCookie) + rw := httptest.NewRecorder() + handler.ServeHTTP(rw, remoteDisable) + if rw.Code != http.StatusBadRequest || !strings.Contains(rw.Body.String(), "invalid_config") { + t.Fatalf("remote disable=%d body=%s want 400 invalid_config", rw.Code, rw.Body.String()) + } + + // 5. 本机关闭管理登录:清除会话与 Cookie,本机免密恢复,远程恢复 403 + disableResp := authExchange(handler, "POST", "/api/test/disable", "", rotatedCookie) + if disableResp.Code != http.StatusOK || len(disableResp.Result().Cookies()) != 1 || disableResp.Result().Cookies()[0].MaxAge != -1 { + t.Fatalf("local disable=%d cookies=%+v", disableResp.Code, disableResp.Result().Cookies()) + } + if got := authExchange(handler, "GET", "/api/status", ""); got.Code != http.StatusNoContent { + t.Fatalf("disabled again local=%d want 204", got.Code) + } + if got := remoteGet("/api/auth/session"); got.Code != http.StatusForbidden { + t.Fatalf("disabled again remote=%d want 403", got.Code) + } +} diff --git a/internal/api/anthropic.go b/internal/api/anthropic.go index 92ec62fc..9b42fb94 100644 --- a/internal/api/anthropic.go +++ b/internal/api/anthropic.go @@ -188,7 +188,7 @@ func (s *server) handleAnthropicMessages(w http.ResponseWriter, r *http.Request) writer := &anthropicStreamWriter{ send: sseSender(stream), id: messageID, model: request.Model, inputTokens: <-estimate, startUsage: startUsage, - searchKey: s.config.APIKey, omitted: request.thinkingOmitted(), + searchKey: s.config.APIKeys(), omitted: request.thinkingOmitted(), media: media, context: contextResult, search: declaredSearch, } if err := writer.start(); err != nil { @@ -208,7 +208,7 @@ func (s *server) handleAnthropicMessages(w http.ResponseWriter, r *http.Request) writeAnthropicRequestError(w, err) return } - response := buildAnthropicResponse(messageID, request.Model, result, s.config.APIKey, request.thinkingOmitted(), media) + response := buildAnthropicResponse(messageID, request.Model, result, s.config.APIKeys(), request.thinkingOmitted(), media) contextResult.response(response, result.usage) writeJSON(w, http.StatusOK, officialOrder("anthropic", response)) } @@ -217,7 +217,7 @@ func (s *server) handleAnthropicMessages(w http.ResponseWriter, r *http.Request) func (s *server) writeAnthropicCompactionPause(w http.ResponseWriter, request anthropicRequest, id string, contextResult anthropicContextResult) { result := generationResult{finishReason: "compaction", usage: &aistudio.Usage{}} if !request.Stream { - response := buildAnthropicResponse(id, request.Model, result, s.config.APIKey, false, mediaOutput{}) + response := buildAnthropicResponse(id, request.Model, result, s.config.APIKeys(), false, mediaOutput{}) contextResult.response(response, result.usage) writeJSON(w, http.StatusOK, officialOrder("anthropic", response)) return @@ -250,7 +250,7 @@ func (s *server) writeAnthropicPrefill(w http.ResponseWriter, r *http.Request, r } result := generationResult{finishReason: "max_tokens", usage: generated.usage} if !request.Stream { - response := buildAnthropicResponse(id, request.Model, result, s.config.APIKey, false, mediaOutput{}) + response := buildAnthropicResponse(id, request.Model, result, s.config.APIKeys(), false, mediaOutput{}) contextResult.response(response, result.usage) writeJSON(w, http.StatusOK, officialOrder("anthropic", response)) return diff --git a/internal/api/anthropic_search.go b/internal/api/anthropic_search.go index a5f7e653..1ed16df7 100644 --- a/internal/api/anthropic_search.go +++ b/internal/api/anthropic_search.go @@ -97,7 +97,7 @@ type anthropicSearchHead struct { // decodeAnthropicSearchHistory 将搜索历史改写为文本块,查询与其结果合并到同一块 func (s *server) decodeAnthropicSearchHistory(request *anthropicRequest) error { - aead := anthropicSearchCipher(s.config.APIKey) + aead := anthropicSearchCipher(s.config.APIKeys()) for index := range request.Messages { message := &request.Messages[index] if !bytes.HasPrefix(bytes.TrimSpace(message.Content), []byte("[")) { diff --git a/internal/api/decisions.go b/internal/api/decisions.go index 99e3d8ea..27cb8234 100644 --- a/internal/api/decisions.go +++ b/internal/api/decisions.go @@ -91,13 +91,20 @@ func (s *server) handleDecision(w http.ResponseWriter, r *http.Request) { return } decision, err := request.decision() - if err == nil { - err = s.inlineDecisionFiles(r, decision.Input) - } if err != nil { writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error()) return } + if err := resolveGeminiFileNames(r.Context(), s.service, []aistudio.Content{{Parts: decision.Input}}); err != nil { + if shouldWriteRequestError(r, err) { + writeGeminiRequestError(w, err) + } + return + } + if err := s.inlineDecisionFiles(r, decision.Input); err != nil { + writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error()) + return + } result, err := service.CreateDecision(r.Context(), decision) var blocked *aistudio.PromptFeedbackError if errors.As(err, &blocked) { diff --git a/internal/api/empty_content_test.go b/internal/api/empty_content_test.go index 6040711a..9e0b6486 100644 --- a/internal/api/empty_content_test.go +++ b/internal/api/empty_content_test.go @@ -69,52 +69,3 @@ func TestMessageWhitespacePreserved(t *testing.T) { } } } - -// TestOpenAIToolMessageNameInference 验证 tool 消息缺少 name 时自动关联前置工具调用名称 -func TestOpenAIToolMessageNameInference(t *testing.T) { - req := chatRequest{ - Model: "gemini-3.8-flash", - Messages: []chatMessage{ - { - Role: "assistant", - ToolCalls: []openAIToolCall{ - { - ID: "call_abc_1", - Type: "function", - Function: struct { - Name string `json:"name"` - Arguments string `json:"arguments"` - }{ - Name: "query_image_presets", - Arguments: `{"category":"preset"}`, - }, - }, - }, - }, - { - Role: "tool", - ToolCallID: "call_mismatched_xyz", - Content: json.RawMessage(`"ok"`), - }, - }, - } - genReq, err := req.toGenerateRequest("test-id") - if err != nil { - t.Fatalf("toGenerateRequest failed: %v", err) - } - if len(genReq.Contents) != 2 { - t.Fatalf("expected 2 contents, got %d", len(genReq.Contents)) - } - wire, _, err := aistudio.EncodeGenerateContentRequest(genReq, aistudio.GenerationDefaults{MaxOutputTokens: 1024}, aistudio.RequestContext{}) - if err != nil { - t.Fatal(err) - } - var root []any - if err := json.Unmarshal(wire, &root); err != nil { - t.Fatal(err) - } - result := root[1].([]any)[1].([]any)[0].([]any)[0].([]any)[11].([]any) - if result[0] != "query_image_presets" || result[2] != "call_mismatched_xyz" { - t.Fatalf("unexpected function result: %#v", result) - } -} diff --git a/internal/api/gemini_output_test.go b/internal/api/gemini_output_test.go index e8e2f5a4..ee5105c9 100644 --- a/internal/api/gemini_output_test.go +++ b/internal/api/gemini_output_test.go @@ -44,48 +44,6 @@ func TestGeminiOutputParts_MergeTextAndReasoning(t *testing.T) { } } -func TestGeminiOutputParts_TextOnly(t *testing.T) { - result := generationResult{ - events: []aistudio.Event{ - {Kind: aistudio.EventText, Text: "Chunk 1 "}, - {Kind: aistudio.EventText, Text: "Chunk 2 "}, - {Kind: aistudio.EventText, Text: "Chunk 3"}, - }, - } - - parts := geminiOutputParts(result) - if len(parts) != 1 { - t.Fatalf("expected 1 part, got %d: %+v", len(parts), parts) - } - - expectedText := map[string]any{ - "text": "Chunk 1 Chunk 2 Chunk 3", - } - if !reflect.DeepEqual(parts[0], expectedText) { - t.Errorf("parts[0] = %+v, want %+v", parts[0], expectedText) - } -} - -func TestGeminiOutputParts_LeadingThoughtSignature(t *testing.T) { - result := generationResult{ - events: []aistudio.Event{ - {Kind: aistudio.EventThoughtSignature, ThoughtSignature: "sig_pre"}, - {Kind: aistudio.EventReasoning, Thought: true, Text: "Thinking step."}, - {Kind: aistudio.EventText, Text: "Final text."}, - }, - } - - parts := geminiOutputParts(result) - want := []map[string]any{ - {"text": "", "thoughtSignature": "sig_pre"}, - {"text": "Thinking step.", "thought": true}, - {"text": "Final text."}, - } - if !reflect.DeepEqual(parts, want) { - t.Fatalf("parts=%+v want=%+v", parts, want) - } -} - func TestGeminiOutputParts_StandaloneThoughtSignatureFallback(t *testing.T) { result := generationResult{ events: []aistudio.Event{ @@ -148,23 +106,6 @@ func TestGeminiOutputParts_SignedBoundaries(t *testing.T) { } } -// TestGeminiOutputParts_PendingSignature 保留前置签名与已有签名 -func TestGeminiOutputParts_PendingSignature(t *testing.T) { - parts := geminiOutputParts(generationResult{events: []aistudio.Event{ - {Kind: aistudio.EventThoughtSignature, ThoughtSignature: "sig-a"}, - {Kind: aistudio.EventReasoning, Thought: true, Text: "reason", ThoughtSignature: "sig-b"}, - {Kind: aistudio.EventText, Text: "answer"}, - }}) - want := []map[string]any{ - {"text": "", "thoughtSignature": "sig-a"}, - {"text": "reason", "thought": true, "thoughtSignature": "sig-b"}, - {"text": "answer"}, - } - if !reflect.DeepEqual(parts, want) { - t.Fatalf("parts=%+v want=%+v", parts, want) - } -} - // TestGeminiOutputParts_TrailingSignatures 保留尾部签名与已有签名的顺序 func TestGeminiOutputParts_TrailingSignatures(t *testing.T) { parts := geminiOutputParts(generationResult{events: []aistudio.Event{ @@ -180,25 +121,6 @@ func TestGeminiOutputParts_TrailingSignatures(t *testing.T) { } } -// TestGeminiOutputParts_LeadingSignatures 保留连续前置签名的原始顺序 -func TestGeminiOutputParts_LeadingSignatures(t *testing.T) { - parts := geminiOutputParts(generationResult{events: []aistudio.Event{ - {Kind: aistudio.EventThoughtSignature, ThoughtSignature: "sig-a"}, - {Kind: aistudio.EventThoughtSignature, ThoughtSignature: "sig-b"}, - {Kind: aistudio.EventThoughtSignature, ThoughtSignature: "sig-c"}, - {Kind: aistudio.EventText, Text: "answer"}, - }}) - want := []map[string]any{ - {"text": "", "thoughtSignature": "sig-a"}, - {"text": "", "thoughtSignature": "sig-b"}, - {"text": "", "thoughtSignature": "sig-c"}, - {"text": "answer"}, - } - if !reflect.DeepEqual(parts, want) { - t.Fatalf("parts=%+v want=%+v", parts, want) - } -} - // TestGeminiOutputParts_SignedAudio 保留 PCM 音频片段的独立签名 func TestGeminiOutputParts_SignedAudio(t *testing.T) { var result generationResult diff --git a/internal/api/image_encoding_test.go b/internal/api/image_encoding_test.go index 7ce9417b..4d2cefc8 100644 --- a/internal/api/image_encoding_test.go +++ b/internal/api/image_encoding_test.go @@ -3,48 +3,12 @@ package api import ( "bytes" "image" - "image/draw" - "image/jpeg" "image/png" "testing" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" ) -// TestFitImageJPEGToPNGIsRGB8 核对 JPEG 源不缩放输出 PNG 时为 8 位 RGB,像素与 image/jpeg 解码后经 draw.Draw 以 draw.Src 转为 RGBA 的结果相同 -func TestFitImageJPEGToPNGIsRGB8(t *testing.T) { - picture := image.NewRGBA(image.Rect(0, 0, 97, 61)) - for y := range 61 { - for x := range 97 { - copy(picture.Pix[picture.PixOffset(x, y):], []byte{byte(x * 5), byte(y * 3), byte(x*y + 7), 0xff}) - } - } - var source bytes.Buffer - if err := jpeg.Encode(&source, picture, &jpeg.Options{Quality: 90}); err != nil { - t.Fatal(err) - } - decoded, err := jpeg.Decode(bytes.NewReader(source.Bytes())) - if err != nil { - t.Fatal(err) - } - want := image.NewRGBA(decoded.Bounds()) - draw.Draw(want, want.Bounds(), decoded, decoded.Bounds().Min, draw.Src) - converted, size, err := fitImage(aistudio.Blob{MIME: "image/jpeg", Data: source.Bytes()}, image.Point{}, "image/png", 100) - if err != nil { - t.Fatal(err) - } - if converted.MIME != "image/png" || size != want.Rect.Size() || len(converted.Data) < 26 || converted.Data[24] != 8 || converted.Data[25] != 2 { - t.Fatalf("输出 %s %v,IHDR 位深与颜色类型 %v,期望 8 位 RGB", converted.MIME, size, converted.Data[24:min(len(converted.Data), 26)]) - } - got, err := png.Decode(bytes.NewReader(converted.Data)) - if err != nil { - t.Fatal(err) - } - if rgba, ok := got.(*image.RGBA); !ok || !bytes.Equal(rgba.Pix, want.Pix) { - t.Fatalf("PNG 解出 %T,像素与 draw.Draw 转换的 RGBA 不同", got) - } -} - // TestFitImageWebPOutputCompression 核对 OpenAI 的 output_compression 作用于 webp 输出:输出为有损 VP8 WebP,压缩级别越低文件越小 func TestFitImageWebPOutputCompression(t *testing.T) { picture := image.NewRGBA(image.Rect(0, 0, 192, 128)) diff --git a/internal/api/interaction_input.go b/internal/api/interaction_input.go index e9b1bceb..949ab7b3 100644 --- a/internal/api/interaction_input.go +++ b/internal/api/interaction_input.go @@ -857,10 +857,8 @@ func (audio outputAudioFormat) encode(media aistudio.Blob) (aistudio.Blob, error switch { case baseType == "audio/mpeg" && encoding.format == "mp3" && sameRate && audio.BitRate == 0: return aistudio.Blob{MIME: fmt.Sprintf("%s;rate=%d;channels=%d", encoding.content, source.SampleRate, source.Channels), Data: media.Data}, nil - case baseType == "audio/l16" && encoding.format == "pcm" && sameRate: + case baseType != "audio/mpeg" && encoding.format == "pcm" && sameRate: return media, nil - case (baseType == "audio/wav" || baseType == "audio/x-wav") && audio.MIME == "audio/wav" && sameRate: - return aistudio.Blob{MIME: "audio/wav", Data: media.Data}, nil } data, encoded, err := encodeAudio(source, audioOutput{Format: encoding.format, SampleRate: audio.SampleRate, BitRate: audio.BitRate}) return aistudio.Blob{MIME: fmt.Sprintf("%s;rate=%d;channels=%d", encoding.content, encoded.SampleRate, encoded.Channels), Data: data}, err diff --git a/internal/api/interaction_resources.go b/internal/api/interaction_resources.go index d4a9c084..79855dba 100644 --- a/internal/api/interaction_resources.go +++ b/internal/api/interaction_resources.go @@ -161,10 +161,6 @@ func (s *server) handleInteractionDelete(w http.ResponseWriter, r *http.Request) // handleInteractionCancel 停止进行中的后台交互并返回保存的交互 func (s *server) handleInteractionCancel(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") - if _, ok := s.responseStates.Interaction(id); !ok { - writeInteractionNotFound(w, id) - return - } s.stopBackground(id) record, ok := s.responseStates.Interaction(id) if !ok { diff --git a/internal/api/ledger.go b/internal/api/ledger.go index 8c6ced54..1443aad2 100644 --- a/internal/api/ledger.go +++ b/internal/api/ledger.go @@ -200,29 +200,32 @@ type ProofPhasesMS struct { // UsageRecord 是一条已完成请求的账本记录 type UsageRecord struct { - ID string `json:"id"` - Time time.Time `json:"time"` - Protocol string `json:"protocol"` - Path string `json:"path"` - Model string `json:"model"` - Account string `json:"account"` - Channel string `json:"channel"` - Status int `json:"status"` - State string `json:"state"` - DurationMS int64 `json:"duration_ms"` - FirstEventMS int64 `json:"first_event_ms"` - QueueMS int64 `json:"queue_ms"` - ProofMS int64 `json:"proof_ms"` - ProofPhases ProofPhasesMS `json:"proof_phases"` - InputTokens int64 `json:"input_tokens"` - CachedTokens int64 `json:"cached_tokens"` - ReasoningTokens int64 `json:"reasoning_tokens"` - ReplyTokens int64 `json:"reply_tokens"` - TotalTokens int64 `json:"total_tokens"` - ToolCalls int `json:"tool_calls"` - Error string `json:"error"` - Attempts []RequestAttempt `json:"attempts"` - HasBody bool `json:"has_body"` + ID string `json:"id"` + Time time.Time `json:"time"` + Protocol string `json:"protocol"` + Path string `json:"path"` + Model string `json:"model"` + Account string `json:"account"` + Channel string `json:"channel"` + Status int `json:"status"` + State string `json:"state"` + DurationMS int64 `json:"duration_ms"` + FirstEventMS int64 `json:"first_event_ms"` + QueueMS int64 `json:"queue_ms"` + ProofMS int64 `json:"proof_ms"` + ProofPhases ProofPhasesMS `json:"proof_phases"` + InputTokens int64 `json:"input_tokens"` + CachedTokens int64 `json:"cached_tokens"` + ReasoningTokens int64 `json:"reasoning_tokens"` + ReplyTokens int64 `json:"reply_tokens"` + TotalTokens int64 `json:"total_tokens"` + ToolCalls int `json:"tool_calls"` + ReplyTool bool `json:"reply_tool"` + ReplyToolCalls int `json:"reply_tool_calls"` + ReplyToolContinuations int `json:"reply_tool_continuations"` + Error string `json:"error"` + Attempts []RequestAttempt `json:"attempts"` + HasBody bool `json:"has_body"` } // UsageRecordPage 是按完成时间倒序的一页请求记录,NextCursor 为空表示没有更早的记录 diff --git a/internal/api/mcp_tools.go b/internal/api/mcp_tools.go index d9443f56..156922cf 100644 --- a/internal/api/mcp_tools.go +++ b/internal/api/mcp_tools.go @@ -155,7 +155,7 @@ func (s *server) resolveMCPTools(ctx context.Context, request aistudio.GenerateR servers = append(servers, server) } request.Tools.MCPServers = servers - request.Tools.ToolConfig.ServerSideInvocations = len(servers) > 0 + request.Tools.ToolConfig.ServerSideInvocations = len(servers) > 0 || slices.Contains(request.Tools.Google, "google_search") || request.Tools.GoogleSearch != nil || len(request.Tools.FileSearch) > 0 return request, nil } diff --git a/internal/api/media.go b/internal/api/media.go index 8ca592ac..d5c26404 100644 --- a/internal/api/media.go +++ b/internal/api/media.go @@ -820,16 +820,13 @@ func normalizeImagePayload(mimeType string, data []byte) (string, []byte) { return mimeType, data } -// maxGIFCanvasPixels 是 GIF 首帧转换允许的最大逻辑画布像素数 -const maxGIFCanvasPixels = 64_000_000 - -// decodeGIFFrame 解码 GIF 的首帧与逻辑画布配置,画布宽或高为 0 或像素数超过 maxGIFCanvasPixels 时返回 false +// decodeGIFFrame 解码 GIF 的首帧与逻辑画布配置 func decodeGIFFrame(data []byte) (*image.Paletted, image.Config, bool) { - config, err := gif.DecodeConfig(bytes.NewReader(data)) - if err != nil || config.Width <= 0 || config.Height <= 0 || int64(config.Width) > maxGIFCanvasPixels/int64(config.Height) { + img, err := gif.Decode(bytes.NewReader(data)) + if err != nil { return nil, image.Config{}, false } - img, err := gif.Decode(bytes.NewReader(data)) + config, err := gif.DecodeConfig(bytes.NewReader(data)) if err != nil { return nil, image.Config{}, false } diff --git a/internal/api/media_store_test.go b/internal/api/media_store_test.go deleted file mode 100644 index 8c6401bc..00000000 --- a/internal/api/media_store_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package api - -import ( - "fmt" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "slices" - "testing" - "time" - - "github.com/Mag1cFall/AIStudio2API/internal/aistudio" -) - -// TestMediaDirectoryLimit 验证媒体目录超过上限时删除最久未使用的文件:启动与保存新文件时回收,读取媒体与续接读回刷新使用时间 -func TestMediaDirectoryLimit(t *testing.T) { - dir := t.TempDir() - setUsed := func(name string, hours int) { - t.Helper() - used := time.Now().Add(time.Duration(hours) * time.Hour) - if err := os.Chtimes(filepath.Join(dir, name), used, used); err != nil { - t.Fatal(err) - } - } - name := func(index int) string { return fmt.Sprintf("%064x.png", index) } - for index := range 4 { - name := name(index) - if err := os.WriteFile(filepath.Join(dir, name), make([]byte, 10), 0o644); err != nil { - t.Fatal(err) - } - setUsed(name, index-10) - } - handler := NewHandler(nil, Config{MediaDir: dir, MediaLimit: 30}) - assertMedia := func(want ...string) { - t.Helper() - entries, err := os.ReadDir(dir) - if err != nil { - t.Fatal(err) - } - var got []string - for _, entry := range entries { - got = append(got, entry.Name()) - } - slices.Sort(want) - if !slices.Equal(got, want) { - t.Fatalf("媒体目录 = %v,期望 %v", got, want) - } - } - assertMedia(name(1), name(2), name(3)) - - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/media/"+name(1), nil)) - if recorder.Code != http.StatusOK { - t.Fatalf("GET /media/%s = %d", name(1), recorder.Code) - } - server := &server{config: Config{MediaDir: dir}, media: &mediaStore{dir: dir, limit: 30}} - output := mediaOutput{base: "http://127.0.0.1:2048", store: server.media} - first := aistudio.Blob{MIME: "image/png", Data: []byte("first-new!")} - if err := output.save(first); err != nil { - t.Fatal(err) - } - assertMedia(name(1), name(3), mediaFileName(first)) - - setUsed(name(1), -5) - setUsed(mediaFileName(first), -4) - link := aistudio.Content{Role: aistudio.RoleAssistant, Parts: []aistudio.Part{{Text: "![media](http://127.0.0.1:2048/media/" + name(3) + ")"}}} - if err := server.restoreMediaLinks([]aistudio.Content{link}); err != nil { - t.Fatal(err) - } - second := aistudio.Blob{MIME: "image/png", Data: []byte("second-new")} - if err := output.save(second); err != nil { - t.Fatal(err) - } - assertMedia(name(3), mediaFileName(first), mediaFileName(second)) -} diff --git a/internal/api/middleware.go b/internal/api/middleware.go index 2bdede4c..9956d4a2 100644 --- a/internal/api/middleware.go +++ b/internal/api/middleware.go @@ -24,41 +24,44 @@ import ( type accessLogContextKey struct{} type accessLogMetadata struct { - mu sync.Mutex - admin AdminService - method string - path string - started bool - generation bool - model string - account string - channel string - finishReason string - err string - canceled bool - detached bool - failureStatus int - firstEvent time.Duration - firstOutput int64 - trailingError string - upstreamBytes int64 - usage *aistudio.Usage - toolCalls int - inputMessages int - inputTextChars int - inputMedia int - inputMediaBytes int64 - inputFiles int - temperature string - topP string - thinking string - maxOutputTokens string - requestID string - startedAt time.Time - queueWait time.Duration - proof ProofTiming - attempts []RequestAttempt - authorized bool + mu sync.Mutex + admin AdminService + method string + path string + started bool + generation bool + model string + account string + channel string + finishReason string + err string + canceled bool + detached bool + failureStatus int + firstEvent time.Duration + firstOutput int64 + trailingError string + upstreamBytes int64 + usage *aistudio.Usage + toolCalls int + replyTool bool + replyToolCalls int + replyToolContinuations int + inputMessages int + inputTextChars int + inputMedia int + inputMediaBytes int64 + inputFiles int + temperature string + topP string + thinking string + maxOutputTokens string + requestID string + startedAt time.Time + queueWait time.Duration + proof ProofTiming + attempts []RequestAttempt + authorized bool } type accessLogResponseWriter struct { @@ -135,6 +138,7 @@ func (metadata *accessLogMetadata) finished(status int, disconnected bool) Acces return AccessLog{ Status: status, FirstEvent: metadata.firstEvent, FirstOutput: metadata.firstOutput, TrailingError: metadata.trailingError, QueueWait: metadata.queueWait, Proof: metadata.proof, UpstreamBytes: metadata.upstreamBytes, Usage: metadata.usage, ToolCalls: metadata.toolCalls, + ReplyTool: metadata.replyTool, ReplyToolCalls: metadata.replyToolCalls, ReplyToolContinuations: metadata.replyToolContinuations, InputMessages: metadata.inputMessages, InputTextChars: metadata.inputTextChars, InputMedia: metadata.inputMedia, InputMediaBytes: metadata.inputMediaBytes, InputFiles: metadata.inputFiles, Temperature: metadata.temperature, TopP: metadata.topP, Thinking: metadata.thinking, MaxOutputTokens: metadata.maxOutputTokens, @@ -407,6 +411,35 @@ func SetAccessLogGenerationResult(ctx context.Context, usage *aistudio.Usage, to } } +// SetAccessLogReplyTool 记录本次生成尝试是否实际启用回复工具并重置 final 调用与续接轮数计数 +func SetAccessLogReplyTool(ctx context.Context, enabled bool) { + if metadata, ok := ctx.Value(accessLogContextKey{}).(*accessLogMetadata); ok { + metadata.mu.Lock() + metadata.replyTool = enabled + metadata.replyToolCalls = 0 + metadata.replyToolContinuations = 0 + metadata.mu.Unlock() + } +} + +// AddAccessLogReplyToolCall 累加本次生成解包的回复工具 final 调用次数 +func AddAccessLogReplyToolCall(ctx context.Context) { + if metadata, ok := ctx.Value(accessLogContextKey{}).(*accessLogMetadata); ok { + metadata.mu.Lock() + metadata.replyToolCalls++ + metadata.mu.Unlock() + } +} + +// AddAccessLogReplyToolContinuation 累加本次生成回复工具 more=true 触发的自动续接轮数 +func AddAccessLogReplyToolContinuation(ctx context.Context) { + if metadata, ok := ctx.Value(accessLogContextKey{}).(*accessLogMetadata); ok { + metadata.mu.Lock() + metadata.replyToolContinuations++ + metadata.mu.Unlock() + } +} + func requestLoggingMiddleware(admin AdminService, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { started := time.Now() @@ -447,10 +480,14 @@ func corsMiddleware(next http.Handler) http.Handler { }) } +func isLoopbackRequest(r *http.Request) bool { + host, _, err := net.SplitHostPort(r.RemoteAddr) + return err == nil && net.ParseIP(host).IsLoopback() && loopbackHost(r.Host) +} + func loopbackMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - host, _, err := net.SplitHostPort(r.RemoteAddr) - if err != nil || !net.ParseIP(host).IsLoopback() || !loopbackHost(r.Host) { + if !isLoopbackRequest(r) { writeAdminError(w, http.StatusForbidden, "control_plane_forbidden", "Control plane is only available from loopback") return } @@ -473,11 +510,12 @@ func loopbackHost(host string) bool { } // browserOriginMiddleware 在未配置 API key 时拒绝外部网页与 null 来源的浏览器请求 -func browserOriginMiddleware(requiredKey string, next http.Handler) http.Handler { - if strings.TrimSpace(requiredKey) != "" { - return next - } +func browserOriginMiddleware(requiredKey func() string, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.TrimSpace(requiredKey()) != "" { + next.ServeHTTP(w, r) + return + } originValue := strings.TrimSpace(r.Header.Get("Origin")) if originValue == "" { next.ServeHTTP(w, r) @@ -565,9 +603,9 @@ func sameOriginMiddleware(next http.Handler) http.Handler { }) } -func authMiddleware(configuredKeys string, next http.Handler) http.Handler { - keys := apiKeys(configuredKeys) +func authMiddleware(configuredKeys func() string, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + keys := apiKeys(configuredKeys()) if len(keys) > 0 && !checkAPIKeyMatches(r, keys) { writeAuthError(w, r) return @@ -593,16 +631,15 @@ func accountContextMiddleware(next http.Handler) http.Handler { } // apiKeyContextMiddleware 把请求所用的已配置 API key 放进请求上下文,供账户池按 key 绑定的账户选号 -func apiKeyContextMiddleware(configuredKeys string, next http.Handler) http.Handler { - keys := apiKeys(configuredKeys) - if len(keys) == 0 { - return next - } +func apiKeyContextMiddleware(configuredKeys func() string, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - for _, candidate := range apiKeyCandidates(r) { - if candidate != "" && slices.Contains(keys, candidate) { - r = r.WithContext(aistudio.ContextWithAPIKey(r.Context(), candidate)) - break + keys := apiKeys(configuredKeys()) + if len(keys) > 0 { + for _, candidate := range apiKeyCandidates(r) { + if candidate != "" && slices.Contains(keys, candidate) { + r = r.WithContext(aistudio.ContextWithAPIKey(r.Context(), candidate)) + break + } } } next.ServeHTTP(w, r) diff --git a/internal/api/middleware_test.go b/internal/api/middleware_test.go index 7dca6cfe..3104b455 100644 --- a/internal/api/middleware_test.go +++ b/internal/api/middleware_test.go @@ -4,11 +4,13 @@ import ( "net/http" "net/http/httptest" "testing" + + "github.com/Mag1cFall/AIStudio2API/internal/aistudio" ) func TestAuthMiddlewarePriorityAndMatching(t *testing.T) { requiredKey := "secret-123" - handler := authMiddleware(requiredKey, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + handler := authMiddleware(func() string { return requiredKey }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) @@ -64,3 +66,65 @@ func TestAuthMiddlewarePriorityAndMatching(t *testing.T) { }) } } + +// TestDynamicAPIKeyHotReload 验证 PROXY_API_KEY 热替换后对下一次请求立即生效,并同步切换无密钥时的跨源拦截与上下文密钥绑定 +func TestDynamicAPIKeyHotReload(t *testing.T) { + currentKey := "" + keySource := func() string { return currentKey } + pool := aistudio.NewAccountPool([]*aistudio.Account{ + {ID: "acct-b", State: aistudio.AccountReady, Config: aistudio.AccountConfig{Enabled: true}}, + {ID: "acct-c", State: aistudio.AccountReady, Config: aistudio.AccountConfig{Enabled: true}}, + }, 1) + pool.SetAPIKeyAccounts(map[string][]string{"key-b": {"acct-b"}, "key-c": {"acct-c"}}) + var allowed []string + handler := browserOriginMiddleware(keySource, authMiddleware(keySource, apiKeyContextMiddleware(keySource, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + allowed = pool.ScopedSelection(r.Context(), aistudio.AccountSelection{}).AllowedAccountIDs + w.WriteHeader(http.StatusOK) + })))) + + send := func(headers map[string]string) int { + allowed = nil + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + for k, v := range headers { + req.Header.Set(k, v) + } + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + return rec.Code + } + + // 1. 初始无密钥:免密放行,跨源浏览器请求被拒 401 + if code := send(nil); code != http.StatusOK || len(allowed) != 0 { + t.Fatalf("empty key no-auth: code=%d allowed=%v", code, allowed) + } + if code := send(map[string]string{"Origin": "https://evil.example"}); code != http.StatusUnauthorized { + t.Fatalf("empty key cross-origin: code=%d want 401", code) + } + + // 2. 热切为多密钥:无密钥 401,匹配 key-b 放行且上下文按 key-b 限定账户,跨源 Origin 放行 + currentKey = "key-a, key-b" + if code := send(nil); code != http.StatusUnauthorized { + t.Fatalf("configured key without auth: code=%d want 401", code) + } + if code := send(map[string]string{"Authorization": "Bearer key-b", "Origin": "https://app.example"}); code != http.StatusOK || len(allowed) != 1 || allowed[0] != "acct-b" { + t.Fatalf("configured key-b: code=%d allowed=%v", code, allowed) + } + + // 3. 热切为新密钥:旧 key-b 立即失效 401,新 key-c 立即放行并绑定 acct-c + currentKey = "key-c" + if code := send(map[string]string{"Authorization": "Bearer key-b"}); code != http.StatusUnauthorized { + t.Fatalf("rotated old key-b: code=%d want 401", code) + } + if code := send(map[string]string{"Authorization": "Bearer key-c"}); code != http.StatusOK || len(allowed) != 1 || allowed[0] != "acct-c" { + t.Fatalf("rotated new key-c: code=%d allowed=%v", code, allowed) + } + + // 4. 热切回空密钥:免密恢复,跨源保护恢复 + currentKey = "" + if code := send(nil); code != http.StatusOK || len(allowed) != 0 { + t.Fatalf("cleared key: code=%d allowed=%v", code, allowed) + } + if code := send(map[string]string{"Origin": "https://evil.example"}); code != http.StatusUnauthorized { + t.Fatalf("cleared key cross-origin: code=%d want 401", code) + } +} diff --git a/internal/api/responses_retrieval.go b/internal/api/responses_retrieval.go index 96ba63fc..8a512644 100644 --- a/internal/api/responses_retrieval.go +++ b/internal/api/responses_retrieval.go @@ -91,10 +91,6 @@ func (s *server) resumeResponseStream(w http.ResponseWriter, r *http.Request) { // handleResponseDelete 删除已保存的响应 func (s *server) handleResponseDelete(w http.ResponseWriter, r *http.Request) { id := r.PathValue("response") - if _, _, ok := s.responseStates.Response(id, nil); !ok { - writeResponseNotFound(w, id) - return - } s.stopBackground(id) if !s.responseStates.Delete(id, false) { writeResponseNotFound(w, id) @@ -105,22 +101,16 @@ func (s *server) handleResponseDelete(w http.ResponseWriter, r *http.Request) { // handleResponseCancel 终止进行中的后台响应并返回保存的 cancelled 对象,已结束的后台响应返回最终对象,其他响应不可取消 func (s *server) handleResponseCancel(w http.ResponseWriter, r *http.Request) { - id := r.PathValue("response") - response, background, ok := s.responseStates.Response(id, nil) + s.stopBackground(r.PathValue("response")) + response, background, ok := s.responseStates.Response(r.PathValue("response"), nil) if !ok { - writeResponseNotFound(w, id) + writeResponseNotFound(w, r.PathValue("response")) return } if !background { writeOpenAIError(w, http.StatusBadRequest, "invalid_request", "Only responses created with background=true can be cancelled.") return } - s.stopBackground(id) - response, _, ok = s.responseStates.Response(id, nil) - if !ok { - writeResponseNotFound(w, id) - return - } writeJSON(w, http.StatusOK, officialOrder("responses", response)) } diff --git a/internal/api/router.go b/internal/api/router.go index c6afba75..73a6d79f 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -16,8 +16,10 @@ import ( // Config 定义公开 API 服务配置 type Config struct { // PickPath 以系统对话框选择账户目录并返回选中的路径,用户取消时返回空串;只在桌面版提供 - PickPath func(start string) (string, error) - APIKey string + PickPath func(start string) (string, error) + APIKey string + // APIKeys 返回当前生效的逗号分隔 API key,为空时使用 APIKey + APIKeys func() string Admin AdminService AdminAuthEnabled bool AdminUsername string @@ -56,6 +58,7 @@ type ResponseModes struct { type server struct { service aistudio.Service config Config + adminAuth *adminAuth responseStates *responseStateStore uploads *geminiUploads caches *geminiCaches @@ -157,12 +160,19 @@ func NewHandler(service aistudio.Service, config Config) http.Handler { root := http.NewServeMux() root.Handle("GET /health", corsMiddleware(http.HandlerFunc(s.handleHealth))) - publicHandler := bodyLimitMiddleware(browserOriginMiddleware(config.APIKey, authMiddleware(config.APIKey, apiKeyContextMiddleware(config.APIKey, accountContextMiddleware(requestEncodingMiddleware(requestBodyMiddleware(config.Ledger, waitLaunchMiddleware(config.WaitLaunch, s.catalogRead, public)))))))) + keySource := config.APIKeys + if keySource == nil { + staticKey := config.APIKey + keySource = func() string { return staticKey } + } + s.config.APIKeys = keySource + publicHandler := bodyLimitMiddleware(browserOriginMiddleware(keySource, authMiddleware(keySource, apiKeyContextMiddleware(keySource, accountContextMiddleware(requestEncodingMiddleware(requestBodyMiddleware(config.Ledger, waitLaunchMiddleware(config.WaitLaunch, s.catalogRead, public)))))))) loggedHandler := requestLoggingMiddleware(config.Admin, corsMiddleware(publicHandler)) root.Handle("/v1/", loggedHandler) root.Handle("/v1beta/", loggedHandler) root.Handle("/upload/", requestLoggingMiddleware(config.Admin, corsMiddleware(s.geminiUploadHandler(publicHandler)))) - root.Handle("/api/", newAdminAuth(config).handler(control)) + s.adminAuth = newAdminAuth(config) + root.Handle("/api/", s.adminAuth.handler(control)) if config.MediaDir != "" { root.Handle("GET /media/{file}", corsMiddleware(http.HandlerFunc(s.handleMedia))) } diff --git a/internal/api/thoughtsig_test.go b/internal/api/thoughtsig_test.go index 17d8cb7f..00906cd2 100644 --- a/internal/api/thoughtsig_test.go +++ b/internal/api/thoughtsig_test.go @@ -2,7 +2,6 @@ package api import ( "encoding/json" - "fmt" "testing" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" @@ -36,13 +35,3 @@ func TestChatRestoresStoredThoughtSignature(t *testing.T) { t.Fatalf("client-supplied signature must win: got %q", got) } } - -func TestThoughtSignatureStoreIsBounded(t *testing.T) { - store := newThoughtSignatureStore() - for i := 0; i < thoughtSignatureCapacity+10; i++ { - store.Remember([]aistudio.FunctionCall{{ID: fmt.Sprintf("call_%d", i), Name: "f", Arguments: json.RawMessage(`{}`), ThoughtSignature: "s"}}) - } - if len(store.signatures) != thoughtSignatureCapacity || len(store.order) != thoughtSignatureCapacity { - t.Fatalf("store size = %d/%d, want %d", len(store.signatures), len(store.order), thoughtSignatureCapacity) - } -} diff --git a/internal/api/update.go b/internal/api/update.go index bb1f3609..6f126f77 100644 --- a/internal/api/update.go +++ b/internal/api/update.go @@ -24,6 +24,8 @@ type UpdateStatus struct { PublishedAt time.Time `json:"published_at,omitzero"` CheckedAt time.Time `json:"checked_at,omitzero"` Error string `json:"error,omitempty"` + ErrorKind string `json:"error_kind,omitempty"` // 限流时为 "rate_limited",其余错误省略 + RetryAt time.Time `json:"retry_at,omitzero"` Updating bool `json:"updating"` Progress *UpdateProgress `json:"progress,omitempty"` // LogDir 是服务日志目录的绝对路径 diff --git a/internal/app/account_usage_seed.go b/internal/app/account_usage_seed.go new file mode 100644 index 00000000..1b8c1164 --- /dev/null +++ b/internal/app/account_usage_seed.go @@ -0,0 +1,47 @@ +package app + +import ( + "context" + "time" + + "github.com/Mag1cFall/AIStudio2API/internal/aistudio" +) + +// SeedAccountUsage 把从请求账本恢复的账户最近使用时间与当日请求数注入账户池 +func (service *trackedService) SeedAccountUsage(seed aistudio.AccountUsageSeed) { + service.pool.SeedUsage(seed) +} + +// seedAccountUsage 从请求账本读回各账户历史使用时间与当前配额日请求数,注入目标生成服务的账户池 +func (manager *runtimeManager) seedAccountUsage(ctx context.Context, target *runtimeGeneration) { + if manager.ledger == nil || target == nil { + return + } + seeder, ok := target.service.(interface { + SeedAccountUsage(aistudio.AccountUsageSeed) + }) + if !ok { + return + } + stored, err := manager.ledger.AccountUsageSeed(ctx, aistudio.QuotaDayStart(time.Now())) + if err != nil { + if ctx.Err() == nil { + manager.requests.log("service", "WARN", "读取账户历史使用记录失败", "error", err) + } + return + } + entries := make([]aistudio.AccountUsageEntry, 0, len(stored.Entries)) + for _, entry := range stored.Entries { + entries = append(entries, aistudio.AccountUsageEntry{ + Account: entry.Account, + Model: entry.Model, + Channel: aistudio.Channel(entry.Channel), + LastUsed: entry.LastUsed, + }) + } + seeder.SeedAccountUsage(aistudio.AccountUsageSeed{ + Entries: entries, + QuotaDayStart: stored.QuotaDayStart, + QuotaDayRequests: stored.QuotaDayRequests, + }) +} diff --git a/internal/app/admin.go b/internal/app/admin.go index ca00f757..e987ff5c 100644 --- a/internal/app/admin.go +++ b/internal/app/admin.go @@ -39,7 +39,11 @@ type runtimeAdmin struct { configPath string config config.Config proxies *aistudio.ProxyPool + proxyMu sync.RWMutex globalProxy string + activeProxy string + probeMu sync.Mutex + probeCancel context.CancelFunc transitionMu sync.Mutex // transitions 是各账户进行中的后台收尾:启停收尾与添加、导入、登录后的目录同步 @@ -334,9 +338,6 @@ func enrichChromeImportProfiles(profiles []api.ChromeImportProfile, statuses []a // CheckChromeImportTiers 按需并发查询选中本机 Chrome 账号的 AI Studio 权益,每完成一个即通过 emit 回调输出 func (admin *runtimeAdmin) CheckChromeImportTiers(ctx context.Context, input api.ChromeTierCheckInput, emit func(api.ChromeProfileTier)) error { - if len(input.AccountIDs) == 0 { - return invalidAccount(fmt.Errorf("未选择 Chrome 账号")) - } root, err := chromeauth.DefaultChromeRoot() if err != nil { return err @@ -1226,7 +1227,7 @@ func (admin *runtimeAdmin) VerifyAccount(ctx context.Context, accountID string, Directory: directory, StorageState: state, AuthUser: account.Config.AuthUser, - Proxy: account.EffectiveProxy(admin.globalProxy), + Proxy: account.EffectiveProxy(admin.currentGlobalProxy()), Locale: account.Config.Locale, Timezone: account.Config.Timezone, View: view, @@ -1371,7 +1372,7 @@ func (admin *runtimeAdmin) saveLogin(ctx context.Context, accountID string, stat if err := replaceAccountState(lease, state, fingerprintDirectory); err != nil { return nil, errors.Join(err, lease.Release()) } - if err := setCookieAuthUser(lease, 0, admin.workers.prepareUpdate); err != nil { + if err := setImportedAccountConfig(lease, 0, "", admin.workers.prepareUpdate); err != nil { return nil, errors.Join(err, lease.Release()) } if err := admin.service.changeModels(func() error { @@ -1428,26 +1429,6 @@ func setImportedAccountConfig(lease *aistudio.AccountLease, authUser int, defaul return nil } -// setCookieAuthUser 把账户 Cookie 的会话序号改为 authUser 并同步到 Worker -func setCookieAuthUser(lease *aistudio.AccountLease, authUser int, prepare func(*aistudio.Account, aistudio.AccountConfig) (*accountWorkerUpdate, error)) error { - account := lease.Account() - if account.Config.AuthUser == authUser { - return nil - } - accountConfig := account.Config - accountConfig.AuthUser = authUser - workerUpdate, err := prepare(account, accountConfig) - if err != nil { - return err - } - if err := lease.SaveConfig(accountConfig); err != nil { - workerUpdate.Discard() - return err - } - workerUpdate.Commit() - return nil -} - // refreshStepMessages 是立即刷新、目录同步与账户保存各步骤写入日志的说明 var refreshStepMessages = map[aistudio.AccountStep]string{ aistudio.AccountStepWaiting: "等待账户的在途请求结束", @@ -1625,6 +1606,61 @@ func (admin *runtimeAdmin) proxyPoolStatus() []api.AdminProxy { return pool } +func (admin *runtimeAdmin) setProxyState(globalProxy, activeProxy string) { + admin.proxyMu.Lock() + admin.globalProxy = strings.TrimSpace(globalProxy) + admin.activeProxy = strings.TrimSpace(activeProxy) + admin.config.Proxy = admin.activeProxy + admin.proxyMu.Unlock() +} + +func (admin *runtimeAdmin) currentGlobalProxy() string { + admin.proxyMu.RLock() + defer admin.proxyMu.RUnlock() + return admin.globalProxy +} + +func (admin *runtimeAdmin) currentActiveProxy() string { + admin.proxyMu.RLock() + active := admin.activeProxy + fallback := admin.config.Proxy + admin.proxyMu.RUnlock() + if active != "" { + return active + } + return fallback +} + +// ProxyState 返回当前生效的代理展示串与代理池健康状态 +func (admin *runtimeAdmin) ProxyState() (string, []api.AdminProxy) { + return admin.currentActiveProxy(), admin.proxyPoolStatus() +} + +// ApplyProxy 热更新全局默认代理与代理池:更新传输、续签与 Worker 配置,并通过后台排空换绑重建受影响账户的 Worker,不中断进行中的请求 +func (admin *runtimeAdmin) ApplyProxy(rawProxy string) error { + if admin.proxies == nil || admin.service == nil { + return nil + } + proxyList, globalProxy, activeProxy, _ := resolveProxyConfig(rawProxy) + prevGlobal := admin.currentGlobalProxy() + prevActive := admin.currentActiveProxy() + if activeProxy == prevActive && globalProxy == prevGlobal { + return nil + } + if err := admin.service.setSharedGlobalProxy(globalProxy); err != nil { + return err + } + admin.setProxyState(globalProxy, activeProxy) + changed, err := admin.proxies.SetProxies(prevGlobal, proxyList) + admin.syncProxyProbe(len(proxyList), true) + if len(changed) > 0 { + admin.rebindAccounts(changed) + } else { + admin.publishRuntimeSnapshot(admin.lifecycle) + } + return err +} + func (admin *runtimeAdmin) effectiveProxy(accountProxy string) string { if proxy := strings.TrimSpace(accountProxy); proxy != "" { return proxy @@ -1632,12 +1668,12 @@ func (admin *runtimeAdmin) effectiveProxy(accountProxy string) string { if proxy := admin.proxies.Next(); proxy != "" { return proxy } - return admin.globalProxy + return admin.currentGlobalProxy() } func (admin *runtimeAdmin) loginRequest(account *aistudio.Account, directory string) aistudio.IsolatedLoginRequest { return aistudio.IsolatedLoginRequest{ - Directory: directory, Proxy: account.EffectiveProxy(admin.globalProxy), + Directory: directory, Proxy: account.EffectiveProxy(admin.currentGlobalProxy()), Locale: account.Config.Locale, Timezone: account.Config.Timezone, } } @@ -1648,8 +1684,8 @@ func adminAccountDTO(status aistudio.AccountStatus) api.AdminAccount { Proxy: status.Proxy, Egress: status.Egress, Locale: status.Locale, Timezone: status.Timezone, Models: status.Models, BenefitTier: status.BenefitTier, Message: status.Message, PairingRenewedAt: pairingRenewedAt(status.Directory), - Transition: string(status.Transition), ActiveRequests: status.ActiveRequests, CatalogError: status.CatalogError, - TransitionStep: string(status.TransitionStep), TransitionIndex: status.TransitionIndex, TransitionTotal: status.TransitionTotal, + Transition: string(status.Transition), ActiveRequests: status.ActiveRequests, CatalogError: status.CatalogError, + TransitionStep: string(status.TransitionStep), TransitionIndex: status.TransitionIndex, TransitionTotal: status.TransitionTotal, VerificationRequired: status.VerificationRequired, DeviceBoundSession: status.DeviceBoundSession && !hasPairingRenewal(status.Directory), } @@ -1698,7 +1734,7 @@ func (admin *runtimeAdmin) RuntimeConfig(context.Context) (api.RuntimeConfig, er return api.RuntimeConfig{}, err } value := runtimeConfigDTO(cfg) - value.ActiveProxy = admin.config.Proxy + value.ActiveProxy = admin.currentActiveProxy() value.ProxyPool = admin.proxyPoolStatus() return value, nil } @@ -1720,6 +1756,14 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt if err != nil { return api.RuntimeConfig{}, invalidConfigError(fmt.Errorf("REQUEST_TIMEOUT 无效: %w", err)) } + switchInterval := strings.ToLower(strings.TrimSpace(value.AccountSwitchInterval)) + if switchInterval == "" { + switchInterval = config.AccountSwitchIntervalOff + } + maxQuotaSwitches := strings.ToLower(strings.TrimSpace(value.MaxQuotaSwitches)) + if maxQuotaSwitches == "" { + maxQuotaSwitches = config.MaxQuotaSwitchesOff + } cfg := config.Config{ AutoStart: value.AutoStart, HideDockIcon: value.HideDockIcon, @@ -1739,6 +1783,8 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt RoutingStrategy: value.RoutingStrategy, AccountOrder: strings.TrimSpace(value.AccountOrder), MaxAccountSwitches: value.MaxAccountSwitches, + AccountSwitchInterval: switchInterval, + MaxQuotaSwitches: maxQuotaSwitches, UpstreamChannels: value.UpstreamChannels, ModelMapping: strings.TrimSpace(value.ModelMapping), ModelChannels: strings.TrimSpace(value.ModelChannels), @@ -1759,7 +1805,7 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt models, _ := admin.CatalogModels(context.Background()) admin.requests.publish(api.AdminEvent{Type: "models", Data: map[string]any{"models": models}}) value = runtimeConfigDTO(cfg) - value.ActiveProxy = admin.config.Proxy + value.ActiveProxy = admin.currentActiveProxy() value.ProxyPool = admin.proxyPoolStatus() return value, nil } @@ -2086,7 +2132,7 @@ func runtimeConfigDTO(cfg config.Config) api.RuntimeConfig { ContinuationRewrite: cfg.ContinuationRewrite, ContinuationPrompt: cfg.ContinuationPrompt, ReplyTool: cfg.ReplyTool, UserMessageRewrite: cfg.UserMessageRewrite, ThinkingGuard: cfg.ThinkingGuard, FirstEventHedge: cfg.FirstEventHedge, FirstEventHedgeModels: cfg.FirstEventHedgeModels, FirstEventTimeout: cfg.FirstEventTimeout, AuthStates: cfg.AuthStates, ListenAddr: cfg.ListenAddr, APIKey: cfg.ProxyAPIKey, - ActiveListenAddr: cfg.ListenAddr, ActiveAPIKey: cfg.ProxyAPIKey, + ActiveListenAddr: cfg.ListenAddr, PreviewListenAddr: cfg.PreviewListenAddr, ActivePreviewListenAddr: cfg.PreviewListenAddr, Proxy: cfg.Proxy, InitTimeout: cfg.InitTimeout.String(), RequestTimeout: cfg.RequestTimeout.String(), WarmWorkerLimit: cfg.WarmWorkerLimit, MaxActiveWorkers: cfg.MaxActiveWorkers, @@ -2095,6 +2141,8 @@ func runtimeConfigDTO(cfg config.Config) api.RuntimeConfig { RoutingStrategy: cfg.RoutingStrategy, AccountOrder: cfg.AccountOrder, MaxAccountSwitches: cfg.MaxAccountSwitches, + AccountSwitchInterval: cfg.AccountSwitchInterval, + MaxQuotaSwitches: cfg.MaxQuotaSwitches, UpstreamChannels: cfg.UpstreamChannels, ModelMapping: cfg.ModelMapping, ModelChannels: cfg.ModelChannels, diff --git a/internal/app/admin_config_test.go b/internal/app/admin_config_test.go index 5951cc61..1362ed3f 100644 --- a/internal/app/admin_config_test.go +++ b/internal/app/admin_config_test.go @@ -13,7 +13,14 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/config" ) -// TestAdminConfig 验证凭据保存、密码保留与管理重启标记 +type stubStateService struct { + managedService + state string +} + +func (s *stubStateService) State() string { return s.state } + +// TestAdminConfig 验证凭据保存、密码保留、热加载键不触发重启与仅必要键触发重启标记 func TestAdminConfig(t *testing.T) { path := filepath.Join(t.TempDir(), ".env") cfg := config.Default() @@ -26,7 +33,8 @@ func TestAdminConfig(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() pool := aistudio.NewAccountPool(nil, 1) - admin := &runtimeAdmin{configPath: path, requests: newRequestRegistry(), pool: pool, service: &trackedService{pool: pool}} + requests := newRequestRegistry() + admin := &runtimeAdmin{configPath: path, requests: requests, pool: pool, service: &trackedService{pool: pool}} value, err := admin.RuntimeConfig(ctx) if err != nil { t.Fatal(err) @@ -38,8 +46,13 @@ func TestAdminConfig(t *testing.T) { if strings.Contains(string(raw), "test-password") || !value.AdminPasswordSet || !value.BuildNativeNonstream { t.Fatalf("config=%s", raw) } + if value.AccountSwitchInterval != config.AccountSwitchIntervalOff || value.MaxQuotaSwitches != config.MaxQuotaSwitchesOff { + t.Fatalf("default switch policy = interval:%q quota:%q", value.AccountSwitchInterval, value.MaxQuotaSwitches) + } value.Proxy = "http://127.0.0.1:1234" value.AutoStart = true + value.AccountSwitchInterval = "5" + value.MaxQuotaSwitches = "1" if _, err := admin.UpdateRuntimeConfig(ctx, value); err != nil { t.Fatal(err) } @@ -47,19 +60,78 @@ func TestAdminConfig(t *testing.T) { if err != nil || saved.AdminPassword != cfg.AdminPassword { t.Fatalf("password changed: %v", err) } - if !saved.AutoStart { - t.Fatal("auto_start was not saved") + if !saved.AutoStart || saved.AccountSwitchInterval != "5" || saved.MaxQuotaSwitches != "1" { + t.Fatalf("saved fields mismatch: auto_start=%v interval=%q quota=%q", saved.AutoStart, saved.AccountSwitchInterval, saved.MaxQuotaSwitches) + } + stateSvc := &stubStateService{state: "RUNNING"} + requests.start(aistudio.GenerateRequest{ID: "req-active", Model: "gemini-flash-latest"}, func() {}) + manager := &runtimeManager{ + activeManagement: cfg, + requests: requests, + current: &runtimeGeneration{service: stateSvc, config: cfg}, } - manager := &runtimeManager{activeManagement: cfg} password := "new-test-password" value.AdminPassword = &password + value.APIKey = "new-hot-api-key" + value.BuildNativeNonstream = false + value.YouTubeLinks = false + value.StripThoughtSignatures = true + value.ContinuationRewrite = false + value.ContinuationPrompt = "custom prompt" + value.RequestTimeout = "90s" + value.InitTimeout = "45s" + value.FirstEventTimeout = "30" + value.FirstEventHedge = "10" + value.FirstEventHedgeModels = "gemini-2.5-pro" + value.UpstreamChannels = []string{"playground", "build"} + value.DiscoverHiddenModels = true value, err = admin.UpdateRuntimeConfig(ctx, value) if err != nil { t.Fatal(err) } decorated := manager.decorateRuntimeConfig(value, cfg) - if !decorated.ManagementRestartRequired || decorated.AdminPassword != nil { - t.Fatalf("restart=%+v", decorated) + if decorated.ManagementRestartRequired || decorated.ServiceRestartRequired || decorated.AdminPassword != nil || decorated.ActiveRequests != 1 { + t.Fatalf("hot reload fields should not require restart and should report active_requests=1: %+v", decorated) + } + // 仅修改监听地址或预览监听地址才触发管理进程重启 + value.ListenAddr = "127.0.0.1:2999" + decorated = manager.decorateRuntimeConfig(value, cfg) + if !decorated.ManagementRestartRequired { + t.Fatalf("listen_addr change should require management restart: %+v", decorated) + } + value.ListenAddr = cfg.ListenAddr + value.PreviewListenAddr = "127.0.0.1:3050" + decorated = manager.decorateRuntimeConfig(value, cfg) + if !decorated.ManagementRestartRequired { + t.Fatalf("preview_listen_addr change should require management restart: %+v", decorated) + } + value.PreviewListenAddr = cfg.PreviewListenAddr + // 修改 WAA_BACKEND / AISTUDIO_AUTH_STATES 仅在生成服务运行时触发重启标记,已停止时不触发 + value.WAABackend = config.WAABackendCamoufox + stateSvc.state = "STOPPED" + if got := manager.decorateRuntimeConfig(value, cfg); got.ServiceRestartRequired { + t.Fatalf("stopped service should not require restart: %+v", got) + } + stateSvc.state = "RUNNING" + if got := manager.decorateRuntimeConfig(value, cfg); !got.ServiceRestartRequired { + t.Fatalf("running service should require restart on WAA_BACKEND change: %+v", got) + } + value.WAABackend = cfg.WAABackend + value.AuthStates = "auth-other" + if got := manager.decorateRuntimeConfig(value, cfg); !got.ServiceRestartRequired { + t.Fatalf("running service should require restart on AISTUDIO_AUTH_STATES change: %+v", got) + } + value.AuthStates = cfg.AuthStates + // 非法换号间隔与额度换号上限返回 400 + badInterval := value + badInterval.AccountSwitchInterval = "0" + if _, err := admin.UpdateRuntimeConfig(ctx, badInterval); err == nil { + t.Fatal("ACCOUNT_SWITCH_INTERVAL=0 should be rejected") + } + badQuota := value + badQuota.MaxQuotaSwitches = "-1" + if _, err := admin.UpdateRuntimeConfig(ctx, badQuota); err == nil { + t.Fatal("MAX_QUOTA_SWITCHES=-1 should be rejected") } value.AdminPassword = new(string) _, err = admin.UpdateRuntimeConfig(ctx, value) diff --git a/internal/app/api_key_accounts_test.go b/internal/app/api_key_accounts_test.go index 0631b5bd..034a8b04 100644 --- a/internal/app/api_key_accounts_test.go +++ b/internal/app/api_key_accounts_test.go @@ -3,19 +3,16 @@ package app import ( "slices" "testing" - - "github.com/Mag1cFall/AIStudio2API/internal/config" ) -// TestAPIKeyAccountsKeepRemovedKeyBinding 核对绑定按保存的 key 列表立即生效,已从列表移除而管理服务仍接受的 key 沿用管理服务启动时的绑定 -func TestAPIKeyAccountsKeepRemovedKeyBinding(t *testing.T) { - active := config.Config{ProxyAPIKey: "key-a,key-b", APIKeyAccounts: "key-a:b@example.com"} - same := apiKeyAccounts("key-a,key-b", "key-a:a@example.com", active) +// TestAPIKeyAccountsBinding 核对绑定按最新保存的 key 列表立即生效,已移除的 key 不再保留绑定 +func TestAPIKeyAccountsBinding(t *testing.T) { + same := apiKeyAccounts("key-a,key-b", "key-a:a@example.com") if len(same) != 1 || !slices.Equal(same["key-a"], []string{"a@example.com"}) { t.Fatalf("key 列表不变时 %v", same) } - rotated := apiKeyAccounts("key-new,key-b", "key-new:b@example.com", active) - if len(rotated) != 2 || !slices.Equal(rotated["key-a"], []string{"b@example.com"}) || !slices.Equal(rotated["key-new"], []string{"b@example.com"}) { + rotated := apiKeyAccounts("key-new,key-b", "key-a:a@example.com,key-new:b@example.com") + if _, kept := rotated["key-a"]; kept || len(rotated) != 1 || !slices.Equal(rotated["key-new"], []string{"b@example.com"}) { t.Fatalf("换 key 后 %v", rotated) } } diff --git a/internal/app/app.go b/internal/app/app.go index 6fdfe1ae..25e85d44 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -148,6 +148,7 @@ func runService(ctx context.Context, cancel func(), cfg config.Config, options c } ledger.SetBodyCapture(cfg.RequestBodyLog) manager.ledger = ledger + manager.seedAccountUsage(ctx, manager.current) prompts, err := promptdb.Open(filepath.Join("runtime", "prompts.db")) if err != nil { return false, errors.Join(fmt.Errorf("打开对话库: %w", err), manager.Close(), ledger.Close()) @@ -264,7 +265,7 @@ func runServer(ctx context.Context, cfg config.Config, manager *runtimeManager, manager.previewAddress = previewListener.Addr().String() manager.settings.Store(requestSettingsOf(manager.currentConfig())) apiHandler := api.NewHandler(manager, api.Config{ - APIKey: cfg.ProxyAPIKey, Admin: manager, Ledger: manager.ledger, Prompts: manager.prompts, Updates: updater, + APIKey: cfg.ProxyAPIKey, APIKeys: manager.currentAPIKey, Admin: manager, Ledger: manager.ledger, Prompts: manager.prompts, Updates: updater, AdminAuthEnabled: cfg.AdminAuthEnabled, AdminUsername: cfg.AdminUsername, AdminPassword: cfg.AdminPassword, AdminSessionPath: filepath.Join("runtime", "admin-sessions.json"), MediaDir: filepath.Join("runtime", "media"), MediaLimit: mediaLimit, MediaLinks: manager.mediaLinks, diff --git a/internal/app/auth_retry.go b/internal/app/auth_retry.go index d59ee17e..ce32c840 100644 --- a/internal/app/auth_retry.go +++ b/internal/app/auth_retry.go @@ -8,6 +8,7 @@ import ( "net/http" "strings" "sync" + "sync/atomic" "time" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" @@ -33,9 +34,29 @@ type authRuntimeRefresher struct { // mergeWorker 把响应 Cookie 写入账户当前 Worker 的页面 mergeWorker func(context.Context, string, []string, string) error // boundLocks 是各账户 DBSC 会话刷新的互斥锁 - boundLocks sync.Map - globalProxy string - requests *requestRegistry + boundLocks sync.Map + hotGlobalProxy atomic.Pointer[string] + requests *requestRegistry +} + +// SetGlobalProxy 替换认证续签使用的默认出口代理 +func (refresher *authRuntimeRefresher) SetGlobalProxy(proxy string) { + if refresher == nil { + return + } + trimmed := strings.TrimSpace(proxy) + refresher.hotGlobalProxy.Store(&trimmed) +} + +// currentGlobalProxy 返回当前默认出口代理 +func (refresher *authRuntimeRefresher) currentGlobalProxy() string { + if refresher == nil { + return "" + } + if proxy := refresher.hotGlobalProxy.Load(); proxy != nil { + return *proxy + } + return "" } // authRetryTransport 为普通 RPC 执行一次认证续签重试 @@ -156,14 +177,15 @@ func newAuthRuntimeRefresher( requests *requestRegistry, globalProxy string, ) *authRuntimeRefresher { - return &authRuntimeRefresher{ + refresher := &authRuntimeRefresher{ pool: workers.pool, refresh: chromeauth.Refresh, importCurrent: importCurrentChromeState, reset: workers.Reset, prepareWorker: workers.prepareUpdate, rotate: chromeauth.RotateBoundCookies, mergeWorker: workers.MergeCookies, - globalProxy: globalProxy, - requests: requests, + requests: requests, } + refresher.SetGlobalProxy(globalProxy) + return refresher } // importCurrentChromeState 从原来源中更新同一 Google 账户的认证材料 @@ -405,7 +427,7 @@ func (refresher *authRuntimeRefresher) Refresh(ctx context.Context, generation u if extension.OAuth == nil { return fmt.Errorf("账户 %s 没有续签材料,需要重新登录", account.ID) } - proxy := account.EffectiveProxy(refresher.globalProxy) + proxy := account.EffectiveProxy(refresher.currentGlobalProxy()) var cookies []aistudio.StateCookie cookies, extension.Bound, err = refresher.refresh(ctx, extension.Source, *extension.OAuth, proxy) if errors.Is(err, chromeauth.ErrCredentialsRejected) { @@ -447,7 +469,7 @@ func (refresher *authRuntimeRefresher) Refresh(ctx context.Context, generation u if !refreshed { return nil } - if err := setCookieAuthUser(lease, 0, refresher.prepareWorker); err != nil { + if err := setImportedAccountConfig(lease, 0, "", refresher.prepareWorker); err != nil { return fmt.Errorf("保存账户 %s 会话序号: %w", account.ID, err) } logRenewal("INFO", api.LogStage{State: "completed"}, "账户认证续签完成", "duration", time.Since(startedAt)) @@ -464,7 +486,7 @@ func (refresher *authRuntimeRefresher) ensureBound(ctx context.Context) error { return refresher.ensureBoundWith( ctx, account.ID, - account.EffectiveProxy(refresher.globalProxy), + account.EffectiveProxy(refresher.currentGlobalProxy()), lease.ReloadStorageState, lease.MergeSetCookieHeaders, ) @@ -485,7 +507,7 @@ func (refresher *authRuntimeRefresher) ensureBoundAccount(ctx context.Context, a return refresher.ensureBoundWith( ctx, account.ID, - account.EffectiveProxy(refresher.globalProxy), + account.EffectiveProxy(refresher.currentGlobalProxy()), func() (aistudio.StorageState, error) { return refresher.pool.ReloadStorageState(account.ID) }, diff --git a/internal/app/auth_retry_test.go b/internal/app/auth_retry_test.go deleted file mode 100644 index 3b622a92..00000000 --- a/internal/app/auth_retry_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package app - -import ( - "context" - "os" - "path/filepath" - "testing" - - "github.com/Mag1cFall/AIStudio2API/internal/aistudio" -) - -// TestAuthRefreshKeepsAccountSource 验证没有 OAuth 续签材料的账户不可续签且认证状态原样保留,重新登录以新登录结果为准 -func TestAuthRefreshKeepsAccountSource(t *testing.T) { - directory := t.TempDir() - storage := filepath.Join(directory, "storage-state.json") - state := `{"cookies":[{"name":"SAPISID","value":"old","domain":".google.com","path":"/","secure":true,"sameSite":"Lax"}],"origins":[]}` - if err := os.WriteFile(storage, []byte(state), 0o600); err != nil { - t.Fatal(err) - } - loaded, err := aistudio.LoadStorageState(storage) - if err != nil { - t.Fatal(err) - } - account := &aistudio.Account{ - ID: "user@example.com", Directory: directory, StoragePath: storage, - RuntimePath: filepath.Join(directory, "runtime-state.json"), StorageState: loaded, - Config: aistudio.DefaultAccountConfig("user@example.com"), - } - pool := aistudio.NewAccountPool([]*aistudio.Account{account}, 1) - lease, err := pool.AcquireAccount(t.Context(), account.ID) - if err != nil { - t.Fatal(err) - } - defer lease.Release() - var cookies []aistudio.StateCookie - for _, name := range []string{"SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID"} { - cookies = append(cookies, aistudio.StateCookie{Name: name, Value: "chrome", Domain: ".google.com", Path: "/", Expires: -1, Secure: true, SameSite: "Lax"}) - } - refresher := &authRuntimeRefresher{ - pool: pool, requests: newRequestRegistry(), - importCurrent: func(_ context.Context, source aistudio.AuthSource, _ aistudio.ChromeOAuthMaterial, _ string) (aistudio.StorageState, error) { - updated := aistudio.StorageState{Cookies: cookies} - updated.SetAuthExtension(aistudio.AuthExtension{ - Source: source, OAuth: &aistudio.ChromeOAuthMaterial{GaiaID: "gaia", RefreshToken: "token"}, - }) - return updated, nil - }, - reset: func(string) error { return nil }, - } - ctx := aistudio.ContextWithAccountLease(t.Context(), lease) - if refresher.Available(ctx) { - t.Fatal("没有 OAuth 续签材料的账户被判定为可续签") - } - if err := refresher.Refresh(ctx, lease.AuthGeneration()); err == nil { - t.Fatal("没有 OAuth 续签材料的账户续签成功") - } - if stored, err := os.ReadFile(storage); err != nil || string(stored) != state { - t.Fatalf("续签失败后认证状态被改写: %s err=%v", stored, err) - } - - chrome := aistudio.StorageState{Cookies: cookies} - chrome.SetAuthExtension(aistudio.AuthExtension{ - Source: aistudio.AuthSource{Browser: "chrome", Email: account.ID}, - OAuth: &aistudio.ChromeOAuthMaterial{GaiaID: "gaia", RefreshToken: "token"}, - }) - if err := lease.SaveStorageState(chrome); err != nil { - t.Fatal(err) - } - login := aistudio.StorageState{Cookies: cookies} - login.SetAuthExtension(aistudio.AuthExtension{Source: aistudio.AuthSource{Browser: "camoufox", Email: account.ID}}) - if err := replaceAccountState(lease, login, ""); err != nil { - t.Fatal(err) - } - stored, err := aistudio.LoadStorageState(storage) - if err != nil { - t.Fatal(err) - } - if extension, _, err := stored.AuthExtension(); err != nil || extension.OAuth != nil || extension.Source.Browser != "camoufox" { - t.Fatalf("重新登录后的认证扩展 %+v err=%v", extension, err) - } -} diff --git a/internal/app/channels.go b/internal/app/channels.go index 7d0386a6..3d2be981 100644 --- a/internal/app/channels.go +++ b/internal/app/channels.go @@ -1,7 +1,6 @@ package app import ( - "slices" "strings" "unicode" @@ -39,14 +38,8 @@ func accountOrder(value string) []string { return strings.FieldsFunc(value, func(char rune) bool { return char == ',' || unicode.IsSpace(char) }) } -// apiKeyAccounts 解析 API_KEY_ACCOUNTS 为各 API key 可用的账户 ID;active 是管理服务启动时的配置,已从 keys 中移除而管理服务仍接受的 key 沿用 active 中的绑定 -func apiKeyAccounts(keys, bindings string, active config.Config) map[string][]string { +// apiKeyAccounts 解析 API_KEY_ACCOUNTS 为各 API key 可用的账户 ID +func apiKeyAccounts(keys, bindings string) map[string][]string { accounts, _ := config.ParseAPIKeyAccounts(bindings, keys) - previous, _ := config.ParseAPIKeyAccounts(active.APIKeyAccounts, active.ProxyAPIKey) - for key, ids := range previous { - if !slices.Contains(config.APIKeys(keys), key) { - accounts[key] = ids - } - } return accounts } diff --git a/internal/app/hedge.go b/internal/app/hedge.go index 50115a73..cfe162b4 100644 --- a/internal/app/hedge.go +++ b/internal/app/hedge.go @@ -83,10 +83,13 @@ func (stats *firstEventStats) latencies(now time.Time) []api.FirstEventLatency { return latencies } -// seed 从请求账本的近期记录补入原请求样本:被备用请求取代的原请求取其已等时长,其余只含落败备用请求或没有尝试记录的取首事件减排队 +// seed 从请求账本的近期记录补入原请求样本:跳过开启回复工具的请求;被备用请求取代的原请求取其已等时长,其余只含落败备用请求或没有尝试记录的取首事件减排队 func (stats *firstEventStats) seed(records []api.UsageRecord) { slices.SortFunc(records, func(a, b api.UsageRecord) int { return a.Time.Compare(b.Time) }) for _, record := range records { + if record.ReplyTool { + continue + } model := strings.TrimPrefix(record.Model, "models/") superseded := slices.IndexFunc(record.Attempts, func(attempt api.RequestAttempt) bool { return attempt.Superseded && !attempt.Hedge }) switch { @@ -119,10 +122,18 @@ func percentile95(waits []time.Duration) time.Duration { return waits[(len(waits)*95+99)/100-1] } +// canHedge 判断请求是否允许在等待首事件超时后发起备用请求,后台任务、助手模型与开启回复工具的请求不发起备用请求 +func (service *trackedService) canHedge(request aistudio.GenerateRequest, assistant bool, modelID string) bool { + policy := service.currentFirstEventPolicy() + return !request.Background && !assistant && !request.ReplyTool && + (policy.hedgeAuto || policy.hedgeAfter > 0) && slices.Contains(policy.hedgeModels, modelID) +} + // hedgeDelay 返回原请求等待首事件多久后发起备用请求,不发起时第二个返回值为 false func (service *trackedService) hedgeDelay(modelID, channel string) (time.Duration, bool) { - if !service.hedgeAuto { - return service.hedgeAfter, service.hedgeAfter > 0 + policy := service.currentFirstEventPolicy() + if !policy.hedgeAuto { + return policy.hedgeAfter, policy.hedgeAfter > 0 } p95, samples := service.requests.firstEvents.p95(modelID, channel, time.Now()) return p95, samples >= firstEventMinSamples @@ -207,7 +218,9 @@ func (service *trackedService) awaitFirstEvent( primaryDone = nil check = nil if primary.err == nil { - service.requests.firstEvents.observe(modelID, string(primary.lease.Channel()), primary.firstAt, primary.firstAt.Sub(primary.startedAt)) + if !request.ReplyTool { + service.requests.firstEvents.observe(modelID, string(primary.lease.Channel()), primary.firstAt, primary.firstAt.Sub(primary.startedAt)) + } if hedgeDone != nil { service.supersede(requestCtx, request.ID, hedge, "原请求先返回首事件") service.requests.logRequestProgress(request.ID, primary.accountLabel, "INFO", "原请求胜出,取消备用请求", "hedge_account", hedge.accountLabel, "model", modelID) @@ -220,7 +233,9 @@ func (service *trackedService) awaitFirstEvent( if hedge.err == nil { waited := time.Since(primary.startedAt) if primaryDone != nil { - service.requests.firstEvents.observe(modelID, string(primary.lease.Channel()), time.Now(), waited) + if !request.ReplyTool { + service.requests.firstEvents.observe(modelID, string(primary.lease.Channel()), time.Now(), waited) + } service.supersede(requestCtx, request.ID, primary, "备用请求先返回首事件") } service.requests.logRequestProgress(request.ID, hedge.accountLabel, "INFO", "备用请求胜出", "primary_waited", waited, "model", modelID) diff --git a/internal/app/lifecycle.go b/internal/app/lifecycle.go index 887ccdfd..86664430 100644 --- a/internal/app/lifecycle.go +++ b/internal/app/lifecycle.go @@ -5,7 +5,6 @@ import ( "errors" "net/http" "reflect" - "slices" "sync" "sync/atomic" "time" @@ -25,6 +24,8 @@ type managedService interface { ApplyCapacity(warmTarget int, maxActive int, startupConcurrency int, perAccountConcurrency int) SetAPIKeyAccounts(map[string][]string) SetRequestPolicy(mapping []config.ModelAlias, maxAccountSwitches int) + ApplyHotConfig(config.Config) + ApplyChannelsAndHidden(config.Config) } // generationAdmin 表示进程级管理器转交给当前生成服务的管理操作 @@ -53,6 +54,8 @@ type generationAdmin interface { RuntimeConfig(context.Context) (api.RuntimeConfig, error) UpdateRuntimeConfig(context.Context, api.RuntimeConfig) (api.RuntimeConfig, error) ApplyAccountSelection(config.Config) + ApplyProxy(string) error + ProxyState() (string, []api.AdminProxy) Cooldowns(context.Context) ([]api.AdminCooldown, error) ClearCooldown(ctx context.Context, accountID string, scope string) error Requests(context.Context) ([]api.AdminRequest, error) @@ -133,10 +136,14 @@ type runtimeManager struct { autoStartCancel context.CancelFunc // settings 是已保存的只决定新请求行为的设置 settings atomic.Pointer[requestSettings] - ledger *requestdb.Store - prompts *promptdb.Store - states api.StateStore - logs *logOutput + // apiKey 是当前生效的逗号分隔本地 API 密钥,保存后立即替换 + apiKey atomic.Pointer[string] + // egressProxyVal 是管理进程访问外网使用的默认代理,为空时回退系统代理,保存 PROXY 后立即替换 + egressProxyVal atomic.Pointer[string] + ledger *requestdb.Store + prompts *promptdb.Store + states api.StateStore + logs *logOutput } // newRuntimeManager 创建进程级管理器与初始生成服务 @@ -156,7 +163,9 @@ func newRuntimeManager( requests.close() return nil, err } - generation.service.SetAPIKeyAccounts(apiKeyAccounts(cfg.ProxyAPIKey, cfg.APIKeyAccounts, cfg)) + generation.service.SetAPIKeyAccounts(apiKeyAccounts(cfg.ProxyAPIKey, cfg.APIKeyAccounts)) + manager.setAPIKey(cfg.ProxyAPIKey) + manager.setEgressProxy(cfg.Proxy) manager.settings.Store(requestSettingsOf(cfg)) manager.current = generation manager.wireAccounts(generation) @@ -166,6 +175,26 @@ func newRuntimeManager( return manager, nil } +// setAPIKey 原子更新当前生效的本地 API 密钥 +func (manager *runtimeManager) setAPIKey(value string) { + copyVal := value + manager.apiKey.Store(©Val) +} + +// currentAPIKey 返回当前生效的本地 API 密钥 +func (manager *runtimeManager) currentAPIKey() string { + if value := manager.apiKey.Load(); value != nil { + return *value + } + return manager.activeManagement.ProxyAPIKey +} + +// setEgressProxy 原子更新管理进程外联使用的代理配置 +func (manager *runtimeManager) setEgressProxy(rawProxy string) { + copyVal := rawProxy + manager.egressProxyVal.Store(©Val) +} + // buildRuntimeGeneration 从配置快照创建账户池、Worker 与协议运行时 func buildRuntimeGeneration( launchCtx context.Context, @@ -237,6 +266,7 @@ func (manager *runtimeManager) startService(ctx context.Context) (api.AdminStatu return api.AdminStatus{}, err } manager.wireAccounts(next) + manager.seedAccountUsage(launchCtx, next) } if launchCtx.Err() != nil { release() @@ -258,11 +288,19 @@ func (manager *runtimeManager) startService(ctx context.Context) (api.AdminStatu } return api.AdminStatus{}, err } + manager.overrides.Apply(&saved) next.admin.ApplyAccountSelection(saved) - next.service.SetAPIKeyAccounts(apiKeyAccounts(saved.ProxyAPIKey, saved.APIKeyAccounts, manager.activeManagement)) + next.service.SetAPIKeyAccounts(apiKeyAccounts(saved.ProxyAPIKey, saved.APIKeyAccounts)) next.service.ApplyCapacity(saved.WarmWorkerLimit, saved.MaxActiveWorkers, saved.WarmStartupConcurrency, saved.PerAccountConcurrency) mapping, _ := config.ParseModelMapping(saved.ModelMapping) next.service.SetRequestPolicy(mapping, saved.MaxAccountSwitches) + next.service.ApplyHotConfig(saved) + next.service.ApplyChannelsAndHidden(saved) + if saved.Proxy != next.config.Proxy { + _ = next.admin.ApplyProxy(saved.Proxy) + } + manager.setAPIKey(saved.ProxyAPIKey) + manager.setEgressProxy(saved.Proxy) manager.settings.Store(requestSettingsOf(saved)) manager.mu.Lock() current = manager.current @@ -342,6 +380,14 @@ func (manager *runtimeManager) StopService(ctx context.Context) (api.AdminStatus return current.admin.StopService(ctx) } +// RestartService 停止当前生成服务并以最新配置重新启动 +func (manager *runtimeManager) RestartService(ctx context.Context) (api.AdminStatus, error) { + if _, err := manager.StopService(ctx); err != nil { + return api.AdminStatus{}, err + } + return manager.StartService(ctx) +} + // DownloadCamoufox 在 Camoufox 未就绪且没有进行中的下载时经出口代理在后台开始下载 func (manager *runtimeManager) DownloadCamoufox(ctx context.Context) (api.AdminStatus, error) { camoufoxnative.PrepareInBackground(manager.egressProxy()) @@ -379,11 +425,11 @@ func (manager *runtimeManager) Close() error { // requestSettings 是只决定新请求行为的设置,保存后下一个请求即采用,进行中的请求沿用开始时的值 type requestSettings struct { - modes api.ResponseModes - searchModelAliases bool - googleSearch bool - mediaOutput string - mediaBaseURL string + modes api.ResponseModes + searchModelAliases bool + googleSearch bool + mediaOutput string + mediaBaseURL string replyTool bool userMessageRewrite string thinkingGuard bool @@ -571,9 +617,17 @@ func (manager *runtimeManager) Transcribe(ctx context.Context, request aistudio. // egressProxy 返回管理进程访问外网的代理:PROXY 的第一个代理,未设置时为系统代理 func (manager *runtimeManager) egressProxy() string { - manager.mu.RLock() - proxies := config.ProxyList(manager.current.config.Proxy) - manager.mu.RUnlock() + raw := "" + if value := manager.egressProxyVal.Load(); value != nil { + raw = *value + } else { + manager.mu.RLock() + if manager.current != nil { + raw = manager.current.config.Proxy + } + manager.mu.RUnlock() + } + proxies := config.ProxyList(raw) if len(proxies) > 0 { return proxies[0] } @@ -762,7 +816,63 @@ func (manager *runtimeManager) RuntimeConfig(ctx context.Context) (api.RuntimeCo return value, err } -// UpdateRuntimeConfig 保存生成服务配置,账户选择策略、容量设置与只决定新请求行为的设置立即生效 +// configFromDTO 把管理接口配置对象转换为内部 Config,供测试替身未落盘时使用 +func configFromDTO(value api.RuntimeConfig) config.Config { + initTimeout, _ := time.ParseDuration(value.InitTimeout) + requestTimeout, _ := time.ParseDuration(value.RequestTimeout) + return config.Config{ + AutoStart: value.AutoStart, + HideDockIcon: value.HideDockIcon, + RequestBodyLog: value.RequestBodyLog, + LogFile: value.LogFile, + LogMaxTotalMB: value.LogMaxTotalMB, + AdminAuthEnabled: value.AdminAuthEnabled, + AdminUsername: value.AdminUsername, + AdminPassword: value.SavedAdminPassword, + BuildNativeNonstream: value.BuildNativeNonstream, + NonstreamKeepalive: value.NonstreamKeepalive, + FakeStream: value.FakeStream, + YouTubeLinks: value.YouTubeLinks, + SearchModelAliases: value.SearchModelAliases, + DiscoverHiddenModels: value.DiscoverHiddenModels, + GoogleSearch: value.GoogleSearch, + StripThoughtSignatures: value.StripThoughtSignatures, + ContinuationRewrite: value.ContinuationRewrite, + ContinuationPrompt: value.ContinuationPrompt, + ReplyTool: value.ReplyTool, + UserMessageRewrite: value.UserMessageRewrite, + ThinkingGuard: value.ThinkingGuard, + FirstEventHedge: value.FirstEventHedge, + FirstEventHedgeModels: value.FirstEventHedgeModels, + FirstEventTimeout: value.FirstEventTimeout, + AuthStates: value.AuthStates, + ListenAddr: value.ListenAddr, + PreviewListenAddr: value.PreviewListenAddr, + ProxyAPIKey: value.APIKey, + Proxy: value.Proxy, + InitTimeout: initTimeout, + RequestTimeout: requestTimeout, + WarmWorkerLimit: value.WarmWorkerLimit, + MaxActiveWorkers: value.MaxActiveWorkers, + WarmStartupConcurrency: value.WarmStartupConcurrency, + PerAccountConcurrency: value.PerAccountConcurrency, + RoutingStrategy: value.RoutingStrategy, + AccountOrder: value.AccountOrder, + MaxAccountSwitches: value.MaxAccountSwitches, + AccountSwitchInterval: value.AccountSwitchInterval, + MaxQuotaSwitches: value.MaxQuotaSwitches, + UpstreamChannels: value.UpstreamChannels, + ModelMapping: value.ModelMapping, + ModelChannels: value.ModelChannels, + ModelAccounts: value.ModelAccounts, + APIKeyAccounts: value.APIKeyAccounts, + WAABackend: value.WAABackend, + MediaOutput: value.MediaOutput, + MediaBaseURL: value.MediaBaseURL, + } +} + +// UpdateRuntimeConfig 保存生成服务配置,除必须重建生成服务或重启程序的极少数项外,其余设置均对下一次请求立即生效 func (manager *runtimeManager) UpdateRuntimeConfig(ctx context.Context, value api.RuntimeConfig) (api.RuntimeConfig, error) { manager.configMu.Lock() defer manager.configMu.Unlock() @@ -772,25 +882,37 @@ func (manager *runtimeManager) UpdateRuntimeConfig(ctx context.Context, value ap if err != nil { return updated, err } - current.service.SetAPIKeyAccounts(apiKeyAccounts(updated.APIKey, updated.APIKeyAccounts, manager.activeManagement)) + var saved config.Config + if manager.configPath != "" { + var loadErr error + saved, loadErr = config.Load(manager.configPath) + if loadErr != nil { + return updated, loadErr + } + } else { + saved = configFromDTO(updated) + } + manager.overrides.Apply(&saved) + manager.setAPIKey(saved.ProxyAPIKey) + manager.setEgressProxy(saved.Proxy) + manager.activeManagement.ProxyAPIKey = saved.ProxyAPIKey + manager.activeManagement.AdminAuthEnabled = saved.AdminAuthEnabled + manager.activeManagement.AdminUsername = saved.AdminUsername + manager.activeManagement.AdminPassword = saved.AdminPassword + current.service.SetAPIKeyAccounts(apiKeyAccounts(saved.ProxyAPIKey, saved.APIKeyAccounts)) current.service.ApplyCapacity( - updated.WarmWorkerLimit, updated.MaxActiveWorkers, updated.WarmStartupConcurrency, updated.PerAccountConcurrency, + saved.WarmWorkerLimit, saved.MaxActiveWorkers, saved.WarmStartupConcurrency, saved.PerAccountConcurrency, ) - mapping, _ := config.ParseModelMapping(updated.ModelMapping) - current.service.SetRequestPolicy(mapping, updated.MaxAccountSwitches) - manager.settings.Store(&requestSettings{ - modes: api.ResponseModes{NonstreamKeepalive: updated.NonstreamKeepalive, FakeStream: updated.FakeStream}, - searchModelAliases: updated.SearchModelAliases, - googleSearch: updated.GoogleSearch, - mediaOutput: updated.MediaOutput, - mediaBaseURL: updated.MediaBaseURL, - replyTool: updated.ReplyTool, - userMessageRewrite: updated.UserMessageRewrite, - thinkingGuard: updated.ThinkingGuard, - }) + mapping, _ := config.ParseModelMapping(saved.ModelMapping) + current.service.SetRequestPolicy(mapping, saved.MaxAccountSwitches) + current.service.ApplyHotConfig(saved) + current.service.ApplyChannelsAndHidden(saved) + proxyErr := current.admin.ApplyProxy(saved.Proxy) + updated.ActiveProxy, updated.ProxyPool = current.admin.ProxyState() + manager.settings.Store(requestSettingsOf(saved)) updated = manager.decorateRuntimeConfig(updated, current.config) - manager.ledger.SetBodyCapture(updated.RequestBodyLog) - return updated, manager.logs.set(updated.LogFile, updated.LogMaxTotalMB) + manager.ledger.SetBodyCapture(saved.RequestBodyLog) + return updated, errors.Join(proxyErr, manager.logs.set(saved.LogFile, saved.LogMaxTotalMB)) } // Cooldowns 返回当前生成服务冷却状态 @@ -845,47 +967,32 @@ func (manager *runtimeManager) RecordAccessLog(entry api.AccessLog) { // decorateRuntimeConfig 标记配置所属的进程级与生成服务生效时机 func (manager *runtimeManager) decorateRuntimeConfig(value api.RuntimeConfig, active config.Config) api.RuntimeConfig { + serviceRunning := false + manager.mu.RLock() + if manager.current != nil && manager.current.service != nil { + serviceRunning = manager.current.service.State() != "STOPPED" + } + manager.mu.RUnlock() value.ActiveListenAddr = manager.activeManagement.ListenAddr value.ReservedListenAddr = manager.reservedListenAddr - value.ActiveAPIKey = manager.activeManagement.ProxyAPIKey value.ActivePreviewListenAddr = manager.previewAddress - value.ManagementRestartRequired = value.ListenAddr != value.ActiveListenAddr && value.ListenAddr != value.ReservedListenAddr || value.APIKey != value.ActiveAPIKey || + if manager.requests != nil { + value.ActiveRequests = manager.requests.count() + } + value.ManagementRestartRequired = (value.ListenAddr != value.ActiveListenAddr && value.ListenAddr != value.ReservedListenAddr) || value.PreviewListenAddr != manager.activeManagement.PreviewListenAddr - value.ManagementRestartRequired = value.ManagementRestartRequired || - value.AdminAuthEnabled != manager.activeManagement.AdminAuthEnabled || - value.AdminUsername != manager.activeManagement.AdminUsername || - value.SavedAdminPassword != manager.activeManagement.AdminPassword - value.ServiceRestartRequired = !sameDataConfig(value, active, manager.overrides) + value.ServiceRestartRequired = serviceRunning && !sameDataConfig(value, active, manager.overrides) return value } -// sameDataConfig 比较已保存配置与当前生成服务配置 +// sameDataConfig 比较必须重建生成服务才能生效的配置项(账户目录与 WAA 后端) func sameDataConfig(value api.RuntimeConfig, active config.Config, overrides dataConfigOverrides) bool { - initTimeout, _ := time.ParseDuration(value.InitTimeout) - requestTimeout, _ := time.ParseDuration(value.RequestTimeout) saved := config.Config{ - AuthStates: value.AuthStates, Proxy: value.Proxy, - InitTimeout: initTimeout, RequestTimeout: requestTimeout, StripThoughtSignatures: value.StripThoughtSignatures, - UpstreamChannels: value.UpstreamChannels, - WAABackend: value.WAABackend, - BuildNativeNonstream: value.BuildNativeNonstream, - YouTubeLinks: value.YouTubeLinks, - DiscoverHiddenModels: value.DiscoverHiddenModels, - FirstEventHedge: value.FirstEventHedge, - FirstEventHedgeModels: value.FirstEventHedgeModels, - FirstEventTimeout: value.FirstEventTimeout, - ContinuationRewrite: value.ContinuationRewrite, - ContinuationPrompt: value.ContinuationPrompt, + AuthStates: value.AuthStates, + WAABackend: value.WAABackend, } overrides.Apply(&saved) - return saved.AuthStates == active.AuthStates && saved.Proxy == active.Proxy && - saved.InitTimeout == active.InitTimeout && saved.RequestTimeout == active.RequestTimeout && - slices.Equal(saved.UpstreamChannels, active.UpstreamChannels) && - saved.WAABackend == active.WAABackend && - saved.BuildNativeNonstream == active.BuildNativeNonstream && - saved.YouTubeLinks == active.YouTubeLinks && saved.StripThoughtSignatures == active.StripThoughtSignatures && saved.FirstEventHedge == active.FirstEventHedge && saved.FirstEventHedgeModels == active.FirstEventHedgeModels && saved.FirstEventTimeout == active.FirstEventTimeout && - saved.DiscoverHiddenModels == active.DiscoverHiddenModels && - saved.ContinuationRewrite == active.ContinuationRewrite && saved.ContinuationPrompt == active.ContinuationPrompt + return saved.AuthStates == active.AuthStates && saved.WAABackend == active.WAABackend } var _ aistudio.Service = (*runtimeManager)(nil) diff --git a/internal/app/logfile.go b/internal/app/logfile.go index 70516af7..66144a74 100644 --- a/internal/app/logfile.go +++ b/internal/app/logfile.go @@ -15,21 +15,28 @@ const logFileName = "aistudio2api.log" // logOutput 把控制台日志写到标准错误与可开关的轮转日志文件 type logOutput struct { - dir string - mu sync.Mutex - file *lumberjack.Logger + dir string + mu sync.Mutex + enabled bool + maxTotalMB int + file *lumberjack.Logger } // set 开启或关闭日志文件;单文件按 config.LogFileMB 轮转,目录总量超过 maxTotalMB 时删除最旧的文件 func (output *logOutput) set(enabled bool, maxTotalMB int) error { output.mu.Lock() defer output.mu.Unlock() + if output.enabled == enabled && (!enabled || output.maxTotalMB == maxTotalMB) && (output.file != nil) == enabled { + return nil + } if output.file != nil { if err := output.file.Close(); err != nil { return err } output.file = nil } + output.enabled = enabled + output.maxTotalMB = maxTotalMB if !enabled { return nil } diff --git a/internal/app/proxy_pool.go b/internal/app/proxy_pool.go index 903bb3b7..47e7229e 100644 --- a/internal/app/proxy_pool.go +++ b/internal/app/proxy_pool.go @@ -90,6 +90,53 @@ func (admin *runtimeAdmin) probeProxies(ctx context.Context) { } } +// syncProxyProbe 按代理池中的代理数量动态启动或停止定时探测协程;initialProbe 为 true 且新启动探测时先异步立即检测一次 +func (admin *runtimeAdmin) syncProxyProbe(proxyCount int, initialProbe bool) { + admin.probeMu.Lock() + if proxyCount <= 1 { + cancel := admin.probeCancel + admin.probeCancel = nil + admin.probeMu.Unlock() + if cancel != nil { + cancel() + } + return + } + if admin.probeCancel != nil { + admin.probeMu.Unlock() + if initialProbe { + go admin.runProxyProbeOnce(admin.lifecycle) + } + return + } + probeCtx, stopProbe := context.WithCancel(admin.lifecycle) + admin.probeCancel = stopProbe + admin.probeMu.Unlock() + if initialProbe { + go admin.runProxyProbeOnce(probeCtx) + } + go admin.probeProxies(probeCtx) +} + +// stopProxyProbe 停止代理池定时探测协程 +func (admin *runtimeAdmin) stopProxyProbe() { + admin.probeMu.Lock() + cancel := admin.probeCancel + admin.probeCancel = nil + admin.probeMu.Unlock() + if cancel != nil { + cancel() + } +} + +func (admin *runtimeAdmin) runProxyProbeOnce(ctx context.Context) { + changed, err := admin.proxies.Probe(ctx, checkProxy) + if err != nil && ctx.Err() == nil { + admin.requests.log("service", "WARN", "代理改绑失败", "error", err) + } + admin.rebindAccounts(changed) +} + // rebindAccounts 在后台按代理池的新绑定各自重建受影响账户的请求头客户端与 Worker func (admin *runtimeAdmin) rebindAccounts(accountIDs []string) { for _, accountID := range accountIDs { @@ -112,6 +159,10 @@ func (admin *runtimeAdmin) rebindAccount(ctx context.Context, accountID string) return errors.Join(err, lease.Release()) } workerUpdate.Commit() - admin.requests.log(account.Config.Label, "WARN", "代理已改绑", "egress", redactedProxy(account.EffectiveProxy(admin.globalProxy))) - return lease.Release() + admin.requests.log(account.Config.Label, "WARN", "代理已改绑", "egress", redactedProxy(account.EffectiveProxy(admin.currentGlobalProxy()))) + err = lease.Release() + if admin.service != nil { + admin.publishRuntimeSnapshot(admin.lifecycle) + } + return err } diff --git a/internal/app/request_logging.go b/internal/app/request_logging.go index ca44c181..7bca62e4 100644 --- a/internal/app/request_logging.go +++ b/internal/app/request_logging.go @@ -19,7 +19,7 @@ func requestLogData(entry api.AccessLog) *api.RequestLog { data := &api.RequestLog{ ID: entry.RequestID, Model: entry.Model, Method: entry.Method, Path: entry.Path, Status: entry.Status, DurationMS: float64(entry.Latency) / float64(time.Millisecond), - ToolCalls: entry.ToolCalls, FinishReason: entry.FinishReason, Error: entry.Error, + ToolCalls: entry.ToolCalls, ReplyTool: entry.ReplyTool, FinishReason: entry.FinishReason, Error: entry.Error, InputMessages: entry.InputMessages, InputTextChars: entry.InputTextChars, InputMedia: entry.InputMedia, InputMediaBytes: entry.InputMediaBytes, InputFiles: entry.InputFiles, FirstEventMS: float64(entry.FirstEvent) / float64(time.Millisecond), UpstreamBytes: entry.UpstreamBytes, @@ -78,6 +78,12 @@ func requestOutcome(entry api.AccessLog) (string, string, string) { // finishedRequestLog 投影请求结果日志,失败且没有错误信息时记录 HTTP 状态 func finishedRequestLog(entry api.AccessLog) (*api.RequestLog, string, string) { data := requestLogData(entry) + if entry.ReplyTool { + calls := entry.ReplyToolCalls + continuations := entry.ReplyToolContinuations + data.ReplyToolCalls = &calls + data.ReplyToolContinuations = &continuations + } state, level, message := requestOutcome(entry) data.State = state if state == "failed" && data.Error == "" { @@ -98,7 +104,9 @@ func requestRow(entry api.AccessLog, finished time.Time) requestdb.Row { row := requestdb.Row{ ID: entry.RequestID, Time: finished, Protocol: requestProtocol(entry.Path), Path: entry.Path, Model: entry.Model, Account: entry.Account, Channel: entry.Channel, Status: entry.Status, State: data.State, - Duration: entry.Latency, FirstEvent: entry.FirstEvent, Queue: entry.QueueWait, Proof: entry.Proof, ToolCalls: entry.ToolCalls, Error: cmp.Or(data.Error, entry.TrailingError), + Duration: entry.Latency, FirstEvent: entry.FirstEvent, Queue: entry.QueueWait, Proof: entry.Proof, + ToolCalls: entry.ToolCalls, ReplyTool: entry.ReplyTool, ReplyToolCalls: entry.ReplyToolCalls, ReplyToolContinuations: entry.ReplyToolContinuations, + Error: cmp.Or(data.Error, entry.TrailingError), Attempts: entry.Attempts, } if usage := data.Usage; usage != nil { diff --git a/internal/app/runtime.go b/internal/app/runtime.go index 1469f01c..bf088245 100644 --- a/internal/app/runtime.go +++ b/internal/app/runtime.go @@ -22,6 +22,22 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/config" ) +// resolveProxyConfig 解析全局代理配置,空时回退系统代理,返回代理池列表、默认出口、展示串与是否来自系统代理 +func resolveProxyConfig(raw string) (proxyList []string, globalProxy string, activeProxy string, fromSystem bool) { + proxyList = config.ProxyList(raw) + if len(proxyList) == 0 { + if system := systemProxy(); system != "" { + proxyList = []string{system} + fromSystem = true + } + } + if len(proxyList) > 0 { + globalProxy = proxyList[0] + } + activeProxy = strings.Join(proxyList, ",") + return proxyList, globalProxy, activeProxy, fromSystem +} + // newRuntime 装配单个生成服务实例 func newRuntime( launchCtx context.Context, @@ -46,25 +62,28 @@ func newRuntime( return nil, nil, nil, err } egress := []any{"egress", "直连"} - proxyList := config.ProxyList(cfg.Proxy) - if len(proxyList) == 0 { - if system := systemProxy(); system != "" { - proxyList = []string{system} - egress = []any{"egress", redactedProxy(system), "proxy_source", "系统代理"} - } - } else { - redacted := make([]string, 0, len(proxyList)) - for _, proxy := range proxyList { - redacted = append(redacted, redactedProxy(proxy)) + proxyList, globalProxy, activeProxy, fromSystem := resolveProxyConfig(cfg.Proxy) + if len(proxyList) > 0 { + if fromSystem { + egress = []any{"egress", redactedProxy(globalProxy), "proxy_source", "系统代理"} + } else { + redacted := make([]string, 0, len(proxyList)) + for _, proxy := range proxyList { + redacted = append(redacted, redactedProxy(proxy)) + } + egress = []any{"egress", strings.Join(redacted, ",")} } - egress = []any{"egress", strings.Join(redacted, ",")} } - globalProxy := "" - if len(proxyList) > 0 { - globalProxy = proxyList[0] + cfg.Proxy = activeProxy + var sharedGlobalProxy atomic.Pointer[string] + sharedGlobalProxy.Store(&globalProxy) + currentProxy := func() string { + if proxy := sharedGlobalProxy.Load(); proxy != nil { + return *proxy + } + return "" } - cfg.Proxy = strings.Join(proxyList, ",") - camoufoxPath, login := prepareWAABackend(cfg, requests, accounts, globalProxy) + camoufoxPath, login := prepareWAABackend(cfg, requests, accounts, currentProxy) requests.logStage("service", "INFO", api.LogStage{Name: "运行时装配", Step: 3, Steps: 3}, "创建协议客户端", egress...) pool := aistudio.NewAccountPool(accounts, cfg.PerAccountConcurrency) pool.SetRoutingStrategy(cfg.RoutingStrategy) @@ -102,35 +121,27 @@ func newRuntime( Static: transport, }) pooled := aistudio.NewPooledService(pool, client) - pooled.BuildNativeNonstream = cfg.BuildNativeNonstream - pooled.YouTubeLinks = cfg.YouTubeLinks - pooled.DiscoverHiddenModels = cfg.DiscoverHiddenModels - pooled.StripThoughtSignatures = cfg.StripThoughtSignatures - pooled.ContinuationRewrite = cfg.ContinuationRewrite - pooled.ContinuationPrompt = cfg.ContinuationPrompt service := newTrackedService(lifecycle, pooled, pool, requests, workers, cfg.RequestTimeout) - service.buildNativeNonstream = cfg.BuildNativeNonstream - service.hedgeAuto, service.hedgeAfter, _ = config.ParseFirstEventHedge(cfg.FirstEventHedge) - service.hedgeModels = config.ModelList(cfg.FirstEventHedgeModels) - service.firstEventTimeout, _ = config.ParseFirstEventTimeout(cfg.FirstEventTimeout) + service.pooled = pooled + service.transport = transport + service.protected = protected + service.refresher = refresher + service.sharedGlobalProxy = &sharedGlobalProxy + service.ApplyHotConfig(cfg) service.discoverHiddenModels = cfg.DiscoverHiddenModels - mapping, _ := config.ParseModelMapping(cfg.ModelMapping) - service.SetRequestPolicy(mapping, cfg.MaxAccountSwitches) if camoufoxPath != "" { - service.camoufoxProxy, service.camoufoxWait = globalProxy, make(chan struct{}) + service.camoufoxWait = make(chan struct{}) } admin := newRuntimeAdmin(lifecycle, pool, store, service, requests, login, workers, cfg) service.publishStatus = func() { admin.publishStatus(lifecycle) } - admin.proxies, admin.globalProxy = proxies, globalProxy + admin.proxies = proxies + admin.setProxyState(globalProxy, activeProxy) service.proxies, service.rebindAccounts = proxies, admin.rebindAccounts workers.proxyFailed = service.reportProxyFailure - probeCtx, stopProbe := context.WithCancel(lifecycle) - if len(proxyList) > 1 { - go admin.probeProxies(probeCtx) - } + admin.syncProxyProbe(len(proxyList), false) requests.logStage("service", "INFO", api.LogStage{Name: "运行时装配", State: "completed"}, "协议运行时就绪", "accounts", len(accounts), "duration", time.Since(startedAt)) closeRuntime := func() error { - stopProbe() + admin.stopProxyProbe() err := workers.Close() camoufoxnative.WaitRetired() transport.CloseIdleConnections() @@ -139,9 +150,23 @@ func newRuntime( return service, admin, closeRuntime, nil } +// firstEventPolicy 是单次请求开始时快照的首字超时与备用请求策略 +type firstEventPolicy struct { + hedgeAuto bool + hedgeAfter time.Duration + hedgeModels []string + firstEventTimeout time.Duration +} + // trackedService 跟踪生成请求及其唯一账户租约 type trackedService struct { buildNativeNonstream bool + hotBuildNative atomic.Pointer[bool] + pooled *aistudio.PooledService + transport *aistudio.MakerSuiteHTTPTransport + protected *aistudio.WorkerProtectedTransport + refresher *authRuntimeRefresher + sharedGlobalProxy *atomic.Pointer[string] proxies *aistudio.ProxyPool rebindAccounts func([]string) lifecycle context.Context @@ -151,6 +176,7 @@ type trackedService struct { requests *requestRegistry workers *accountWorkerManager timeout time.Duration + hotTimeout atomic.Pointer[time.Duration] state atomic.Int32 lifecycleMu sync.Mutex transitionDone chan struct{} @@ -175,26 +201,31 @@ type trackedService struct { catalogRoundDone chan struct{} // catalogRoundWake 让巡检循环立即开始请求缺少模型时排定的一轮 catalogRoundWake chan struct{} - // hedgeAuto 与 hedgeAfter 是首事件超时备用请求的自适应开关与自定义等待 - hedgeAuto bool - hedgeAfter time.Duration - // hedgeModels 是发起备用请求的模型 - hedgeModels []string - // firstEventTimeout 是单次尝试从取得账户起等待首个上游事件的最长时间,零值表示不限制 + // hedgeAuto、hedgeAfter、hedgeModels 与 firstEventTimeout 保留为未调用 ApplyHotConfig 时的测试兼容回退字段 + hedgeAuto bool + hedgeAfter time.Duration + hedgeModels []string firstEventTimeout time.Duration + // firstEventPolicy 是保存设置后立即替换的首字超时与备用请求策略快照 + firstEventPolicy atomic.Pointer[firstEventPolicy] // hedges 是正在进行的备用请求数 hedges atomic.Int32 // maxAccountSwitches 是一个请求因非额度失败换号的次数上限,保存设置后立即替换 maxAccountSwitches atomic.Int64 + // accountSwitchInterval 是同一请求内换号前的最短等待间隔(纳秒),0 表示关闭 + accountSwitchInterval atomic.Int64 + // quotaSwitchLimit 编码额度失败换号上限:0 表示不限制,k > 0 表示最多换 k-1 次号(零值即默认不限) + quotaSwitchLimit atomic.Int64 // modelMapping 是 MODEL_MAPPING 解析出的模型别名,保存设置后立即替换 modelMapping atomic.Pointer[[]config.ModelAlias] // disconnects 记录各模型与通道最近的请求终态,判断成片断连 disconnects disconnectTracker - // discoverHiddenModels 表示同步账户目录时探测官网隐藏模型 + // discoverHiddenModels 表示同步账户目录时探测官网隐藏模型(未热更新前的初始值);热更新后以 hotDiscoverHidden 为准 discoverHiddenModels bool + hotDiscoverHidden atomic.Pointer[bool] // camoufoxWait 在 Camoufox 后端的启动开始等待 Camoufox 下载时关闭,SpiderMonkey 后端为 nil camoufoxWait chan struct{} - // camoufoxProxy 是 Camoufox 后端下载 Camoufox 的出口代理 + // camoufoxProxy 是未绑定 sharedGlobalProxy 时 Camoufox 下载使用的兼容回退代理 camoufoxProxy string // step 是生成服务正在进行的启动或停止步骤,没有时为 nil,取值见 api.AdminStatus.Transition // 约束:启动步骤在持有 lifecycleMu 且服务仍在启动时写入,停止步骤由停止流程写入 @@ -228,7 +259,8 @@ func newTrackedService( catalog := service.(modelCatalogService) tracked := &trackedService{ lifecycle: lifecycle, service: service, catalog: catalog, pool: pool, requests: requests, workers: workers, - timeout: timeout, modelRetries: make(map[string]struct{}), catalogRoundWake: make(chan struct{}, 1), + timeout: timeout, + modelRetries: make(map[string]struct{}), catalogRoundWake: make(chan struct{}, 1), publishStatus: func() {}, } tracked.SetRequestPolicy(nil, config.DefaultMaxAccountSwitches) @@ -295,6 +327,258 @@ func (service *trackedService) SetRequestPolicy(mapping []config.ModelAlias, max service.maxAccountSwitches.Store(int64(maxAccountSwitches)) } +// SetSwitchPolicy 替换之后的请求使用的最短换号间隔与额度失败换号上限 +func (service *trackedService) SetSwitchPolicy(interval time.Duration, maxQuotaSwitches int, quotaLimited bool) { + service.accountSwitchInterval.Store(int64(max(interval, 0))) + if !quotaLimited { + service.quotaSwitchLimit.Store(0) + return + } + service.quotaSwitchLimit.Store(int64(max(maxQuotaSwitches, 0)) + 1) +} + +// ApplyHotConfig 原子应用所有支持热加载的生成服务设置,不中断进行中的请求 +func (service *trackedService) ApplyHotConfig(cfg config.Config) { + if service.pooled != nil { + service.pooled.SetRequestOptions(aistudio.RequestOptions{ + BuildNativeNonstream: cfg.BuildNativeNonstream, + YouTubeLinks: cfg.YouTubeLinks, + DiscoverHiddenModels: cfg.DiscoverHiddenModels, + StripThoughtSignatures: cfg.StripThoughtSignatures, + ContinuationRewrite: cfg.ContinuationRewrite, + ContinuationPrompt: cfg.ContinuationPrompt, + }) + } + buildNative := cfg.BuildNativeNonstream + service.hotBuildNative.Store(&buildNative) + if cfg.RequestTimeout > 0 { + timeout := cfg.RequestTimeout + service.hotTimeout.Store(&timeout) + } + if cfg.InitTimeout > 0 { + if service.workers != nil { + service.workers.SetInitTimeout(cfg.InitTimeout) + } + if service.protected != nil { + service.protected.SetSetupTimeout(cfg.InitTimeout) + } + } + hedgeAuto, hedgeAfter, _ := config.ParseFirstEventHedge(cfg.FirstEventHedge) + firstEventTimeout, _ := config.ParseFirstEventTimeout(cfg.FirstEventTimeout) + service.firstEventPolicy.Store(&firstEventPolicy{ + hedgeAuto: hedgeAuto, + hedgeAfter: hedgeAfter, + hedgeModels: config.ModelList(cfg.FirstEventHedgeModels), + firstEventTimeout: firstEventTimeout, + }) + mapping, _ := config.ParseModelMapping(cfg.ModelMapping) + service.SetRequestPolicy(mapping, cfg.MaxAccountSwitches) + switchInterval, _ := config.ParseAccountSwitchInterval(cfg.AccountSwitchInterval) + quotaLimit, quotaLimited, _ := config.ParseMaxQuotaSwitches(cfg.MaxQuotaSwitches) + service.SetSwitchPolicy(switchInterval, quotaLimit, quotaLimited) +} + +// useBuildNativeNonstream 返回非流式请求是否优先使用 Build 原生单次调用 +func (service *trackedService) useBuildNativeNonstream() bool { + if value := service.hotBuildNative.Load(); value != nil { + return *value + } + return service.buildNativeNonstream +} + +// currentFirstEventPolicy 返回当前生效的首字超时与备用请求策略快照 +func (service *trackedService) currentFirstEventPolicy() firstEventPolicy { + if policy := service.firstEventPolicy.Load(); policy != nil { + return *policy + } + return firstEventPolicy{ + hedgeAuto: service.hedgeAuto, + hedgeAfter: service.hedgeAfter, + hedgeModels: service.hedgeModels, + firstEventTimeout: service.firstEventTimeout, + } +} + +// requestTimeout 返回后续请求使用的无数据超时时长 +func (service *trackedService) requestTimeout() time.Duration { + if timeout := service.hotTimeout.Load(); timeout != nil { + return *timeout + } + return service.timeout +} + +// switchInterval 返回同一请求内换号前的最短等待间隔,未启用时为 0 +func (service *trackedService) switchInterval() time.Duration { + return time.Duration(service.accountSwitchInterval.Load()) +} + +// currentCamoufoxProxy 返回 Camoufox 下载使用的当前出口代理 +func (service *trackedService) currentCamoufoxProxy() string { + if service.sharedGlobalProxy != nil { + if proxy := service.sharedGlobalProxy.Load(); proxy != nil { + return *proxy + } + } + return service.camoufoxProxy +} + +// setSharedGlobalProxy 同步更新生成服务内部各传输、续签器与 Worker 管理器持有的默认出口代理 +func (service *trackedService) setSharedGlobalProxy(proxy string) error { + if service.transport != nil { + if err := service.transport.SetGlobalProxy(proxy); err != nil { + return err + } + } + if service.sharedGlobalProxy != nil { + copyProxy := proxy + service.sharedGlobalProxy.Store(©Proxy) + } + if service.workers != nil { + service.workers.SetGlobalProxy(proxy) + } + if service.refresher != nil { + service.refresher.SetGlobalProxy(proxy) + } + return nil +} + +// applyUpstreamChannels 热替换上游通道,必要时在后台为缺失 Build 目录的账户补拉 Build 目录 +func (service *trackedService) applyUpstreamChannels(channels []string) { + if service.pool == nil { + return + } + wasBuild := service.pool.BuildEnabled() + service.pool.SetUpstreamChannels(upstreamChannels(channels)) + if service.catalog != nil { + service.modelSyncMu.Lock() + service.applyCachedModelCatalog() + service.modelSyncMu.Unlock() + } + if wasBuild || !service.pool.BuildEnabled() || service.pooled == nil { + return + } + missing := service.pool.AccountsMissingBuildCatalog() + if len(missing) == 0 { + return + } + service.lifecycleMu.Lock() + dataCtx := service.dataContext + running := service.state.Load() == serviceRunning && dataCtx != nil && dataCtx.Err() == nil + service.lifecycleMu.Unlock() + if !running { + return + } + go func() { + updated := false + for _, accountID := range missing { + if dataCtx.Err() != nil { + return + } + reqCtx, cancel := service.lifecycleRequestContext(dataCtx) + ok, err := service.pooled.RefreshBuildCatalog(reqCtx, accountID) + cancel() + if err != nil { + if dataCtx.Err() == nil { + service.requests.log(accountID, "WARN", "Build 模型目录同步失败", "error", err) + } + continue + } + if ok { + updated = true + } + } + if updated && dataCtx.Err() == nil { + service.modelSyncMu.Lock() + service.applyCachedModelCatalog() + service.modelSyncMu.Unlock() + service.publishModelAccess() + } + }() +} + +// isDiscoverHiddenModels 返回当前是否开启官网隐藏模型探测 +func (service *trackedService) isDiscoverHiddenModels() bool { + if value := service.hotDiscoverHidden.Load(); value != nil { + return *value + } + return service.discoverHiddenModels +} + +// applyDiscoverHiddenModels 热切换官网隐藏模型探测:关闭时立即从目录剥离并持久化,开启时在运行中后台增量探测 +func (service *trackedService) applyDiscoverHiddenModels(enabled bool) { + next := enabled + prevPtr := service.hotDiscoverHidden.Swap(&next) + previous := service.discoverHiddenModels + if prevPtr != nil { + previous = *prevPtr + } + if previous == enabled { + return + } + if !enabled { + if service.pooled != nil && service.pooled.ClearHiddenModels() > 0 { + service.modelSyncMu.Lock() + service.applyCachedModelCatalog() + service.modelSyncMu.Unlock() + } + service.publishModelAccess() + return + } + service.lifecycleMu.Lock() + dataCtx := service.dataContext + running := service.state.Load() == serviceRunning && dataCtx != nil && dataCtx.Err() == nil + service.lifecycleMu.Unlock() + if !running || service.catalog == nil { + return + } + accounts := service.modelCatalogAccountIDs() + if len(accounts) == 0 { + return + } + go func() { + for result := range service.refreshAccountModelCatalogs(dataCtx, accounts, false) { + if dataCtx.Err() != nil { + return + } + if !result.skipped && result.err == nil && len(result.models) > 0 { + service.modelSyncMu.Lock() + service.applyCachedModelCatalog() + service.modelSyncMu.Unlock() + service.publishModelAccess() + } + } + }() +} + +// ApplyChannelsAndHidden 应用上游通道与官网隐藏模型探测的热切换 +func (service *trackedService) ApplyChannelsAndHidden(cfg config.Config) { + service.applyUpstreamChannels(cfg.UpstreamChannels) + service.applyDiscoverHiddenModels(cfg.DiscoverHiddenModels) +} + +// waitSwitchInterval 等满从 lastFailureAt 算起的最短换号间隔,等待期间 ctx 取消则立即返回 +func (service *trackedService) waitSwitchInterval(ctx context.Context, requestID string, lastFailureAt time.Time) error { + interval := service.switchInterval() + if interval <= 0 || lastFailureAt.IsZero() { + return nil + } + remaining := interval - time.Since(lastFailureAt) + if remaining <= 0 { + return nil + } + if requestID != "" && service.requests != nil { + service.requests.logRequestProgress(requestID, "request", "INFO", "等待换号间隔", "wait", remaining.Round(time.Millisecond)) + } + timer := time.NewTimer(remaining) + defer timer.Stop() + select { + case <-timer.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + // aliases 返回之后的请求使用的模型别名 func (service *trackedService) aliases() []config.ModelAlias { if mapping := service.modelMapping.Load(); mapping != nil { @@ -378,7 +662,7 @@ func (service *trackedService) prepareCamoufox(ctx context.Context) error { return nil } if camoufoxnative.PreparationState().Ready { - _, err := camoufoxnative.Prepare(ctx, service.camoufoxProxy) + _, err := camoufoxnative.Prepare(ctx, service.currentCamoufoxProxy()) return err } select { @@ -389,7 +673,7 @@ func (service *trackedService) prepareCamoufox(ctx context.Context) error { startedAt := time.Now() service.enterLaunchStep("wait_camoufox") service.requests.logStage("service", "INFO", api.LogStage{Name: "生成服务启动"}, "等待 Camoufox 下载") - if _, err := camoufoxnative.Prepare(ctx, service.camoufoxProxy); err != nil { + if _, err := camoufoxnative.Prepare(ctx, service.currentCamoufoxProxy()); err != nil { return err } service.requests.logStage("service", "INFO", api.LogStage{Name: "生成服务启动"}, "Camoufox 已就绪", "duration", time.Since(startedAt)) @@ -923,9 +1207,10 @@ func (service *trackedService) modelCatalogAccountIDs() []string { func (service *trackedService) staleCatalogAccountIDs(accountIDs []string) []string { now := time.Now() fresh := make(map[string]bool) + discoverHidden := service.isDiscoverHiddenModels() for _, status := range service.pool.Status() { fresh[status.ID] = len(status.Models) > 0 && now.Sub(status.CatalogSyncedAt) < accountStateRefreshInterval && - status.HiddenDiscovered == service.discoverHiddenModels && (service.discoverHiddenModels || status.HiddenModels == 0) + status.HiddenDiscovered == discoverHidden && (discoverHidden || status.HiddenModels == 0) } return slices.DeleteFunc(accountIDs, func(accountID string) bool { return fresh[accountID] }) } @@ -970,14 +1255,16 @@ func (service *trackedService) refreshAccountModelCatalogs( return results } -// refreshAccountModelCatalog 以账户页面载入时的响应同步权益与模型目录,reload 为 true 时重新载入页面,失败或目录为空时登记 30 秒后重试 +// refreshAccountModelCatalog 以账户页面载入时的响应同步权益与模型目录,reload 为 true 时重新载入页面,失败或目录为空时登记 30 秒后重试(出口地区不受支持除外) func (service *trackedService) refreshAccountModelCatalog(ctx context.Context, accountID string, reload bool) ([]aistudio.Model, error) { requestCtx, cancel := service.lifecycleRequestContext(ctx) defer cancel() models, err := service.catalog.RefreshAccountModels(requestCtx, accountID, reload) service.modelRetriesMu.Lock() if err != nil { - if ctx.Err() == nil { + if errors.Is(err, camoufoxnative.ErrRegionNotSupported) { + delete(service.modelRetries, accountID) + } else if ctx.Err() == nil { service.modelRetries[accountID] = struct{}{} } service.modelRetriesMu.Unlock() @@ -1157,7 +1444,7 @@ func (service *trackedService) awaitCatalogModel(ctx context.Context, model stri if done == nil { return } - ctx, cancel := context.WithTimeout(ctx, service.timeout) + ctx, cancel := context.WithTimeout(ctx, service.requestTimeout()) defer cancel() for { changed := service.pool.Changed() @@ -1233,7 +1520,7 @@ func (service *trackedService) refreshAccountStates(ctx context.Context) { } } -// refreshAccountState 重新载入账户页面读取权益与模型目录,失败或变化时发布账户与模型事件并记录日志,失败的账户登记 30 秒后重试目录 +// refreshAccountState 重新载入账户页面读取权益与模型目录,失败或变化时发布账户与模型事件并记录日志,失败的账户登记 30 秒后重试目录(出口地区不受支持除外) func (service *trackedService) refreshAccountState(ctx context.Context, accountID string, wait bool) (aistudio.AccountRefresh, error) { requestCtx, cancel := service.lifecycleRequestContext(ctx) defer cancel() @@ -1243,7 +1530,11 @@ func (service *trackedService) refreshAccountState(ctx context.Context, accountI } if err != nil { service.modelRetriesMu.Lock() - service.modelRetries[accountID] = struct{}{} + if errors.Is(err, camoufoxnative.ErrRegionNotSupported) { + delete(service.modelRetries, accountID) + } else { + service.modelRetries[accountID] = struct{}{} + } service.modelRetriesMu.Unlock() service.publishModelAccess() service.requests.log(accountID, "WARN", "账户状态刷新失败", "error", err) @@ -1673,7 +1964,9 @@ func (service *trackedService) acquireWarmLease(ctx context.Context, selection a failedWorkers := make(map[string]struct{}) var promoteFailure error dispatch := service.workers.dispatch - waiter := dispatch.join(service.pool.ScopedSelection(ctx, selection)) + // scoped 是并入请求指定账户、API key 与模型绑定账户后的选择,没有账户可用时按它写明原因 + scoped := service.pool.ScopedSelection(ctx, selection) + waiter := dispatch.join(scoped) defer dispatch.leave(waiter) wait := func(delay time.Duration) error { return waitScheduling(ctx, waiter.wake, delay) @@ -1819,8 +2112,11 @@ func (service *trackedService) acquireWarmLease(ctx context.Context, selection a } failedWorkers[accountID] = struct{}{} promoteFailure = promoteErr - if !service.countSwitchFailure(failures, promoteErr) { - return nil, promotionFailure(service.pool, selection, promoteErr) + if !service.countSwitchFailure(failures, nil, promoteErr) { + return nil, promotionFailure(service.pool, scoped, promoteErr) + } + if waitErr := service.waitSwitchInterval(ctx, "", time.Now()); waitErr != nil { + return nil, waitErr } continue } @@ -1847,12 +2143,12 @@ func (service *trackedService) acquireWarmLease(ctx context.Context, selection a continue } if promoteFailure != nil { - return nil, promotionFailure(service.pool, selection, promoteFailure) + return nil, promotionFailure(service.pool, scoped, promoteFailure) } if runtimeBusyErr != nil { return nil, runtimeBusyErr } - return nil, service.pool.NoEligibleError(selection) + return nil, service.pool.NoEligibleError(scoped) } } @@ -2123,17 +2419,18 @@ type generateAttempt struct { source <-chan aistudio.Event first aistudio.Event firstAt time.Time - err error - cancel context.CancelFunc - stopFirstEvent func() - done chan struct{} + err error + cancel context.CancelFunc + stopFirstEvent func() + done chan struct{} // serving 是正在生成回答的账户租约,续写轮换账户后为新账户的租约 serving atomic.Pointer[aistudio.AccountLease] - // failures 是请求已用掉的换号次数,续写轮换号在此基础上计数 + // failures 是请求已用掉的非额度换号次数,续写轮换号在此基础上计数 failures int - // interactionStream 与 interactionTask 是租约账户与通道对该模型的 Interaction 路由 - interactionStream bool - interactionTask bool + // quotaFailures 是请求已用掉的额度失败换号次数,续写轮换号在此基础上计数 + quotaFailures int + // interaction 是租约账户与通道对该模型的 Interaction 选路 + interaction aistudio.InteractionRouting } // generateRetry 是生成请求跨尝试的换号与恢复状态 @@ -2165,6 +2462,10 @@ type generateRetry struct { rejectionRetried bool // failures 是本次请求中换号重试的非额度失败次数 failures int + // quotaFailures 是本次请求中因额度用尽换号重试的次数 + quotaFailures int + // lastSwitchFailureAt 是上次准备换号时的失败时刻,用于满足最短换号间隔 + lastSwitchFailureAt time.Time } // attemptOutcome 是失败尝试处理后的错误与换号决定 @@ -2172,6 +2473,8 @@ type attemptOutcome struct { err error retryable bool recoverWorker bool + sameAccount bool + failedAt time.Time accountID string accountLabel string } @@ -2203,7 +2506,9 @@ func (service *trackedService) generateWithRetry( } else { preferredAccountID = service.pool.InlineMediaAccount(request.Contents) } - hedgeable := !request.Background && !assistant && (service.hedgeAuto || service.hedgeAfter > 0) && slices.Contains(service.hedgeModels, modelID) + fePolicy := service.currentFirstEventPolicy() + buildNativeNonstream := service.useBuildNativeNonstream() + hedgeable := service.canHedge(request, assistant, modelID) hedged := false var winner *generateAttempt var activity *upstreamActivity @@ -2246,7 +2551,7 @@ func (service *trackedService) generateWithRetry( fallbackReason = "请求包含 Playground 专用能力或文件引用" case selection.Channel != "": case !service.pool.BuildEnabled(): - case !service.buildNativeNonstream: + case !buildNativeNonstream: fallbackReason = "Build 非流式优先选项已关闭" default: selection.PreferredChannel = aistudio.ChannelBuild @@ -2268,6 +2573,24 @@ func (service *trackedService) generateWithRetry( if len(retry.attempted) > 0 { service.requests.markQueued(request.ID, request.AccountID) } + if !retry.lastSwitchFailureAt.IsZero() { + hasCandidate := (!unbound && !fileBound) || len(selection.AllowedAccountIDs) > 0 + if hasCandidate { + if _, checkErr := service.pool.ClassifyCandidates(requestCtx, selection, nil); checkErr != nil { + hasCandidate = false + } + } + if hasCandidate { + waitErr := service.waitSwitchInterval(requestCtx, request.ID, retry.lastSwitchFailureAt) + retry.lastSwitchFailureAt = time.Time{} + if waitErr != nil { + err = waitErr + break + } + } else { + retry.lastSwitchFailureAt = time.Time{} + } + } queueStartedAt := time.Now() queueWait := startWaitReporter(func(waited time.Duration) { service.requests.logRequestProgress(request.ID, "request", "WARN", "排队等待", "waited", waited, "model", modelID) @@ -2330,16 +2653,16 @@ func (service *trackedService) generateWithRetry( service.requests.logRequestProgress(request.ID, accountLabel, "INFO", "排队结束", "waited", time.Since(queueStartedAt)) } service.requests.logRequestProgress(request.ID, accountLabel, "INFO", "等待上游响应") - primary := service.startAttempt(requestCtx, request, resourceID, modelID, fallbackReason, lease, selection, false, retry.failures) + primary := service.startAttempt(requestCtx, request, resourceID, modelID, fallbackReason, lease, selection, false, retry.failures, retry.quotaFailures, fePolicy.firstEventTimeout) var plan *hedgePlan - if hedgeable && !primary.interactionTask && !hedged { + if hedgeable && !primary.interaction.IsAgent() && !hedged { if delay, ok := service.hedgeDelay(modelID, string(lease.Channel())); ok { fixed := resourceID != "" || requestedAccountID != "" plan = &hedgePlan{delay: delay, selections: service.hedgeSelections(selection, lease.Account().ID, fixed, retry.attempted)} plan.start = func(hedgeLease *aistudio.AccountLease, hedgeSelection aistudio.AccountSelection) *generateAttempt { hedged = true retry.attempted[hedgeLease.Account().ID] = struct{}{} - return service.startAttempt(requestCtx, request, resourceID, modelID, fallbackReason, hedgeLease, hedgeSelection, true, retry.failures) + return service.startAttempt(requestCtx, request, resourceID, modelID, fallbackReason, hedgeLease, hedgeSelection, true, retry.failures, retry.quotaFailures, fePolicy.firstEventTimeout) } } } @@ -2427,6 +2750,9 @@ func (service *trackedService) generateWithRetry( service.requests.logRequestProgress(request.ID, last.accountLabel, "WARN", "WAA Worker 重建,重放当前请求", attemptFields(modelID, err)...) continue } + if !last.sameAccount { + retry.lastSwitchFailureAt = last.failedAt + } service.requests.logRequestProgress(request.ID, last.accountLabel, "WARN", "账号切换", attemptFields(modelID, err)...) } if winner == nil { @@ -2472,7 +2798,7 @@ func (service *trackedService) accountLabel(accountID string) string { return accountID } -// startAttempt 在租约账户上准备并发送请求,后台等待首事件,结束时关闭 done;failures 是发起这次尝试前请求已用掉的换号次数 +// startAttempt 在租约账户上准备并发送请求,后台等待首事件,结束时关闭 done;failures 与 quotaFailures 是发起这次尝试前请求已用掉的换号次数 func (service *trackedService) startAttempt( requestCtx context.Context, request aistudio.GenerateRequest, @@ -2483,21 +2809,23 @@ func (service *trackedService) startAttempt( selection aistudio.AccountSelection, hedge bool, failures int, + quotaFailures int, + firstEventTimeout time.Duration, ) *generateAttempt { unbound := strings.TrimSpace(request.AccountID) == "" && resourceID == "" request.AccountID = lease.Account().ID - interactionStream, interactionTask := lease.InteractionRoute(modelID) + interaction := lease.InteractionRoute(modelID) attempt := &generateAttempt{ lease: lease, selection: selection, hedge: hedge, unbound: unbound, accountLabel: lease.Account().Config.Label, proxy: service.proxies.Binding(request.AccountID), workerGeneration: service.workers.WorkerGeneration(request.AccountID), - startedAt: time.Now(), activity: &upstreamActivity{}, done: make(chan struct{}), failures: failures, - interactionStream: interactionStream, interactionTask: interactionTask, + startedAt: time.Now(), activity: &upstreamActivity{}, done: make(chan struct{}), failures: failures, quotaFailures: quotaFailures, + interaction: interaction, } attempt.serving.Store(lease) attemptCtx, cancel := context.WithCancelCause(requestCtx) attempt.cancel = func() { cancel(context.Canceled) } - if service.firstEventTimeout > 0 && !request.Background && !attempt.interactionTask { - timeout := service.firstEventTimeout + if firstEventTimeout > 0 && !request.Background && !attempt.interaction.IsAgent() { + timeout := firstEventTimeout var mu sync.Mutex stopped := false timer := time.AfterFunc(timeout, func() { @@ -2534,7 +2862,7 @@ func (service *trackedService) runAttempt( defer attempt.stopFirstEvent() } lease, accountLabel := attempt.lease, attempt.accountLabel - if attempt.interactionTask { + if attempt.interaction.IsAgent() { // agent 后台任务只发送 AgentInput 选出的内容,其余轮次的文件不复制、附件不上传 request.Contents = aistudio.AgentInput(request.Contents, request.PreviousInteractionID != "") } @@ -2562,7 +2890,7 @@ func (service *trackedService) runAttempt( uploadStartedAt := time.Now() request.Contents, attempt.copies, err = service.service.(interface { UploadInlineMediaToLease(context.Context, *aistudio.AccountLease, []aistudio.Content, *aistudio.TemporaryFileCopies, bool) ([]aistudio.Content, *aistudio.TemporaryFileCopies, error) - }).UploadInlineMediaToLease(ctx, lease, request.Contents, attempt.copies, attempt.interactionStream) + }).UploadInlineMediaToLease(ctx, lease, request.Contents, attempt.copies, attempt.interaction.IsModel()) if err == nil { service.requests.logRequestProgress(request.ID, accountLabel, "INFO", "内联附件处理完成", "attachments", mediaCount, "bytes", fmt.Sprintf("%d B", mediaBytes), "duration", time.Since(uploadStartedAt)) @@ -2581,6 +2909,17 @@ func (service *trackedService) runAttempt( ctx = aistudio.ContextWithReplyToolBypassObserver(ctx, func() { service.requests.logRequestProgress(request.ID, accountLabel, "INFO", "模型没有使用回复工具", "model", modelID) }) + ctx = aistudio.ContextWithReplyToolObserver(ctx, aistudio.ReplyToolObserver{ + OnActive: func(enabled bool) { + api.SetAccessLogReplyTool(ctx, enabled) + }, + OnCall: func() { + api.AddAccessLogReplyToolCall(ctx) + }, + OnContinuation: func() { + api.AddAccessLogReplyToolContinuation(ctx) + }, + }) ctx = aistudio.ContextWithRequestPhaseObserver(ctx, prepareTiming.observe) if err == nil { attempt.source, err = service.service.Generate(ctx, request) @@ -2674,9 +3013,12 @@ func (service *trackedService) continuationAccount(ctx context.Context, requestI if releaseErr := current.Release(); releaseErr != nil { return nil, releaseErr } - if !service.countSwitchFailure(&attempt.failures, err) { + if !service.countSwitchFailure(&attempt.failures, &attempt.quotaFailures, err) { return nil, aistudio.ErrNoEligibleAccount } + if waitErr := service.waitSwitchInterval(ctx, requestID, time.Now()); waitErr != nil { + return nil, waitErr + } selection := aistudio.AccountSelection{ModelID: modelID, Method: "generateContent", PlaygroundOnly: true, AllowedAccountIDs: []string{}} for _, accountID := range service.pool.EnabledAccounts() { if _, exists := failed[accountID]; !exists { @@ -2845,6 +3187,7 @@ func (service *trackedService) settleAttempt( } // cooledUntil 是这次失败使账户在该模型上冷却到的时刻 var cooledUntil time.Time + sameAccountChannel := false cooldown, quotaFailure := aistudio.QuotaCooldownForError(err, time.Now()) if quotaFailure { cooldown.RequestSize = attempt.selection.RequestSize @@ -2862,6 +3205,7 @@ func (service *trackedService) settleAttempt( err = "aCooldownError{err: err, until: retry.quotaUntil} } if !cooldown.Global && service.pool.AccountChannelAvailable(accountID, attempt.selection) { + sameAccountChannel = true delete(retry.attempted, accountID) retry.maxAttempts++ } @@ -2926,9 +3270,11 @@ func (service *trackedService) settleAttempt( retry.attemptFailure = err } if releaseErr := lease.Release(); releaseErr != nil { - return attemptOutcome{err: errors.Join(err, releaseErr), accountID: accountID, accountLabel: accountLabel} + return attemptOutcome{err: errors.Join(err, releaseErr), failedAt: time.Now(), accountID: accountID, accountLabel: accountLabel} + } + if service.switchInterval() == 0 { + service.workers.spareForCooling(requestCtx, attempt.selection, accountID, cooledUntil) } - service.workers.spareForCooling(requestCtx, attempt.selection, accountID, cooledUntil) recoverWorker := false var firstEventTimedOut *firstEventTimeoutError // 上游以额度、权限拒绝、服务受限或首字超时结束尝试时不重建 Worker 重放,直接换号 @@ -2944,19 +3290,28 @@ func (service *trackedService) settleAttempt( retryable = false } } - if retryable && !buildRejected && !missingInlineMedia && !recoverWorker { - retryable = service.countSwitchFailure(&retry.failures, err) + if retryable && !buildRejected && !missingInlineMedia && !recoverWorker && !sameAccountChannel { + retryable = service.countSwitchFailure(&retry.failures, &retry.quotaFailures, err) + } + return attemptOutcome{ + err: err, retryable: retryable, recoverWorker: recoverWorker, + sameAccount: recoverWorker || buildRejected || missingInlineMedia || coolingDown || sameAccountChannel, + failedAt: time.Now(), accountID: accountID, accountLabel: accountLabel, } - return attemptOutcome{err: err, retryable: retryable, recoverWorker: recoverWorker, accountID: accountID, accountLabel: accountLabel} } -// countSwitchFailure 判断 err 引起的换号是否计入 MAX_ACCOUNT_SWITCHES,返回是否仍在换号上限内;登录失效、发送前进入冷却与额度失败不计入 -func (service *trackedService) countSwitchFailure(failures *int, err error) bool { +// countSwitchFailure 判断 err 引起的换号是否仍在换号上限内:登录失效与发送前进入冷却不计入;额度失败按 MAX_QUOTA_SWITCHES 计数(默认不限),其余非额度失败按 MAX_ACCOUNT_SWITCHES 计数 +func (service *trackedService) countSwitchFailure(failures *int, quotaFailures *int, err error) bool { if aistudio.DefinitiveAuthenticationFailure(err) || errors.Is(err, aistudio.ErrAccountCoolingDown) { return true } if _, quota := aistudio.QuotaCooldownForError(err, time.Now()); quota { - return true + encoded := service.quotaSwitchLimit.Load() + if encoded <= 0 || quotaFailures == nil { + return true + } + *quotaFailures++ + return int64(*quotaFailures) <= encoded-1 } *failures++ return int64(*failures) <= service.maxAccountSwitches.Load() @@ -3091,7 +3446,7 @@ func retryableGenerateAccountError(ctx context.Context, err error) bool { } func (service *trackedService) lifecycleRequestContext(ctx context.Context) (context.Context, context.CancelFunc) { - requestCtx, cancel := context.WithTimeout(ctx, service.timeout) + requestCtx, cancel := context.WithTimeout(ctx, service.requestTimeout()) stopLifecycle := context.AfterFunc(service.lifecycle, cancel) return requestCtx, func() { stopLifecycle() @@ -3106,7 +3461,7 @@ func (service *trackedService) dataRequestContext(ctx context.Context) (context. service.lifecycleMu.Unlock() return nil, nil, service.stoppedError() } - deadline, cancel := newIdleDeadlineContext(ctx, service.timeout) + deadline, cancel := newIdleDeadlineContext(ctx, service.requestTimeout()) run := service.dataContext stopData := context.AfterFunc(run, cancel) service.lifecycleMu.Unlock() diff --git a/internal/app/update.go b/internal/app/update.go index 4a1c60c3..e3994461 100644 --- a/internal/app/update.go +++ b/internal/app/update.go @@ -8,7 +8,7 @@ import ( "context" "crypto/sha256" "encoding/hex" - "encoding/json" + "encoding/xml" "errors" "fmt" "io" @@ -21,6 +21,7 @@ import ( "path/filepath" "runtime" "slices" + "strconv" "strings" "sync" "syscall" @@ -31,29 +32,24 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/api" ) -// releaseAPI 为 GitHub 最新发行版本接口 -const releaseAPI = "https://api.github.com/repos/Mag1cFall/AIStudio2API/releases/latest" +// releaseRepo 为 GitHub 仓库网页根地址,在线更新的跳转、Atom 订阅、SHA256SUMS 与发行包下载均基于此地址 +const releaseRepo = "https://github.com/Mag1cFall/AIStudio2API" -// releaseCheckInterval 为最新发行版本的缓存时长 +// releaseCheckInterval 为成功读取最新发行版本后的缓存时长 const releaseCheckInterval = time.Hour +// releaseRetryInterval 为检查失败且上游未给出恢复时刻时的自动重查间隔 +const releaseRetryInterval = 5 * time.Minute + // releaseCheckTimeout 是读取一次最新发行版本的总时限 const releaseCheckTimeout = 10 * time.Second -// githubRelease 为 GitHub 发行版本接口中用到的字段 +// githubRelease 为 GitHub 最新正式发行版本中用到的字段 type githubRelease struct { - TagName string `json:"tag_name"` - Body string `json:"body"` - HTMLURL string `json:"html_url"` - PublishedAt time.Time `json:"published_at"` - Assets []githubAsset `json:"assets"` -} - -// githubAsset 为发行版本中的一个文件 -type githubAsset struct { - Name string `json:"name"` - URL string `json:"browser_download_url"` - Digest string `json:"digest"` + TagName string + Body string + HTMLURL string + PublishedAt time.Time } // updateConflictError 表示当前状态不能安装更新 @@ -64,6 +60,23 @@ func (err updateConflictError) Error() string { return string(err) } // HTTPStatus 返回更新冲突的 HTTP 状态码 func (updateConflictError) HTTPStatus() int { return http.StatusConflict } +// updateHTTPError 表示访问 GitHub 返回了非预期 HTTP 状态 +type updateHTTPError struct { + status int + rateLimited bool + retryAt time.Time +} + +func (err *updateHTTPError) Error() string { + if err.rateLimited { + return fmt.Sprintf("GitHub 访问频率受限(HTTP %d)", err.status) + } + if text := http.StatusText(err.status); text != "" { + return fmt.Sprintf("HTTP %d %s", err.status, text) + } + return fmt.Sprintf("HTTP %d", err.status) +} + // selfUpdater 读取最新发行版本并替换当前可执行文件 type selfUpdater struct { version string @@ -73,10 +86,13 @@ type selfUpdater struct { proxy func() string requests *requestRegistry restart func() + now func() time.Time mu sync.Mutex release *githubRelease checked time.Time checkErr error + errorKind string + retryAt time.Time updating bool progress api.UpdateProgress } @@ -84,11 +100,22 @@ type selfUpdater struct { // newSelfUpdater 按构建版本与运行环境创建替换 executable 的更新器 func newSelfUpdater(version, executable string, proxy func() string, requests *requestRegistry, restart func()) *selfUpdater { return &selfUpdater{ - version: version, mode: updateMode(version), releaseURL: releaseAPI, executable: executable, - proxy: proxy, requests: requests, restart: restart, + version: version, mode: updateMode(version), releaseURL: releaseRepo, executable: executable, + proxy: proxy, requests: requests, restart: restart, now: time.Now, } } +func (u *selfUpdater) currentTime() time.Time { + if u.now != nil { + return u.now() + } + return time.Now() +} + +func (u *selfUpdater) repoURL() string { + return strings.TrimRight(u.releaseURL, "/") +} + // updateMode 返回更新方式:managed 由分发方更新,binary 可原地替换,container 随镜像更新,development 为源码构建 func updateMode(version string) string { if managedBy != "" { @@ -105,21 +132,40 @@ func updateMode(version string) string { return platformUpdateMode() } -// UpdateStatus 返回当前版本与最新发行版本,refresh 为 true 或缓存过期时重新读取 +// UpdateStatus 返回当前版本与最新发行版本,refresh 为 true、成功缓存过期或到达失败重查时刻时重新读取 func (u *selfUpdater) UpdateStatus(ctx context.Context, refresh bool) (api.UpdateStatus, error) { + now := u.currentTime() u.mu.Lock() - stale := u.mode != "managed" && (refresh || time.Since(u.checked) >= releaseCheckInterval) + stale := false + if u.mode != "managed" { + switch { + case refresh || u.checked.IsZero(): + stale = true + case u.checkErr != nil: + if !u.retryAt.IsZero() { + stale = !now.Before(u.retryAt) + } else { + stale = now.Sub(u.checked) >= releaseRetryInterval + } + default: + stale = now.Sub(u.checked) >= releaseCheckInterval + } + } u.mu.Unlock() if stale { - release, err := u.fetchRelease(ctx) + release, kind, retryAt, err := u.fetchRelease(ctx) if ctx.Err() != nil { return api.UpdateStatus{}, ctx.Err() } if err != nil { - u.requests.log("service", "WARN", "检查更新失败", "error", err) + if kind == "rate_limited" && !retryAt.IsZero() { + u.requests.log("service", "WARN", "检查更新失败", "error", err, "until", retryAt.Format(time.RFC3339)) + } else { + u.requests.log("service", "WARN", "检查更新失败", "error", err) + } } u.mu.Lock() - u.checked, u.checkErr = time.Now(), err + u.checked, u.checkErr, u.errorKind, u.retryAt = u.currentTime(), err, kind, retryAt if err == nil { u.release = release } @@ -130,7 +176,7 @@ func (u *selfUpdater) UpdateStatus(ctx context.Context, refresh bool) (api.Updat return u.statusLocked(), nil } -// ApplyUpdate 下载最新发行包,校验摘要后替换当前可执行文件并重启管理进程 +// ApplyUpdate 下载最新发行包,校验 SHA256SUMS 后替换当前可执行文件并重启管理进程 func (u *selfUpdater) ApplyUpdate(ctx context.Context) (api.UpdateStatus, error) { u.mu.Lock() if u.mode == "managed" { @@ -148,7 +194,7 @@ func (u *selfUpdater) ApplyUpdate(ctx context.Context) (api.UpdateStatus, error) u.updating = true u.progress = api.UpdateProgress{Stage: "download"} u.mu.Unlock() - release, err := u.fetchRelease(ctx) + release, _, _, err := u.fetchRelease(ctx) if err == nil && semver.Compare(release.TagName, u.version) <= 0 { err = updateConflictError("当前已是最新版本 " + u.version) } @@ -163,7 +209,7 @@ func (u *selfUpdater) ApplyUpdate(ctx context.Context) (api.UpdateStatus, error) u.requests.logStage("service", "ERROR", api.LogStage{Name: "在线更新", State: "failed"}, "在线更新失败", "error", err) return api.UpdateStatus{}, err } - u.release, u.checked, u.checkErr = release, time.Now(), nil + u.release, u.checked, u.checkErr, u.errorKind, u.retryAt = release, u.currentTime(), nil, "", time.Time{} u.progress.Stage = "restart" u.requests.logStage("service", "INFO", api.LogStage{Name: "在线更新", State: "completed"}, "在线更新完成", "version", release.TagName) status := u.statusLocked() @@ -181,49 +227,129 @@ func (u *selfUpdater) statusLocked() api.UpdateStatus { } if u.checkErr != nil { status.Error = u.checkErr.Error() + status.ErrorKind = u.errorKind + status.RetryAt = u.retryAt } if release := u.release; release != nil { status.Latest, status.Notes, status.URL, status.PublishedAt = release.TagName, release.Body, release.HTMLURL, release.PublishedAt status.Available = semver.Compare(release.TagName, u.version) > 0 + } else if u.mode != "managed" { + status.URL = u.repoURL() + "/releases/latest" } return status } -// fetchRelease 读取 GitHub 最新发行版本,总时限 releaseCheckTimeout -func (u *selfUpdater) fetchRelease(ctx context.Context) (*githubRelease, error) { - ctx, cancel := context.WithTimeout(ctx, releaseCheckTimeout) +// fetchRelease 经 releases/latest 跳转与 releases.atom 读取最新正式发行版本,总时限 releaseCheckTimeout,不调用 api.github.com +func (u *selfUpdater) fetchRelease(ctx context.Context) (*githubRelease, string, time.Time, error) { + fetchCtx, cancel := context.WithTimeout(ctx, releaseCheckTimeout) defer cancel() - var release githubRelease - response, err := u.get(ctx, u.releaseURL, "application/vnd.github+json") + transport, err := u.newTransport() + if err != nil { + return nil, "", u.currentTime().Add(releaseRetryInterval).UTC(), fmt.Errorf("读取最新发行版本: %w", err) + } + defer transport.CloseIdleConnections() + client := &http.Client{Transport: transport} + noRedirect := &http.Client{ + Transport: transport, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } + + tag, htmlURL, err := u.fetchLatestTag(fetchCtx, noRedirect) + var notes string + var publishedAt time.Time if err == nil { - defer response.Body.Close() - err = json.NewDecoder(response.Body).Decode(&release) + notes, publishedAt, err = u.fetchReleaseNotes(fetchCtx, client, tag) } if err != nil { - if errors.Is(ctx.Err(), context.DeadlineExceeded) { + now := u.currentTime() + retryAt := now.Add(releaseRetryInterval).UTC() + if errors.Is(fetchCtx.Err(), context.DeadlineExceeded) { err = fmt.Errorf("GitHub 在 %d 秒内没有响应", int(releaseCheckTimeout/time.Second)) + return nil, "", retryAt, fmt.Errorf("读取最新发行版本: %w", err) + } + var httpErr *updateHTTPError + if errors.As(err, &httpErr) && httpErr.rateLimited { + if !httpErr.retryAt.IsZero() && httpErr.retryAt.After(now) { + retryAt = httpErr.retryAt + } + return nil, "rate_limited", retryAt, fmt.Errorf("读取最新发行版本: %w", err) + } + return nil, "", retryAt, fmt.Errorf("读取最新发行版本: %w", err) + } + return &githubRelease{TagName: tag, Body: notes, HTMLURL: htmlURL, PublishedAt: publishedAt}, "", time.Time{}, nil +} + +// fetchLatestTag 请求 releases/latest 跳转并从 Location 提取最新正式版版本号与页面地址 +func (u *selfUpdater) fetchLatestTag(ctx context.Context, client *http.Client) (string, string, error) { + address := u.repoURL() + "/releases/latest" + response, err := u.doRequest(ctx, client, http.MethodHead, address, "text/html") + if err != nil { + return "", "", err + } + if response.StatusCode == http.StatusMethodNotAllowed { + response.Body.Close() + response, err = u.doRequest(ctx, client, http.MethodGet, address, "text/html") + if err != nil { + return "", "", err + } + } + defer response.Body.Close() + if response.StatusCode >= 300 && response.StatusCode < 400 { + location := strings.TrimSpace(response.Header.Get("Location")) + resolved, parseErr := response.Request.URL.Parse(location) + if location == "" || parseErr != nil { + return "", "", errors.New("最新发行版本跳转缺少版本号") + } + tag := tagFromReleasePath(resolved.Path) + if tag == "" { + return "", "", errors.New("最新发行版本跳转缺少版本号") } - return nil, fmt.Errorf("读取最新发行版本: %w", err) + return tag, resolved.String(), nil } - return &release, nil + return "", "", readUpdateHTTPError(response, u.currentTime()) } -// download 下载 release 中名为 name 的发行包并按发行版本记录的 SHA-256 校验 +// fetchReleaseNotes 从 releases.atom 中精确匹配 tag 条目,原样返回 GitHub 渲染后的 HTML 说明与发布时间 +func (u *selfUpdater) fetchReleaseNotes(ctx context.Context, client *http.Client, tag string) (string, time.Time, error) { + response, err := u.doRequest(ctx, client, http.MethodGet, u.repoURL()+"/releases.atom", "application/atom+xml, application/xml;q=0.9") + if err != nil { + return "", time.Time{}, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return "", time.Time{}, readUpdateHTTPError(response, u.currentTime()) + } + body, err := io.ReadAll(io.LimitReader(response.Body, 4<<20)) + if err != nil { + return "", time.Time{}, err + } + return parseReleaseAtom(body, tag) +} + +// download 读取 SHA256SUMS 取得目标发行包摘要,经 releases/download 直链下载并校验 func (u *selfUpdater) download(ctx context.Context, release *githubRelease, name string) ([]byte, error) { - index := slices.IndexFunc(release.Assets, func(asset githubAsset) bool { return asset.Name == name }) - if index < 0 { - return nil, fmt.Errorf("发行版本 %s 没有 %s", release.TagName, name) + transport, err := u.newTransport() + if err != nil { + return nil, fmt.Errorf("下载 %s: %w", name, err) } - asset := release.Assets[index] - expected, ok := strings.CutPrefix(asset.Digest, "sha256:") - if !ok { - return nil, fmt.Errorf("发行包 %s 缺少 SHA-256 摘要", name) + defer transport.CloseIdleConnections() + client := &http.Client{Transport: transport} + + expected, err := u.fetchDigest(ctx, client, release.TagName, name) + if err != nil { + return nil, err } - response, err := u.get(ctx, asset.URL, "application/octet-stream") + assetURL := fmt.Sprintf("%s/releases/download/%s/%s", u.repoURL(), url.PathEscape(release.TagName), url.PathEscape(name)) + response, err := u.doRequest(ctx, client, http.MethodGet, assetURL, "application/octet-stream") if err != nil { return nil, fmt.Errorf("下载 %s: %w", name, err) } defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return nil, fmt.Errorf("下载 %s: %w", name, readUpdateHTTPError(response, u.currentTime())) + } u.mu.Lock() u.progress = api.UpdateProgress{Stage: "download", Total: max(response.ContentLength, 0)} u.mu.Unlock() @@ -239,6 +365,31 @@ func (u *selfUpdater) download(ctx context.Context, release *githubRelease, name return archive.Bytes(), nil } +// fetchDigest 从随 Release 上传的 SHA256SUMS 中读取目标发行包的小写 SHA-256 摘要 +func (u *selfUpdater) fetchDigest(ctx context.Context, client *http.Client, tag, name string) (string, error) { + sumsURL := fmt.Sprintf("%s/releases/download/%s/SHA256SUMS", u.repoURL(), url.PathEscape(tag)) + response, err := u.doRequest(ctx, client, http.MethodGet, sumsURL, "text/plain, */*;q=0.8") + if err != nil { + return "", fmt.Errorf("读取校验摘要: %w", err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return "", fmt.Errorf("读取校验摘要: %w", readUpdateHTTPError(response, u.currentTime())) + } + body, err := io.ReadAll(io.LimitReader(response.Body, 256<<10)) + if err != nil { + return "", fmt.Errorf("读取校验摘要: %w", err) + } + digest, found := parseSHA256Sums(body, name) + if !found { + return "", fmt.Errorf("发行版本 %s 没有 %s", tag, name) + } + if digest == "" { + return "", fmt.Errorf("发行包 %s 缺少 SHA-256 摘要", name) + } + return digest, nil +} + // setStage 记录在线更新进入的阶段 func (u *selfUpdater) setStage(stage string) { u.mu.Lock() @@ -257,8 +408,8 @@ func (c downloadCounter) Write(p []byte) (int, error) { return len(p), nil } -// get 经管理进程出口发出 GET,非 200 响应返回错误 -func (u *selfUpdater) get(ctx context.Context, address, accept string) (*http.Response, error) { +// newTransport 创建走管理进程出口代理的 HTTP Transport +func (u *selfUpdater) newTransport() (*http.Transport, error) { transport := http.DefaultTransport.(*http.Transport).Clone() if proxy := u.proxy(); proxy != "" { proxyURL, err := url.Parse(proxy) @@ -267,21 +418,142 @@ func (u *selfUpdater) get(ctx context.Context, address, accept string) (*http.Re } transport.Proxy = http.ProxyURL(proxyURL) } - request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) + return transport, nil +} + +func (u *selfUpdater) doRequest(ctx context.Context, client *http.Client, method, address, accept string) (*http.Response, error) { + request, err := http.NewRequestWithContext(ctx, method, address, nil) if err != nil { return nil, err } request.Header.Set("Accept", accept) - response, err := (&http.Client{Transport: transport}).Do(request) + request.Header.Set("User-Agent", "AIStudio2API") + return client.Do(request) +} + +// readUpdateHTTPError 把非预期 HTTP 响应转为结构化错误:识别限流与恢复时刻,不把原始 HTML 或 JSON 暴露到错误文本 +func readUpdateHTTPError(response *http.Response, now time.Time) *updateHTTPError { + body, _ := io.ReadAll(io.LimitReader(response.Body, 4096)) + rateLimited := response.StatusCode == http.StatusTooManyRequests || + (response.StatusCode == http.StatusForbidden && (strings.TrimSpace(response.Header.Get("X-RateLimit-Remaining")) == "0" || + strings.TrimSpace(response.Header.Get("Retry-After")) != "" || + strings.Contains(strings.ToLower(string(body)), "rate limit"))) + return &updateHTTPError{ + status: response.StatusCode, + rateLimited: rateLimited, + retryAt: parseRetryAt(response.Header, now), + } +} + +// parseRetryAt 优先从 Retry-After、其次从 X-RateLimit-Reset 解析未来恢复时刻(UTC) +func parseRetryAt(header http.Header, now time.Time) time.Time { + if value := strings.TrimSpace(header.Get("Retry-After")); value != "" { + if seconds, err := strconv.ParseInt(value, 10, 64); err == nil && seconds > 0 { + return now.Add(time.Duration(seconds) * time.Second).UTC() + } + if parsed, err := http.ParseTime(value); err == nil && parsed.After(now) { + return parsed.UTC() + } + } + if value := strings.TrimSpace(header.Get("X-RateLimit-Reset")); value != "" { + if unix, err := strconv.ParseInt(value, 10, 64); err == nil && unix > 0 { + if parsed := time.Unix(unix, 0).UTC(); parsed.After(now) { + return parsed + } + } + } + return time.Time{} +} + +// tagFromReleasePath 从 /.../releases/tag/ 路径中取出 tag +func tagFromReleasePath(rawPath string) string { + const marker = "/releases/tag/" + index := strings.Index(rawPath, marker) + if index < 0 { + return "" + } + rest := strings.Trim(rawPath[index+len(marker):], "/") + if rest == "" || strings.Contains(rest, "/") { + return "" + } + tag, err := url.PathUnescape(rest) if err != nil { - return nil, err + return rest } - if response.StatusCode != http.StatusOK { - body, _ := io.ReadAll(io.LimitReader(response.Body, 512)) - response.Body.Close() - return nil, fmt.Errorf("HTTP %d %s", response.StatusCode, strings.TrimSpace(string(body))) + return strings.TrimSpace(tag) +} + +type atomFeed struct { + Entries []atomEntry `xml:"entry"` +} + +type atomEntry struct { + ID string `xml:"id"` + Updated string `xml:"updated"` + Links []atomLink `xml:"link"` + Content string `xml:"content"` +} + +type atomLink struct { + Href string `xml:"href,attr"` +} + +// parseReleaseAtom 在 releases.atom 中精确匹配 tag 对应的条目,原样返回 GitHub 渲染后的 HTML 说明与发布时间 +func parseReleaseAtom(data []byte, tag string) (string, time.Time, error) { + var feed atomFeed + if err := xml.Unmarshal(data, &feed); err != nil { + return "", time.Time{}, err + } + for _, entry := range feed.Entries { + if !atomEntryMatchesTag(entry, tag) { + continue + } + var publishedAt time.Time + if ts := strings.TrimSpace(entry.Updated); ts != "" { + if parsed, err := time.Parse(time.RFC3339, ts); err == nil { + publishedAt = parsed.UTC() + } + } + return strings.TrimSpace(entry.Content), publishedAt, nil + } + return "", time.Time{}, nil +} + +func atomEntryMatchesTag(entry atomEntry, tag string) bool { + for _, link := range entry.Links { + if parsed, err := url.Parse(strings.TrimSpace(link.Href)); err == nil && tagFromReleasePath(parsed.Path) == tag { + return true + } + } + return strings.HasSuffix(strings.TrimSpace(entry.ID), "/"+tag) +} + +// parseSHA256Sums 解析 sha256sum 输出格式(<64位十六进制> <文件名>),返回 name 对应的小写 SHA-256 及是否找到该文件 +func parseSHA256Sums(data []byte, name string) (digest string, found bool) { + for line := range strings.SplitSeq(string(data), "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + fields := strings.Fields(line) + if len(fields) < 2 { + continue + } + file := strings.TrimSpace(line[len(fields[0]):]) + file = strings.TrimPrefix(file, "*") + file = strings.TrimPrefix(file, "./") + if file != name && path.Base(file) != name { + continue + } + sum := strings.ToLower(strings.TrimSpace(fields[0])) + if len(sum) == 64 { + if _, err := hex.DecodeString(sum); err == nil { + return sum, true + } + } + return "", true } - return response, nil + return "", false } // extractExecutable 从 zip 或 tar.gz 发行包中取出可执行文件 diff --git a/internal/app/waa_backend.go b/internal/app/waa_backend.go index dfd329e6..62c763e9 100644 --- a/internal/app/waa_backend.go +++ b/internal/app/waa_backend.go @@ -13,7 +13,7 @@ import ( const camoufoxWorkerPath = "camoufox" // prepareWAABackend 按 WAA 后端返回 Worker 选项中的 Camoufox 路径与账户登录驱动,Camoufox 后端在后台准备 Camoufox -func prepareWAABackend(cfg config.Config, requests *requestRegistry, accounts []*aistudio.Account, proxy string) (string, aistudio.IsolatedLoginDriver) { +func prepareWAABackend(cfg config.Config, requests *requestRegistry, accounts []*aistudio.Account, proxy func() string) (string, aistudio.IsolatedLoginDriver) { removeStaleCamoufoxProfiles(requests) login := camoufoxLoginDriver{proxy: proxy} if cfg.WAABackend == config.WAABackendSpiderMonkey { @@ -26,7 +26,7 @@ func prepareWAABackend(cfg config.Config, requests *requestRegistry, accounts [] return "", login } requests.logStage("service", "INFO", api.LogStage{Name: "运行时装配", Step: 2, Steps: 3}, "使用 Camoufox WAA 后端", "accounts", len(accounts)) - camoufoxnative.PrepareInBackground(proxy) + camoufoxnative.PrepareInBackground(proxy()) return camoufoxWorkerPath, login } @@ -54,12 +54,16 @@ func newWAAWorker(ctx context.Context, accountID string, options camoufoxnative. // camoufoxLoginDriver 在登录时准备 Camoufox,同一进程内的登录与生成服务共用一次进行中的下载 type camoufoxLoginDriver struct { - proxy string + proxy func() string } // Login 等 Camoufox 就绪后执行隔离登录 func (driver camoufoxLoginDriver) Login(ctx context.Context, request aistudio.IsolatedLoginRequest) (aistudio.IsolatedLoginResult, error) { - path, err := camoufoxnative.Prepare(ctx, driver.proxy) + proxy := "" + if driver.proxy != nil { + proxy = driver.proxy() + } + path, err := camoufoxnative.Prepare(ctx, proxy) if err != nil { return aistudio.IsolatedLoginResult{}, err } @@ -72,7 +76,11 @@ func (driver camoufoxLoginDriver) Login(ctx context.Context, request aistudio.Is // Verify 等 Camoufox 就绪后打开账户验证页并自动再核对 func (driver camoufoxLoginDriver) Verify(ctx context.Context, request aistudio.AccountVerifyRequest) (bool, error) { - path, err := camoufoxnative.Prepare(ctx, driver.proxy) + proxy := "" + if driver.proxy != nil { + proxy = driver.proxy() + } + path, err := camoufoxnative.Prepare(ctx, proxy) if err != nil { return true, err } diff --git a/internal/app/worker_manager.go b/internal/app/worker_manager.go index 7fd3fb97..0b1ca865 100644 --- a/internal/app/worker_manager.go +++ b/internal/app/worker_manager.go @@ -29,8 +29,8 @@ type accountWorkerManager struct { refresher *authRuntimeRefresher proxyFailed func(proxy string, accountID string, err error) camoufox string - globalProxy string - initTimeout time.Duration + hotGlobalProxy atomic.Pointer[string] + initTimeout atomic.Int64 warmTarget atomic.Int64 maxActive atomic.Int64 startup startupLimiter @@ -206,11 +206,12 @@ func newAccountWorkerManager( lifecycle, cancel := context.WithCancel(context.Background()) manager := &accountWorkerManager{ pool: pool, accounts: make(map[string]*accountWorker, len(accounts)), requests: requests, camoufox: camoufoxPath, - globalProxy: globalProxy, initTimeout: initTimeout, openings: make(map[string]chan struct{}), lifecycle: lifecycle, cancel: cancel, signal: make(chan struct{}), dispatch: newDispatchQueue(), victims: make(map[string]struct{}), pageHeaders: make(map[string]http.Header), } + manager.SetGlobalProxy(globalProxy) + manager.SetInitTimeout(initTimeout) manager.setLimits(warmTarget, maxActive, warmConcurrency) manager.background, manager.stopBackground = context.WithCancel(lifecycle) for _, account := range accounts { @@ -221,6 +222,42 @@ func newAccountWorkerManager( return manager } +// SetGlobalProxy 替换后续新建或重建 Worker 使用的默认代理 +func (manager *accountWorkerManager) SetGlobalProxy(proxy string) { + if manager == nil { + return + } + trimmed := strings.TrimSpace(proxy) + manager.hotGlobalProxy.Store(&trimmed) +} + +// currentGlobalProxy 返回当前默认代理 +func (manager *accountWorkerManager) currentGlobalProxy() string { + if manager == nil { + return "" + } + if proxy := manager.hotGlobalProxy.Load(); proxy != nil { + return *proxy + } + return "" +} + +// SetInitTimeout 替换后续冷启动与重新载入页面使用的初始化超时 +func (manager *accountWorkerManager) SetInitTimeout(timeout time.Duration) { + if manager == nil { + return + } + manager.initTimeout.Store(int64(timeout)) +} + +// currentInitTimeout 返回当前初始化超时 +func (manager *accountWorkerManager) currentInitTimeout() time.Duration { + if manager == nil { + return 0 + } + return time.Duration(manager.initTimeout.Load()) +} + // SetCapacity 设置常驻 Worker 数、峰值 Worker 上限与 Camoufox 启动并发,随后关闭超出峰值上限的空闲 Worker func (manager *accountWorkerManager) SetCapacity(warmTarget int, maxActive int, startupConcurrency int) { manager.setLimits(warmTarget, maxActive, startupConcurrency) @@ -675,7 +712,7 @@ func (manager *accountWorkerManager) workerConfigFor( ) camoufoxnative.Options { proxy := strings.TrimSpace(config.Proxy) if proxy == "" { - proxy = account.PoolProxy(manager.globalProxy) + proxy = account.PoolProxy(manager.currentGlobalProxy()) } return camoufoxnative.Options{ ExecutablePath: manager.camoufox, @@ -858,8 +895,8 @@ func (manager *accountWorkerManager) classifyBootstrapCandidates( if !matched { return aistudio.AccountCandidateGroups{}, aistudio.ErrNoEligibleAccount } - combined.StandbyReady = manager.pool.PreferWarmPool(combined.StandbyReady) - combined.StandbyBusy = manager.pool.PreferWarmPool(combined.StandbyBusy) + combined.StandbyReady = manager.pool.PreferWarmPool(combined.StandbyReady, warm) + combined.StandbyBusy = manager.pool.PreferWarmPool(combined.StandbyBusy, warm) return combined, nil } @@ -989,7 +1026,7 @@ func (manager *accountWorkerManager) reloadWorker(ctx context.Context, accountID } defer manager.startup.release() startedAt := time.Now() - reloadCtx, cancel := context.WithTimeout(ctx, manager.initTimeout) + reloadCtx, cancel := context.WithTimeout(ctx, manager.currentInitTimeout()) err := worker.Reload(reloadCtx) cancel() if err != nil { @@ -1179,7 +1216,7 @@ func (manager *accountWorkerManager) startReservedWorker( manager.requests.logStage(label, "INFO", api.LogStage{Name: "WAA Worker 启动", Step: step, Steps: 7}, message, attrs...) } logStep(1, "初始化页面", "page_model", bootstrapModel) - initCtx, cancel := context.WithTimeout(ctx, manager.initTimeout) + initCtx, cancel := context.WithTimeout(ctx, manager.currentInitTimeout()) options.Model = bootstrapModel options.StartupProgress = func(stage camoufoxnative.StartupStage) { logStep(workerStartupProgress(stage)) diff --git a/internal/camoufoxnative/chat_turns_test.go b/internal/camoufoxnative/chat_turns_test.go deleted file mode 100644 index 14f2557b..00000000 --- a/internal/camoufoxnative/chat_turns_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package camoufoxnative - -import ( - "encoding/json" - "testing" -) - -// turnContents 把 [parts, role] 形式的 wire 轮次文本拆成 contents -func turnContents(t *testing.T, value string) []json.RawMessage { - t.Helper() - var contents []json.RawMessage - if err := json.Unmarshal([]byte(value), &contents); err != nil { - t.Fatal(err) - } - return contents -} - -// TestChatActionFollowsOfficialTurns 断言界面运行按官网用户的操作选择:页面没有对话时直接输入,同一对话再次运行点 Rerun,在上一轮之后追加 model 与 user 两轮时继续当前对话,其余对话先开新对话 -func TestChatActionFollowsOfficialTurns(t *testing.T) { - first := `[[[[null,"alpha"]],"user"]]` - continued := `[[[[null,"alpha"]],"user"],[[[null,"A"]],"model"],[[[null,"beta"]],"user"]]` - cases := []struct { - name string - previous string - contents string - want chatAction - }{ - {name: "empty page", previous: "", contents: first, want: chatContinue}, - {name: "same conversation", previous: first, contents: first, want: chatRerun}, - {name: "model and user appended", previous: first, contents: continued, want: chatContinue}, - {name: "rerun after continuation", previous: continued, contents: continued, want: chatRerun}, - {name: "only user appended", previous: first, contents: `[[[[null,"alpha"]],"user"],[[[null,"beta"]],"user"]]`, want: chatNew}, - {name: "different first turn", previous: first, contents: `[[[[null,"gamma"]],"user"],[[[null,"A"]],"model"],[[[null,"beta"]],"user"]]`, want: chatNew}, - {name: "shorter conversation", previous: continued, contents: first, want: chatNew}, - {name: "unrelated conversation", previous: continued, contents: `[[[[null,"delta"]],"user"]]`, want: chatNew}, - } - for _, item := range cases { - t.Run(item.name, func(t *testing.T) { - var previous []json.RawMessage - if item.previous != "" { - previous = turnContents(t, item.previous) - } - if got := nextChatAction(previous, turnContents(t, item.contents)); got != item.want { - t.Fatalf("nextChatAction = %d,应为 %d", got, item.want) - } - }) - } -} - -// TestGeneratePromptIsLastUserText 断言界面输入的提示词是最后一个 user 轮次各文本 Part 以空格连接的结果,最后一个轮次不是带文本的 user 轮次时不在界面运行 -func TestGeneratePromptIsLastUserText(t *testing.T) { - cases := []struct { - name string - body string - want string - ok bool - }{ - {name: "single text", body: `["models/m",[[[[null,"alpha"]],"user"]],null,null,"proof"]`, want: "alpha", ok: true}, - {name: "text parts joined", body: `["models/m",[[[[null,"a"]],"user"],[[[null,"A"]],"model"],[[[null,"b"],[null,null,["image/png","AAAA"]],[null,"c"]],"user"]],null,null,"proof"]`, want: "b c", ok: true}, - {name: "image only", body: `["models/m",[[[[null,null,["image/png","AAAA"]]],"user"]],null,null,"proof"]`, ok: false}, - {name: "model last", body: `["models/m",[[[[null,"a"]],"user"],[[[null,"A"]],"model"]],null,null,"proof"]`, ok: false}, - } - for _, item := range cases { - t.Run(item.name, func(t *testing.T) { - got, ok := GeneratePrompt([]byte(item.body)) - if got != item.want || ok != item.ok { - t.Fatalf("GeneratePrompt = %q %v,应为 %q %v", got, ok, item.want, item.ok) - } - }) - } -} diff --git a/internal/camoufoxnative/generate.go b/internal/camoufoxnative/generate.go index 6b3fea0d..9dd80802 100644 --- a/internal/camoufoxnative/generate.go +++ b/internal/camoufoxnative/generate.go @@ -223,6 +223,11 @@ func nextChatAction(previous, contents []json.RawMessage) chatAction { return chatNew } +// StartsNewChat 返回页面上一次发出的对话 previous 之后要发出 contents 时是否先开新对话 +func StartsNewChat(previous, contents []json.RawMessage) bool { + return nextChatAction(previous, contents) == chatNew +} + // generateArmFunction 是在页面上为下一次 Run 安装一次性钩子的函数声明 // 参数依次为页面对象、请求 ID、digest、head、tail 与通道;页面发送的正文换成 head + proof + tail // 通道先发出 {sent: true, proof, refresh, compute},再依次发出响应头、正文块与结束标记 diff --git a/internal/camoufoxnative/generate_test.go b/internal/camoufoxnative/generate_test.go deleted file mode 100644 index 0a9974f5..00000000 --- a/internal/camoufoxnative/generate_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package camoufoxnative - -import ( - "strings" - "testing" - "unicode/utf16" - "unicode/utf8" -) - -// TestPromptHeadFitsPasteLimit 断言写入官网输入框的提示词开头是放得下的最长完整字符前缀,UTF-16 长度不超过官网把粘贴转为文本附件的 25000 -func TestPromptHeadFitsPasteLimit(t *testing.T) { - const emoji = "\U0001F600" - cases := []struct { - name string - prompt string - units int - }{ - {name: "ascii", prompt: strings.Repeat("a", 30000), units: 25000}, - {name: "emoji head", prompt: emoji + strings.Repeat("a", 30000), units: 25000}, - {name: "surrogate pair at limit", prompt: "a" + strings.Repeat(emoji, 20000), units: 24999}, - {name: "exactly limit", prompt: emoji + strings.Repeat("a", 24998), units: 25000}, - } - for _, item := range cases { - t.Run(item.name, func(t *testing.T) { - head := promptHead(item.prompt) - if !strings.HasPrefix(item.prompt, head) || !utf8.ValidString(head) { - t.Fatal("开头不是提示词的完整字符前缀") - } - if got := len(utf16.Encode([]rune(head))); got != item.units { - t.Fatalf("开头为 %d 个 UTF-16 码元,应为 %d", got, item.units) - } - }) - } -} diff --git a/internal/camoufoxnative/page_test.go b/internal/camoufoxnative/page_test.go deleted file mode 100644 index e8e29114..00000000 --- a/internal/camoufoxnative/page_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package camoufoxnative - -import "testing" - -// TestNormalizePromptNewlines 覆盖官网 textarea 把写入值规范化为 LF 的比较场景 -func TestNormalizePromptNewlines(t *testing.T) { - cases := []struct { - name string - value string - want string - }{ - {name: "lf", value: "a\nb", want: "a\nb"}, - {name: "crlf", value: "a\r\nb", want: "a\nb"}, - {name: "cr", value: "a\rb", want: "a\nb"}, - {name: "mixed", value: "a\r\nb\nc\rd", want: "a\nb\nc\nd"}, - {name: "empty", value: "", want: ""}, - {name: "no newline", value: "abc", want: "abc"}, - } - for _, item := range cases { - t.Run(item.name, func(t *testing.T) { - if got := normalizePromptNewlines(item.value); got != item.want { - t.Fatalf("normalizePromptNewlines(%q) = %q, want %q", item.value, got, item.want) - } - }) - } -} - -// TestNormalizePromptNewlinesMatchesTextareaValue 确认 CRLF 提示词与官网返回的 LF 值判定为同步 -func TestNormalizePromptNewlinesMatchesTextareaValue(t *testing.T) { - prompt := "line1\r\nline2\r\nline3" - textarea := "line1\nline2\nline3" - if prompt == textarea { - t.Fatal("用例前提失效: CRLF 提示词不应与 textarea 值直接相等") - } - if normalizePromptNewlines(prompt) != normalizePromptNewlines(textarea) { - t.Fatal("CRLF 提示词与 textarea LF 值应判定为已同步") - } -} diff --git a/internal/camoufoxnative/profile_test.go b/internal/camoufoxnative/profile_test.go deleted file mode 100644 index 060c97fd..00000000 --- a/internal/camoufoxnative/profile_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package camoufoxnative - -import ( - "bufio" - "errors" - "fmt" - "io" - "io/fs" - "os" - "os/exec" - "testing" - "time" -) - -// profileProcessEnv 让测试二进制作为使用 profile 的进程运行:parent 启动一个 child 后报告就绪,两者运行 30 秒后写出 exited -const profileProcessEnv = "CAMOUFOX_PROFILE_PROCESS" - -// TestMain 在设置了 profileProcessEnv 时作为测试用的进程运行,否则运行测试 -func TestMain(m *testing.M) { - switch os.Getenv(profileProcessEnv) { - case "": - os.Exit(m.Run()) - case "parent": - child := exec.Command(os.Args[0]) - child.Env = append(os.Environ(), profileProcessEnv+"=child") - child.Stdout = os.Stdout - if err := child.Start(); err != nil { - os.Exit(1) - } - fmt.Println("ready") - } - time.Sleep(30 * time.Second) - fmt.Println("exited") - os.Exit(0) -} - -// TestRemoveStaleProfilesEndsProfileProcesses 确认遗留 profile 删除前,以 -profile 引用它的进程连同子进程被结束 -func TestRemoveStaleProfilesEndsProfileProcesses(t *testing.T) { - root := t.TempDir() - t.Setenv("TMPDIR", root) - t.Setenv("TMP", root) - profile, lock, err := createProfile() - if err != nil { - t.Fatal(err) - } - if err := lock.Unlock(); err != nil { - t.Fatal(err) - } - command := exec.Command(os.Args[0], "-profile", profile) - command.Env = append(os.Environ(), profileProcessEnv+"=parent") - stdout, err := command.StdoutPipe() - if err != nil { - t.Fatal(err) - } - if err := command.Start(); err != nil { - t.Fatal(err) - } - output := bufio.NewReader(stdout) - if line, err := output.ReadString('\n'); line != "ready\n" { - t.Fatalf("使用 profile 的进程没有就绪: %q, %v", line, err) - } - removed, err := RemoveStaleProfiles() - if removed != 1 || err != nil { - t.Fatalf("RemoveStaleProfiles() = %d, %v,期望删除 1 个 profile", removed, err) - } - rest, err := io.ReadAll(output) - if len(rest) != 0 || err != nil { - t.Fatalf("使用 profile 的进程或其子进程运行到了结尾: %q, %v", rest, err) - } - if err := command.Wait(); err == nil { - t.Fatal("使用 profile 的进程正常退出,没有被结束") - } - if _, err := os.Stat(profile); !errors.Is(err, fs.ErrNotExist) { - t.Fatalf("profile 仍然存在: %v", err) - } -} diff --git a/internal/camoufoxnative/worker.go b/internal/camoufoxnative/worker.go index 8c2c2ffe..8aaecd08 100644 --- a/internal/camoufoxnative/worker.go +++ b/internal/camoufoxnative/worker.go @@ -463,7 +463,7 @@ func (worker *Worker) PageCatalog() PageCatalog { return worker.pageCatalog } -// Reload 像官网用户一样在当前标签页中按官网冷启动重新载入页面,载入期间界面对话不取用该标签页;当前标签页有进行中的请求时改在新标签页中载入并切换过去,原标签页在其中的请求结束后关闭 +// Reload 在新标签页中按官网冷启动重新载入页面,载入成功后切换过去并关闭空闲旧标签页,有进行中请求的旧标签页在其请求结束后关闭;载入失败时关闭新标签页并保留原页面 func (worker *Worker) Reload(ctx context.Context) error { worker.mu.Lock() if worker.closed { @@ -475,44 +475,32 @@ func (worker *Worker) Reload(ctx context.Context) error { options.StartupProgress = nil worker.lockInput() defer worker.inputMu.Unlock() - worker.mu.Lock() - contextID := worker.contextID - busy := worker.tabs[contextID] != nil - if !busy { - reloading := worker.chats[0] - reloading.busy, reloading.resetting = true, true - defer func() { - worker.mu.Lock() - reloading.busy, reloading.resetting = false, false - worker.notifyChats() - worker.mu.Unlock() - }() - } - worker.mu.Unlock() - if busy { - opened, err := worker.openTab(ctx) - if err != nil { - return err - } - contextID = opened + contextID, err := worker.openTab(ctx) + if err != nil { + return err } loaded, err := worker.openPage(ctx, options, contextID) - if err == nil && !busy { - worker.mu.Lock() - selected := worker.selected - worker.mu.Unlock() - if selected != "" && selected != contextID { - err = worker.selectTab(ctx, contextID) - } - } if err == nil && options.Headless && !options.liveView { err = worker.stopRendering(ctx) } - if err != nil && busy { - return errors.Join(err, worker.closeTab(contextID)) - } if err != nil { - return err + worker.mu.Lock() + if worker.selected == contextID { + worker.selected = "" + } + worker.mu.Unlock() + closeErr := worker.closeTab(contextID) + if closeErr == nil && options.Headless && !options.liveView { + worker.frameMu.Lock() + idle := worker.frameBoosts == 0 + worker.frameMu.Unlock() + if idle { + stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + _ = worker.stopRendering(stopCtx) + cancel() + } + } + return errors.Join(err, closeErr) } return worker.switchTab(contextID, loaded) } diff --git a/internal/chromeauth/bidi_test.go b/internal/chromeauth/bidi_test.go index e1572731..8d2b0de9 100644 --- a/internal/chromeauth/bidi_test.go +++ b/internal/chromeauth/bidi_test.go @@ -3,13 +3,9 @@ package chromeauth import ( "context" "encoding/json" - "errors" "net/http" "net/http/httptest" - "os" - "path/filepath" "strings" - "sync" "testing" "time" @@ -49,23 +45,14 @@ func bidiGoogleCookies() []map[string]any { } } -type fakeBiDiOptions struct { - mode string - blockCookies chan struct{} - cookiesRequested chan struct{} - failCookiesMessage string -} - -// newBiDiRemoteServer 启动模拟 Firefox WebDriver BiDi 服务端,按真实 Firefox 语义只允许同时存在一个活跃会话,断线不自动销毁会话 -func newBiDiRemoteServer(t *testing.T, opts fakeBiDiOptions) (*httptest.Server, <-chan bool) { +// newBiDiRemoteServer 启动模拟 Firefox WebDriver BiDi 服务端,核对按浏览器选择 BiDi 协议的流程 +func newBiDiRemoteServer(t *testing.T, mode string) (*httptest.Server, <-chan bool) { t.Helper() upgrader := websocket.Upgrader{} ended := make(chan bool, 4) - var mu sync.Mutex - activeSession := false mux := http.NewServeMux() mux.HandleFunc("/json/version", func(w http.ResponseWriter, _ *http.Request) { - switch opts.mode { + switch mode { case "firefox-both": w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]string{ @@ -83,12 +70,6 @@ func newBiDiRemoteServer(t *testing.T, opts fakeBiDiOptions) (*httptest.Server, return } defer conn.Close() - var writeMu sync.Mutex - write := func(payload any) error { - writeMu.Lock() - defer writeMu.Unlock() - return conn.WriteJSON(payload) - } for { var message struct { ID int `json:"id"` @@ -100,19 +81,7 @@ func newBiDiRemoteServer(t *testing.T, opts fakeBiDiOptions) (*httptest.Server, } switch message.Method { case "session.new": - mu.Lock() - already := activeSession - if !already { - activeSession = true - } - mu.Unlock() - if already { - _ = write(map[string]any{ - "id": message.ID, "error": "session not created", "message": "Maximum number of active sessions", - }) - continue - } - _ = write(map[string]any{ + _ = conn.WriteJSON(map[string]any{ "id": message.ID, "result": map[string]any{ "sessionId": "test-session", @@ -122,49 +91,16 @@ func newBiDiRemoteServer(t *testing.T, opts fakeBiDiOptions) (*httptest.Server, }, }) case "storage.getCookies": - if opts.cookiesRequested != nil { - select { - case opts.cookiesRequested <- struct{}{}: - default: - } - } - if opts.blockCookies != nil { - // 在独立协程中等待放行,确保同一连接上后续到达的 session.end 可被读取循环及时处理 - msgID := message.ID - params := message.Params - go func() { - <-opts.blockCookies - _ = write(map[string]any{ - "id": msgID, - "result": map[string]any{"cookies": fakeBiDiCookiesForParams(params)}, - }) - }() - continue - } - if opts.failCookiesMessage != "" { - _ = write(map[string]any{ - "id": message.ID, "error": "unknown error", "message": opts.failCookiesMessage, - }) - continue - } - _ = write(map[string]any{ + _ = conn.WriteJSON(map[string]any{ "id": message.ID, "result": map[string]any{"cookies": fakeBiDiCookiesForParams(message.Params)}, }) case "session.end": - mu.Lock() - activeSession = false - mu.Unlock() ended <- len(message.Params) == 0 - if opts.mode == "stall-end" { - var discard any - _ = conn.ReadJSON(&discard) - return - } - _ = write(map[string]any{"id": message.ID, "result": map[string]any{}}) + _ = conn.WriteJSON(map[string]any{"id": message.ID, "result": map[string]any{}}) return default: - _ = write(map[string]any{ + _ = conn.WriteJSON(map[string]any{ "id": message.ID, "error": "unknown command", "message": message.Method, }) return @@ -211,306 +147,72 @@ func waitSessionEnded(t *testing.T, ended <-chan bool) { } } -// newCDPRemoteServer 启动只说 CDP 的模拟 Chromium 调试端口 -func newCDPRemoteServer(t *testing.T, failCookies bool) *httptest.Server { +// assertExportedCookieState 验证 Cookie 文本可被存储状态解析且登录 Cookie 齐全 +func assertExportedCookieState(t *testing.T, text string) aistudio.StorageState { t.Helper() - expiry := float64(time.Now().Add(24 * time.Hour).Unix()) - upgrader := websocket.Upgrader{} - mux := http.NewServeMux() - mux.HandleFunc("/devtools/browser/test", func(w http.ResponseWriter, r *http.Request) { - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - t.Errorf("升级 CDP WebSocket 失败: %v", err) - return - } - defer conn.Close() - for { - var message struct { - ID int `json:"id"` - Method string `json:"method"` - } - if err := conn.ReadJSON(&message); err != nil { - return - } - if failCookies || message.Method != "Storage.getCookies" { - _ = conn.WriteJSON(map[string]any{"id": message.ID, "error": map[string]string{"message": "storage unavailable"}}) - return - } - _ = conn.WriteJSON(map[string]any{ - "id": message.ID, - "result": map[string]any{"cookies": []map[string]any{ - { - "name": "__Secure-1PSID", "value": "sid-value", "domain": ".google.com", - "path": "/", "expires": expiry, "httpOnly": true, "secure": true, "sameSite": "None", - }, - { - "name": "SAPISID", "value": "sapisid-value", "domain": ".google.com", - "path": "/", "session": true, "httpOnly": true, "secure": true, "sameSite": "Lax", - }, - { - "name": "__Secure-1PAPISID", "value": "papisid1", "domain": ".google.com", - "path": "/", "expires": expiry, "httpOnly": true, "secure": true, - }, - { - "name": "__Secure-3PAPISID", "value": "papisid3", "domain": ".google.com", - "path": "/", "expires": expiry, "httpOnly": true, "secure": true, - }, - { - "name": "PartitionedCookie", "value": "partitioned", "domain": ".google.com", - "path": "/", "secure": true, "partitionKey": "https://aistudio.google.com", - }, - }}, - }) - } - }) - var server *httptest.Server - mux.HandleFunc("/json/version", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]string{ - "Browser": "Chrome/131.0.0.0", - "webSocketDebuggerUrl": "ws://" + strings.TrimPrefix(server.URL, "http://") + "/devtools/browser/test", - }) - }) - server = httptest.NewServer(mux) - t.Cleanup(server.Close) - return server -} - -func TestReadBrowserCookiesBiDiFallback(t *testing.T) { - server, ended := newBiDiRemoteServer(t, fakeBiDiOptions{mode: "bidi-only"}) - address := strings.TrimPrefix(server.URL, "http://") - - browser, err := ReadBrowserCookies(context.Background(), address) + state, err := aistudio.ParseCookieText(text) if err != nil { - t.Fatalf("BiDi 读取失败: %v", err) - } - if browser.Product != "Firefox/128.0.2" { - t.Fatalf("产品名 = %q,期望 Firefox/128.0.2", browser.Product) + t.Fatalf("Cookie 解析为存储状态失败: %v", err) } - waitSessionEnded(t, ended) - state := assertExportedCookieState(t, browser.Cookies) - var sawBase64 bool + names := make(map[string]string, len(state.Cookies)) for _, cookie := range state.Cookies { - if cookie.Name == "__Secure-1PSID" && cookie.Value != "sid-value" { - t.Fatalf("__Secure-1PSID = %q,期望未分区的 sid-value", cookie.Value) - } - if cookie.Name == "BiDiBase64" { - if cookie.Value != "hello" { - t.Fatalf("base64 Cookie 值 = %q,期望 hello", cookie.Value) - } - sawBase64 = true - } + names[cookie.Name] = cookie.Value } - if !sawBase64 { - t.Fatal("缺少解码后的 BiDiBase64 Cookie") + for _, required := range []string{"__Secure-1PSID", "SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID"} { + if _, ok := names[required]; !ok { + t.Fatalf("缺少必需 Cookie %s,实际有 %v", required, names) + } } + return state } -func TestReadBrowserCookiesFirefoxWithBothProtocols(t *testing.T) { - server, ended := newBiDiRemoteServer(t, fakeBiDiOptions{mode: "firefox-both"}) - address := strings.TrimPrefix(server.URL, "http://") - - browser, err := ReadBrowserCookies(context.Background(), address) - if err != nil { - t.Fatalf("双协议 Firefox 读取失败: %v", err) - } - if browser.Product != "Firefox/128.0.2" { - t.Fatalf("产品名 = %q,期望 Firefox/128.0.2", browser.Product) +// TestReadBrowserCookiesProtocolSelection 按浏览器响应与地址形态核对 WebDriver BiDi 协议选择:404 回退、双协议 Firefox 优先 BiDi 与直连 BiDi WebSocket +func TestReadBrowserCookiesProtocolSelection(t *testing.T) { + cases := []struct { + name string + mode string + address func(hostPort string) string + checkCookies bool + }{ + {name: "bidi-fallback", mode: "bidi-only", address: func(hp string) string { return hp }, checkCookies: true}, + {name: "firefox-both-protocols", mode: "firefox-both", address: func(hp string) string { return hp }}, + {name: "direct-bidi-empty", mode: "bidi-only", address: func(hp string) string { return "ws://" + hp }}, + {name: "direct-bidi-root", mode: "bidi-only", address: func(hp string) string { return "ws://" + hp + "/" }}, + {name: "direct-bidi-session", mode: "bidi-only", address: func(hp string) string { return "ws://" + hp + "/session" }}, + {name: "direct-bidi-session-slash", mode: "bidi-only", address: func(hp string) string { return "ws://" + hp + "/session/" }}, } - waitSessionEnded(t, ended) -} - -func TestReadBrowserCookiesDirectBiDiURL(t *testing.T) { - for _, suffix := range []string{"", "/", "/session", "/session/"} { - t.Run("path="+suffix, func(t *testing.T) { - server, ended := newBiDiRemoteServer(t, fakeBiDiOptions{mode: "bidi-only"}) - address := "ws://" + strings.TrimPrefix(server.URL, "http://") + suffix - + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + server, ended := newBiDiRemoteServer(t, tc.mode) + address := tc.address(strings.TrimPrefix(server.URL, "http://")) browser, err := ReadBrowserCookies(context.Background(), address) if err != nil { - t.Fatalf("直连 BiDi WebSocket (%q) 失败: %v", address, err) + t.Fatalf("读取失败 (%q): %v", address, err) } if browser.Product != "Firefox/128.0.2" { t.Fatalf("产品名 = %q,期望 Firefox/128.0.2", browser.Product) } waitSessionEnded(t, ended) - }) - } -} - -func TestReadBrowserCookiesBiDiCancelReleasesSession(t *testing.T) { - block := make(chan struct{}) - requested := make(chan struct{}, 1) - server, ended := newBiDiRemoteServer(t, fakeBiDiOptions{ - mode: "bidi-only", - blockCookies: block, - cookiesRequested: requested, - }) - address := strings.TrimPrefix(server.URL, "http://") - - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan error, 1) - go func() { - _, err := ReadBrowserCookies(ctx, address) - done <- err - }() - select { - case <-requested: - case <-time.After(2 * time.Second): - t.Fatal("等待 storage.getCookies 请求超时") - } - cancel() - select { - case err := <-done: - if !errors.Is(err, context.Canceled) { - t.Fatalf("取消后的错误 = %v,期望 context.Canceled", err) - } - case <-time.After(3 * time.Second): - t.Fatal("取消后 ReadBrowserCookies 未及时返回") - } - waitSessionEnded(t, ended) - close(block) - - // 会话已正确结束,第二次扫描必须能立即新建会话并读出 Cookie - browser, err := ReadBrowserCookies(context.Background(), address) - if err != nil { - t.Fatalf("取消后第二次 BiDi 读取失败: %v", err) - } - if browser.Product != "Firefox/128.0.2" { - t.Fatalf("产品名 = %q,期望 Firefox/128.0.2", browser.Product) - } - waitSessionEnded(t, ended) -} - -func TestReadBrowserCookiesBiDiSessionEndTimeout(t *testing.T) { - previous := bidiSessionEndTimeout - bidiSessionEndTimeout = 50 * time.Millisecond - t.Cleanup(func() { bidiSessionEndTimeout = previous }) - - server, ended := newBiDiRemoteServer(t, fakeBiDiOptions{mode: "stall-end"}) - started := time.Now() - browser, err := ReadBrowserCookies(context.Background(), strings.TrimPrefix(server.URL, "http://")) - if err != nil { - t.Fatalf("BiDi 读取失败: %v", err) - } - if browser.Product != "Firefox/128.0.2" { - t.Fatalf("产品名 = %q,期望 Firefox/128.0.2", browser.Product) - } - waitSessionEnded(t, ended) - if elapsed := time.Since(started); elapsed > 2*time.Second { - t.Fatalf("session.end 阻塞过久: %v", elapsed) - } -} - -func TestReadBrowserCookiesPreservesProductOnReadError(t *testing.T) { - cdpServer := newCDPRemoteServer(t, true) - cdpBrowser, err := ReadBrowserCookies(context.Background(), strings.TrimPrefix(cdpServer.URL, "http://")) - if err == nil { - t.Fatal("CDP Cookie 读取失败应当返回错误") - } - if cdpBrowser.Product != "Chrome/131.0.0.0" { - t.Fatalf("CDP 失败时产品名 = %q,期望保留 Chrome/131.0.0.0", cdpBrowser.Product) - } - - bidiServer, ended := newBiDiRemoteServer(t, fakeBiDiOptions{mode: "bidi-only", failCookiesMessage: "storage error"}) - bidiBrowser, err := ReadBrowserCookies(context.Background(), strings.TrimPrefix(bidiServer.URL, "http://")) - if err == nil { - t.Fatal("BiDi Cookie 读取失败应当返回错误") - } - if bidiBrowser.Product != "Firefox/128.0.2" { - t.Fatalf("BiDi 失败时产品名 = %q,期望保留 Firefox/128.0.2", bidiBrowser.Product) - } - waitSessionEnded(t, ended) -} - -func TestReadBrowserCookiesVersionReadErrorDoesNotFallbackToBiDi(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/json/version" { - t.Errorf("收到非预期的 BiDi 回退请求 %s", r.URL.Path) - http.NotFound(w, r) - return - } - w.Header().Set("Content-Length", "100") - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"Browser":"Chrome"`)) - if flusher, ok := w.(http.Flusher); ok { - flusher.Flush() - } - if hijacker, ok := w.(http.Hijacker); ok { - conn, _, err := hijacker.Hijack() - if err == nil { - _ = conn.Close() + if tc.checkCookies { + state := assertExportedCookieState(t, browser.Cookies) + var sawBase64 bool + for _, cookie := range state.Cookies { + if cookie.Name == "__Secure-1PSID" && cookie.Value != "sid-value" { + t.Fatalf("__Secure-1PSID = %q,期望未分区的 sid-value", cookie.Value) + } + if cookie.Name == "BiDiBase64" { + if cookie.Value != "hello" { + t.Fatalf("base64 Cookie 值 = %q,期望 hello", cookie.Value) + } + sawBase64 = true + } + } + if !sawBase64 { + t.Fatal("缺少解码后的 BiDiBase64 Cookie") + } } - } - })) - t.Cleanup(server.Close) - - _, err := ReadBrowserCookies(context.Background(), strings.TrimPrefix(server.URL, "http://")) - if err == nil { - t.Fatal("中断的 /json/version 响应应当返回错误") - } - if !strings.Contains(err.Error(), "读取浏览器调试信息") || strings.Contains(err.Error(), "WebDriver BiDi") { - t.Fatalf("错误 = %q,期望保留读取错误而不回退 BiDi", err.Error()) - } -} - -func TestReadBrowserCookiesCDP(t *testing.T) { - server := newCDPRemoteServer(t, false) - address := strings.TrimPrefix(server.URL, "http://") - - browser, err := ReadBrowserCookies(context.Background(), address) - if err != nil { - t.Fatalf("CDP 读取失败: %v", err) - } - if browser.Product != "Chrome/131.0.0.0" { - t.Fatalf("产品名 = %q,期望 Chrome/131.0.0.0", browser.Product) - } - var cookies []map[string]any - if err := json.Unmarshal([]byte(browser.Cookies), &cookies); err != nil { - t.Fatalf("Cookie JSON 无效: %v", err) - } - for _, cookie := range cookies { - if cookie["name"] == "PartitionedCookie" { - t.Fatal("分区 Cookie 没有被过滤") - } - } - assertExportedCookieState(t, browser.Cookies) -} - -func TestReadBrowserCookiesUnreachable(t *testing.T) { - listener := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) - address := strings.TrimPrefix(listener.URL, "http://") - listener.Close() - - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - if _, err := ReadBrowserCookies(ctx, address); err == nil { - t.Fatal("不可达的调试地址应当返回错误") - } else if !strings.Contains(err.Error(), "连接浏览器调试地址") { - t.Fatalf("错误 = %q,期望包含连接失败说明", err.Error()) - } -} - -// assertExportedCookieState 验证 Cookie 文本可被存储状态解析、登录 Cookie 齐全且分区 Cookie 被过滤,返回解析后的状态 -func assertExportedCookieState(t *testing.T, text string) aistudio.StorageState { - t.Helper() - state, err := aistudio.ParseCookieText(text) - if err != nil { - t.Fatalf("Cookie 解析为存储状态失败: %v", err) - } - names := make(map[string]string, len(state.Cookies)) - for _, cookie := range state.Cookies { - names[cookie.Name] = cookie.Value - } - for _, required := range []string{"__Secure-1PSID", "SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID"} { - if _, ok := names[required]; !ok { - t.Fatalf("缺少必需 Cookie %s,实际有 %v", required, names) - } - } - if _, ok := names["PartitionedCookie"]; ok { - t.Fatal("分区 Cookie 不应进入存储状态") + }) } - return state } func TestBiDiCookiesToExport(t *testing.T) { @@ -560,61 +262,11 @@ func TestBiDiCookiesToExport(t *testing.T) { } invalid := []bidiCookie{{ - Name: "BadBase64", + Name: "BadBase64", Domain: ".google.com", - Value: bidiBytesValue{Type: "base64", Value: "not-base64!"}, + Value: bidiBytesValue{Type: "base64", Value: "not-base64!"}, }} if _, err := bidiCookiesToExport(invalid); err == nil { t.Fatal("非法 base64 应当返回错误") } } - -func TestDebugAddress(t *testing.T) { - userData := t.TempDir() - if err := os.WriteFile(filepath.Join(userData, "DevToolsActivePort"), []byte("9333\n/devtools/browser/x\n"), 0o600); err != nil { - t.Fatal(err) - } - extFirefox := t.TempDir() - if err := os.WriteFile(filepath.Join(extFirefox, "WebDriverBiDiServer.json"), []byte(`{"ws_host":"127.0.0.1","ws_port":9444}`), 0o600); err != nil { - t.Fatal(err) - } - ownCamoufox := filepath.Join(t.TempDir(), "aistudio-camoufox-12345") - if err := os.MkdirAll(ownCamoufox, 0o700); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(ownCamoufox, "WebDriverBiDiServer.json"), []byte(`{"ws_host":"127.0.0.1","ws_port":9555}`), 0o600); err != nil { - t.Fatal(err) - } - lockedCamoufox := t.TempDir() - if err := os.WriteFile(filepath.Join(lockedCamoufox, ".aistudio2api-profile.lock"), nil, 0o600); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(lockedCamoufox, "WebDriverBiDiServer.json"), []byte(`{"ws_host":"127.0.0.1","ws_port":9556}`), 0o600); err != nil { - t.Fatal(err) - } - - cases := []struct { - name string - args []string - expect string - }{ - {name: "等号形式", args: []string{"firefox.exe", "--remote-debugging-port=9222"}, expect: "127.0.0.1:9222"}, - {name: "空格分隔", args: []string{"firefox.exe", "--remote-debugging-port", "9225", "-headless"}, expect: "127.0.0.1:9225"}, - {name: "单短横线等号", args: []string{"firefox.exe", "-remote-debugging-port=9223"}, expect: "127.0.0.1:9223"}, - {name: "单短横线空格", args: []string{"firefox.exe", "-remote-debugging-port", "9224"}, expect: "127.0.0.1:9224"}, - {name: "Firefox 省略端口默认 9222", args: []string{"firefox.exe", "--remote-debugging-port", "-headless"}, expect: "127.0.0.1:9222"}, - {name: "Firefox 末尾省略端口默认 9222", args: []string{"firefox.exe", "-remote-debugging-port"}, expect: "127.0.0.1:9222"}, - {name: "Chromium 端口 0 读 DevToolsActivePort", args: []string{"chrome.exe", "--remote-debugging-port=0", "--user-data-dir=" + userData}, expect: "127.0.0.1:9333"}, - {name: "Chromium 空格参数读 DevToolsActivePort", args: []string{"chrome.exe", "--remote-debugging-port", "0", "--user-data-dir", userData}, expect: "127.0.0.1:9333"}, - {name: "外部 Firefox 端口 0 读 WebDriverBiDiServer.json", args: []string{"firefox.exe", "--remote-debugging-port=0", "-profile", extFirefox}, expect: "127.0.0.1:9444"}, - {name: "内置 Camoufox 前缀目录不纳入扫描", args: []string{"camoufox.exe", "--remote-debugging-port=0", "-no-remote", "-headless", "-profile", ownCamoufox}, expect: ""}, - {name: "内置 Camoufox 锁文件目录不纳入扫描", args: []string{"camoufox.exe", "--remote-debugging-port=0", "-profile", lockedCamoufox}, expect: ""}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := debugAddress(tc.args); got != tc.expect { - t.Fatalf("debugAddress(%v) = %q,期望 %q", tc.args, got, tc.expect) - } - }) - } -} diff --git a/internal/chromeauth/bound_test.go b/internal/chromeauth/bound_test.go deleted file mode 100644 index 41054388..00000000 --- a/internal/chromeauth/bound_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package chromeauth - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/sha256" - "crypto/x509" - "encoding/base64" - "encoding/json" - "errors" - "math/big" - "reflect" - "strings" - "testing" - - "github.com/Mag1cFall/AIStudio2API/internal/aistudio" -) - -// softwareBindingKey 是以内存 P-256 私钥签发 IEEE P1363 签名的设备绑定密钥 -type softwareBindingKey struct { - key *ecdsa.PrivateKey -} - -func (key softwareBindingKey) PublicKey() ([]byte, error) { - return x509.MarshalPKIXPublicKey(&key.key.PublicKey) -} - -func (key softwareBindingKey) SignSHA256(value []byte) ([]byte, error) { - digest := sha256.Sum256(value) - r, s, err := ecdsa.Sign(rand.Reader, key.key, digest[:]) - if err != nil { - return nil, err - } - signature := make([]byte, 64) - r.FillBytes(signature[:32]) - s.FillBytes(signature[32:]) - return signature, nil -} - -func (softwareBindingKey) Close() {} - -// TestGoogleBoundSession 验证 OAuthMultilogin 响应中 google.com 的 DBSC 会话登记按 Chromium OAuthMultiloginResult 的字段解析,相对刷新地址按 Gaia 地址补全 -func TestGoogleBoundSession(t *testing.T) { - body := `{"status":"OK","device_bound_session_info":[ - {"is_device_bound":false,"domain":"GOOGLE_COM","register_session_payload":{"session_identifier":"unbound","refresh_url":"/Unbound","credentials":[{"type":"cookie","name":"SID"}]}}, - {"is_device_bound":true,"domain":"YOUTUBE_COM","register_session_payload":{"session_identifier":"yt","refresh_url":"/RotateBoundCookies","credentials":[{"type":"cookie","name":"YT"}]}}, - {"is_device_bound":true,"domain":"GOOGLE_COM","register_session_payload":{"session_identifier":"sidts_session","credentials":[ - {"type":"cookie","name":"__Secure-1PSIDTS","scope":{"domain":".google.com","path":"/"},"attributes":"Secure; HttpOnly; Domain=.google.com; Path=/"}, - {"type":"cookie","name":"__Secure-3PSIDTS","scope":{"domain":".google.com","path":"/"},"attributes":"Secure; HttpOnly; Domain=.google.com; Path=/; SameSite=None"}, - {"type":"cookie","name":"__Secure-1PSIDRTS","scope":{"domain":".google.com","path":"/"},"attributes":"Secure; HttpOnly; Domain=.google.com; Path=/"}, - {"type":"cookie","name":"__Secure-3PSIDRTS","scope":{"domain":".google.com","path":"/"},"attributes":"Secure; HttpOnly; Domain=.google.com; Path=/; SameSite=None"} - ],"refresh_url":"/RotateBoundCookies","scope":{"origin":"https://google.com","include_site":true},"allowed_refresh_initiators":["*"]}}]}` - var response multiloginResponse - if err := json.Unmarshal([]byte(body), &response); err != nil { - t.Fatal(err) - } - want := &aistudio.BoundSession{ - ID: "sidts_session", RefreshURL: "https://accounts.google.com/RotateBoundCookies", - Credentials: []string{"__Secure-1PSIDTS", "__Secure-3PSIDTS", "__Secure-1PSIDRTS", "__Secure-3PSIDRTS"}, - } - if got := response.googleBoundSession(); !reflect.DeepEqual(got, want) { - t.Fatalf("DBSC 会话登记 = %+v,期望 %+v", got, want) - } - if got := (multiloginResponse{Status: "OK"}).googleBoundSession(); got != nil { - t.Fatalf("没有 device_bound_session_info 时返回 %+v", got) - } -} - -// TestBoundChallenge 验证按 DBSC Secure-Session-Challenge 结构化列表取出属于本会话或未指明会话的挑战 -func TestBoundChallenge(t *testing.T) { - for _, item := range []struct{ header, want string }{ - {`"abc";id="sidts_session"`, "abc"}, - {`"other";id="yt", "mine";id="sidts_session"`, "mine"}, - {`"bare"`, "bare"}, - {`"other";id="yt"`, ""}, - {``, ""}, - } { - if got := boundChallenge(item.header, "sidts_session"); got != item.want { - t.Fatalf("boundChallenge(%q) = %q,期望 %q", item.header, got, item.want) - } - } -} - -// TestSignBoundRefresh 验证 DBSC 刷新令牌与 Chromium CreateKeyRefreshHeaderAndPayload 一致:header 只有 ES256 与 dbsc+jwt,payload 只有 jti,签名为设备密钥的 ES256 -func TestSignBoundRefresh(t *testing.T) { - private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - signed, err := signBoundRefresh(softwareBindingKey{private}, "challenge-value") - if err != nil { - t.Fatal(err) - } - parts := strings.Split(signed, ".") - if len(parts) != 3 { - t.Fatalf("JWT 段数 %d", len(parts)) - } - header, _ := base64.RawURLEncoding.DecodeString(parts[0]) - payload, _ := base64.RawURLEncoding.DecodeString(parts[1]) - if string(header) != `{"alg":"ES256","typ":"dbsc+jwt"}` || string(payload) != `{"jti":"challenge-value"}` { - t.Fatalf("header=%s payload=%s", header, payload) - } - signature, _ := base64.RawURLEncoding.DecodeString(parts[2]) - digest := sha256.Sum256([]byte(parts[0] + "." + parts[1])) - if len(signature) != 64 || !ecdsa.Verify(&private.PublicKey, digest[:], new(big.Int).SetBytes(signature[:32]), new(big.Int).SetBytes(signature[32:])) { - t.Fatal("签名无法以设备公钥验证") - } -} - -// TestBoundRefreshStatusError 验证按 Chromium RegistrationFetcher 把 3xx 与 4xx(429 除外)归为会话被拒绝 -func TestBoundRefreshStatusError(t *testing.T) { - for status, rejected := range map[int]bool{302: true, 400: true, 401: true, 403: true, 429: false, 500: false, 503: false} { - if got := errors.Is(boundRefreshStatusError(status), ErrBoundSessionRejected); got != rejected { - t.Fatalf("HTTP %d 被拒绝=%t,期望 %t", status, got, rejected) - } - } -} diff --git a/internal/chromeauth/platform_windows_test.go b/internal/chromeauth/platform_windows_test.go deleted file mode 100644 index 0b37752b..00000000 --- a/internal/chromeauth/platform_windows_test.go +++ /dev/null @@ -1,60 +0,0 @@ -//go:build windows - -package chromeauth - -import ( - "database/sql" - "os" - "path/filepath" - "testing" -) - -func TestDiscoverAndReadMultipleAccounts(t *testing.T) { - root := t.TempDir() - os.MkdirAll(filepath.Join(root, "Default"), 0700) - os.WriteFile(filepath.Join(root, "Local State"), []byte(`{"profile":{"info_cache":{"Default":{"name":"Fixture","user_name":"first@example.com"}}}}`), 0600) - os.WriteFile(filepath.Join(root, "Default", "Preferences"), []byte(`{"account_info":[{"gaia":"111","email":"first@example.com"},{"gaia":"222","email":"second@example.com"},{"gaia":"333","email":"missing@example.com"}],"intl":{"accept_languages":"zh-CN"}}`), 0600) - db, err := sql.Open("sqlite3", filepath.Join(root, "Default", "Web Data")) - if err != nil { - t.Fatal(err) - } - if _, err = db.Exec("CREATE TABLE token_service(service TEXT PRIMARY KEY, encrypted_token BLOB, binding_key BLOB)"); err != nil { - t.Fatal(err) - } - for _, id := range []string{"111", "222"} { - if _, err = db.Exec("INSERT INTO token_service VALUES(?,?,?)", "AccountId-"+id, []byte("v20-fixture-"+id), []byte("binding-"+id)); err != nil { - t.Fatal(err) - } - } - db.Close() - accounts, err := Discover(root) - if err != nil { - t.Fatal(err) - } - if len(accounts) != 3 { - t.Fatalf("got %d accounts", len(accounts)) - } - if !accounts[0].Importable || !accounts[1].Importable || accounts[2].Importable { - t.Fatal("incorrect per-account eligibility") - } - selected, err := selectAccounts(accounts, nil, nil, []string{"Default/222"}) - if err != nil { - t.Fatal(err) - } - if len(selected) != 1 || selected[0].Email != "second@example.com" { - t.Fatal("selected wrong account") - } - gaia, token, binding, err := readTokenService(root, selected[0].Profile, selected[0].GaiaID) - if err != nil || gaia != "222" || string(token) != "v20-fixture-222" || string(binding) != "binding-222" { - t.Fatal("credentials do not match selection") - } - if _, _, _, err = readTokenService(root, "Default", "999"); err == nil { - t.Fatal("missing identity must fail, not fall back to another account") - } - if _, err = selectAccounts(accounts, nil, nil, []string{"Default/999"}); err == nil { - t.Fatal("stale selection must fail") - } - if _, err = selectAccounts(accounts, nil, nil, []string{"Default/333"}); err == nil { - t.Fatal("missing credentials must fail") - } -} diff --git a/internal/config/config.go b/internal/config/config.go index 38627486..7e2d624d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -44,6 +44,8 @@ var configKeys = [...]string{ "ROUTING_STRATEGY", "ACCOUNT_ORDER", "MAX_ACCOUNT_SWITCHES", + "ACCOUNT_SWITCH_INTERVAL", + "MAX_QUOTA_SWITCHES", "UPSTREAM_CHANNELS", "MODEL_MAPPING", "MODEL_CHANNELS", @@ -104,6 +106,12 @@ const FirstEventTimeoutOff = "off" // DefaultMaxAccountSwitches 是 MAX_ACCOUNT_SWITCHES 的默认值 const DefaultMaxAccountSwitches = 3 +// AccountSwitchIntervalOff 表示换号前不等待最短间隔 +const AccountSwitchIntervalOff = "off" + +// MaxQuotaSwitchesOff 表示额度失败换号次数不限制 +const MaxQuotaSwitchesOff = "off" + // DefaultFirstEventHedgeModels 是 FIRST_EVENT_HEDGE_MODELS 的默认值 const DefaultFirstEventHedgeModels = "gemini-4-argon" @@ -166,6 +174,8 @@ type Config struct { RoutingStrategy string AccountOrder string MaxAccountSwitches int + AccountSwitchInterval string + MaxQuotaSwitches string UpstreamChannels []string ModelMapping string ModelChannels string @@ -217,6 +227,8 @@ func Default() Config { PerAccountConcurrency: defaultAccountConcurrency, RoutingStrategy: "round-robin", MaxAccountSwitches: DefaultMaxAccountSwitches, + AccountSwitchInterval: AccountSwitchIntervalOff, + MaxQuotaSwitches: MaxQuotaSwitchesOff, UpstreamChannels: []string{"playground"}, WAABackend: WAABackendSpiderMonkey, MediaOutput: MediaOutputInline, @@ -256,16 +268,18 @@ var configSetters = map[string]func(*Config, string) error{ "GOOGLE_SEARCH": boolSetter("GOOGLE_SEARCH", func(c *Config) *bool { return &c.GoogleSearch }), "YOUTUBE_LINKS": boolSetter("YOUTUBE_LINKS", func(c *Config) *bool { return &c.YouTubeLinks }), "STRIP_THOUGHT_SIGNATURES": boolSetter("STRIP_THOUGHT_SIGNATURES", func(c *Config) *bool { return &c.StripThoughtSignatures }), - "CONTINUATION_REWRITE": boolSetter("CONTINUATION_REWRITE", func(c *Config) *bool { return &c.ContinuationRewrite }), - "REPLY_TOOL": boolSetter("REPLY_TOOL", func(c *Config) *bool { return &c.ReplyTool }), - "USER_MESSAGE_REWRITE": textSetter(func(c *Config) *string { return &c.UserMessageRewrite }, lowerTrim), - "THINKING_GUARD": boolSetter("THINKING_GUARD", func(c *Config) *bool { return &c.ThinkingGuard }), + "CONTINUATION_REWRITE": boolSetter("CONTINUATION_REWRITE", func(c *Config) *bool { return &c.ContinuationRewrite }), + "REPLY_TOOL": boolSetter("REPLY_TOOL", func(c *Config) *bool { return &c.ReplyTool }), + "USER_MESSAGE_REWRITE": textSetter(func(c *Config) *string { return &c.UserMessageRewrite }, lowerTrim), + "THINKING_GUARD": boolSetter("THINKING_GUARD", func(c *Config) *bool { return &c.ThinkingGuard }), "LOG_MAX_TOTAL_MB": intSetter("LOG_MAX_TOTAL_MB", func(c *Config) *int { return &c.LogMaxTotalMB }), "WARM_WORKER_LIMIT": intSetter("WARM_WORKER_LIMIT", func(c *Config) *int { return &c.WarmWorkerLimit }), "MAX_ACTIVE_WORKERS": intSetter("MAX_ACTIVE_WORKERS", func(c *Config) *int { return &c.MaxActiveWorkers }), "WARM_STARTUP_CONCURRENCY": intSetter("WARM_STARTUP_CONCURRENCY", func(c *Config) *int { return &c.WarmStartupConcurrency }), "PER_ACCOUNT_CONCURRENCY": intSetter("PER_ACCOUNT_CONCURRENCY", func(c *Config) *int { return &c.PerAccountConcurrency }), "MAX_ACCOUNT_SWITCHES": setMaxAccountSwitches, + "ACCOUNT_SWITCH_INTERVAL": textSetter(func(c *Config) *string { return &c.AccountSwitchInterval }, lowerTrim), + "MAX_QUOTA_SWITCHES": textSetter(func(c *Config) *string { return &c.MaxQuotaSwitches }, lowerTrim), "INIT_TIMEOUT": durationSetter("INIT_TIMEOUT", func(c *Config) *time.Duration { return &c.InitTimeout }), "REQUEST_TIMEOUT": durationSetter("REQUEST_TIMEOUT", func(c *Config) *time.Duration { return &c.RequestTimeout }), "ADMIN_USERNAME": textSetter(func(c *Config) *string { return &c.AdminUsername }, strings.TrimSpace), @@ -435,6 +449,14 @@ var configChecks = []configCheck{ } return nil }}, + {[]string{"ACCOUNT_SWITCH_INTERVAL"}, func(c Config) error { + _, err := ParseAccountSwitchInterval(c.AccountSwitchInterval) + return err + }}, + {[]string{"MAX_QUOTA_SWITCHES"}, func(c Config) error { + _, _, err := ParseMaxQuotaSwitches(c.MaxQuotaSwitches) + return err + }}, {[]string{"UPSTREAM_CHANNELS"}, func(c Config) error { return validateUpstreamChannels(c.UpstreamChannels) }}, {[]string{"MODEL_MAPPING"}, func(c Config) error { _, err := ParseModelMapping(c.ModelMapping) @@ -649,11 +671,11 @@ func (c Config) envValues() map[string]string { "FIRST_EVENT_HEDGE": c.FirstEventHedge, "FIRST_EVENT_HEDGE_MODELS": c.FirstEventHedgeModels, "FIRST_EVENT_TIMEOUT": c.FirstEventTimeout, - "CONTINUATION_REWRITE": strconv.FormatBool(c.ContinuationRewrite), - "CONTINUATION_PROMPT": c.ContinuationPrompt, - "REPLY_TOOL": strconv.FormatBool(c.ReplyTool), - "USER_MESSAGE_REWRITE": c.UserMessageRewrite, - "THINKING_GUARD": strconv.FormatBool(c.ThinkingGuard), + "CONTINUATION_REWRITE": strconv.FormatBool(c.ContinuationRewrite), + "CONTINUATION_PROMPT": c.ContinuationPrompt, + "REPLY_TOOL": strconv.FormatBool(c.ReplyTool), + "USER_MESSAGE_REWRITE": c.UserMessageRewrite, + "THINKING_GUARD": strconv.FormatBool(c.ThinkingGuard), "AISTUDIO_AUTH_STATES": c.AuthStates, "LISTEN_ADDR": c.ListenAddr, "PREVIEW_LISTEN_ADDR": c.PreviewListenAddr, @@ -668,6 +690,8 @@ func (c Config) envValues() map[string]string { "ROUTING_STRATEGY": c.RoutingStrategy, "ACCOUNT_ORDER": c.AccountOrder, "MAX_ACCOUNT_SWITCHES": strconv.Itoa(c.MaxAccountSwitches), + "ACCOUNT_SWITCH_INTERVAL": c.AccountSwitchInterval, + "MAX_QUOTA_SWITCHES": c.MaxQuotaSwitches, "UPSTREAM_CHANNELS": strings.Join(c.UpstreamChannels, ","), "MODEL_MAPPING": c.ModelMapping, "MODEL_CHANNELS": c.ModelChannels, @@ -778,6 +802,30 @@ func ParseFirstEventTimeout(value string) (time.Duration, error) { return time.Duration(seconds) * time.Second, nil } +// ParseAccountSwitchInterval 解析 ACCOUNT_SWITCH_INTERVAL,返回同一请求内换号前的最短等待间隔,off 时为零值 +func ParseAccountSwitchInterval(value string) (time.Duration, error) { + if value == AccountSwitchIntervalOff { + return 0, nil + } + seconds, err := strconv.Atoi(value) + if err != nil || seconds <= 0 { + return 0, fmt.Errorf("ACCOUNT_SWITCH_INTERVAL 必须是 off 或正整数秒") + } + return time.Duration(seconds) * time.Second, nil +} + +// ParseMaxQuotaSwitches 解析 MAX_QUOTA_SWITCHES,返回额度失败时的换号次数上限与是否启用上限,off 时不限制 +func ParseMaxQuotaSwitches(value string) (int, bool, error) { + if value == MaxQuotaSwitchesOff { + return 0, false, nil + } + limit, err := strconv.Atoi(value) + if err != nil || limit < 0 { + return 0, false, fmt.Errorf("MAX_QUOTA_SWITCHES 必须是 off、0 或正整数") + } + return limit, true, nil +} + // ModelList 解析逗号分隔的模型 ID 列表 func ModelList(value string) []string { var models []string diff --git a/internal/i18n/messages/de.json b/internal/i18n/messages/de.json index e88cff8b..2e9c42e8 100644 --- a/internal/i18n/messages/de.json +++ b/internal/i18n/messages/de.json @@ -1531,5 +1531,17 @@ "解析 WebDriver BiDi Cookie: %w": "WebDriver-BiDi-Cookies parsen: {0}", "解码 WebDriver BiDi Cookie %s 的 base64 值: %w": "Base64-Wert des WebDriver-BiDi-Cookies {0} dekodieren: {1}", "WebDriver BiDi 读取失败: %w": "WebDriver-BiDi-Lesen fehlgeschlagen: {0}", - "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "Browser-Debug-Adresse hat keine Debug-Informationen zurückgegeben: HTTP {0}; WebDriver-BiDi-Lesen fehlgeschlagen: {1}" + "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "Browser-Debug-Adresse hat keine Debug-Informationen zurückgegeben: HTTP {0}; WebDriver-BiDi-Lesen fehlgeschlagen: {1}", + "ACCOUNT_SWITCH_INTERVAL 必须是 off 或正整数秒": "ACCOUNT_SWITCH_INTERVAL muss off oder eine positive ganze Zahl in Sekunden sein", + "Build 模型目录同步失败": "Synchronisierung des Build-Modellkatalogs fehlgeschlagen", + "GitHub 访问频率受限(HTTP %d)": "GitHub-Ratenlimit überschritten (HTTP {0})", + "MAX_QUOTA_SWITCHES 必须是 off、0 或正整数": "MAX_QUOTA_SWITCHES muss off, 0 oder eine positive Ganzzahl sein", + "只能在本机访问时关闭管理登录": "Die Konsolenanmeldung kann nur auf diesem Computer deaktiviert werden", + "最新发行版本跳转缺少版本号": "Die Weiterleitung zur neuesten Version enthält keine Versionsnummer", + "等待换号间隔": "Warten auf Kontowechsel-Intervall", + "读取校验摘要: %w": "Prüfsumme wird gelesen: {0}", + "读取账户历史使用记录失败": "Lesen des Kontonutzungsverlaufs fehlgeschlagen", + "模型 %s 需要 %s,本次请求可用的账户 %s 都不具备": "Modell {0} erfordert {1}, die für diese Anfrage verfügbaren Konten ({2}) verfügen nicht darüber", + "模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "Modell {0} erfordert eine dieser Berechtigungen, die für diese Anfrage verfügbaren Konten ({1}) verfügen nicht darüber: {2}", + "Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction-Modell contents[{0}] akzeptiert keinen serverseitigen Tool-Schritt {1}" } diff --git a/internal/i18n/messages/en.json b/internal/i18n/messages/en.json index e4864305..6fb114c8 100644 --- a/internal/i18n/messages/en.json +++ b/internal/i18n/messages/en.json @@ -1531,5 +1531,17 @@ "解析 WebDriver BiDi Cookie: %w": "Parsing WebDriver BiDi cookies: {0}", "解码 WebDriver BiDi Cookie %s 的 base64 值: %w": "Decoding base64 value of WebDriver BiDi cookie {0}: {1}", "WebDriver BiDi 读取失败: %w": "WebDriver BiDi read failed: {0}", - "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "Browser debugging address returned no debugging information: HTTP {0}; WebDriver BiDi read failed: {1}" + "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "Browser debugging address returned no debugging information: HTTP {0}; WebDriver BiDi read failed: {1}", + "ACCOUNT_SWITCH_INTERVAL 必须是 off 或正整数秒": "ACCOUNT_SWITCH_INTERVAL must be off or a positive integer in seconds", + "Build 模型目录同步失败": "Build model catalog sync failed", + "GitHub 访问频率受限(HTTP %d)": "GitHub rate limit exceeded (HTTP {0})", + "MAX_QUOTA_SWITCHES 必须是 off、0 或正整数": "MAX_QUOTA_SWITCHES must be off, 0, or a positive integer", + "只能在本机访问时关闭管理登录": "Console login can only be turned off from this computer", + "最新发行版本跳转缺少版本号": "Latest release redirect is missing a version tag", + "等待换号间隔": "Waiting for account switch interval", + "读取校验摘要: %w": "Reading checksums: {0}", + "读取账户历史使用记录失败": "Failed to read account usage history", + "模型 %s 需要 %s,本次请求可用的账户 %s 都不具备": "Model {0} requires {1}, which the accounts available to this request ({2}) do not have", + "模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "Model {0} requires one of these entitlements, which the accounts available to this request ({1}) do not have: {2}", + "Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction model contents[{0}] does not accept server-side tool step {1}" } diff --git a/internal/i18n/messages/fr.json b/internal/i18n/messages/fr.json index f128d70d..3146276c 100644 --- a/internal/i18n/messages/fr.json +++ b/internal/i18n/messages/fr.json @@ -1531,5 +1531,17 @@ "解析 WebDriver BiDi Cookie: %w": "Analyse des cookies WebDriver BiDi : {0}", "解码 WebDriver BiDi Cookie %s 的 base64 值: %w": "Décodage de la valeur base64 du cookie WebDriver BiDi {0} : {1}", "WebDriver BiDi 读取失败: %w": "Échec de la lecture WebDriver BiDi : {0}", - "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "L’adresse de débogage du navigateur n’a renvoyé aucune information de débogage: HTTP {0}; Échec de la lecture WebDriver BiDi : {1}" + "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "L’adresse de débogage du navigateur n’a renvoyé aucune information de débogage: HTTP {0}; Échec de la lecture WebDriver BiDi : {1}", + "ACCOUNT_SWITCH_INTERVAL 必须是 off 或正整数秒": "ACCOUNT_SWITCH_INTERVAL doit être off ou un entier positif en secondes", + "Build 模型目录同步失败": "Échec de la synchronisation du catalogue de modèles Build", + "GitHub 访问频率受限(HTTP %d)": "Limite de fréquence GitHub dépassée (HTTP {0})", + "MAX_QUOTA_SWITCHES 必须是 off、0 或正整数": "MAX_QUOTA_SWITCHES doit être off, 0 ou un entier positif", + "只能在本机访问时关闭管理登录": "La connexion à la console ne peut être désactivée que depuis cet ordinateur", + "最新发行版本跳转缺少版本号": "La redirection de la dernière version ne contient pas de numéro de version", + "等待换号间隔": "Attente de l’intervalle de changement de compte", + "读取校验摘要: %w": "Lecture de la somme de contrôle : {0}", + "读取账户历史使用记录失败": "Échec de la lecture de l’historique d’utilisation des comptes", + "模型 %s 需要 %s,本次请求可用的账户 %s 都不具备": "Le modèle {0} nécessite {1}, que ne possèdent pas les comptes disponibles pour cette requête ({2})", + "模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "Le modèle {0} nécessite l'un de ces droits, que ne possèdent pas les comptes disponibles pour cette requête ({1}) : {2}", + "Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Le modèle Interaction contents[{0}] n'accepte pas l'étape d'outil côté serveur {1}" } diff --git a/internal/i18n/messages/ja.json b/internal/i18n/messages/ja.json index 74ea4445..2750afc5 100644 --- a/internal/i18n/messages/ja.json +++ b/internal/i18n/messages/ja.json @@ -1531,5 +1531,17 @@ "解析 WebDriver BiDi Cookie: %w": "WebDriver BiDi Cookie の解析: {0}", "解码 WebDriver BiDi Cookie %s 的 base64 值: %w": "WebDriver BiDi Cookie {0} の base64 値をデコード: {1}", "WebDriver BiDi 读取失败: %w": "WebDriver BiDi の読み取りに失敗しました: {0}", - "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "ブラウザのデバッグ アドレスからデバッグ情報が返されませんでした: HTTP {0};WebDriver BiDi の読み取りに失敗しました: {1}" + "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "ブラウザのデバッグ アドレスからデバッグ情報が返されませんでした: HTTP {0};WebDriver BiDi の読み取りに失敗しました: {1}", + "ACCOUNT_SWITCH_INTERVAL 必须是 off 或正整数秒": "ACCOUNT_SWITCH_INTERVAL は off または正の整数(秒)である必要があります", + "Build 模型目录同步失败": "Build モデル一覧の同期失敗", + "GitHub 访问频率受限(HTTP %d)": "GitHub のアクセス頻度制限に達しました(HTTP {0})", + "MAX_QUOTA_SWITCHES 必须是 off、0 或正整数": "MAX_QUOTA_SWITCHES は off、0 または正の整数である必要があります", + "只能在本机访问时关闭管理登录": "管理ログインの無効化はローカルアクセスからのみ可能です", + "最新发行版本跳转缺少版本号": "最新リリースのリダイレクトにバージョンタグがありません", + "等待换号间隔": "アカウント切替間隔を待機中", + "读取校验摘要: %w": "チェックサムの読み込み: {0}", + "读取账户历史使用记录失败": "アカウント使用履歴の読み込みに失敗しました", + "模型 %s 需要 %s,本次请求可用的账户 %s 都不具备": "モデル {0} には {1} が必要ですが、このリクエストで使用できるアカウント({2})はいずれも備えていません", + "模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "モデル {0} には次のいずれかの権限が必要ですが、このリクエストで使用できるアカウント({1})はいずれも備えていません: {2}", + "Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction モデルの contents[{0}] はサーバー側ツールのステップ {1} を受け付けません" } diff --git a/internal/i18n/messages/ko.json b/internal/i18n/messages/ko.json index 80b8d0cc..98fa8154 100644 --- a/internal/i18n/messages/ko.json +++ b/internal/i18n/messages/ko.json @@ -1531,5 +1531,17 @@ "解析 WebDriver BiDi Cookie: %w": "WebDriver BiDi 쿠키 구문 분석: {0}", "解码 WebDriver BiDi Cookie %s 的 base64 值: %w": "WebDriver BiDi 쿠키 {0}의 base64 값 디코딩: {1}", "WebDriver BiDi 读取失败: %w": "WebDriver BiDi 읽기 실패: {0}", - "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "브라우저 디버그 주소에서 디버그 정보를 반환하지 않았습니다: HTTP {0}; WebDriver BiDi 읽기 실패: {1}" + "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "브라우저 디버그 주소에서 디버그 정보를 반환하지 않았습니다: HTTP {0}; WebDriver BiDi 읽기 실패: {1}", + "ACCOUNT_SWITCH_INTERVAL 必须是 off 或正整数秒": "ACCOUNT_SWITCH_INTERVAL은 off 또는 양의 정수(초)여야 합니다", + "Build 模型目录同步失败": "Build 모델 목록 동기화 실패", + "GitHub 访问频率受限(HTTP %d)": "GitHub 요청 빈도 제한에 도달했습니다 (HTTP {0})", + "MAX_QUOTA_SWITCHES 必须是 off、0 或正整数": "MAX_QUOTA_SWITCHES는 off, 0 또는 양의 정수여야 합니다", + "只能在本机访问时关闭管理登录": "관리 로그인은 로컬 접속에서만 비활성화할 수 있습니다", + "最新发行版本跳转缺少版本号": "최신 릴리스 리디렉션에 버전 태그가 없습니다", + "等待换号间隔": "계정 전환 간격 대기 중", + "读取校验摘要: %w": "체크섬 읽기: {0}", + "读取账户历史使用记录失败": "계정 사용 기록 읽기 실패", + "模型 %s 需要 %s,本次请求可用的账户 %s 都不具备": "모델 {0}에는 {1}이(가) 필요하지만 이 요청에서 사용할 수 있는 계정({2})에 없습니다", + "模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "모델 {0}에는 다음 권한 중 하나가 필요하지만 이 요청에서 사용할 수 있는 계정({1})에 없습니다: {2}", + "Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction 모델의 contents[{0}]은(는) 서버 측 도구 단계 {1}을(를) 허용하지 않습니다" } diff --git a/internal/i18n/messages/zh-TW.json b/internal/i18n/messages/zh-TW.json index 73317674..a60f5c95 100644 --- a/internal/i18n/messages/zh-TW.json +++ b/internal/i18n/messages/zh-TW.json @@ -1531,5 +1531,17 @@ "解析 WebDriver BiDi Cookie: %w": "剖析 WebDriver BiDi Cookie: {0}", "解码 WebDriver BiDi Cookie %s 的 base64 值: %w": "解碼 WebDriver BiDi Cookie {0} 的 base64 值: {1}", "WebDriver BiDi 读取失败: %w": "WebDriver BiDi 讀取失敗: {0}", - "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "瀏覽器偵錯位址沒有傳回偵錯資訊: HTTP {0};WebDriver BiDi 讀取失敗: {1}" + "浏览器调试地址没有返回调试信息: HTTP %d;WebDriver BiDi 读取失败: %w": "瀏覽器偵錯位址沒有傳回偵錯資訊: HTTP {0};WebDriver BiDi 讀取失敗: {1}", + "ACCOUNT_SWITCH_INTERVAL 必须是 off 或正整数秒": "ACCOUNT_SWITCH_INTERVAL 必須是 off 或正整數秒", + "Build 模型目录同步失败": "Build 模型目錄同步失敗", + "GitHub 访问频率受限(HTTP %d)": "GitHub 存取頻率受限(HTTP {0})", + "MAX_QUOTA_SWITCHES 必须是 off、0 或正整数": "MAX_QUOTA_SWITCHES 必須是 off、0 或正整數", + "只能在本机访问时关闭管理登录": "只能在本機存取時關閉管理登入", + "最新发行版本跳转缺少版本号": "最新發行版本跳轉缺少版本號", + "等待换号间隔": "等待換號間隔", + "读取校验摘要: %w": "讀取校驗摘要: {0}", + "读取账户历史使用记录失败": "讀取帳號歷史使用記錄失敗", + "模型 %s 需要 %s,本次请求可用的账户 %s 都不具备": "模型 {0} 需要 {1},本次請求可用的帳號 {2} 都不具備", + "模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "模型 {0} 需要以下任一權益,本次請求可用的帳號 {1} 都不具備:{2}", + "Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction 模型的 contents[{0}] 不接受伺服器端工具步驟 {1}" } diff --git a/internal/pricing/pricing_test.go b/internal/pricing/pricing_test.go deleted file mode 100644 index 4b0bf2d7..00000000 --- a/internal/pricing/pricing_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package pricing - -import ( - "math" - "testing" - "time" -) - -// TestPricingSchedule 验证单价历史表顺序、美国太平洋时间零点生效切换,以及 Boundaries 只返回开区间内的切点 -func TestPricingSchedule(t *testing.T) { - for model, entries := range prices { - if len(entries) == 0 { - t.Fatalf("%s 缺少单价分段", model) - } - if !entries[0].from.IsZero() { - t.Errorf("%s 首段生效时间应为零值,得到 %v", model, entries[0].from) - } - for index := 1; index < len(entries); index++ { - if !entries[index].from.After(entries[index-1].from) { - t.Errorf("%s 第 %d 段生效时间 %v 不晚于前一段 %v", model, index, entries[index].from, entries[index-1].from) - } - } - } - pacific, err := time.LoadLocation("America/Los_Angeles") - if err != nil { - t.Fatal(err) - } - dec1 := time.Date(2026, time.December, 1, 0, 0, 0, 0, pacific) - jan1 := time.Date(2027, time.January, 1, 0, 0, 0, 0, pacific) - for _, check := range []struct { - name string - model string - at time.Time - input, cached, output int64 - want float64 - }{ - {"Carbon 11-30 PT 末尾", "gemini-4-carbon", dec1.Add(-time.Millisecond), 1_000_000, 500_000, 100_000, 2.05}, - {"Carbon 12-01 PT 零点", "gemini-4-carbon", dec1, 1_000_000, 500_000, 100_000, 4.10}, - {"Argon 11-30 PT 末尾", "gemini-4-argon", dec1.Add(-time.Millisecond), 1_000_000, 0, 100_000, 3.00}, - {"Argon 12-01 PT 零点", "gemini-4-argon", dec1, 1_000_000, 0, 100_000, 6.00}, - {"3.8 Flash 12-31 PT 末尾", "gemini-3.8-flash", jan1.Add(-time.Millisecond), 1_000_000, 500_000, 100_000, 0.7875}, - {"3.8 Flash 01-01 PT 零点", "gemini-3.8-flash", jan1, 1_000_000, 500_000, 100_000, 1.575}, - } { - if got := TierCost(check.model, check.at, check.input > LongContext, check.input, check.cached, check.output); math.Abs(got-check.want) > 1e-9 { - t.Errorf("%s: TierCost = %v, 应为 %v", check.name, got, check.want) - } - } - if got := Boundaries(dec1, jan1); len(got) != 0 { - t.Errorf("Boundaries(dec1, jan1) 应为空,得到 %v", got) - } - if got := Boundaries(dec1.Add(-time.Second), jan1.Add(time.Second)); len(got) != 2 || !got[0].Equal(dec1) || !got[1].Equal(jan1) { - t.Errorf("Boundaries 跨两切点 = %v, 应为 [%v %v]", got, dec1, jan1) - } -} diff --git a/internal/requestdb/records.go b/internal/requestdb/records.go index f36f1fe5..50b54b15 100644 --- a/internal/requestdb/records.go +++ b/internal/requestdb/records.go @@ -17,7 +17,7 @@ import ( // recordColumns 是请求记录查询读取的列,最后一列表示是否保存了正文 const recordColumns = `r.id, r.time, r.protocol, r.path, r.model, r.account, r.channel, r.status, r.state, r.duration_ms, r.first_event_ms, r.queue_ms, r.input_tokens, r.cached_tokens, r.reasoning_tokens, r.reply_tokens, r.total_tokens, - r.tool_calls, r.error, r.attempts, r.proof_ms, r.proof_lock_ms, r.proof_interaction_ms, r.proof_refresh_ms, r.proof_compute_ms, + r.tool_calls, r.reply_tool, r.reply_tool_calls, r.reply_tool_continuations, r.error, r.attempts, r.proof_ms, r.proof_lock_ms, r.proof_interaction_ms, r.proof_refresh_ms, r.proof_compute_ms, EXISTS(SELECT 1 FROM request_bodies b WHERE b.id = r.id)` // recordFilter 返回请求记录的范围、维度筛选、状态码与关键字条件 @@ -41,15 +41,18 @@ func recordFilter(query api.UsageRecordQuery) (string, []any) { func scanRecord(rows *sql.Rows) (api.UsageRecord, error) { var record api.UsageRecord var at int64 + var replyTool int var attempts string err := rows.Scan(&record.ID, &at, &record.Protocol, &record.Path, &record.Model, &record.Account, &record.Channel, &record.Status, &record.State, &record.DurationMS, &record.FirstEventMS, &record.QueueMS, &record.InputTokens, &record.CachedTokens, - &record.ReasoningTokens, &record.ReplyTokens, &record.TotalTokens, &record.ToolCalls, &record.Error, &attempts, + &record.ReasoningTokens, &record.ReplyTokens, &record.TotalTokens, &record.ToolCalls, &replyTool, &record.ReplyToolCalls, &record.ReplyToolContinuations, + &record.Error, &attempts, &record.ProofMS, &record.ProofPhases.LockMS, &record.ProofPhases.InteractionMS, &record.ProofPhases.RefreshMS, &record.ProofPhases.ComputeMS, &record.HasBody) if err != nil { return record, err } + record.ReplyTool = replyTool != 0 record.Time = time.UnixMilli(at).UTC() if err := json.Unmarshal([]byte(attempts), &record.Attempts); err != nil { return record, err @@ -91,7 +94,7 @@ func (store *Store) Records(ctx context.Context, query api.UsageRecordQuery) (ap // csvHeader 是导出文件的列名 var csvHeader = []string{ "time", "id", "protocol", "path", "model", "account", "channel", "status", "state", "duration_ms", "first_event_ms", - "queue_ms", "input_tokens", "cached_tokens", "reasoning_tokens", "reply_tokens", "total_tokens", "tool_calls", "error", "attempts", + "queue_ms", "input_tokens", "cached_tokens", "reasoning_tokens", "reply_tokens", "total_tokens", "tool_calls", "reply_tool", "reply_tool_calls", "reply_tool_continuations", "error", "attempts", "proof_ms", "proof_lock_ms", "proof_interaction_ms", "proof_refresh_ms", "proof_compute_ms", } @@ -136,7 +139,7 @@ func (store *Store) ExportRecords(ctx context.Context, query api.UsageRecordQuer record.Time.Format(time.RFC3339Nano), record.ID, record.Protocol, csvText(record.Path), csvText(record.Model), csvText(record.Account), record.Channel, strconv.Itoa(record.Status), record.State, integer(record.DurationMS), integer(record.FirstEventMS), integer(record.QueueMS), integer(record.InputTokens), integer(record.CachedTokens), integer(record.ReasoningTokens), - integer(record.ReplyTokens), integer(record.TotalTokens), strconv.Itoa(record.ToolCalls), csvText(record.Error), string(attempts), + integer(record.ReplyTokens), integer(record.TotalTokens), strconv.Itoa(record.ToolCalls), strconv.FormatBool(record.ReplyTool), strconv.Itoa(record.ReplyToolCalls), strconv.Itoa(record.ReplyToolContinuations), csvText(record.Error), string(attempts), integer(record.ProofMS), milliseconds(record.ProofPhases.LockMS), milliseconds(record.ProofPhases.InteractionMS), milliseconds(record.ProofPhases.RefreshMS), milliseconds(record.ProofPhases.ComputeMS), }); err != nil { diff --git a/internal/requestdb/requestdb.go b/internal/requestdb/requestdb.go index 033e8fdb..70f37a86 100644 --- a/internal/requestdb/requestdb.go +++ b/internal/requestdb/requestdb.go @@ -55,7 +55,8 @@ CREATE TABLE IF NOT EXISTS requests ( input_tokens INTEGER NOT NULL, reasoning_tokens INTEGER NOT NULL, reply_tokens INTEGER NOT NULL, total_tokens INTEGER NOT NULL, tool_calls INTEGER NOT NULL, error TEXT NOT NULL, attempts TEXT NOT NULL, cached_tokens INTEGER NOT NULL DEFAULT 0, proof_ms INTEGER NOT NULL DEFAULT 0, proof_lock_ms INTEGER NOT NULL DEFAULT 0, - proof_interaction_ms INTEGER NOT NULL DEFAULT 0, proof_refresh_ms INTEGER NOT NULL DEFAULT 0, proof_compute_ms INTEGER NOT NULL DEFAULT 0); + proof_interaction_ms INTEGER NOT NULL DEFAULT 0, proof_refresh_ms INTEGER NOT NULL DEFAULT 0, proof_compute_ms INTEGER NOT NULL DEFAULT 0, + reply_tool INTEGER NOT NULL DEFAULT 0, reply_tool_calls INTEGER NOT NULL DEFAULT 0, reply_tool_continuations INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS requests_time ON requests(time); CREATE INDEX IF NOT EXISTS requests_cost ON requests(time, model, input_tokens, cached_tokens, reasoning_tokens, reply_tokens); CREATE INDEX IF NOT EXISTS requests_model_time ON requests(model, time); @@ -69,27 +70,30 @@ CREATE TABLE IF NOT EXISTS request_bodies ( // Row 是一次完成请求的用量记录 type Row struct { - ID string - Time time.Time - Protocol string - Path string - Model string - Account string - Channel string - Status int - State string - Duration time.Duration - FirstEvent time.Duration - Queue time.Duration - Proof api.ProofTiming - InputTokens int64 - CachedTokens int64 - ReasoningTokens int64 - ReplyTokens int64 - TotalTokens int64 - ToolCalls int - Error string - Attempts []api.RequestAttempt + ID string + Time time.Time + Protocol string + Path string + Model string + Account string + Channel string + Status int + State string + Duration time.Duration + FirstEvent time.Duration + Queue time.Duration + Proof api.ProofTiming + InputTokens int64 + CachedTokens int64 + ReasoningTokens int64 + ReplyTokens int64 + TotalTokens int64 + ToolCalls int + ReplyTool bool + ReplyToolCalls int + ReplyToolContinuations int + Error string + Attempts []api.RequestAttempt } // write 是写入协程处理的一条用量或正文 @@ -282,12 +286,16 @@ func (store *Store) write(batch []write) (err error) { if err != nil { return err } - result, err := tx.Exec(`INSERT OR IGNORE INTO requests VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + replyTool := 0 + if row.ReplyTool { + replyTool = 1 + } + result, err := tx.Exec(`INSERT OR IGNORE INTO requests VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, row.ID, row.Time.UnixMilli(), row.Protocol, row.Path, row.Model, row.Account, row.Channel, row.Status, row.State, row.Duration.Milliseconds(), row.FirstEvent.Milliseconds(), row.Queue.Milliseconds(), row.InputTokens, row.ReasoningTokens, row.ReplyTokens, row.TotalTokens, row.ToolCalls, row.Error, string(encoded), row.CachedTokens, row.Proof.Total.Milliseconds(), row.Proof.Lock.Milliseconds(), row.Proof.Interaction.Milliseconds(), - row.Proof.Refresh.Milliseconds(), row.Proof.Compute.Milliseconds()) + row.Proof.Refresh.Milliseconds(), row.Proof.Compute.Milliseconds(), replyTool, row.ReplyToolCalls, row.ReplyToolContinuations) if err != nil { return err } diff --git a/internal/requestdb/usage_seed.go b/internal/requestdb/usage_seed.go new file mode 100644 index 00000000..610dc5d8 --- /dev/null +++ b/internal/requestdb/usage_seed.go @@ -0,0 +1,71 @@ +package requestdb + +import ( + "context" + "errors" + "strings" + "time" +) + +// AccountUsageEntry 表示单个账户在指定模型与通道上的最近使用时刻 +type AccountUsageEntry struct { + Account string + Model string + Channel string + LastUsed time.Time +} + +// AccountUsageSeed 保存启动时从请求账本读回的账户最近使用记录与当前配额日请求数 +type AccountUsageSeed struct { + Entries []AccountUsageEntry + QuotaDayStart time.Time + QuotaDayRequests map[string]int64 +} + +// AccountUsageSeed 返回各账户按模型与通道聚合的最近使用时刻,以及自 quotaDayStart 起至今的请求数 +func (store *Store) AccountUsageSeed(ctx context.Context, quotaDayStart time.Time) (AccountUsageSeed, error) { + seed := AccountUsageSeed{ + QuotaDayStart: quotaDayStart, + QuotaDayRequests: map[string]int64{}, + } + rows, err := store.db.QueryContext(ctx, `SELECT account, model, channel, MAX(last_time) FROM days WHERE account != '' GROUP BY account, model, channel`) + if err != nil { + return AccountUsageSeed{}, err + } + for rows.Next() { + var account, model, channel string + var lastTime int64 + if err := rows.Scan(&account, &model, &channel, &lastTime); err != nil { + return AccountUsageSeed{}, errors.Join(err, rows.Close()) + } + if lastTime <= 0 { + continue + } + seed.Entries = append(seed.Entries, AccountUsageEntry{ + Account: strings.TrimSpace(account), + Model: strings.TrimPrefix(strings.TrimSpace(model), "models/"), + Channel: strings.TrimSpace(channel), + LastUsed: time.UnixMilli(lastTime).UTC(), + }) + } + if err := errors.Join(rows.Err(), rows.Close()); err != nil { + return AccountUsageSeed{}, err + } + if quotaDayStart.IsZero() { + return seed, nil + } + from, to := quotaDayStart.UnixMilli(), time.Now().UnixMilli()+1 + if from >= to { + return seed, nil + } + for _, part := range plan(from, to, nil) { + if err := store.scan(ctx, part, nil, func(value *entry) { + if account := strings.TrimSpace(value.account); account != "" { + seed.QuotaDayRequests[account] += value.requests + } + }); err != nil { + return AccountUsageSeed{}, err + } + } + return seed, nil +} diff --git a/internal/setup/remote_test.go b/internal/setup/remote_test.go index cb6d9c45..7d1eb3fa 100644 --- a/internal/setup/remote_test.go +++ b/internal/setup/remote_test.go @@ -1,13 +1,8 @@ package setup import ( - "encoding/json" - "net/http" - "net/http/httptest" "testing" - "github.com/Mag1cFall/AIStudio2API/internal/aistudio" - "github.com/Mag1cFall/AIStudio2API/internal/api" "github.com/Mag1cFall/AIStudio2API/internal/config" ) @@ -35,34 +30,3 @@ func TestSetupRemoteOrigin(t *testing.T) { t.Fatal("没有 --remote 时接受了 --token") } } - -// TestPairingRenewalUploadWithoutBoundSession 验证远程上传保留 Chrome 来源与 OAuth 续签材料,DBSC 会话登记留在持有设备绑定密钥的本机 -func TestPairingRenewalUploadWithoutBoundSession(t *testing.T) { - var uploaded aistudio.AuthExtension - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var input api.AccountStateInput - if err := json.NewDecoder(r.Body).Decode(&input); err != nil { - t.Error(err) - } - uploaded, _, _ = input.StorageState.AuthExtension() - w.WriteHeader(http.StatusCreated) - json.NewEncoder(w).Encode(api.PairingAccountResult{Account: api.AdminAccount{ID: "user@example.com", Label: "user@example.com"}, RenewalToken: "renewal"}) - })) - defer server.Close() - state := aistudio.StorageState{Cookies: []aistudio.StateCookie{}, Origins: []aistudio.StorageOrigin{}} - state.SetAuthExtension(aistudio.AuthExtension{ - Source: aistudio.AuthSource{Browser: "chrome", Profile: "Default", Email: "user@example.com"}, - OAuth: &aistudio.ChromeOAuthMaterial{GaiaID: "gaia", RefreshToken: "token", WrappedBindingKey: []byte("key")}, - Bound: &aistudio.BoundSession{ID: "sidts_session", RefreshURL: "https://accounts.google.com/RotateBoundCookies", Credentials: []string{"__Secure-1PSIDRTS"}}, - }) - target := &remoteTarget{client: server.Client(), origin: server.URL, token: "pairing"} - if _, err := target.Save(t.Context(), aistudio.DefaultAccountConfig("user@example.com"), state, ""); err != nil { - t.Fatal(err) - } - if uploaded.OAuth == nil || uploaded.OAuth.RefreshToken != "token" || uploaded.Bound != nil { - t.Fatalf("上传的认证扩展 %+v", uploaded) - } - if len(target.renewals) != 1 || target.renewals[0].OAuth.RefreshToken != "token" { - t.Fatalf("本机续签材料 %+v", target.renewals) - } -} diff --git a/internal/waa/clock_test.go b/internal/waa/clock_test.go deleted file mode 100644 index 25d2b97e..00000000 --- a/internal/waa/clock_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package waa - -import ( - "context" - "encoding/json" - "testing" - "time" - - "github.com/Mag1cFall/AIStudio2API/internal/waa/mozjs" - "github.com/Mag1cFall/AIStudio2API/internal/waa/rhythm" -) - -// TestProofNotAheadOfRealTime 核对没有空闲时连续取 proof,snapshot 中读到的 Date.now 不晚于 RunProof 返回时的真实时间:本进程取 proof 的 CPU 耗时短于官网耗时、取 proof 一步的 VM 时钟走得比真实时间快时,这一步开始前真实等待走完时 VM 时钟会超出真实时间的部分 -func TestProofNotAheadOfRealTime(t *testing.T) { - snapshotCosts.Lock() - saved, count := snapshotCosts.recent, snapshotCosts.count - snapshotCosts.Unlock() - t.Cleanup(func() { - snapshotCosts.Lock() - snapshotCosts.recent, snapshotCosts.count = saved, count - snapshotCosts.Unlock() - }) - for range 9 { - recordSnapshotCost(1.0) - } - ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) - defer cancel() - runtime, err := NewRuntime(ctx, Options{ - Challenge: Challenge{GlobalName: "ahead", Program: "local"}, - Interpreter: `globalThis.ahead = {a(program, ready) { - ready(done => { __aheadCPU(); done(String(Date.now())); }); - }};`, - Profile: Profile{NavigationStart: time.Now(), Locale: "en-US"}, - Rhythm: rhythm.Rhythm{Press: 10, Hold: 65, Proof: 50, Control: 30, Key: 100, Release: 27}, - }) - if err != nil { - t.Fatal(err) - } - defer runtime.Close() - installed := make(chan error, 1) - runtime.loop.post(func() { - cx, global := runtime.agent.cx, runtime.agent.top.global - callback, err := cx.NewFunction(global, "__aheadCPU", 0, func(*mozjs.Call) error { - started := mozjs.CPU() - for mozjs.CPU()-started < 1.1 { - } - return nil - }) - if err == nil { - err = cx.Set(global, "__aheadCPU", mozjs.Object(callback)) - cx.Release(callback) - } - installed <- err - }) - if err := <-installed; err != nil { - t.Fatal(err) - } - var leads []float64 - for range 5 { - value, err := runtime.RunProof(ctx, "local", "hello") - returned := float64(time.Now().UnixMilli()) - if err != nil { - t.Fatal(err) - } - var date float64 - if err := json.Unmarshal([]byte(value), &date); err != nil { - t.Fatal(err) - } - leads = append(leads, date-returned) - } - t.Logf("snapshot 中的 Date.now 减 RunProof 返回时的真实时间:%v ms", leads) - for _, lead := range leads { - if lead > 1 { - t.Fatalf("snapshot 中的 Date.now 晚于 RunProof 返回时的真实时间:%v ms", leads) - } - } -} diff --git a/internal/waa/rhythm/rhythm_test.go b/internal/waa/rhythm/rhythm_test.go deleted file mode 100644 index 742b22d6..00000000 --- a/internal/waa/rhythm/rhythm_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package rhythm - -import ( - "math" - "slices" - "testing" -) - -// TestNewRhythmsDistinct 核对新生成的 300 份节奏两两不同,每个间隔都落在官网现场的最小与最大值之间 -func TestNewRhythmsDistinct(t *testing.T) { - seen := map[Rhythm]bool{} - for range 300 { - value := New() - if seen[value] { - t.Fatalf("节奏重复 %+v", value) - } - seen[value] = true - for name, pair := range map[string]struct { - got float64 - from []float64 - }{"press": {value.Press, official.press}, "hold": {value.Hold, official.hold}, "proof": {value.Proof, official.proof}, "control": {value.Control, official.control}, "key": {value.Key, official.key}, "release": {value.Release, official.release}} { - if pair.got < slices.Min(pair.from) || pair.got > slices.Max(pair.from) { - t.Fatalf("%s=%.2f 超出官网现场 %v", name, pair.got, pair.from) - } - } - } -} - -// TestNewRhythmsMatchOfficial 核对 300 份节奏中点击的三个间隔与官网现场同分布:两样本 Kolmogorov–Smirnov 距离小于 0.05 显著性水平的临界值 -func TestNewRhythmsMatchOfficial(t *testing.T) { - var press, hold, proof []float64 - for range 300 { - value := New() - press, hold, proof = append(press, value.Press), append(hold, value.Hold), append(proof, value.Proof) - } - for name, pair := range map[string][2][]float64{"press": {press, official.press}, "hold": {hold, official.hold}, "proof": {proof, official.proof}} { - generated, observed := pair[0], pair[1] - critical := 1.358 * math.Sqrt(float64(len(generated)+len(observed))/float64(len(generated)*len(observed))) - if distance := ksDistance(generated, observed); distance >= critical { - t.Fatalf("%s 的 KS 距离 %.3f 不小于临界值 %.3f", name, distance, critical) - } - } -} - -// ksDistance 返回两个样本经验分布函数的最大差 -func ksDistance(a, b []float64) float64 { - a, b = slices.Sorted(slices.Values(a)), slices.Sorted(slices.Values(b)) - var distance float64 - for _, x := range slices.Concat(a, b) { - fa := float64(countAtMost(a, x)) / float64(len(a)) - fb := float64(countAtMost(b, x)) / float64(len(b)) - distance = max(distance, math.Abs(fa-fb)) - } - return distance -} - -// countAtMost 返回有序样本中不大于 x 的个数 -func countAtMost(sorted []float64, x float64) int { - index, found := slices.BinarySearch(sorted, x) - for found && index < len(sorted) && sorted[index] <= x { - index++ - } - return index -} diff --git a/web/src/App.vue b/web/src/App.vue index 30c36d7d..4971f067 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -598,10 +598,10 @@ onMounted(revealCurrentTab)
- {{ + {{ deletedNotice }} +
diff --git a/web/src/ConsoleRoot.vue b/web/src/ConsoleRoot.vue index 9c1cd9d2..e5c76d37 100644 --- a/web/src/ConsoleRoot.vue +++ b/web/src/ConsoleRoot.vue @@ -74,6 +74,7 @@ async function logout(): Promise { onMounted(() => { startDesktop(locale, router) window.addEventListener('admin-session-expired', expireSession) + window.addEventListener('admin-session-changed', () => void loadSession()) void loadSession(initialSession) }) diff --git a/web/src/api.ts b/web/src/api.ts index ad99cecd..ebbbeb80 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -268,6 +268,7 @@ export const api = { ).task, startService: () => requestJSON('/api/control/start', { method: 'POST' }), stopService: () => requestJSON('/api/control/stop', { method: 'POST' }), + restartService: () => requestJSON('/api/control/restart', { method: 'POST' }), downloadCamoufox: () => requestJSON('/api/camoufox/download', { method: 'POST' }), clearLogs: () => requestCommand('/api/logs', { method: 'DELETE' }), firstEventLatency: async () => diff --git a/web/src/components/AccessPanel.vue b/web/src/components/AccessPanel.vue index 916187ec..aed6a54f 100644 --- a/web/src/components/AccessPanel.vue +++ b/web/src/components/AccessPanel.vue @@ -75,7 +75,7 @@ const section = useQueryParam( const current = computed(() => sections.find((item) => item.id === section.value)!) // keys 是生效中的 API key,多个 key 用逗号分隔 -const keys = computed(() => splitKeys(props.config?.active_proxy_api_key ?? '')) +const keys = computed(() => splitKeys(props.config?.proxy_api_key ?? '')) const keyIndex = ref(0) const keyShown = ref(false) watch(keys, (list) => { diff --git a/web/src/components/AccountExits.vue b/web/src/components/AccountExits.vue index 4fdbd89f..4d607021 100644 --- a/web/src/components/AccountExits.vue +++ b/web/src/components/AccountExits.vue @@ -1,9 +1,10 @@ diff --git a/web/src/components/AccountFilterMenu.vue b/web/src/components/AccountFilterMenu.vue new file mode 100644 index 00000000..11d710ea --- /dev/null +++ b/web/src/components/AccountFilterMenu.vue @@ -0,0 +1,92 @@ + + + + diff --git a/web/src/components/AccountsPanel.vue b/web/src/components/AccountsPanel.vue index 4e6f0a86..7c50c7c0 100644 --- a/web/src/components/AccountsPanel.vue +++ b/web/src/components/AccountsPanel.vue @@ -34,6 +34,7 @@ import type { IconName } from '@/icons' import AccountEnvironmentFields from './AccountEnvironmentFields.vue' import AccountModelsDialog from './AccountModelsDialog.vue' import AccountExits from './AccountExits.vue' +import AutoDismissRow from './AutoDismissRow.vue' import CamoufoxProgressBar from './CamoufoxProgressBar.vue' import DetailDialog from './DetailDialog.vue' import DisclosureChevron from './DisclosureChevron.vue' @@ -799,7 +800,6 @@ function viewerUnavailable(): void { async function beginBrowserLogin(): Promise { pendingAction.value = 'browser-login' try { - await commitDelete() openViewer(await api.createAccount({ ...accountEnvironment }, newViewID())) showBrowserLogin.value = false } catch (error) { @@ -871,14 +871,6 @@ async function openChromeImport(): Promise { pendingAction.value = 'chrome-discover' try { await commitDelete() - chromeTierController?.abort() - chromeTierController = undefined - probingChromeTiers.value = false - chromeTiers.clear() - chromeCheckingIDs.clear() - chromeTierDone.value = 0 - chromeTierTotal.value = 0 - resetChromeFilter() chromeProfiles.value = await api.chromeImportProfiles() selectedChromeProfiles.value = [] showChromeImport.value = true @@ -906,7 +898,6 @@ function closeChromeImport(): void { async function importChromeAccounts(): Promise { pendingAction.value = 'chrome-import' try { - await commitDelete() const chosen = new Set(selectedChromeProfiles.value) await api.importChromeAccounts({ accounts: chromeProfiles.value @@ -986,7 +977,6 @@ async function discoverCookieAccounts(): Promise { // failed 是出错时正在识别的文件名 let failed = '' try { - await commitDelete() const found: CookieCandidate[] = [] for (const [source, item] of sources.entries()) { failed = item.name @@ -1099,7 +1089,6 @@ async function scanBrowsers(): Promise { browserLookupStartedAt.value = Date.now() scanningBrowsers.value = true try { - await commitDelete() cookieBrowsers.value = await api.cookieBrowsers(accountEnvironment.proxy) selectedBrowsers.value = cookieBrowsers.value .filter( @@ -1135,7 +1124,6 @@ function switchToCookiePaste(): void { async function importBrowserAccounts(): Promise { pendingAction.value = 'browser-import' try { - await commitDelete() const chosen = new Set(selectedBrowsers.value) await api.importCookieAccounts({ items: cookieBrowsers.value @@ -1210,7 +1198,6 @@ async function importCookieAccounts(): Promise { } pendingAction.value = 'cookie-import' try { - await commitDelete() const sources = cookieSources() const chosen = new Set(selectedCookieUsers.value) await api.importCookieAccounts({ @@ -1302,7 +1289,6 @@ async function changeState(account: Account, state: 'ready' | 'disabled'): Promi async function loginAccount(account: Account): Promise { pendingAction.value = `login:${account.id}` try { - await commitDelete() openViewer(await api.loginAccount(account.id, newViewID())) } catch (error) { actionError(error) @@ -1315,7 +1301,6 @@ async function loginAccount(account: Account): Promise { async function verifyAccount(account: Account): Promise { pendingAction.value = `verify:${account.id}` try { - await commitDelete() openViewer(await api.verifyAccount(account.id, newViewID())) } catch (error) { actionError(error) @@ -1496,10 +1481,16 @@ watch( >
    -
  • +
    - {{ - t(taskTitles[task.kind]) - }} + {{ t(taskTitles[task.kind]) }} {{ taskFinished(task) }}/{{ task.items.length }} @@ -1660,7 +1653,7 @@ watch(
- +
+import { onActivated, onBeforeUnmount, onDeactivated, ref, useTemplateRef, watch } from 'vue' + +// active 为真时开始倒计时,到时发出 dismiss +const props = defineProps<{ active: boolean }>() +const emit = defineEmits<{ dismiss: [] }>() + +// duration 是自动关闭前的显示时长,单位 ms +const duration = 12000 +const bar = useTemplateRef('bar') +const hovered = ref(false) +const focused = ref(false) +// shown 是所在页面是否显示,切到管理端其他页面时为假 +const shown = ref(true) +const visible = ref(document.visibilityState === 'visible') +let animation: Animation | undefined + +// sync 在悬停、聚焦、页面不可见或所在页面切走时暂停倒计时,其余时候继续 +function sync(): void { + if (animation === undefined) return + if (hovered.value || focused.value || !visible.value || !shown.value) animation.pause() + else animation.play() +} + +watch( + [() => props.active, bar], + ([active, element]) => { + if (!active || element === null || animation !== undefined) return + animation = element.animate([{ transform: 'scaleX(1)' }, { transform: 'scaleX(0)' }], { + duration, + easing: 'linear', + fill: 'forwards', + }) + animation.onfinish = () => emit('dismiss') + sync() + }, + { flush: 'post', immediate: true }, +) +watch([hovered, focused, visible, shown], sync) + +// onFocusOut 在焦点移出整行时结束聚焦 +function onFocusOut(event: FocusEvent): void { + focused.value = (event.currentTarget as HTMLElement).contains(event.relatedTarget as Node | null) +} + +// onVisibility 记录浏览器标签页是否可见 +function onVisibility(): void { + visible.value = document.visibilityState === 'visible' +} +document.addEventListener('visibilitychange', onVisibility) +onBeforeUnmount(() => { + document.removeEventListener('visibilitychange', onVisibility) + animation?.cancel() +}) +onActivated(() => (shown.value = true)) +onDeactivated(() => (shown.value = false)) + + + diff --git a/web/src/components/FilterMenu.vue b/web/src/components/FilterMenu.vue index 48f1d9ac..6810dc88 100644 --- a/web/src/components/FilterMenu.vue +++ b/web/src/components/FilterMenu.vue @@ -10,11 +10,14 @@ const props = defineProps<{ label: string options: string[] selected: string[] + // format 返回取值的显示与搜索文字,提供 option 插槽时只用于搜索 format: (value: string) => string searchLabel: string emptyLabel: string clearLabel: string disabled?: boolean + // badge 是触发器上代替选中数显示的文字,空串时不显示 + badge?: string // field 表示触发器使用表单下拉框的样式 field?: boolean }>() @@ -56,9 +59,9 @@ function toggle(value: string, checked: boolean): void { > {{ label }} {{ selected.length }}{{ badge ?? selected.length }} @@ -101,9 +104,11 @@ function toggle(value: string, checked: boolean): void { :disabled="disabled" @change="toggle(value, ($event.target as HTMLInputElement).checked)" /> - {{ - format(value) - }} + + {{ + format(value) + }} +
diff --git a/web/src/components/ImportFilterBar.vue b/web/src/components/ImportFilterBar.vue index fbdfca15..85f0ff75 100644 --- a/web/src/components/ImportFilterBar.vue +++ b/web/src/components/ImportFilterBar.vue @@ -1,6 +1,7 @@ + + diff --git a/web/src/components/ModelsTable.vue b/web/src/components/ModelsTable.vue index 97693a8c..9ee57a20 100644 --- a/web/src/components/ModelsTable.vue +++ b/web/src/components/ModelsTable.vue @@ -6,8 +6,8 @@ import { channelLabelKey, useI18n, type TranslationKey } from '@/i18n' import { capabilityNames, outputLimit, priceLines, tokenLimit } from '@/playground/catalog' import type { Account, Model, ServiceConfig, UpstreamChannel } from '@/types' import { useQueryText } from '@/url' +import AccountFilterMenu from './AccountFilterMenu.vue' import DetailDialog from './DetailDialog.vue' -import FilterMenu from './FilterMenu.vue' import UiIcon from './UiIcon.vue' import UiSelect, { keepSelected } from './UiSelect.vue' @@ -84,18 +84,6 @@ function modelAccounts(model: Model): string[] { return modelAccountBindings(props.config?.model_accounts ?? '').get(model.id) ?? [] } -// accountLabel 返回账户 ID 对应的显示名称 -function accountLabel(id: string): string { - return props.accounts.find((account) => account.id === id)?.label ?? id -} - -// modelAccountsLabel 是模型账户选择按钮的文字:未选时为全部账户,只选一个时为该账户 -function modelAccountsLabel(model: Model): string { - const ids = modelAccounts(model) - if (ids.length === 0) return t('settings.keyAccountsAll') - return ids.length === 1 ? accountLabel(ids[0]!) : t('settings.keyAccountsSome') -} - // setModelAccounts 保存模型可用的账户,空列表表示可用全部账户 async function setModelAccounts(model: Model, ids: string[]): Promise { if (props.config === null) return @@ -483,14 +471,9 @@ function modelSummary(model: Model): string {
{{ t('models.accounts') }} - diff --git a/web/src/components/SettingRow.vue b/web/src/components/SettingRow.vue index 7da4fe8d..424668c2 100644 --- a/web/src/components/SettingRow.vue +++ b/web/src/components/SettingRow.vue @@ -7,7 +7,8 @@ defineProps<{ controlId?: string groupId?: string description?: string - effect: 'immediate' | 'service' | 'management' + // effect 是保存后的生效时机:立即、重启生成服务、重启程序、下次启动程序 + effect: 'immediate' | 'service' | 'management' | 'launch' changed?: boolean env?: string | undefined // envNote 是部分控件由环境变量决定时的说明,整行控件仍可编辑 diff --git a/web/src/components/SettingsPanel.vue b/web/src/components/SettingsPanel.vue index f29fff20..e916c15f 100644 --- a/web/src/components/SettingsPanel.vue +++ b/web/src/components/SettingsPanel.vue @@ -4,6 +4,7 @@ import { useRouter } from 'vue-router' import { parseAccountBindings } from '@/accountBindings' import { api } from '@/api' import { maskKey, splitKeys } from '@/apikey' +import { useConsole } from '@/console' import { desktopPlatform, keepPage, sendDesktop } from '@/desktop' import { channelLabelKey, useI18n, type TranslationKey } from '@/i18n' import type { IconName } from '@/icons' @@ -11,9 +12,12 @@ import { maskedProxy } from '@/proxy' import type { Account, FirstEventLatency, Model, ServiceConfig, UpstreamChannel } from '@/types' import { useQueryParam } from '@/url' import { SliderRange, SliderRoot, SliderThumb, SliderTrack } from 'reka-ui' +import AccountFilterMenu from './AccountFilterMenu.vue' import AccountOrderList from './AccountOrderList.vue' import ApiKeyInput from './ApiKeyInput.vue' +import DetailDialog from './DetailDialog.vue' import DurationInput from './DurationInput.vue' +import ModelAccountRows from './ModelAccountRows.vue' import PairRows from './PairRows.vue' import PathList from './PathList.vue' import SettingRow from './SettingRow.vue' @@ -86,6 +90,8 @@ const sections: { 'routing_strategy', 'account_order', 'max_account_switches', + 'max_quota_switches', + 'account_switch_interval', ], }, { @@ -110,6 +116,7 @@ const sections: { fields: [ 'model_mapping', 'model_channels', + 'model_accounts', 'nonstream_keepalive', 'fake_stream', 'youtube_links', @@ -306,6 +313,22 @@ const firstEventTimeoutMode = computed({ }, }) +// quotaSwitchesMode 是额度用尽换号上限的方式,选自定义时填入 1 次 +const quotaSwitchesMode = computed({ + get: () => (form.max_quota_switches === 'off' ? 'off' : 'custom'), + set: (mode: string) => { + form.max_quota_switches = mode === 'custom' ? '1' : 'off' + }, +}) + +// switchIntervalMode 是换号最短间隔的方式,选自定义时填入 5 秒 +const switchIntervalMode = computed({ + get: () => (form.account_switch_interval === 'off' ? 'off' : 'custom'), + set: (mode: string) => { + form.account_switch_interval = mode === 'custom' ? '5' : 'off' + }, +}) + // firstEventTimeoutHedgeWarning 在同时自定义首字超时与首字对冲且首字超时不大于对冲秒数时提醒 const firstEventTimeoutHedgeWarning = computed(() => { if (firstEventTimeoutMode.value !== 'custom' || hedgeMode.value !== 'custom') return false @@ -347,8 +370,6 @@ function environmentKey(field: keyof ServiceConfig): string | undefined { // apiKeyList 是表单中逗号分隔的各个 API key const apiKeyList = computed(() => splitKeys(form.proxy_api_key ?? '')) -// activeKeys 是生效中的各个 API key -const activeKeys = computed(() => splitKeys(props.config?.active_proxy_api_key ?? '')) // writeKeyAccounts 按 API key 的顺序写回 api_key_accounts,去掉已不在 key 列表中的绑定 function writeKeyAccounts(bindings: Map): void { @@ -361,6 +382,13 @@ function writeKeyAccounts(bindings: Map): void { // keyBindings 是表单中各 API key 可用的账户 ID const keyBindings = computed(() => parseAccountBindings(form.api_key_accounts ?? '')) +// keyAccountsText 是 key 可用的全部账户名称,下拉按钮截断时悬停显示 +function keyAccountsText(key: string): string { + return (keyBindings.value.get(key) ?? []) + .map((id) => props.accounts.find((account) => account.id === id)?.label ?? id) + .join(', ') +} + // setKeyAccounts 设置 key 可用的账户,空列表表示可用全部账户 function setKeyAccounts(key: string, ids: string[]): void { const bindings = new Map(keyBindings.value) @@ -369,16 +397,11 @@ function setKeyAccounts(key: string, ids: string[]): void { writeKeyAccounts(bindings) } -// accountLabel 返回账户 ID 对应的显示名称 -function accountLabel(id: string): string { - return props.accounts.find((account) => account.id === id)?.label ?? id -} - -// keyAccountsLabel 是 key 账户选择按钮的文字:未选时为全部账户,只选一个时为该账户 -function keyAccountsLabel(key: string): string { - const ids = keyBindings.value.get(key) ?? [] - if (ids.length === 0) return t('settings.keyAccountsAll') - return ids.length === 1 ? accountLabel(ids[0]!) : t('settings.keyAccountsSome') +// focusKeyInput 把本地 API 密钥的输入框滚入视野并聚焦 +function focusKeyInput(): void { + const input = document.getElementById('setting-api-key') + input?.scrollIntoView({ block: 'center' }) + input?.focus({ preventScroll: true }) } // modelIDs 是模型目录中的全部模型 ID @@ -411,6 +434,53 @@ watch(apiKeyList, () => { writeKeyAccounts(parseAccountBindings(form.api_key_accounts)) }) +const { status, serviceState } = useConsole() +// restartPending 表示已保存的 WAA 后端或账户状态目录要在生成服务重启后生效,生成服务停止后清除 +const restartPending = ref(false) +watch( + () => props.config, + (config) => (restartPending.value = config?.service_restart_required === true), + { immediate: true }, +) +watch(serviceState, (state) => { + if (state === 'stopping' || state === 'stopped') restartPending.value = false +}) +// restartDialog 表示保存后询问是否立即重启生成服务 +const restartDialog = ref(false) +const restarting = ref(false) +// activeRequests 是生成服务进行中的请求数 +const activeRequests = computed(() => status.value?.active_requests ?? 0) +// restartImpact 是重启生成服务会中断的请求数说明 +const restartImpact = computed(() => { + if (activeRequests.value === 0) return t('settings.restartNoRequests') + return t( + activeRequests.value === 1 ? 'settings.restartInterruptsOne' : 'settings.restartInterrupts', + ).replace('{count}', String(activeRequests.value)) +}) + +// restartService 以已保存的配置重启生成服务,进行中的请求随之中断 +async function restartService(): Promise { + restartDialog.value = false + restarting.value = true + try { + status.value = await api.restartService() + if (status.value.state === 'RUNNING') emit('notice', t('settings.serviceRestarted'), 'success') + else + emit( + 'notice', + t('settings.serviceRestartState').replace( + '{state}', + t(status.value.state === 'LAUNCHING' ? 'state.launching' : 'state.stopped'), + ), + 'error', + ) + } catch (error) { + emit('notice', errorText(error), 'error') + } finally { + restarting.value = false + } +} + // resetForm 用已保存配置覆盖表单 function resetForm(config: ServiceConfig): void { Object.assign(form, JSON.parse(JSON.stringify(config)) as ServiceConfig) @@ -459,6 +529,12 @@ onUnmounted(() => { // saveConfig 原子保存全局配置 async function saveConfig(): Promise { saving.value = true + const restartFields = + changedFields.value.has('waa_backend') || changedFields.value.has('auth_states') + const sessionFields = + changedFields.value.has('admin_auth_enabled') || + changedFields.value.has('admin_username') || + adminPassword.value !== '' try { const saved = await api.saveConfig({ ...form, @@ -468,15 +544,13 @@ async function saveConfig(): Promise { }) emit('saved', saved) if (desktopPlatform === 'darwin') sendDesktop(`dock:${saved.hide_dock_icon ? 'hide' : 'show'}`) - if (saved.management_restart_required && saved.service_restart_required) { - emit('notice', t('settings.savedBoth'), 'success') - } else if (saved.management_restart_required) { - emit('notice', t('settings.savedManagement'), 'success') - } else if (saved.service_restart_required) { - emit('notice', t('settings.savedService'), 'success') - } else { - emit('notice', t('settings.saved'), 'success') - } + if (sessionFields) window.dispatchEvent(new Event('admin-session-changed')) + emit( + 'notice', + t(saved.management_restart_required ? 'settings.savedManagement' : 'settings.saved'), + 'success', + ) + if (restartFields && saved.service_restart_required) restartDialog.value = true } catch (error) { emit('notice', errorText(error), 'error') } finally { @@ -538,10 +612,23 @@ async function saveConfig(): Promise {
- {{ t('settings.pendingService') }} +

+ {{ t('settings.pendingService') }} + {{ restartImpact }} +

+
{ :label="t('settings.autoStart')" control-id="setting-auto-start" :description="t('settings.autoStartHelp')" - effect="management" + effect="launch" :changed="changedFields.has('auto_start')" :env="environmentKey('auto_start')" > @@ -632,7 +719,7 @@ async function saveConfig(): Promise { :label="t('settings.apiKey')" control-id="setting-api-key" :description="t('settings.apiKeyHelp')" - effect="management" + effect="immediate" :changed="changedFields.has('proxy_api_key')" :env="environmentKey('proxy_api_key')" > @@ -641,22 +728,9 @@ async function saveConfig(): Promise { v-model:revealed="revealKey" input-id="setting-api-key" /> -
- {{ t('settings.activeValue') }}: - {{ revealKey ? key : maskKey(key) }} - {{ t('common.empty') }} -
{ :env="environmentKey('api_key_accounts')" >
-
+ +
+
+ {{ t('settings.apiKeyAccountsEmpty') }} +
{ min="0" /> + + + + + +
+ + {{ + t('settings.maxQuotaSwitchesUnit') + }} +
+
+ + + + + +
+ + {{ + t('settings.firstEventHedgeUnit') + }} +
+
diff --git a/web/src/components/VersionPanel.vue b/web/src/components/VersionPanel.vue index cde0b206..30f6c027 100644 --- a/web/src/components/VersionPanel.vue +++ b/web/src/components/VersionPanel.vue @@ -1,8 +1,17 @@